繁体   English   中英

我无法理解 cross_val_score 和 accuracy_score 之间的区别

[英]I could not get the idea about difference between cross_val_score and accuracy_score

我正在尝试了解交叉验证分数和准确性分数。 我的准确度得分 = 0.79,交叉验证得分 = 0.73。 据我所知,这些分数应该非常接近。 通过查看这些分数,我能对我的 model 说些什么?

sonar_x = df_2.iloc[:,0:61].values.astype(int)
sonar_y = df_2.iloc[:,62:].values.ravel().astype(int)

from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split,KFold,cross_val_score
from sklearn.ensemble import RandomForestClassifier

x_train,x_test,y_train,y_test=train_test_split(sonar_x,sonar_y,test_size=0.33,random_state=0)

rf = RandomForestClassifier(n_jobs=-1, class_weight='balanced', max_depth=5)

folds = KFold(n_splits = 10, shuffle = False, random_state = 0)
scores = []

for n_fold, (train_index, valid_index) in enumerate(folds.split(sonar_x,sonar_y)):
    print('\n Fold '+ str(n_fold+1 ) + 
          ' \n\n train ids :' +  str(train_index) +
          ' \n\n validation ids :' +  str(valid_index))
    
    x_train, x_valid = sonar_x[train_index], sonar_x[valid_index]
    y_train, y_valid = sonar_y[train_index], sonar_y[valid_index]
    
    rf.fit(x_train, y_train)
    y_pred = rf.predict(x_test)
    
    
    acc_score = accuracy_score(y_test, y_pred)
    scores.append(acc_score)
    print('\n Accuracy score for Fold ' +str(n_fold+1) + ' --> ' + str(acc_score)+'\n')

    
print(scores)
print('Avg. accuracy score :' + str(np.mean(scores)))


##Cross validation score 
scores = cross_val_score(rf, sonar_x, sonar_y, cv=10)

print(scores.mean())

您的代码中有一个错误导致了差距。 您正在对一组折叠的火车进行训练,但要根据固定测试进行评估。

for循环中的这两行:

y_pred = rf.predict(x_test)

acc_score = accuracy_score(y_test, y_pred)

应该:

y_pred = rf.predict(x_valid)
acc_score = accuracy_score(y_pred , y_valid)

由于在您的手写交叉验证中,您正在根据固定的x_testy_test进行评估,因此对于某些折叠,存在泄漏,导致总体平均结果过于乐观。

如果您更正此问题,则值应该更接近,因为从概念上讲,您所做的与cross_val_score所做的相同。

但是,由于随机性和数据集的大小(非常小),它们可能并不完全匹配。

最后,如果您只想获得一个测试分数,则不需要 KFold 部分,您可以这样做:

x_train,x_test,y_train,y_test=train_test_split(sonar_x,sonar_y,test_size=0.33,random_state=0)
rf = RandomForestClassifier(n_jobs=-1, class_weight='balanced', max_depth=5)
rf.fit(x_train, y_train)  
y_pred = rf.predict(x_test)    
acc_score = accuracy_score(y_test, y_pred)

此结果不如交叉验证结果稳健,因为您只拆分数据集一次,因此您可能会偶然获得更好或更差的结果,这取决于随机种子生成的训练测试拆分的难度.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM