我正在尝试理解交叉验证评分和准确度评分。我得到了准确度评分为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_scorefrom sklearn.model_selection import train_test_split,KFold,cross_val_scorefrom sklearn.ensemble import RandomForestClassifierx_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_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)
这种结果的稳健性不如交叉验证的结果,因为你只分割了数据集一次,因此根据随机种子生成的训练-测试分割的难易程度,你可能会得到更好或更差的结果,这取决于机会。