运行套索回归方法时出错
Posted
技术标签:
【中文标题】运行套索回归方法时出错【英文标题】:I got an error while running lasso regression method 【发布时间】:2021-12-10 19:41:54 【问题描述】:raise NotFittedError(msg % 'name': type(estimator).name) sklearn.exceptions.NotFittedError:此套索实例未安装 然而。在使用它之前使用适当的参数调用“fit” 估算器。
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)
【问题讨论】:
您在运行lasso.fit
之后创建了一个新的Lasso
对象,因此旧的套索对象及其拟合结果将丢失。
旧的套索对象实际上并没有丢失,它只是存储在不同的变量中。
【参考方案1】:
正如错误所说,您必须在调用 lasso_reg.predict(X_test)
之前调用 lasso_reg.fit(X_test, y_test)
这将解决问题。
lasso_reg = Lasso(normalize=True)
lasso_reg.fit(X_test, y_test)
y_pred_lass =lasso_reg.predict(X_test)
print(y_pred_lass)
【讨论】:
【参考方案2】:您实际上已经创建了套索模型。一个叫lasso
,你适合。但在那之后,您创建了另一个lasso_reg = Lasso(normalize=True)
,您尝试调用predict
,但该模型尚未安装。试试这个:
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)
【讨论】:
以上是关于运行套索回归方法时出错的主要内容,如果未能解决你的问题,请参考以下文章
为啥岭回归和套索回归分类器需要 random_state? [关闭]