首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AttributeError: LinearRegression对象没有属性“coef_”

AttributeError: LinearRegression对象没有属性“coef_”
EN

Stack Overflow用户
提问于 2022-03-01 19:18:07
回答 1查看 1K关注 0票数 1

我是自学机器学习和蟒蛇。我正在使用sklearn,我想绘制回归线,但是我得到了attributeError:'LinearRegression‘对象没有属性'coef_’,有人能帮我修复它吗?

代码语言:javascript
运行
复制
x=data['size']
y=data['price']
x_matrix=x.values.reshape(-1,1)
reg=LinearRegression()
reg.fit(x_matrix,y)
plt.scatter(x,y)
yhat= reg.coef_ * x_matrix + reg.intercept_
fig=plt.plot(x, yhat, lw=4, c="orange", label="regression line")
plt.xlabel("size", fontsize=20)
plt.ylabel("price", fontsize=20)
plt.show() 
 
AttributeError: 'LinearRegression' object has no attribute 'coef_
EN

回答 1

Stack Overflow用户

发布于 2022-03-31 08:32:18

提供的代码不会产生任何属性错误。但是,只有在调用coef_方法时才会创建fit()属性。在此之前,它将是undefined,正如在this answer中所解释的。

代码语言:javascript
运行
复制
from sklearn.linear_model import LinearRegression
import pandas as pd

data = pd.DataFrame([[1,2],[3,4]], columns=['size', 'price'])

x=data['size']
y=data['price']
x_matrix=x.values.reshape(-1,1)

reg=LinearRegression()
# make sure to call fit
reg.fit(x_matrix,y)
yhat= reg.coef_ * x_matrix + reg.intercept_
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71313576

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档