gpt4 book ai didi

python - numpy 识别的特殊方法的文档位置

转载 作者:太空宇宙 更新时间:2023-11-03 14:43:24 24 4
gpt4 key购买 nike

math.expnumpy.exp 之间的一个区别是,如果您有一个自定义类 C,它有一个 C.exp 方法,numpy.exp 会注意到并委托(delegate)给这个方法,而 math.exp 不会:

class C:
def exp(self):
return 'hey!'

import math
math.exp(C()) # raises TypeError
import numpy
numpy.exp(C()) # evaluates to 'hey!'

但是,如果您转到 web documentation of numpy.exp ,这似乎是理所当然的。它没有在任何地方明确说明。是否有记录此功能的地方?

更一般地说,是否有一个地方列出了 numpy 识别的所有此类方法?

最佳答案

这不是 np.exp 函数的特殊行为;这只是对象 dtype 数组的计算方式的结果。

np.exp 像许多 numpy 函数一样,在执行之前尝试将非数组输入转换为数组。

In [227]: class C:
...: def exp(self):
...: return 'hey!'
...:
In [228]: np.exp(C())
Out[228]: 'hey!'

In [229]: np.array(C())
Out[229]: array(<__main__.C object at 0x7feb7154fa58>, dtype=object)
In [230]: np.exp(np.array(C()))
Out[230]: 'hey!'

所以 C() 被转换成一个数组,它是一个对象 dtype *(C() 不像 [1,2 ,3])。通常一个 numpy 函数,如果给定一个对象 dtype 数组,迭代元素,要求每个元素执行相应的方法。这解释了 [228] 如何最终评估 C().exp()

In [231]: np.exp([C(),C()])
Out[231]: array(['hey!', 'hey!'], dtype=object)
In [232]: np.exp([C(),C(),2])
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-232-5010b59d525d> in <module>()
----> 1 np.exp([C(),C(),2])

AttributeError: 'int' object has no attribute 'exp'

np.exp 可以处理数组对象 dtype,前提是所有元素都有 exp 方法。整数没有。 ndarray 也没有。

In [233]: np.exp([C(),C(),np.array(2)])
AttributeError: 'numpy.ndarray' object has no attribute 'exp'

math.exp 需要一个数字,一个 Python 标量(或者可以转换为标量的东西,例如 np.array(3)

我希望这种行为对所有ufunc 都是常见的。我不知道其他不遵循该协议(protocol)的 numpy 函数。

在某些情况下,ufunc 委托(delegate)给 __ 方法:

In [242]: class C:
...: def exp(self):
...: return 'hey!'
...: def __abs__(self):
...: return 'HEY'
...: def __add__(self, other):
...: return 'heyhey'
...:
In [243]:
In [243]: np.abs(C())
Out[243]: 'HEY'
In [244]: np.add(C(),C())
Out[244]: 'heyhey'

关于python - numpy 识别的特殊方法的文档位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51447460/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com