【发布时间】:2020-05-13 04:52:46
【问题描述】:
我正在研究蘑菇分类数据集(可在此处找到:https://www.kaggle.com/uciml/mushroom-classification)。
我正在尝试将我的数据拆分为我的模型的训练集和测试集,但是如果我使用 train_test_split 方法,我的模型总是可以达到 100% 的准确率。当我手动拆分数据时,情况并非如此。
x = data.copy()
y = x['class']
del x['class']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33)
model = xgb.XGBClassifier()
model.fit(x_train, y_train)
predictions = model.predict(x_test)
print(confusion_matrix(y_test, predictions))
print(accuracy_score(y_test, predictions))
这会产生:
[[1299 0]
[ 0 1382]]
1.0
如果我手动拆分数据,我会得到更合理的结果。
x = data.copy()
y = x['class']
del x['class']
x_train = x[0:5443]
x_test = x[5444:]
y_train = y[0:5443]
y_test = y[5444:]
model = xgb.XGBClassifier()
model.fit(x_train, y_train)
predictions = model.predict(x_test)
print(confusion_matrix(y_test, predictions))
print(accuracy_score(y_test, predictions))
结果:
[[2007 0]
[ 336 337]]
0.8746268656716418
什么可能导致这种行为?
编辑: 根据要求,我包括切片的形状。
train_test_split:
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.33)
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
结果:
(5443, 64)
(5443,)
(2681, 64)
(2681,)
手动拆分:
x_train = x[0:5443]
x_test = x[5444:]
y_train = y[0:5443]
y_test = y[5444:]
print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)
结果:
(5443, 64)
(5443,)
(2680, 64)
(2680,)
我已经尝试定义自己的拆分函数,结果拆分也可以实现 100% 的分类器准确度。
这是拆分的代码
def split_data(dataFrame, testRatio):
dataCopy = dataFrame.copy()
testCount = int(len(dataFrame)*testRatio)
dataCopy = dataCopy.sample(frac = 1)
y = dataCopy['class']
del dataCopy['class']
return dataCopy[testCount:], dataCopy[0:testCount], y[testCount:], y[0:testCount]
【问题讨论】:
-
X_train, X_test, y_train, y_test各个方法拆分后的形状是什么? -
@G.Anderson 我已经用形状更新了我的问题
-
如果再次运行 train_test_plit 或更改
test_size参数,行为是否仍然存在?有可能(虽然不太可能)你第一次得到了一个非常幸运的分裂。否则,您是否对数据进行了任何其他未显示的转换?这看起来很像训练和测试之间或目标和特征之间的数据泄漏 -
它会在整个尝试过程中持续存在,如果我更改测试大小(无论我将其更改为 100%)。我已经对数据进行了一些预处理,但这一切都是在我拆分数据集之前完成的。
-
等等!分手前
preprocessing做了什么?您不应该对整个数据集执行feature selection。就在火车集和变换火车上,用它来测试集。standard scalar也相同,在拆分和转换两个训练后拟合训练数据,用它进行测试。如果您的手动拆分代码没有问题,您可能会以这种方式将数据从训练集泄漏到测试集。
标签: python dataframe machine-learning