我有一个函数x,如下所示,它接受两个NumPy数组作为输入,并且我想通过一些计算得到一个布尔值.
import numpy as np
def x(a,b):
print(a)
print(b)
# Some computation...
return boolean_value
wrappedFunc = np.frompyfunc(x,nin=2,nout=1)
arg_a = np.arange(8).reshape(2,4)
# arg_b is a numpy array having shape (2,1)
arg_b = np.array((np.array([[0, 1, 0],
[0, 0, 0],
[1, 0, 0],
[1, 1, 0]]),
np.array([[0., 1., 0.],
[0., 0., 0.],
[1., 0., 0.],
[1., 1., 0.],
[0.5, 0.5, 0.]])), dtype=object).reshape(2, 1)
执行上面的代码将产生以下输出.
# Output of a is:
0
1
2
3
4
5
6
7
# output of b is:
[[0 1 0]
[0 0 0]
[1 0 0]
[1 1 0]]
[[0 1 0]
[0 0 0]
[1 0 0]
[1 1 0]]
[[0 1 0]
[0 0 0]
[1 0 0]
[1 1 0]]
[[0 1 0]
[0 0 0]
[1 0 0]
[1 1 0]]
[[0. 1. 0. ]
[0. 0. 0. ]
[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.5 0. ]]
[[0. 1. 0. ]
[0. 0. 0. ]
[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.5 0. ]]
[[0. 1. 0. ]
[0. 0. 0. ]
[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.5 0. ]]
[[0. 1. 0. ]
[0. 0. 0. ]
[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.5 0. ]]
正如您可以看到的,变量a
和b
分别打印了8次,这不是预期的行为,因为我预计会分别看到a
和b
的打印语句的输出两次.print(a)
和print(b)
语句的预期输出如下所示:
On first call:
a needs to be:[0,1,2,3]
b needs to be:[[0 1 0]
[0 0 0]
[1 0 0]
[1 1 0]]
On second call:
a needs to be:[4,5,6,7]
b needs to be:[[0. 1. 0. ]
[0. 0. 0. ]
[1. 0. 0. ]
[1. 1. 0. ]
[0.5 0.5 0. ]]
我到底做错了什么?