我正在处理蘑菇分类数据集(数据集在这里:https://www.kaggle.com/uciml/mushroom-classification)。
我对数据进行了一些预处理(删除了冗余属性,将分类数据转换为数值数据),并尝试使用这些数据来训练分类器。
每当我洗牌数据,无论是手动操作还是使用train_test_split函数,所有我使用的模型(XGB、MLP、LinearSVC、决策树)的准确率都达到100%。而当我在未洗牌的数据上测试这些模型时,准确率大约在50-85%之间。
以下是我分割数据的方法:
x = testing.copy()x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.3, shuffle=True)
以及手动操作:
x = testing.copy()x = x.sample(frac=1)testRatio = 0.3testCount = int(len(x)*testRatio)x_train = x[testCount:]x_test = x[0:testCount]y_train = y[testCount:]y_test = y[0:testCount]
我是否做错了什么,或者遗漏了什么重要的东西?
编辑:我能看到的唯一区别是在分割数据时是否洗牌行导致的类别分布的不同。
不洗牌时:
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.3, shuffle=False)print(y_test.value_counts())print(y_train.value_counts())
结果为:
0 18281 610Name: class, dtype: int641 35980 2088Name: class, dtype: int64
而洗牌时:
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.3, shuffle=True)print(y_test.value_counts())print(y_train.value_counts())
结果为:
0 12381 1200Name: class, dtype: int641 30080 2678Name: class, dtype: int64
但我不明白这如何会对模型的准确率产生如此大的影响。
编辑2:按照PV8的建议,我尝试通过交叉验证来验证我的结果,这种方法似乎有效,我得到了更为合理的结果。
model = LinearSVC()scores = cross_val_score(model,x,y,cv=5)print(scores)print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))
输出:
[1. 1. 1. 1. 0.75246305]Accuracy: 0.95 (+/- 0.20)
回答:
这种情况可能是正常的,你尝试了多少次洗牌操作?
这表明你的数据对分割方式非常敏感。我希望你测量的是测试准确率而不是训练准确率?
我建议你使用交叉验证,这将帮助你验证你的整体结果。