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倍沒有被觀察到。爲什麼是這樣?我做錯了什麼?我的方法邏輯錯了嗎?
不知道太多關於sklearn StratifiedKFold我認爲'shuffle = True'在每個'skf.split'前洗牌數據。如果將它設置爲False,它看起來如何?你也可以保持'shuffle = True'並且設置'random_state = 1'來在每次迭代中實現相同的洗牌。 –
沒有嘗試過,但沒有奏效。儘管我設置了shuffle = True,但我爲每個shuffle捕獲了分割索引。 – Kaushal