Python 我无法理解交叉评分和准确评分之间的区别
我试图了解交叉验证分数和准确性分数。我的准确度得分为0.79,交叉验证得分为0.73。我知道,这些分数应该非常接近。通过查看这些分数,我可以对我的模型说些什么Python 我无法理解交叉评分和准确评分之间的区别,python,machine-learning,scikit-learn,cross-validation,Python,Machine Learning,Scikit Learn,Cross Validation,我试图了解交叉验证分数和准确性分数。我的准确度得分为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_select
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())
您的代码中有一个bug,它解释了这个漏洞。 您在一组折叠的列车上进行训练,但要根据固定的测试进行评估 for循环中的这两行:
y\u pred=rf.predict(x\u测试)
acc_分数=准确性_分数(y_测试,y_预测)
应该是:
y\u pred=rf.predict(x\u有效)
acc_分数=准确度_分数(y_pred,y_valid)
由于在手写交叉验证中,您是根据固定的x_测试
和y_测试
进行评估的,因此对于某些折叠,存在泄漏,这是总体平均结果过于乐观的原因
如果您纠正了这一点,值应该更接近,因为从概念上讲,您所做的与cross\u val\u score
所做的相同
但是,由于随机性和数据集的大小(非常小),它们可能不完全匹配
最后,如果您只想获得一个测试分数,则不需要KFold部分,您可以执行以下操作:
x_列,x_测试,y_列,y_测试=列测试分割(声纳x,声纳y,测试大小=0.33,随机状态=0)
rf=RandomForestClassifier(n_作业=-1,类权重=-balanced',最大深度=5)
右前安装(x_系列、y_系列)
y_pred=射频预测(x_测试)
acc_分数=准确性_分数(y_测试,y_预测)
此结果不如交叉验证结果稳健,因为您只拆分了一次数据集,因此您可能会偶然获得更好或更差的结果,这取决于随机种子生成的列车测试拆分的难度。Thx用于提醒我错误匹配。因此,我们可以说计算每个折叠的准确度分数与计算交叉验证分数是一样的。是的。确切地你同样做了两次。首先,使用手写机制。第二,为同样的事情使用高级API。如果你转到源代码,cross_val_score调用cross_validate,在这一行你会看到
cv.split()
正在发生。请记住,如果它解决了你的疑问,请接受答案;)再次感谢你,伙计。