【问题标题】:train_test_split producing inconsistent samplestrain_test_split 产生不一致的样本
【发布时间】:2019-11-13 09:00:23
【问题描述】:

我正在使用sklearntrain_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]

所以,看起来我的 XY 的行数相同 (6262),但列数不同,因为我认为 Y 应该只是标签的一列或您试图预测的值。

如何使用 train_test_split 为我提供可用于 KNN 回归器的训练和测试数据集?

【问题讨论】:

    标签: python python-3.x scikit-learn


    【解决方案1】:

    据我所知,您已经切换了train_test_split 的输出。

    函数按顺序返回:训练特征、测试特征、训练标签、测试标签。

    常见的命名约定是X_train, X_test, y_train, y_test=...,其中X 是特征(列或特征),yy 是目标(标签,或者我假设是代码中的“类”)

    您似乎正试图让它返回,而不是 X_train, y_train, X_test, y_test

    试试这个,看看它是否适合你:

    train_data, test_data, train_classes, test_classes = train_test_split(thedata, label, test_size = 0.3)
    

    【讨论】:

      猜你喜欢
      • 2020-11-03
      • 2020-02-03
      • 1970-01-01
      • 2017-02-02
      • 2012-01-16
      • 1970-01-01
      • 2017-06-10
      • 2011-12-17
      • 1970-01-01
      相关资源
      最近更新 更多