【发布时间】:2019-11-13 09:00:23
【问题描述】:
我正在使用sklearn 的train_test_split 为我的数据创建一个训练集和测试集。
我的脚本如下:
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import neighbors
# function to perform one hot encoding and dropping the original item
# in this case its the part number
def encode_and_bind(original_dataframe, feature_to_encode):
dummies = pd.get_dummies(original_dataframe[[feature_to_encode]])
res = pd.concat([original_dataframe, dummies], axis=1)
res = res.drop([feature_to_encode], axis=1)
return(res)
# read in data from csv
data = pd.read_csv('export2.csv')
# one hot encode the part number
new = encode_and_bind(data, 'PART_NO')
# create the labels, or field we are trying to estimate
label = new['TOTAL_DAYS_TO_COMPLETE']
# remove the header
label = label[1:]
# create the data, or the data that is to be estimated
thedata = new.drop('TOTAL_DAYS_TO_COMPLETE', axis=1)
# remove the header
thedata = thedata[1:]
print(label.shape)
print(thedata.shape)
# # split into training and testing sets
train_data, train_classes, test_data, test_classes = train_test_split(thedata, label, test_size = 0.3)
# create a knn model
knn = neighbors.KNeighborsRegressor()
# fit it with our data
knn.fit(train_data, train_classes)
运行它,我得到以下信息:
C:\Users\jerry\Desktop>python test.py (6262,) (6262, 253) Traceback (最近一次通话最后):文件“test.py”,第 37 行,在 knn.fit(train_data, train_classes) 文件“C:\Python367-64\lib\site-packages\sklearn\neighbors\base.py”,行 872,合身 X, y = check_X_y(X, y, "csr", multi_output=True) 文件 "C:\Python367-64\lib\site-packages\sklearn\utils\validation.py",行 第729章 check_consistent_length(X, y) 文件“C:\Python367-64\lib\site-packages\sklearn\utils\validation.py”,行 205,在 check_consistent_length " samples: %r" % [int(l) for l in lengths]) ValueError: 发现样本数量不一致的输入变量:[4383, 1879]
所以,看起来我的 X 和 Y 的行数相同 (6262),但列数不同,因为我认为 Y 应该只是标签的一列或您试图预测的值。
如何使用 train_test_split 为我提供可用于 KNN 回归器的训练和测试数据集?
【问题讨论】:
标签: python python-3.x scikit-learn