【问题标题】:Using sklearn's RandomizedSearchCV with SMOTE oversampling only on training folds仅在训练折叠上使用带有 SMOTE 过采样的 sklearn 的 RandomizedSearchCV
【发布时间】:2020-08-10 16:59:22
【问题描述】:

我有一个高度不平衡的数据集 (99.5:0.5)。我想使用sklearnRandomizedSearchCV 对随机森林模型执行超参数调整。我希望使用 SMOTE 对每个训练折叠进行过采样,然后在最终折叠上对每个测试进行评估,保持原始分布而不进行任何过采样。由于这些测试折叠非常不平衡,我希望使用 F1 分数来评估测试。

我尝试了以下方法:

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import make_pipeline
import pandas as pd

dataset = pd.read_csv("data/dataset.csv")

data_x = dataset.drop(["label"], axis=1)
data_y = dataset["label"]

smote = SMOTE()
model = RandomForestClassifier()

pipeline = make_pipeline(smote, model)

grid = {
    "randomforestclassifier__n_estimators": [10, 25, 50, 100, 250, 500, 750, 1000, 1250, 1500, 1750, 2000],
    "randomforestclassifier__criterion": ["gini", "entropy"],
    "randomforestclassifier__max_depth": [10, 20, 30, 40, 50, 75, 100, 150, 200, None],
    "randomforestclassifier__min_samples_split": [1, 2, 3, 4, 5, 8, 10, 15, 20],
    "randomforestclassifier__min_samples_leaf": [1, 2, 3, 4, 5, 8, 10, 15, 20],
    "randomforestclassifier__max_features": ["auto", None, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
    "randomforestclassifier__bootstrap": [True, False],
    "randomforestclassifier__max_samples": [None, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
}

kf = StratifiedKFold(n_splits=5)

search = RandomizedSearchCV(pipeline, grid, scoring='f1', n_iter=10, n_jobs=-1, cv=kf)

search = search.fit(data_x, data_y)

print(search.best_params_)

但是,我不确定是否在每次迭代中都将 SMOTE 应用于测试集。

如何确保 SMOTE 仅应用于训练折叠而不是测试折叠?

编辑:

This article 似乎回答了我的问题(特别是在第 3B 节中),提供了我正在尝试做的示例代码,并演示了它是如何按照我指定的方式工作的

【问题讨论】:

  • 与问题无关并且出于好奇 - 管道是否这样运行?我认为您需要将网格参数中的前缀更改为model__ 而不是randomforestclassifier__。它是否按照您在此处发布的那样运行?
  • 是的,我认为make_pipeline 只是读取类的名称并将其全部转换为小写。否则,您可以自己初始化一个Pipeline 对象并根据需要手动设置名称。
  • 我现在实际上已经将我的代码更改为pipeline = Pipeline([("smote", SMOTE()), ("rf", RandomForestClassifier())])grid = {"rf__n_estimators": ... }
  • 是的,很明显这个版本可以正常运行;但我承认,如果在没有被允许实际运行的情况下被问到,我的猜测是你帖子中的内容不会运行。
  • 它运行良好,我只是不知道它是否在做我想要/期望的事情,但我正在实施我在问题编辑中链接的文章中读到的内容,并将报告结果如果它似乎工作正常,请返回。

标签: python machine-learning scikit-learn pipeline cross-validation


【解决方案1】:

如我编辑中链接的文章所示,当 imblearn Pipeline 传递给 sklearnRandomizedSearchCV 时,转换似乎只应用于训练折叠上的数据,而不是验证折叠。 (不过我不明白这是如何工作的,因为例如,如果将缩放器传递到管道中,您会希望将其应用于所有数据,而不仅仅是训练折叠)。

我使用以下代码对此进行了测试,该代码实际上没有进行任何超参数调整,而是模拟了正在调整的参数,并且验证 F1 分数与我最终测试的 F1 分数几乎相同。

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.model_selection import RandomizedSearchCV, StratifiedKFold
from sklearn.metrics import confusion_matrix, classification_report
from imblearn.over_sampling import SMOTE
from imblearn.pipeline import Pipeline
import pandas as pd

# TRAIN / TEST SPLIT

dataset = pd.read_csv("data/dataset.csv")

data_x = dataset.drop(["label"], axis=1)
data_y = dataset["label"]

train_x, test_x, train_y, test_y = train_test_split(
    data_x, data_y, test_size=0.3, shuffle=True
)

# HYPERPARAMETER TUNING

pipeline = Pipeline([("smote", SMOTE()), ("rf", RandomForestClassifier())])

grid = {
    "rf__n_estimators": [100],
}

kf = StratifiedKFold(n_splits=5)

# Just applies smote to the k-1 training folds, and not to the validation fold
search = RandomizedSearchCV(
    pipeline, grid, scoring="f1", n_iter=1, n_jobs=-1, cv=kf
).fit(train_x, train_y)

best_score = search.best_score_
best_params = {
    key.replace("rf__", ""): value for key, value in search.best_params_.items()
}

print(f"Best Tuning F1 Score: {best_score}")
print(f"Best Tuning Params:   {best_params}")

# EVALUTING BEST MODEL ON TEST SET

best_model = RandomForestClassifier(**best_params).fit(train_x, train_y)

accuracy = best_model.score(test_x, test_y)

test_pred = best_model.predict(test_x)
tn, fp, fn, tp = confusion_matrix(test_y, test_pred).ravel()
conf_mat = pd.DataFrame(
    {"Model (0)": [tn, fn], "Model (1)": [fp, tp]}, index=["Actual (0)", "Actual (1)"],
)

classif_report = classification_report(test_y, test_pred)

feature_importance = pd.DataFrame(
    {"feature": list(train_x.columns), "importance": best_model.feature_importances_}
).sort_values("importance", ascending=False)

print(f"Accuracy: {round(accuracy * 100, 2)}%")
print("")

print(conf_mat)
print("")

print(classif_report)
print("")

pd.set_option("display.max_rows", len(feature_importance))
print(feature_importance)
pd.reset_option("display.max_rows")

【讨论】:

  • 也许你能帮助回答这个问题? stackoverflow.com/questions/61482581/…
  • 在我的例子中,它只将管道的预处理步骤应用于训练集,但当然在某些情况下,您希望将预处理器应用于验证集和测试集好吧,但我不明白你如何区分这两种情况。
猜你喜欢
  • 2019-06-02
  • 2018-02-05
  • 2019-05-24
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2017-10-28
  • 2020-03-08
  • 2018-05-10
相关资源
最近更新 更多