【发布时间】:2018-09-07 18:10:11
【问题描述】:
我很困惑,为什么没有交叉验证的随机森林分类模型的平均准确度得分为 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
从文档中,数据分为训练和测试
# 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
关于交叉验证:
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)
它要低得多!
并验证第二种方法:
#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
根据我的理解,交叉验证不应该将预测的准确性降低这么多,而是提高模型的预测,因为模型已经看到了所有数据的“更好”表示。
【问题讨论】:
-
您的目标类(0,1 和 2)之间的大致划分是多少?你有多少样本?
-
另外,你的数据是按目标类排序的吗?
-
没有数据是按删除的两个列排序的:groupID和timestamp(它是一个纵向重复测量数据集,监控了大约80个单独的环境)
-
StratifiedKFold(在cross_val_score中使用)默认情况下不会在拆分前洗牌。我的理解是,这意味着您在进行交叉验证时还试图预测数据的时间元素。与train_test_split不同,后者从数据集中随机抽取。作为测试,尝试设置cv=ms.StratifiedKFold(n_splits=5, shuffle=True)。 -
所以都修好了?如果是这样,那太好了,我会把它作为答案,因为人们了解这种行为很重要。
标签: python scikit-learn random-forest cross-validation