如何解决sklearn.train_test_split-test_size 导致 ValueError 样本数量不一致
我遇到了一个非常奇怪的问题。下面,我展示了我的代码。
代码:
#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.
有人可以帮我吗?非常感谢。
解决方法
- 您确定要使用线性回归解决您的问题吗?我的意思是您基本上有 60 个特征作为输入,并且您正在尝试预测这 60 个特征是否具有标签 R 或 M。我会将这个问题归类为分类问题。回归以输出值的形式返回,但是在您的情况下,您对“R”或“M”类感兴趣(您将 0 和 1 指定为目标)
- R^2 只对回归有用(你应该用准确率替换它)
- 您需要发布负责生成 (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,)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。