Search code examples
pythonscikit-learndata-sciencelasso-regression

I got an error while running lasso regression method


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)

Solution

  • 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)