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

标签 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)

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

>>> 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'

我还尝试预先设置基本估计器,即 AdaBoostClassifier(base_estimator=DecisionTreeClassifier(),**x) 但这也无法解决与上述相同的错误。

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

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

最佳答案

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

base_estimator=None,
n_estimators=50,
learning_rate=1.,
algorithm='SAMME.R',
random_state=None

对于它来说base_estimator__max_depth是一个未知参数。

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

Set the parameters of this estimator.

The method works on simple estimators as well as on nested objects (such as pipelines). The latter have parameters of the form component__parameter so that it’s possible to update each component of a nested object.

所以你可以这样做:

x = {'base_estimator__max_depth':5}
clf = AdaBoostClassifier(base_estimator=DecisionTreeClassifier())
clf.set_params(**x)

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

x = {'base_estimator':DecisionTreeClassifier(),
     'base_estimator__max_depth':5}
clf = AdaBoostClassifier()
clf.set_params(**x)

目前,上述内容在 python2 中已损坏,将在下一版本中修复。请参阅issue here .

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

类似这样的事情:

x = {'max_depth': 5}
base_est = DecisionTreeClassifier(**x)
clf = AdaBoostClassifier(base_estimator = base_est)

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

关于python - 将字典传递给具有 base_estimator 特征的 sklearn 分类器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506065/

相关文章:

c++ - Boost如何创建类型选择的 map ?

scikit-learn - sklearn随机森林未并行化

Python:我可以在字典中将字符串作为键并将函数作为值吗?

swift - NSDictionary 在检索信息时返回一个可选的整数

python - Scikit-Learn KDE 中的 PDF 估计

python - TfidfVectorizer toarray() 和 HashingVectorizer 的含义

python - 如何将函数应用于 DataFrame 中的几列之一?

python - 使用逻辑回归的泰坦尼克号机器学习问题

python - 根据搜索条件从 Python 数组中返回随机元素

python - 删除 XML 中的重复节点