【问题标题】:sklearn.train_test_split-test_size causes ValueError inconsistent numbers of samplessklearn.train_test_split-test_size 导致 ValueError 样本数不一致
【发布时间】:2021-04-04 01:19:33
【问题描述】:

我遇到了一个非常奇怪的问题。下面,我展示我的代码。

代码:

#The df here is a data with 208 samples, 60 feature(0-59th) The 60th column is the label "R" OR "M" which I m turning it to 1 and 0.

df[60] = [1 if x == 'R' else 0 for x in df[60]]

X = df.loc[:,[x for x in range(60)]]
y = df[60]

print(X.shape) #(208, 60)
print(y.shape) #(208,)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state=123)


#.... this is where causes the error message. Where I have to calculate the r2 score after using linear regression. 

print(r2_score(y_test,acc))
#....

Error message:

ValueError: Found input variables with inconsistent numbers of samples: [42, 60]

*********************
print(y_test.shape) #### (42,)
print(acc.shape) #### (60,60) -> this is the predicted after running linear regression on the data.

有人可以帮我吗?非常感谢。

【问题讨论】:

  • acc 不能是多维数组。它必须是形状为(42,) 的一维。你能发布你的适合和预测代码吗?

标签: python scikit-learn linear-regression valueerror


【解决方案1】:
  1. 您确定要使用线性回归解决您的问题吗?我的意思是您基本上有 60 个特征作为输入,并且您试图预测这 60 个特征是否具有标签 R 或 M。我会将这个问题归类为分类问题。回归作为输出值返回,但在您的情况下,您对“R”或“M”类感兴趣(您将自己指定为 0 和 1 作为目标)
  2. R^2 只对回归有用(你应该用准确度替换它)
  3. 您需要发布负责生成 (60,60) 向量的代码。这似乎很奇怪。您是否尝试为输入 60 预测 60 个值?你应该做的是(假设你仍然想使用线性回归——不建议)
reg = LinearRegression().fit(X_train, y_train)
print(reg.score(X_train, y_train)) #to get R^2 score for train
print(reg.predict(X_test)) #to get predictions for test which you may use to calculate your r^2 (once again ill advised -- treat it as classification imo)

请记住,您的形状应该是在 train_test 拆分之后:

X_train: (166, 60)

y_train: (166,)

X_test: (42, 60)

y_test: (42,)

火车预测:(166,)

测试预测:(42,)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-16
    • 2016-05-17
    • 2016-11-14
    • 2016-05-24
    • 2016-09-12
    • 2021-06-20
    • 2018-06-25
    • 2022-08-14
    相关资源
    最近更新 更多