Don*_*dre 8 python machine-learning dataframe
我正在研究蘑菇分类数据集(在这里找到: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))
Run Code Online (Sandbox Code Playgroud)
这产生:
[[1299 0]
[ 0 1382]]
1.0
Run Code Online (Sandbox Code Playgroud)
如果我手动拆分数据,我会得到更合理的结果。
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))
Run Code Online (Sandbox Code Playgroud)
结果:
[[2007 0]
[ 336 337]]
0.8746268656716418
Run Code Online (Sandbox Code Playgroud)
什么可能导致这种行为?
编辑: 根据要求,我包括切片的形状。
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)
Run Code Online (Sandbox Code Playgroud)
结果:
(5443, 64)
(5443,)
(2681, 64)
(2681,)
Run Code Online (Sandbox Code Playgroud)
手动拆分:
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)
Run Code Online (Sandbox Code Playgroud)
结果:
(5443, 64)
(5443,)
(2680, 64)
(2680,)
Run Code Online (Sandbox Code Playgroud)
我尝试定义我自己的拆分函数,结果拆分也导致 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]
Run Code Online (Sandbox Code Playgroud)
你在 train_test_split 上很幸运。您手动执行的拆分可能具有最不可见的数据,这比 train_test_split 进行了更好的验证,train_test_split 在内部对数据进行洗牌以进行拆分。
为了更好的验证,请使用 K 折交叉验证,这将允许使用数据中的每个不同部分作为测试和其余部分作为训练来验证模型的准确性。
| 归档时间: |
|
| 查看次数: |
595 次 |
| 最近记录: |