首页 > 解决方案 > 在尝试使用 train_test_split 时,我的测试集形状很奇怪

问题描述

我正在尝试将 KNN 应用于 Diabetes prima 数据,为了将我的数据集拆分为训练和测试数据集,我使用了代码中描述的 iloc 函数。但是当我使用这段代码时,我得到了非常奇怪的测试数据形状。谁能解释我在这里做错了什么

这是代码:

# first 8 columns from index 0 to 7 to be used for parameters
X = dataset.iloc[:,0:8]
y = dataset.iloc[:,8]
# lets split X and Y into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size =0.2,random_state =0)
# let us check the shape of all of these
print("X_train shape is : ", X_train.shape)
print("X_test shape  is : ", X_test.shape)
print("y_train shape is : ", y_train.shape)
print("y_test shape is : ", y_test.shape)

This is the output I am getting : 
X_train shape is :  (614, 8)
X_test shape  is :  (154, 8)
y_train shape is :  (614,)
y_test shape is :  (154,)

标签: pythonpandasmachine-learningknn

解决方案


你的代码是对的。在您的数据集中,您可能有 668 行和 9 列,其中最后一列是要预测的列。当您使用该iloc函数时,您将从响应(第 9 列)中拆分特征(第 1 列到第 8 列)。将train_test_split您的数据(x 和 y)分成训练集和测试集。

你得到的形状是正确的:

X_train shape is :  (614, 8)   614 rows and 8 columns
X_test shape  is :  (154, 8)   154 rows and 8 columns
y_train shape is :  (614,)     614 rows and 1 column
y_test shape is :  (154,)      154 rows and 1 column

推荐阅读