Skip to main content
 首页 » 编程设计

regression之在 Scikit Learn 中使用网格搜索 (GridSearchCV) 和管道的支持向量回归 (SVR) 系数

2024年10月17日31bjzhanghao

当模型嵌入管道和网格搜索中时,我无法在 scikit learn 中访问支持向量回归模型 (SVR) 的系数。 考虑以下示例:

from sklearn.datasets import load_iris 
import numpy as np 
from sklearn.grid_search import GridSearchCV 
from sklearn.svm import SVR 
from sklearn.feature_selection import SelectKBest 
from sklearn.pipeline import Pipeline 
 
iris = load_iris() 
X_train = iris.data 
y_train = iris.target 
 
clf = SVR(kernel='linear') 
select = SelectKBest(k=2) 
steps = [('feature_selection', select), ('svr', clf)] 
pipeline = Pipeline(steps) 
grid = GridSearchCV(pipeline, param_grid={"svr__C":[10,10,100],"svr__gamma": np.logspace(-2, 2)}) 
grid.fit(X_train, y_train) 

这似乎工作正常但是当我尝试访问最佳拟合模型的系数时

grid.best_estimator_.coef_ 

我收到一条错误消息:AttributeError:“管道”对象没有属性“coef_”。

我还尝试访问管道的各个步骤:

pipeline.named_steps['svr'] 

但在那里找不到系数。

请您参考如下方法:

刚好遇到同样的问题和this post 有答案: grid.best_estimator_ 包含管道实例,它由 steps 组成。最后一步应该始终是估算器,因此您应该始终在以下位置找到系数:

grid.best_estimator_.steps[-1][1].coef_