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,但我理想地想解压一个设置分类器多个参数的字典。所以我的问题是,这可能吗?如果可能的话,如何实现?
注意:我知道如何设置这些参数,我只是想知道是否可以通过解压字典来完成此操作,因为这对我来说看起来更好
那是因为 AdaBoostClassifier 的 python 构造函数仅在 中定义了以下参数__init__():
base_estimator=None,\nn_estimators=50,\nlearning_rate=1.,\nalgorithm=\'SAMME.R\',\nrandom_state=None\nRun Code Online (Sandbox Code Playgroud)\n\n因为它base_estimator__max_depth是一个未知的参数。
但是,您可以set_params()根据文档使用它将正确处理它们:
\n\n\n设置该估计器的参数。
\n\n该方法适用于简单的估计器以及嵌套对象(例如管道)。后者具有component__parameter形式的参数 ,以便可以更新嵌套对象的每个组件。
\n
所以你可以这样做:
\n\nx = {\'base_estimator__max_depth\':5}\nclf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier())\nclf.set_params(**x)\nRun Code Online (Sandbox Code Playgroud)\n\n注意:在 python 3 中,您还可以执行以下操作(这就是我认为您正在寻找的):
\n\nx = {\'base_estimator\':DecisionTreeClassifier(),\n \'base_estimator__max_depth\':5}\nclf = AdaBoostClassifier()\nclf.set_params(**x)\nRun Code Online (Sandbox Code Playgroud)\n\n目前,上述内容在 python2 中已被破坏,将在下一版本中修复。请参阅此处的问题。
\n\n另一种方法是,您始终可以先将字典设置为 DecisionTreeClassifier,然后将其传递给 AdaBoostClassifier。
\n\n像这样的东西:
\n\nx = {\'max_depth\': 5}\nbase_est = DecisionTreeClassifier(**x)\nclf = AdaBoostClassifier(base_estimator = base_est)\nRun Code Online (Sandbox Code Playgroud)\n\n您还有别的想法吗?如果是,请发布您想要执行的完整代码片段,我们可以找到方法。
\n| 归档时间: |
|
| 查看次数: |
5376 次 |
| 最近记录: |