1

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_
Emilly
  • 11
  • 2
  • What makes you think `reg` has an attribute `coef_`? – Scott Hunter Mar 01 '22 at 19:26
  • @Scott Hunter Sorry, I do not get what you exactly mean, what I did is to fit reg and as we can have the coefficient and the intercept by reg.coef_ and reg.intercept_, then I think we can plot it. But I get that error. I am so sorry if my explanation is not so clear I am new to the subject and I self-study. – Emilly Mar 01 '22 at 20:00
  • Did you resolve the issue? – There Apr 27 '22 at 16:30
  • @ScottHunter There should be a `coef_` attribute for the model at least per sklearn docs (https://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html). – There Apr 27 '22 at 19:50

1 Answers1

0

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_
KarelZe
  • 1,466
  • 1
  • 11
  • 21
  • But they do call `fit`, right? `reg.fit(x_matrix,y); plt.scatter(x,y); yhat= reg.coef_ * x_matrix + reg.intercept_`. – There Apr 27 '22 at 16:29
  • Downvoted because the code is simply a repetition of OP's code, but with a different example. – There Apr 27 '22 at 17:14