简体   繁体   English

将Python函数参数作为变量传递

[英]Passing in Python function arguments as variables

I'm trying to write a function that runs through various iterations of classification algorithm (k-Means). 我正在尝试编写一个通过分类算法(k-Means)的各种迭代运行的函数。

In sklearn.neighbors.KNeighborsClassifier, there are a few parameters to adjust: n_neighbors and leaf_size. 在sklearn.neighbors.KNeighborsClassifier中,有几个参数需要调整:n_neighbors和leaf_size。 I'd like to know if there is a way to specify which parameter to adjustment during a particular iteration. 我想知道是否有一种方法可以指定在特定迭代期间要调整的参数。

from sklearn.neighbors import KNeighborsClassifier
def useNeighbors(iterations, *args):
    print(iterations) #normal argument
    for arg in args:
        KNeighborsClassifier(arg=20)

useNeighbors(2, "n_neighbors", "leaf_size")

I want this to essentially instantiate a KNeighborsClassifer instance twice- the first time with the # of neighbors at 20, and then the second time with the leaf size at 20 (default values for # of neighbors is 5, and default leaf size is 30). 我想让它本质上实例化一个KNeighborsClassifer实例两次-第一次将邻居数设置为20,然后第二次将叶子大小设置为20(邻居数的默认值为5,默认叶子大小为30)。 。

This, however, unsurprisingly yields 然而,这毫不奇怪

2
TypeError: _init_params() got an unexpected keyword argument 'arg'

It prints the iterations argument as expected, but then KNeighborsClassifer is not recognizing the string argument 'n_neighbors' as my attempt to specify which parameter to adjust. 它按预期打印迭代参数,但随后KNeighborsClassifer无法识别字符串参数'n_neighbors'作为我尝试指定要调整的参数的尝试。

How do I switch which parameter/argument I want to adjust across many different iterations? 如何在许多不同的迭代中切换要调整的参数/参数?

Also, obviously this is a toy case- I'm asking because I'm hoping to integrate different ML classification algorithms into an ensemble package with hyperparameters tuned through a Markov Chain Monte Carlo iterative method. 另外,显然这是一个玩具案-我之所以问是因为我希望将不同的ML分类算法集成到具有通过Markov Chain Monte Carlo迭代方法调整的超参数的整体包装中。 But in order to do that, I need to be able to specify which parameters in each algorithm take the "steps" found in the Markov Chain across each iteration. 但是为了做到这一点,我需要能够指定每种算法中的哪些参数采用每次迭代中在马尔可夫链中找到的“步骤”。

If I understand what you want, you can use partials for this. 如果我了解您想要的内容,则可以使用partials函数。 Example

from functools import partial
from sklearn.neighbors import KNeighborsClassifier

    classifiers = [partial(KNeighborsClassifier, n_neighbors=20),
                   partial(KNeighborsClassifier, leaf_size=20)]
    for classifier in classifiers:
        classifier()

Here 'sa good explanation of using partials. 是使用局部函数的很好的解释。

You just need to use a spread : 您只需要使用点差即可

from sklearn.neighbors import KNeighborsClassifier
def useNeighbors(iterations, *args):
    print(iterations) #normal argument
    for arg in args:
        my_dict = {}
        my_dict[arg] = 20
        KNeighborsClassifier(**my_dict)

useNeighbors(2, "n_neighbors", "leaf_size")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM