我正在尝试了解交叉验证分数和准确度分数。我得到了准确度分数 = 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())
答案 0 :(得分: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
进行评估,因此对于某些折叠,存在泄漏导致总体平均值过于乐观的原因。< /p>
如果您更正这一点,这些值应该更接近,因为从概念上讲,您所做的与 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)
此结果不如交叉验证结果稳健,因为您只对数据集进行了一次拆分,因此您可能会偶然获得更好或更差的结果,这取决于训练-测试拆分的难度随机种子生成。