如何在scikit学习流水线中实现随机欠采样?

2024-05-01 21:43:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个scikit学习管道来缩放数字特征和编码分类特征。在我试图实现imblearn中的RandomUnderSampler之前,它运行得很好。我的目标是实现欠采样步骤,因为我的数据集非常不平衡1:1000。在

我确保使用imblearn的Pipeline方法而不是sklearn。下面是我尝试过的代码。在

代码数据工作(使用sklearn管道)而不使用欠采样方法。在

from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from imblearn.pipeline import make_pipeline as make_pipeline_imb
from imblearn.pipeline import Pipeline as Pipeline_imb

from sklearn.base import BaseEstimator, TransformerMixin
class TypeSelector(BaseEstimator, TransformerMixin):
    def __init__(self, dtype):
        self.dtype = dtype
    def fit(self, X, y=None):
        return self
    def transform(self, X):
        assert isinstance(X, pd.DataFrame)
        return X.select_dtypes(include=[self.dtype])

transformer = Pipeline([
    # Union numeric, categoricals and boolean
    ('features', FeatureUnion(n_jobs=1, transformer_list=[
         # Select bolean features                                                  
        ('boolean', Pipeline([
            ('selector', TypeSelector('bool')),
        ])),
         # Select and scale numericals
        ('numericals', Pipeline([
            ('selector', TypeSelector(np.number)),
            ('scaler', StandardScaler()),
        ])),
         # Select and encode categoricals
        ('categoricals', Pipeline([
            ('selector', TypeSelector('category')),
            ('encoder', OneHotEncoder(handle_unknown='ignore')),
        ])) 
    ])),
])
pipe = Pipeline([('prep', transformer), 
                 ('clf', RandomForestClassifier(n_estimators=500, class_weight='balanced'))
                 ])

使用欠采样方法(使用imblearn管道)无法工作的代码。在

^{pr2}$

以下是我得到的错误:

/usr/local/lib/python3.6/dist-packages/sklearn/pipeline.py in __init__(self, steps, memory, verbose)
    133     def __init__(self, steps, memory=None, verbose=False):
    134         self.steps = steps
--> 135         self._validate_steps()
    136         self.memory = memory
    137         self.verbose = verbose

/usr/local/lib/python3.6/dist-packages/imblearn/pipeline.py in _validate_steps(self)
    144             if isinstance(t, pipeline.Pipeline):
    145                 raise TypeError(
--> 146                     "All intermediate steps of the chain should not be"
    147                     " Pipelines")
    148 

TypeError: All intermediate steps of the chain should not be Pipelines


Tags: 方法fromimportselfverbose管道pipelinedef
1条回答
网友
1楼 · 发布于 2024-05-01 21:43:19

如果您研究文件imblearn/pipeline.pyhere中的imblen代码,在函数_validate_steps下,他们将检查transformers中的每一项是否有一个转换器是scikit管道的实例(isinstance(t, pipeline.Pipeline))。在

从您的代码中,transformers

  1. RandomUnderSampler
  2. transformer

Pipeline_imb继承scikit的管道,而在代码中使用Pipeline_imb是多余的。在

已经说过,我会调整你的代码如下

transformer = FeatureUnion(n_jobs=1, transformer_list=[
     # Select bolean features                                                  
    ('selector1', TypeSelector('bool'),
     # Select and scale numericals
    ('selector2', TypeSelector(np.number)),
    ('scaler', StandardScaler()),
     # Select and encode categoricals
    ('selector3', TypeSelector('category')),
    ('encoder', OneHotEncoder(handle_unknown='ignore'))
])

pipe = Pipeline_imb([
    ('sampler', RandomUnderSampler(0.1)),
    ('prep', transformer), 
    ('clf', RandomForestClassifier(n_estimators=500, class_weight='balanced'))
])

相关问题 更多 >