Search code examples
h2o

h2o set_params() takes exactly 1 argument (2 given), even though only 1 given?


Getting error

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

even though I only appear to be providing a single argument...

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)

Looking at the source code,

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

there does not appear to be much going on that I see could go wrong. Anyone know what I'm missing here or what is happening to cause this error?


Solution

  • TLDR: Need to unpack the keys/values as **kwargs keywords in order to get the expected behavior of updating the _parms dict. So do

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

    Example:

    # 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}
    
    

    Can now see that this is not directly related to h2o, but keeping post up anyway so others with this problem may find, since did not immediately think to do this from just reading the popup docs for the method (and also since the other SE post commented in the example that I used to actually use variables as **kwarg keywords was not even on the first page of a Google search of "How to use python variable as keyword for kwargs parameter?" so would like to add more avenues to it).