如何正确使用字典的 args 或 kwargs 以将它们用作函数中的 Regressor 输入变量?

How do I use args or kwargs for dicts properly to use them as Regressor input variables in function?

我已经通过 GridSearchCV 生成了一些值为字典的输入参数。

输入参数如下所示:

在:print(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)

输出:{'max_depth': 4} {'min_samples_split': 14} {'max_leaf_nodes': 14}

如果我将它们作为 kwarg 放入 Regressor 函数中,它会很好地工作。

在:print(DecisionTreeRegressor(**grid_maxdepth, **grid_min_samples_split, **grid_max_leaf_nodes))

输出:

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

现在如果我想在下面的函数中做同样的事情,它会将变量放在错误的位置和错误的格式中。例如,它没有使用 max_depth=4,而是将字典放入标准 ("criterion={'max_depth': 4}").

在:

def test(*sss):
    print(DecisionTreeRegressor(*sss))

test(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)

输出:

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

我做错了什么? 请记住,我对使用 arg / kwarg 还很陌生,我已经研究过这篇文章: https://www.geeksforgeeks.org/args-kwargs-python/

为了python解释任何关键字参数;调用该方法时需要明确使用 ** 语法。

示例:myMethod(**kwargs1, **kwargs2)

试试这个:

def test(**sss):
    print(DecisionTreeRegressor(**sss))

d1={'max_depth': 4}
d2={'min_samples_split': 14} 
d3={'max_leaf_nodes': 14}

test(**d1, **d2, **d3)

说明

您正在尝试将关键字参数传递给包装在 test 函数中的 DescisionTreeRegressor 函数。

您的函数接受任意数量的参数 (*args):

def test(*sss):
    print(DecisionTreeRegressor(*sss))

test(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)

在内部,您的测试方法调用转换为:

DescisionTreeRegressor(grid_maxdepth, grid_min_samples_split, grid_max_leaf_nodes)

请注意以上只是常规字典参数,因此字典中的关键字被评估。

要使 kwargs 正常工作,test 方法中的调用实际上应该如下所示:

DescisionTreeRegressor(**grid_maxdepth, **grid_min_samples_split, **grid_max_leaf_nodes)