将字典传递给具有 base_estimator 特征的 sklearn 分类器

Mag*_*gaP 5 python dictionary scikit-learn iterable-unpacking

我正在尝试将字典传递给 sklearn 分类器来设置其参数,但我也想设置base_estimator功能,例如:

>>> from sklearn.ensemble import AdaBoostClassifier
>>> x = {'n_estimators': 200}
>>> clf = AdaBoostClassifier(**x)
>>> clf
AdaBoostClassifier(algorithm='SAMME.R', base_estimator=None,
      learning_rate=1.0, n_estimators=200, random_state=None)
Run Code Online (Sandbox Code Playgroud)

工作正常,但如果我尝试:

>>> x = {'base_estimator__max_depth':5}
>>> clf = AdaBoostClassifier(**x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 
'base_estimator__max_depth'
Run Code Online (Sandbox Code Playgroud)

我也尝试预先设置基本估计器,AdaBoostClassifier(base_estimator=DecisionTreeClassifier(),**x)但这也不适用于与上面相同的错误。

我意识到它可以设置clf.base_estimator__max_depth = 5,但我理想地想解压一个设置分类器多个参数的字典。所以我的问题是,这可能吗?如果可能的话,如何实现?

注意:我知道如何设置这些参数,我只是想知道是否可以通过解压字典来完成此操作,因为这对我来说看起来更好

Viv*_*mar 6

那是因为 AdaBoostClassifier 的 python 构造函数仅在 中定义了以下参数__init__()

\n\n
base_estimator=None,\nn_estimators=50,\nlearning_rate=1.,\nalgorithm=\'SAMME.R\',\nrandom_state=None\n
Run Code Online (Sandbox Code Playgroud)\n\n

因为它base_estimator__max_depth是一个未知的参数。

\n\n

但是,您可以set_params()根据文档使用它将正确处理它们:

\n\n
\n

设置该估计器的参数。

\n\n

该方法适用于简单的估计器以及嵌套对象(例如管道)。后者具有component__parameter形式的参数 ,以便可以更新嵌套对象的每个组件。

\n
\n\n

所以你可以这样做:

\n\n
x = {\'base_estimator__max_depth\':5}\nclf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier())\nclf.set_params(**x)\n
Run Code Online (Sandbox Code Playgroud)\n\n

注意:在 python 3 中,您还可以执行以下操作(这就是我认为您正在寻找的):

\n\n
x = {\'base_estimator\':DecisionTreeClassifier(),\n     \'base_estimator__max_depth\':5}\nclf = AdaBoostClassifier()\nclf.set_params(**x)\n
Run Code Online (Sandbox Code Playgroud)\n\n

目前,上述内容在 python2 中已被破坏,将在下一版本中修复。请参阅此处的问题

\n\n

另一种方法是,您始终可以先将字典设置为 DecisionTreeClassifier,然后将其传递给 AdaBoostClassifier。

\n\n

像这样的东西:

\n\n
x = {\'max_depth\': 5}\nbase_est = DecisionTreeClassifier(**x)\nclf = AdaBoostClassifier(base_estimator = base_est)\n
Run Code Online (Sandbox Code Playgroud)\n\n

您还有别的想法吗?如果是,请发布您想要执行的完整代码片段,我们可以找到方法。

\n