'AttributeError: 'LinearRegression' object has no attribute 'coef_'
I am self-studying machine learning and python. I am using sklearn and I want to plot the regression line, but I get the attributeError: 'LinearRegression' object has no attribute 'coef_. Could somebody help me to fix it, thank you in advance.
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_
Solution 1:[1]
The code provided doesn't yield any attribute error. However, the coef_
attribute is only created when the fit()
method is called. Before that, it will be undefined
, as explained in 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_
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | KarelZe |