Python 组合GridSearchCV和StackingClassifier
我想使用StackingClassifier组合一些分类器,然后使用GridSearchCV优化参数:Python 组合GridSearchCV和StackingClassifier,python,scikit-learn,gridsearchcv,Python,Scikit Learn,Gridsearchcv,我想使用StackingClassifier组合一些分类器,然后使用GridSearchCV优化参数: clf1 = RandomForestClassifier() clf2 = LogisticRegression() dt = DecisionTreeClassifier() sclf = StackingClassifier(estimators=[clf1, clf2],final_estimator=dt) params = {'randomforestclassifier__n_
clf1 = RandomForestClassifier()
clf2 = LogisticRegression()
dt = DecisionTreeClassifier()
sclf = StackingClassifier(estimators=[clf1, clf2],final_estimator=dt)
params = {'randomforestclassifier__n_estimators': [10, 50],
'logisticregression__C': [1,2,3]}
grid = GridSearchCV(estimator=sclf, param_grid=params, cv=5)
grid.fit(x, y)
但这是一个错误:
'RandomForestClassifier' object has no attribute 'estimators_'
我使用了n_估计量
。为什么它警告我没有估计器
通常GridSearchCV应用于单个模型,所以我只需要在dict中写入单个模型的参数名称
我参考了这个页面,但它使用了早期版本的参数。即使我更改了新的参数,它也不起作用
顺便说一句,我在哪里可以了解这些参数的命名规则的细节?经过一些尝试,也许我能找到一个可用的解决方案 解决这个问题的关键是使用
get_params()
了解StackingClassifier的参数
我使用另一种方法创建sclf:
clf1 = RandomForestClassifier()
clf2 = LogisticRegression()
dt = DecisionTreeClassifier()
estimators = [('rf', clf1),
('lr', clf2)]
sclf = StackingClassifier(estimators=estimators,final_estimator=dt)
params = {'rf__n_estimators': list(range(100,1000,100)),
'lr__C': list(range(1,10,1))}
grid = GridSearchCV(estimator=sclf, param_grid=params,verbose=2, cv=5,n_jobs=-1)
grid.fit(x, y)
通过这种方式,我可以命名每个基本分类器,然后用它们的名称设置参数。首先,
估计器
需要是一个列表,包含元组中的模型,并具有相应的名称
estimators = [('model1', model()), # model() named model1 by myself
('model2', model2())] # model2() named model2 by myself
接下来,您需要使用出现在
sclf.get_params()
中的名称。
此外,该名称与您在上述估计器
列表中给出的特定模型的名称相同。因此,以下是您需要的model1参数:
params = {'model1__n_estimators': [5,10]} # model1__SOME_PARAM
工作玩具示例:
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import StackingClassifier
from sklearn.model_selection import GridSearchCV
X, y = make_classification(n_samples=1000, n_features=4,
n_informative=2, n_redundant=0,
random_state=0, shuffle=False)
estimators = [('rf', RandomForestClassifier(n_estimators=10, random_state=42)),
('logreg', LogisticRegression())]
sclf = StackingClassifier(estimators= estimators , final_estimator=DecisionTreeClassifier())
params = {'rf__n_estimators': [5,10]}
grid = GridSearchCV(estimator=sclf, param_grid=params, cv=5)
grid.fit(X, y)
如果执行
sclf.fit(X,y)
得到什么?'RandomForestClassifier'对象没有属性'estimators'请参见我的答案。希望它能帮助我在上面找到答案