首页 > 解决方案 > h2o set_params() 只接受 1 个参数(给定 2 个),即使只给定 1 个?

问题描述

得到错误

TypeError: set_params() takes exactly 1 argument (2 given)

即使我似乎只提供了一个论点......

HYPARAMS = {
            unicode(HYPER_PARAM): best_random_forest.params[unicode(HYPER_PARAM)][u'actual']
            for HYPER_PARAM in list_of_hyperparams_names
            }
assert isinstance(HYPARAMS, dict)
print 'Setting optimal params for full-train model...'
pp.pprint(HYPARAMS)
model = model.set_params(HYPARAMS)

#output
{   u'col_sample_rate_per_tree': 1.0,
    u'max_depth': 3,
    u'min_rows': 1024.0,
    u'min_split_improvement': 0.001,
    u'mtries': 5,
    u'nbins': 3,
    u'nbins_cats': 8,
    u'ntrees': 8,
    u'sample_rate': 0.25}
model = model.set_params(OPTIM_HYPARAMS)
TypeError: set_params() takes exactly 1 argument (2 given)

源代码

def set_params(self, **parms):
    """Used by sklearn for updating parameters during grid search.

    Parameters
    ----------
      parms : dict
        A dictionary of parameters that will be set on this model.

    Returns
    -------
      Returns self, the current estimator object with the parameters all set as desired.
    """
    self._parms.update(parms)
    return self

似乎没有发生太多我认为可能出错的事情。任何人都知道我在这里缺少什么或发生了什么导致此错误?

标签: h2o

解决方案


TLDR:需要将键/值解包为 **kwargs 关键字,以获得更新_parms字典的预期行为。也一样

model = model.set_params(**HYPARAMS)  #see https://stackoverflow.com/a/22384521/8236733

例子:

# here's a basic standin for the set_params method
>>> def kfunc(**parms):
...     print parms
... 

# what I was doing
>>> kfunc({1:2})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)
# and also tried
>>> kfunc(parms={1:2})
{'parms': {1: 2}}
>>> kfunc({u'1':2, u'2':3})
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: kfunc() takes exactly 0 arguments (1 given)

# what should have been done
>>> kfunc(**{'1':2})
{'1': 2}
>>> kfunc(**{u'1':2, u'2':3})
{u'1': 2, u'2': 3}

现在可以看到这与 h2o 没有直接关系,但无论如何都要保持发布,以便其他有这个问题的人可能会发现,因为没有立即想到通过阅读该方法的弹出文档来做到这一点(以及因为其他 SE 帖子在示例中评论说,我曾经实际使用变量作为 **kwarg 关键字甚至不在 Google 搜索“如何使用 python 变量作为 kwargs 参数的关键字?”的第一页上,所以想为它添加更多途径)。


推荐阅读