我无法理解交叉验证评分和准确度评分之间的区别

我正在尝试理解交叉验证评分和准确度评分。我得到了准确度评分为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_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)

这种结果的稳健性不如交叉验证的结果,因为你只分割了数据集一次,因此根据随机种子生成的训练-测试分割的难易程度,你可能会得到更好或更差的结果,这取决于机会。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注