我对Python比较陌生。你能帮我改进我的SMOTE实现到合适的管道吗?我想要的是在每个k次迭代的训练集上应用上下采样,以便在平衡数据集上训练模型并在不平衡的左侧部分上进行评估。问题在于,当我这样做时,我无法使用熟悉的sklearn
界面进行评估和网格搜索。
是否可以制作与model_selection.RandomizedSearchCV
类似的内容。我对此的看法:
df = pd.read_csv("Imbalanced_data.csv") #Load the data set
X = df.iloc[:,0:64]
X = X.values
y = df.iloc[:,64]
y = y.values
n_splits = 2
n_measures = 2 #Recall and AUC
kf = StratifiedKFold(n_splits=n_splits) #Stratified because we need balanced samples
kf.get_n_splits(X)
clf_rf = RandomForestClassifier(n_estimators=25, random_state=1)
s =(n_splits,n_measures)
scores = np.zeros(s)
for train_index, test_index in kf.split(X,y):
print("TRAIN:", train_index, "TEST:", test_index)
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
sm = SMOTE(ratio = 'auto',k_neighbors = 5, n_jobs = -1)
smote_enn = SMOTEENN(smote = sm)
x_train_res, y_train_res = smote_enn.fit_sample(X_train, y_train)
clf_rf.fit(x_train_res, y_train_res)
y_pred = clf_rf.predict(X_test,y_test)
scores[test_index,1] = recall_score(y_test, y_pred)
scores[test_index,2] = auc(y_test, y_pred)
答案 0 :(得分:6)
您需要查看管道对象。 imbalanced-learn有一个Pipeline,它扩展了scikit-learn Pipeline,除了fit_predict(),fit_transform()和predict()scikit-learn方法之外,还适用于fit_sample()和sample()方法。
在这里看一下这个例子:
对于您的代码,您可能希望这样做:
from imblearn.pipeline import make_pipeline, Pipeline
smote_enn = SMOTEENN(smote = sm)
clf_rf = RandomForestClassifier(n_estimators=25, random_state=1)
pipeline = make_pipeline(smote_enn, clf_rf)
OR
pipeline = Pipeline([('smote_enn', smote_enn),
('clf_rf', clf_rf)])
然后你可以将这个pipeline
对象传递给GridSearchCV,RandomizedSearchCV或scikit中的其他交叉验证工具 - 作为常规对象学习。
kf = StratifiedKFold(n_splits=n_splits)
random_search = RandomizedSearchCV(pipeline, param_distributions=param_dist,
n_iter=1000,
cv = kf)
答案 1 :(得分:3)
这看起来符合法案http://contrib.scikit-learn.org/imbalanced-learn/stable/generated/imblearn.over_sampling.SMOTE.html
您需要创建自己的transformer
(http://scikit-learn.org/stable/modules/generated/sklearn.base.TransformerMixin.html),在调用fit
时会返回一个平衡数据集(可能是从StratifiedKFold
获得的数据集),但是在调用predict
时,测试数据会发生这种情况,调用SMOTE。