首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >imblearn管道是否关闭采样以进行测试?

imblearn管道是否关闭采样以进行测试?
EN

Stack Overflow用户
提问于 2020-08-21 10:14:14
回答 1查看 1.1K关注 0票数 7

让我们假设下面的代码(来自管道上的imblearn学习实例)

代码语言:javascript
复制
...    
# Instanciate a PCA object for the sake of easy visualisation
pca = PCA(n_components=2)

# Create the samplers
enn = EditedNearestNeighbours()
renn = RepeatedEditedNearestNeighbours()

# Create the classifier
knn = KNN(1)

# Make the splits
X_train, X_test, y_train, y_test = tts(X, y, random_state=42)

# Add one transformers and two samplers in the pipeline object
pipeline = make_pipeline(pca, enn, renn, knn)

pipeline.fit(X_train, y_train)
y_hat = pipeline.predict(X_test)

我希望确保在执行pipeline.predict(X_test)时,不会执行采样过程ennrenn (当然,必须执行pca )。

  1. 首先,我很清楚,over-, under-, and mixed-sampling是应用于training set而不是test/validation set的过程。如果我错了,请在这里纠正我。
  2. 我浏览了imblearn Pipeline代码,但在那里找不到predict方法。
  3. 我还希望确保当管道位于GridSearchCV中时,这种正确的行为是有效的。

我只是需要一些保证,这就是发生在imblearn.Pipeline上的事情。

编辑: 2020-08-28

@wundermahn的答案是我所需要的。

这个编辑只是想补充一下,这就是为什么我们应该使用imblearn.Pipeline进行不平衡的预处理,而不是sklearn.Pipelineimblearn文档中的任何地方,我找到了为什么在存在sklearn.Pipeline时需要imblearn.Pipeline的原因。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-08-24 18:59:30

问题很大。按照你发布的顺序浏览它们:

  1. 首先,在我看来,过度抽样、低于抽样和混合抽样是适用于培训集,而不是测试/验证集的程序。如果我错了,请在这里纠正我。

这是正确的。您当然不希望在testvalidation数据上测试数据,即而不是代表实际的、实时的、“生产”数据集。你真的应该把这个应用到训练中。请注意,如果您正在使用交叉折叠验证之类的技术,您应该按照这份IEEE文件的指示,将抽样应用于每个折叠。

  1. 我浏览了imblearn管道代码,但在那里找不到预测方法。

我假设您找到了imblearn.pipeline 源代码,所以如果您找到了,那么您要做的就是查看fit_predict方法:

代码语言:javascript
复制
 @if_delegate_has_method(delegate="_final_estimator")
    def fit_predict(self, X, y=None, **fit_params):
        """Apply `fit_predict` of last step in pipeline after transforms.
        Applies fit_transforms of a pipeline to the data, followed by the
        fit_predict method of the final estimator in the pipeline. Valid
        only if the final estimator implements fit_predict.
        Parameters
        ----------
        X : iterable
            Training data. Must fulfill input requirements of first step of
            the pipeline.
        y : iterable, default=None
            Training targets. Must fulfill label requirements for all steps
            of the pipeline.
        **fit_params : dict of string -> object
            Parameters passed to the ``fit`` method of each step, where
            each parameter name is prefixed such that parameter ``p`` for step
            ``s`` has key ``s__p``.
        Returns
        -------
        y_pred : ndarray of shape (n_samples,)
            The predicted target.
        """
        Xt, yt, fit_params = self._fit(X, y, **fit_params)
        with _print_elapsed_time('Pipeline',
                                 self._log_message(len(self.steps) - 1)):
            y_pred = self.steps[-1][-1].fit_predict(Xt, yt, **fit_params)
        return y_pred

在这里,我们可以看到pipeline利用了管道中最终估计器的.predict方法,在您发布的示例scikit-learn's knn

代码语言:javascript
复制
 def predict(self, X):
        """Predict the class labels for the provided data.
        Parameters
        ----------
        X : array-like of shape (n_queries, n_features), \
                or (n_queries, n_indexed) if metric == 'precomputed'
            Test samples.
        Returns
        -------
        y : ndarray of shape (n_queries,) or (n_queries, n_outputs)
            Class labels for each data sample.
        """
        X = check_array(X, accept_sparse='csr')

        neigh_dist, neigh_ind = self.kneighbors(X)
        classes_ = self.classes_
        _y = self._y
        if not self.outputs_2d_:
            _y = self._y.reshape((-1, 1))
            classes_ = [self.classes_]

        n_outputs = len(classes_)
        n_queries = _num_samples(X)
        weights = _get_weights(neigh_dist, self.weights)

        y_pred = np.empty((n_queries, n_outputs), dtype=classes_[0].dtype)
        for k, classes_k in enumerate(classes_):
            if weights is None:
                mode, _ = stats.mode(_y[neigh_ind, k], axis=1)
            else:
                mode, _ = weighted_mode(_y[neigh_ind, k], weights, axis=1)

            mode = np.asarray(mode.ravel(), dtype=np.intp)
            y_pred[:, k] = classes_k.take(mode)

        if not self.outputs_2d_:
            y_pred = y_pred.ravel()

        return y_pred

  1. 我还想确定,当管道位于GridSearchCV中时,这种正确的行为是可行的。

这类假设假设上述两个假设是正确的,我认为这意味着您希望在一个完整的,最小的,可重复的例子中工作。在这上面提供了大量的文档,但是我使用knn创建的一个示例如下:

代码语言:javascript
复制
import pandas as pd, numpy as np

from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
from sklearn.neighbors import KNeighborsClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import GridSearchCV, train_test_split

param_grid = [
    {
        'classification__n_neighbors': [1,3,5,7,10],
    }
]

X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, test_size=0.20)

pipe = Pipeline([
    ('sampling', SMOTE()),
    ('classification', KNeighborsClassifier())
])

grid = GridSearchCV(pipe, param_grid=param_grid)
grid.fit(X_train, y_train)
mean_scores = np.array(grid.cv_results_['mean_test_score'])
print(mean_scores)

# [0.98051926 0.98121129 0.97981998 0.98050474 0.97494193]

你的直觉是正确的,干得好:)

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63520908

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档