解决ValueError: Found input variables with inconsistent numbers of samples

问题背景

使用python的sklearn库进行线性回归时,对x,y的素材进行训练时报错:

ValueError: Found input variables with inconsistent numbers of samples

部分代码如下:

# 自变量(天数)
x = np.arange(1,len(detail_tstep_group3[detail_tstep_group3.渠道名称 == name])+1).reshape(-1,1)

# 因变量(期望次单人数差)
y = detail_tstep_group3[detail_tstep_group3.渠道名称 == name].期望次单用户数差.values.reshape(-1,1)

# 创建模型
model = LinearRegression()

# 训练模型
model.fit(x,y)

# 获取线性回归模型系数 (分别对应线性回归中的未知数a,b y=ax+b)
a = model.coef_
b = model.intercept_
print(a,b,'y=f(x)={}*x+{}'.format(a[0][0],b[0]))

# 结果预测写法2
y_predict = model.predict(x)
print(y_predict)

问题解决

分别输出x,y的素材后发现,两者的素材量不对等,修改后就能运行了
在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐