我是自学机器学习和蟒蛇。我正在使用sklearn,我想绘制回归线,但是我得到了attributeError:'LinearRegression‘对象没有属性'coef_’,有人能帮我修复它吗?
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_
发布于 2022-03-31 08:32:18
提供的代码不会产生任何属性错误。但是,只有在调用coef_
方法时才会创建fit()
属性。在此之前,它将是undefined
,正如在this answer中所解释的。
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_
https://stackoverflow.com/questions/71313576
复制相似问题