Python-矩阵外部产品 [英] Python - Matrix outer product
问题描述
给出两个矩阵
A: m * r
B: n * r
我想生成另一个矩阵C: m * n
,每个条目C_ij
是由A_i
和B_j
的外积计算的矩阵.
I want to generate another matrix C: m * n
, with each entry C_ij
being a matrix calculated by the outer product of A_i
and B_j
.
例如,
A: [[1, 2],
[3, 4]]
B: [[3, 1],
[1, 2]]
给予
C: [[[3, 1], [[1 ,2],
[6, 2]], [2 ,4]],
[9, 3], [[3, 6],
[12,4]], [4, 8]]]
我可以使用for循环来完成它,例如
I can do it using for loops, like
for i in range (A.shape(0)):
for j in range (B.shape(0)):
C_ij = np.outer(A_i, B_j)
我想知道是否有矢量化的方法可以加快计算速度?
I wonder If there is a vectorised way of doing this calculation to speed it up?
推荐答案
temp = numpy.multiply.outer(A, B)
C = numpy.swapaxes(temp, 1, 2)
NumPy ufuncs, such as multiply
, have an outer
method that almost does what you want. The following:
temp = numpy.multiply.outer(A, B)
产生的结果为temp[a, b, c, d] == A[a, b] * B[c, d]
.您需要C[a, b, c, d] == A[a, c] * B[b, d]
. swapaxes
调用重新排列了 temp
按照您想要的顺序.
produces a result such that temp[a, b, c, d] == A[a, b] * B[c, d]
. You want C[a, b, c, d] == A[a, c] * B[b, d]
. The swapaxes
call rearranges temp
to put it in the order you want.
这篇关于Python-矩阵外部产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!