-2

raise NotFittedError(msg % {'name': type(estimator).name}) sklearn.exceptions.NotFittedError: This Lasso instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.


from sklearn import datasets
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split
#
# Load the Boston Data Set
#
bh = datasets.load_boston()
X = bh.data
y = bh.target
#
# Create training and test split
#
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
#
# Create an instance of Lasso Regression implementation
#
lasso = Lasso(alpha=1.0)
#
# Fit the Lasso model
#
lasso.fit(X_test, y_test)
#
# Create the model score
#
#lasso.score(X_test, y_test), lasso.score(X_train, y_train)
lasso_reg = Lasso(normalize=True)
y_pred_lass =lasso_reg.predict(X_test)
print(y_pred_lass)
Kaushal Sharma
  • 1,770
  • 13
  • 16
anna
  • 1
  • 3
  • You create a new `Lasso` object *after* running `lasso.fit`, thus the old lasso objecct, and its fit result, will have been lost. – 9769953 Oct 25 '21 at 10:06
  • The old lasso object isn't actually lost, its just stored in a different variable. – pseudoabdul Oct 25 '21 at 10:08

2 Answers2

1

You've actually created two lasso models. One called lasso which you fit. But after that you create another one lasso_reg = Lasso(normalize=True) which you try to call predict on but that model hasn't been fitted yet. Try this:

from sklearn import datasets
from sklearn.linear_model import Lasso
from sklearn.model_selection import train_test_split

bh = datasets.load_boston()
X = bh.data
y = bh.target

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

lasso = Lasso(alpha=1.0, normalize=True)

lasso.fit(X_test, y_test)

y_pred_lass =lasso.predict(X_test)
print(y_pred_lass)
P. Camilleri
  • 12,664
  • 7
  • 41
  • 76
pseudoabdul
  • 616
  • 3
  • 12
0

As the error says you have to call lasso_reg.fit(X_test, y_test) before calling lasso_reg.predict(X_test) This will fix the issue.

lasso_reg = Lasso(normalize=True)
lasso_reg.fit(X_test, y_test)
y_pred_lass =lasso_reg.predict(X_test)
print(y_pred_lass)
Kaushal Sharma
  • 1,770
  • 13
  • 16