如何在我自己定义的函数中使用来自另一个模块的函数或函数集作为参数?
我正在尝试编写一个函数来比较一个向量 q
并计算它与一组向量 x
中每个向量的距离。 get_distances
函数应采用一个向量 q
、一组向量 x
和一个参数 dist_method
。 dist_method
应该从 scipy.spatial.distance 中获取任何一个距离计算并将其用于计算,因此我可以这样调用该函数:distances = get_distances(q, x, 'euclidean')
这是 scipy 引用页 - get_distances
应该能够采用任何距离函数 braycurtis、canberra、...、sqeuclidean、wminkowski:
https://docs.scipy.org/doc/scipy/reference/spatial.distance.html
在这个函数所在的 file1.py
文件的顶部,我导入了 scipy.spatial.distance,我认为我应该可以从中访问像距离一样使用的函数.euclidean(),但是当我在解释器中调用 get_distances
时,我得到了 AttributeError: 'module' object has no attribute 'dist_method'
。
我已经找到了很多像下面这样的答案,它们说函数是“一等对象”,我应该能够像使用任何其他参数一样将它们用作参数,并且我已经尝试使用 **kwargs概念,但我不能把它们放在一起。
- Passing functions with arguments to another function in Python?
- How do I pass a method as a parameter in Python
- https://docs.python.org/3/tutorial/controlflow.html#keyword-arguments
有人可以帮助我了解我所缺少的吗?
KNN.py:
import numpy as np
import scipy.spatial.distance as dist
def get_distances(q, x, dist_method='euclidean', *args, **kwargs):
"""Query dataset to get distances for KNN
Given a numpy array of vectors x and
query point q, use dist_method to calculate
distance from q to each vector in x
Parameters:
q: tuple
x: numpy array
dist_method (optional): distance function from scipy.spatial.distance
Returns: list of distances
"""
return [dist.dist_method(q, x_i) for x_i in x]
def load_samples():
x = np.array([[1, 6],[2, 4],[3, 7],[6, 8],[7, 1],[8, 4]])
y = np.array([[7],[8],[16],[44],[50],[68]])
q = (4, 2)
return x, y, q
这是我在解释器中所做的:
>>> import KNN as knn
>>> x, y, q = knn.load_samples()
>>> x
array([[1, 6],
[2, 4],
[3, 7],
[6, 8],
[7, 1],
[8, 4]])
>>> d = knn.get_distances(q, x, 'cityblock')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "KNN.py", line 19, in get_distances
return [dist.dist_method(q, x_i) for x_i in x]
AttributeError: 'module' object has no attribute 'dist_method'
最佳答案
问题在于:
return [dist.dist_method(q, x_i) for x_i in x]
是您尝试使用 dist_method
从 dist
访问函数,该函数的名称与字符串的值匹配(即 "euclidean"
),但是 dist.dist_method
将在 dist
对象中查找名为 "dist_method"
的函数,该函数不存在。
要按名称访问对象的函数,您可以使用 getattr
,它将返回与字符串匹配的对象属性。
你要做的是:
[getattr(dist,dist_method)(q, x_i) for x_i in x]
关于Python - 在函数中使用来自另一个模块的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900428/