1

我想找到我的StratifiedKFold最好的分裂和建立我的最好的分成模式.The代码如下:Scikit学习(Python)的不同的指标结果(F1分数)为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) 

现在,因为我CA Pture最好的分割和我的分类器我再次测试它为同一分裂只是为了检查我是否得到了相同的结果,因为我得到的功能。但显然并非如此。 代码:

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

+1

不知道太多关于sklearn StratifiedKFold我认为'shuffle = True'在每个'skf.split'前洗牌数据。如果将它设置为False,它看起来如何?你也可以保持'shuffle = True'并且设置'random_state = 1'来在每次迭代中实现相同的洗牌。 –

+0

没有尝试过,但没有奏效。尽管我设置了shuffle = True,但我为每个shuffle捕获了分割索引。 – Kaushal

回答

0

解决了这个问题,因为我没有深刻地将我的clf对象拷贝到bestclf。每当用于运行bestclf参考的第K个折叠更改为当前clf时,因为我没有进行深度复制。

bestclf = copy.deepcopy(clf)