gpt4 book ai didi

python - 使用 __numpy_ufunc__()

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

我正在尝试使用 __numpy_ufunc__() 方法解释 here in the Numpy v1.11 docs ,以覆盖 ndarray 子类上 numpy ufuncs 的行为,但它似乎从未被调用过。尽管指南中列出了这个用例,但我找不到任何实际使用 __numpy_ufunc__() 的示例。有人试过这个吗?这是一个最小的例子:

# Check python version
import sys
print(sys.version)

3.5.1 |Continuum Analytics, Inc.| (默认,2016 年 6 月 15 日,15:32:45)

[GCC 4.4.7 20120313(红帽 4.4.7-1)

# Check numpy version
import numpy as np
print(np.__version__)

1.11.2

# Subclass ndarray as discussed in 
# https://docs.scipy.org/doc/numpy/user/basics.subclassing.html
class Function(np.ndarray):

# Create subclass object by view
def __new__(cls):
obj = np.asarray([1,2,3]).view(cls)
return obj

# I'm not even adding anything functionality yet
def __array_finalize(self,obj): pass

# Override ufuncs
def __numpy_ufunc__(ufunc, method, i, inputs, **kwargs):
print("In PF __numpy_ufunc__")
# do other stuff here if I want to
# and probably need to return a value...

# Create two Functions
f1=Function()
f2=Function()

# Check that they are correctly initialized as Function objects
# not just ndarrays
print(type(f1),type(f2))

⟨class 'ma​​in.Function'⟩ ⟨class 'ma​​in.Function'⟩

# Add using operator
f1+f2

函数([2, 4, 6])

# Add, explicitly demanding a numpy ufunc
np.add(f1,f2)

函数([2, 4, 6])

显然,子类化有效,并且它使用 numpy 在幕后添加数组。我正在使用足够新的 numpy 版本来使用 __numpy_ufunc__() 功能(根据该文档页面,它是 v1.11 中的新功能)。但是这段代码永远不会打印出 "In PF __numpy_ufunc__"。给了什么?

最佳答案

此功能终于在 Numpy 1.13 中发布了在一个新的名字下:

__array_ufunc__ added

This is the renamed and redesigned __numpy_ufunc__. Any class, ndarray subclass or not, can define this method or set it to None in order to override the behavior of NumPy’s ufuncs. This works quite similarly to Python’s __mul__ and other binary operation routines. See the documentation for a more detailed description of the implementation and behavior of this new option. The API is provisional, we do not yet guarantee backward compatibility as modifications may be made pending feedback. See the NEP and documentation for more details.

这应该可以解决这个问题。

关于python - 使用 __numpy_ufunc__(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41494823/

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