为什么交叉验证 RF 分类的性能比没有交叉验证要差?

Eva*_*van 4 python random-forest scikit-learn cross-validation

我很困惑为什么没有交叉验证的随机森林分类模型产生的平均准确度分数为 0.996,但使用 5 折交叉验证,模型的平均准确度分数为 0.687。

有 275,956 个样本。第 0 类 = 217891,第 1 类 = 6073,第 2 类 = 51992

我试图预测“TARGET”列,它是 3 个类 [0,1,2]:

data.head()
bottom_temperature  bottom_humidity top_temperature top_humidity    external_temperature    external_humidity   weight  TARGET  
26.35   42.94   27.15   40.43   27.19   0.0  0.0    1   
36.39   82.40   33.39   49.08   29.06   0.0  0.0    1   
36.32   73.74   33.84   42.41   21.25   0.0  0.0    1   
Run Code Online (Sandbox Code Playgroud)

从文档中,数据分为训练和测试

# link to docs http://scikit-learn.org/stable/modules/cross_validation.html
from sklearn.model_selection import train_test_split
from sklearn import datasets
from sklearn import svm

# Create a list of the feature column's names
features = data.columns[:7]

# View features
features
Out[]: Index([u'bottom_temperature', u'bottom_humidity', u'top_temperature',
       u'top_humidity', u'external_temperature', u'external_humidity',
       u'weight'],
      dtype='object')


#split data
X_train, X_test, y_train, y_test = train_test_split(data[features], data.TARGET, test_size=0.4, random_state=0)

#build model
clf = RandomForestClassifier(n_jobs=2, random_state=0)
clf.fit(X_train, y_train)

#predict
preds = clf.predict(X_test)

#accuracy of predictions
accuracy = accuracy_score(y_test, preds)
print('Mean accuracy score:', accuracy)

('Mean accuracy score:', 0.96607267423425713)

#verify - its the same
clf.score(X_test, y_test)
0.96607267423425713
Run Code Online (Sandbox Code Playgroud)

进入交叉验证:

from sklearn.model_selection import cross_val_score
scores = cross_val_score(clf, data[features], data.TARGET, cv=5)
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))

Accuracy: 0.69 (+/- 0.07)
Run Code Online (Sandbox Code Playgroud)

它要低得多!

并验证第二种方式:

#predict with CV
# http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.cross_val_predict.html#sklearn.model_selection.cross_val_predict
from sklearn.model_selection import cross_val_predict
predicted = cross_val_predict(clf, data[features], data.queen3, cv=5)
metrics.accuracy_score(data.queen3, predicted) 

Out[]: 0.68741031178883594
Run Code Online (Sandbox Code Playgroud)

根据我的理解,交叉验证不应该将预测的准确性降低这个数量,而是提高模型的预测,因为模型已经看到了所有数据的“更好”表示。

Ste*_*tev 5

通常我会同意 Vivek 并告诉你相信你的交叉验证。

但是,随机森林中固有的某种程度的 CV 是因为每棵树都是从自举样本中生长出来的,所以在运行交叉验证时,您不应该期望看到准确度有如此大的下降。我怀疑您的问题是由于数据排序中的某种时间或位置依赖性造成的。

当您使用 时train_test_split,数据是从数据集中随机抽取的,因此您的所有 80 个环境都可能出现在您的训练和测试数据集中。但是,当您使用 CV 的默认选项进行拆分时,我相信每个折叠都是按顺序绘制的,因此您的每个环境都不会出现在每个折叠中(假设您的数据是按环境排序的)。这会导致较低的准确度,因为您正在使用来自另一个环境的数据来预测一个环境。

简单的解决方案是设置cv=ms.StratifiedKFold(n_splits=5, shuffle=True).

在使用连接数据集之前,我曾多次遇到过这个问题,而且肯定有数百人已经意识到但没有意识到问题是什么。默认行为的想法是保持时间序列中的顺序(从我在 GitHub 讨论中看到的)。