所以我有两个矩阵,一个是I×H,另一个是I×I,其中H = M * I.我想把第一个矩阵的前M行的点积与第二个矩阵的第一行,接下来的M行和第二行的下一行等等。
有没有人知道在NumPy中执行此操作的简单方法?我试图避免循环。
答案 0 :(得分:2)
import numpy as np
# just some examples
i = 5
m = 3
h = m * i
first = np.arange(h * i).reshape(h, i) # note dimension H×i, not I×H
second = np.arange(i * i).reshape(i, i)
# Let's compute the dot product of
# every column of `first`
# with every column of `second` (i.e. every row of `second` transposed):
#
full_matrix_product = np.dot(first, second.transpose()) # no (explicit) loops,
# but does much more
# multiplications than
# we need in the end.
# Extract the specific dot products you want:
wanted_rows = np.arange(h)
wanted_columns = np.arange(m).repeat(i)
result = full_matrix_product[wanted_rows, wanted_columns].reshape(m, i)