I have generated some input parameters with values as dicts through GridSearchCV.
The input parameters look like this:
In: print(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)
Out: {'max_depth': 4} {'min_samples_split': 14} {'max_leaf_nodes': 14}
If I put them as kwarg into a Regressor function, it works nicely.
In: print(DecisionTreeRegressor(**grid_maxdepth, **grid_min_samples_split, **grid_max_leaf_nodes))
Out:
DecisionTreeRegressor(criterion='mse', max_depth=4, max_features=None,
max_leaf_nodes=14, min_impurity_decrease=0.0,
min_impurity_split=None, min_samples_leaf=1,
min_samples_split=14, min_weight_fraction_leaf=0.0,
presort=False, random_state=None, splitter='best')
Now if I want to do the same in the following function, it puts the variables into the wrong position and in the wrong format. For expample, instead of using max_depth=4
, it puts the dict into criterion ("criterion={'max_depth': 4}")
.
In:
def test(*sss):
print(DecisionTreeRegressor(*sss))
test(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)
Out:
DecisionTreeRegressor(criterion={'max_depth': 4},
max_depth={'max_leaf_nodes': 14}, max_features=None,
max_leaf_nodes=None, min_impurity_decrease=0.0,
min_impurity_split=None, min_samples_leaf=1,
min_samples_split=2, min_weight_fraction_leaf=0.0,
presort=False, random_state=None,
splitter={'min_samples_split': 14})
What am I doing wrong? Keep in mind, that I am quite new to using arg / kwarg and I have already looked into this article: https://www.geeksforgeeks.org/args-kwargs-python/
For python to interpret any keyword arguments; you need to explicitly use **
syntax when calling the method.
Example: myMethod(**kwargs1, **kwargs2)
Try this:
def test(**sss):
print(DecisionTreeRegressor(**sss))
d1={'max_depth': 4}
d2={'min_samples_split': 14}
d3={'max_leaf_nodes': 14}
test(**d1, **d2, **d3)
Explanation
You are trying to pass keyword arguments to a DescisionTreeRegressor
function that's wrapped in your test
function.
Your function takes any number of arguments (*args):
def test(*sss):
print(DecisionTreeRegressor(*sss))
test(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)
Internally your test method call translates to this:
DescisionTreeRegressor(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)
Notice how the above are just regular dictionary parameters so the keywords inside the dictionaries are not evaluated.
For kwargs to work, the call from within test
method should actually look like this:
DescisionTreeRegressor(**grid_maxdepth, **grid_min_samples_split, **grid_max_leaf_nodes)