gpt4 book ai didi

python - 将 sklearn 的 RandomizedSearchCV 与 SMOTE 过采样仅用于训练折叠

转载 作者:行者123 更新时间:2023-12-04 15:29:47 25 4
gpt4 key购买 nike

我有一个高度不平衡的数据集 (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 节),提供了我正在尝试做的事情的示例代码,并演示了它如何按照我指定的方式工作

最佳答案

如我编辑中链接的文章所示,当 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")

关于python - 将 sklearn 的 RandomizedSearchCV 与 SMOTE 过采样仅用于训练折叠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61453795/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com