【发布时间】:2017-03-09 14:11:14
【问题描述】:
我想为我的 StratifiedKFold 找到最佳拆分,并在最佳拆分上构建我的模型。代码如下:
def best_classifier(clf,k,x,y):
skf = StratifiedKFold(n_splits=k,shuffle=True)
bestclf = None
bestf1 = 0
bestsplit = []
cnt = 1
totalf1 = 0
for train_index,test_index in skf.split(x,y):
x_train,x_test = x[train_index],x[test_index]
y_train,y_test = y[train_index],y[test_index]
clf.fit(x_train,y_train)
predicted_y = clf.predict(x_test)
f1 = f1_score(y_test,predicted_y)
totalf1 = totalf1+f1
print(y_test.shape)
print(cnt," iteration f1 score",f1)
if cnt==10:
avg = totalf1/10
print(avg)
if f1>bestf1:
bestf1 = f1
bestclf = clf
bestsplit = [train_index,test_index]
cnt = cnt+1
return [bestclf,bestf1,bestsplit]
此函数返回我的分类器数组(适合最佳拆分)、最佳 f1score 和最佳拆分的索引
我这样称呼它:
best_of_best = best_classifier(sgd,10,x_selected,y)
现在,由于我捕获了最佳拆分和我的分类器,我再次对其进行相同拆分测试,以检查我得到的结果是否与我在函数中得到的结果相同。但显然事实并非如此。 代码:
bestclf= best_of_best[0]
test_index = best_of_best[2][1]
x_cv = x_selected[test_index]
y_cv = y[test_index]
pred_cv = bestclf.predict(x_cv)
f1_score(y_cv,pred_cv)
方法为 best_classifier 时的结果:
(679,)
1 iteration f1 score 0.643298969072
(679,)
2 iteration f1 score 0.761750405186
(678,)
3 iteration f1 score 0.732773109244
(678,)
4 iteration f1 score 0.632911392405
(678,)
5 iteration f1 score 0.74179743224
(678,)
6 iteration f1 score 0.749140893471
(677,)
7 iteration f1 score 0.750830564784
(677,)
8 iteration f1 score 0.756756756757
(677,)
9 iteration f1 score 0.682170542636
(677,)
10 iteration f1 score 0.63813229572
0.708956236151
当我预测在 statifiedkfold 的最佳分割之外时的结果
0.86181818181818182
我们可以看到这个f1分数在10折中没有观察到。为什么会这样?我做错了什么吗?我的方法逻辑错了吗?
【问题讨论】:
-
在不太了解 sklearn StratifiedKFold 的情况下,我认为
shuffle=True会在每个skf.split之前对数据进行洗牌。如果将其设置为 False,它看起来如何?您还可以保留shuffle=True并设置random_state = 1以在每次迭代中实现相同的随机播放。 -
没有试过但没用。即使我设置了 shuffle=True,我也会为每个 shuffle 捕获我的拆分索引。
标签: python machine-learning scikit-learn artificial-intelligence