首页 > 解决方案 > Python:Ridge 回归 - 使用 GridSearchCV 后,“Ridge”对象没有属性“coef_”

问题描述

我正在使用 Python 3.6.5 和 scikit-learn 0.23.2

from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, cross_val_score

ridge = Ridge()

r_parameters = {'alpha':[1e-15, 1e-10, 1e-8, 1e-4, 1e-3, 1e-2, 1, 5, 10, 20]} # this is the Ridge regressor penalty, across different values

ridge_regressor = GridSearchCV(ridge, r_parameters, scoring = 'neg_mean_squared_error', cv = 5)

ridge_regressor.fit(X,y)

ridge_best_params_ = ridge_regressor.best_params_
ridge_best_score_ = -ridge_regressor.best_score_

这成功地为我提供了 best_params_ 和 best_score_ 值。意义.fit已经跑了。refit 没有被调整,因此它应该是默认的refit = True

然而,当试图返回我的岭回归模型的系数时:

for coef, col in enumerate(X.columns):
    print(f"{col}:  {ridge.coef_[coef]}")

它导致我出现以下错误:

AttributeError                            Traceback (most recent call last)
<ipython-input-7-e59d1af522dc> in <module>
      2 
      3 for coef, col in enumerate(X.columns):
----> 4     print(f"{col}:  {ridge.coef_[coef]}")

AttributeError: 'Ridge' object has no attribute 'coef_

感谢任何帮助。

标签: pythonpython-3.xscikit-learngrid-search

解决方案


ridge(实例)在拟合(实例)Ridge时实际上并没有被拟合;相反,安装了 of 的克隆,并将其中的一个另存为. 因此将包含改装模型的系数。ridge_regressorGridSearchCVridgeridge.best_estimator_ridge.best_estimator_.coef_

请注意,它GridSearchCV确实提供了一些方便的功能来访问best_estimator_; egridge.score只是ridge.best_estimator_.score,predict和它的变体的简写。但它并没有为 的所有方法/属性提供这种传递best_estimator_,并且coef_是不可用的方法之一。


推荐阅读