ValueError: Found arrays with inconsistent numbers of samples 的解决方案

sklearn常见错误01

最近用sklearn进行了线性回归的预测问题,情况是用一维的一个特征x来预测一个y值。但是用sklearn中的linear_model进行fit的时候出现了如题错误:ValueError: Found arrays with inconsistent numbers of samples

数据情况如图

ValueError: Found arrays with inconsistent numbers of samples 的解决方案

利用sklearn做线性回归

出现的问题

ValueError: Found arrays with inconsistent numbers of samples 的解决方案
ValueError: Found arrays with inconsistent numbers of samples 的解决方案

问题原因

开始时的数据读取情况

ValueError: Found arrays with inconsistent numbers of samples 的解决方案

我们可以看到,这样读取数据训练集X是一个向量。而sklearn里的model.fit(X,y) 中的X,y必须是矩阵形式

解决方案

ValueError: Found arrays with inconsistent numbers of samples 的解决方案

读取数据时要按图示那样读取,这样虽然也是读取的一列数据但是最终是以矩阵形式呈现的。如图,X是一个21*1的矩阵

看看修改后是不是可以运行了!

ValueError: Found arrays with inconsistent numbers of samples 的解决方案

Bingo! It works!