使用向量化遍历输入矩阵的行

Loop through rows of input matrices with vectorize

我有一个 4x2 和一个 2x2 矩阵。我想使用 vectorize.

通过函数 foo 循环每个行组合(维度 2 的向量)

这是矩阵:

X = np.array([[1, 0], [2, 0], [3, 0], [4,0]])
Y = np.array([[1, 0], [2, 0]])

以下是我尝试 运行 的方法:

def foo(x, y):
    print("inputs:", x, y)
    return x[0] * y[0]

bar = np.vectorize(foo, signature="???")
output = bar(X, Y)
print(output)

我正在寻找以下输出。 bar 会 return 一个 4x2 矩阵:

inputs: [1,0] [1,0]
inputs: [1,0] [2,0]
inputs: [2,0] [1,0]
inputs: [2,0] [2,0]
inputs: [3,0] [1,0]
inputs: [3,0] [2,0]
inputs: [4,0] [1,0]
inputs: [4,0] [2,0]
[[1,2], [2,4], [3,6], [4,8]]

我已经尝试了 signature 的各种组合,但我只是不知道如何使用它给出我正在寻找的输出。

注意:我知道 vectorize 只是在后台使用 Python for 循环,并没有提供任何性能优势。我只是想了解如何使用它。

vectorize 的基本用法是相互广播输入,并将标量元组传递给您的函数。 A (4,2) 不能用 (2,2) 广播。签名是一个附加项,应该可以传递数组的“行”。甚至更慢,我还没有看到它使用太多(或推荐它)。

In [536]: bar = np.vectorize(foo, signature="(n),(n)->()")

In [533]: bar(X,Y[0,:])
inputs: [1 0] [1 0]
inputs: [2 0] [1 0]
inputs: [3 0] [1 0]
inputs: [4 0] [1 0]
Out[533]: array([1, 2, 3, 4])

In [537]: bar(X[:,None],Y[None])
inputs: [1 0] [1 0]
inputs: [1 0] [2 0]
inputs: [2 0] [1 0]
inputs: [2 0] [2 0]
inputs: [3 0] [1 0]
inputs: [3 0] [2 0]
inputs: [4 0] [1 0]
inputs: [4 0] [2 0]
Out[537]: 
array([[1, 2],
       [2, 4],
       [3, 6],
       [4, 8]])

所以这给出了 bar a (4,1,2) and (1,2,2);广播为 (4,2,2)。或者使用这个签名,它广播一个 (4,1) 和 1,2) => (4,2)。它是决定最后一个维度如何匹配的签名。

在某些情况下可能会很方便,但我不建议花太多时间来理解 vectorize