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 = 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_

对此表示感谢。

解决方法

ridgeRidge实例)在拟合ridge_regressorGridSearchCV实例)时实际上没有拟合;而是拟合ridge的克隆,并将其中一个保存为ridge.best_estimator_。因此,ridge.best_estimator_.coef_将包含重新模型的系数。

请注意,GridSearchCV确实提供了一些访问best_estimator_的便利功能;例如ridge.score只是ridge.best_estimator_.score的简写,predict及其变体也类似。但是它没有为best_estimator_的方法/属性的 all 提供这种传递,而coef_是其中之一。