Scikit-learn(Python) StratifiedKFold 的不同指标结果(f1 分数)

Scikit-learn(Python) Different metric results(f1 score) for StratifiedKFold

我想为我的 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]

这个函数 returns 我的分类器数组(适合最佳分割)、最佳 f1score 和最佳分割的索引

我这样称呼它:

best_of_best = best_classifier(sgd,10,x_selected,y)

现在,由于我捕获了最佳拆分和我的分类器,我再次针对相同的拆分对其进行测试,只是为了检查我是否得到了与 function.But 内得到的结果相同的结果,显然事实并非如此。 代码:

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折中没有观察到。为什么会这样?我做错了吗?我的方法逻辑错了吗?

解决了 it.The 问题是因为我没有将我的 clf 对象深度复制到 bestclf。每次第 K 折用于 运行 我的 bestclf 参考更改为当前 clf,因为我没有深度复制。

bestclf = copy.deepcopy(clf)