【问题标题】:Output of shape for training after oversampling with imbalanced-learn使用不平衡学习进行过采样后的训练形状输出
【发布时间】:2019-11-13 06:43:57
【问题描述】:

我正在使用不平衡学习对数据进行过采样。我想知道使用过采样方法后每个类中有多少条目。 此代码运行良好:

import imblearn.over_sampling import SMOTE
from collections import Counter

def oversample(x_values, y_values):
    oversampler = SMOTE(random_state=42, n_jobs=-1)
    x_oversampled, y_oversampled = oversampler.fit_resample(x_values, y_values)
    print("Oversampling training set from {0} to {1} using {2}".format(dict(Counter(y_values)), dict(Counter(y_over_sampled)), oversampling_method))
    return x_oversampled, y_oversampled

但我转而使用管道,因此我可以使用 GridSearchCV 来找到最佳的过采样方法(ADASYN、SMOTE 和 BorderlineSMOTE)。因此,我从来没有真正自己调用 fit_resample 并使用这样的方法丢失我的输出:

from imblearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler
from sklearn.ensemble import RandomForestClassifier

pipe = Pipeline([('scaler', MinMaxScaler()), ('sampler', SMOTE(random_state=42, n_jobs=-1)), ('estimator', RandomForestClassifier())])
pipe.fit(x_values, y_values)

上采样有效,但我失去了关于训练集中每个类有多少条目的输出。

有没有办法获得与使用管道的第一个示例类似的输出?

【问题讨论】:

    标签: python python-3.x scikit-learn oversampling imblearn


    【解决方案1】:

    理论上是的。当安装过采样器时,会创建一个属性sampling_strategy_,其中包含调用fit_resample 时要生成的少数类的样本数。您可以使用它来获得与上面示例类似的输出。这是根据您的代码修改的示例:

    # Imports
    from collections import Counter
    from sklearn.datasets import make_classification
    from sklearn.preprocessing import MinMaxScaler
    from sklearn.ensemble import RandomForestClassifier
    from imblearn.over_sampling import SMOTE    
    from imblearn.pipeline import Pipeline
    
    # Create toy dataset
    X, y = make_classification(weights=[0.20, 0.80], random_state=0)
    init_class_distribution = Counter(y)
    min_class_label, _ = init_class_distribution.most_common()[-1]
    print(f'Initial class distribution: {dict(init_class_distribution)}')
    
    # Create and fit pipeline
    pipe = Pipeline([('scaler', MinMaxScaler()), ('sampler', SMOTE(random_state=42, n_jobs=-1)), ('estimator', RandomForestClassifier(random_state=23))])
    pipe.fit(X, y)
    sampling_strategy = dict(pipe.steps).get('sampler').sampling_strategy_
    expected_n_samples = sampling_strategy.get(min_class_label)
    print(f'Expected number of generated samples: {expected_n_samples}')
    
    # Fit and resample over-sampler pipeline
     sampler_pipe = Pipeline(pipe.steps[:-1])
    X_res, y_res = sampler_pipe.fit_resample(X, y)
    actual_class_distribution = Counter(y_res)
    print(f'Actual class distribution: {actual_class_distribution}')
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2019-12-19
      • 2017-11-09
      • 2020-09-09
      • 2017-09-19
      • 1970-01-01
      • 2018-03-02
      • 2016-05-05
      • 1970-01-01
      相关资源
      最近更新 更多