【问题标题】:I could not get the idea about difference between cross_val_score and accuracy_score我无法理解 cross_val_score 和 accuracy_score 之间的区别
【发布时间】:2021-06-27 16:49:17
【问题描述】:

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

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())

【问题讨论】:

    标签: python machine-learning scikit-learn cross-validation


    【解决方案1】:

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

    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_test 和 y_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)
    

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

    【讨论】:

    • 谢谢提醒我的错误伙伴。所以我们可以说计算每个折叠的准确度分数与计算交叉验证分数是一回事。
    • 是的。确切地。你做同样的事情两次。首先,使用手写机制。其次,为同一件事使用高级 API。
    • 如果你查看源代码,cross_val_score 会调用 cross_validate 并且在这一行 github.com/scikit-learn/scikit-learn/blob/… 你会看到 cv.split() 正在发生。
    • 如果它解决了您的疑问,请记住接受答案;)
    • 再次感谢伙计。
    猜你喜欢
    • 2014-04-08
    • 2013-11-04
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多