python 线性回归异常值_Python Sklearn线性回归值错误

在尝试使用 sklearn 的 LinearRegression 进行线性回归时遇到 ValueError 错误,错误信息提示输入样本数量不一致。问题在于 x 的形状不符合模型要求。解决方案是将 x 转换为形状为 (-1, 1) 的 numpy 数组。通过调用 `x.reshape(-1, 1)` 可以修正这个问题,然后再次尝试模型拟合。
摘要由CSDN通过智能技术生成

Ive been trying out Linear Regression using sklearn. Sometime I get a value error, sometimes it works fine. Im not sure which approach to use.

Error Message is as follows:

Traceback (most recent call last):

File "", line 1, in

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/linear_model/base.py", line 512, in fit

y_numeric=True, multi_output=True)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 531, in check_X_y

check_consistent_length(X, y)

File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/sklearn/utils/validation.py", line 181, in check_consistent_length

" samples: %r" % [int(l) for l in lengths])

ValueError: Found input variables with inconsistent numbers of samples: [1, 200]

The code is something like this:

import pandas as pd

from sklearn.linear_model import LinearRegression

data = pd.read_csv('http://www-bcf.usc.edu/~gareth/ISL/Advertising.csv', index_col=0);

x = data['TV']

y = data['Sales']

lm = LinearRegression()

lm.fit(x,y)

Please help me out. I am a student, trying to pick up on Machine Learning basics.

解决方案

lm.fit expects X to be a

numpy array or sparse matrix of shape [n_samples,n_features]

Your x has shape:

In [6]: x.shape

Out[6]: (200,)

Just use:

lm.fit(x.reshape(-1,1) ,y)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值