我有两个矩阵,一个是I×H,另一个是I×I,其中H = M*I。我想取第一个矩阵的前M行与第二个矩阵的第一行的点积,下一个M行与第二个矩阵的下一行的点积,等等。
有谁知道在NumPy中这样做的简单方法吗?我想避免循环
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)