问题
I started learning numpy and I'm trying to do a kind of strange matrix multiplication between a 2-dimensional and a 3-dimensional matrices. I have a function that does what I need, but I'm curious if there's a better way of doing it.
Let's consider we have a matrix M1 with (KxN) dimensions, and have another matrix M2 with (KxNxN) dimensions. I'm trying to multiply each (1xN) rows of M1 with the corresponding (NxN) matrix of M2. Here's my code with sample matrices:
a = [[1., 2., 3.],
[0., 9., 8.]]
a = np.array(a)
b = [[[.5, .5, .5],
[.5, .5, .5],
[.5, .5, .5]],
[[.25, .25, .25],
[.25, .25, .25],
[.25, .25, .25]]]
b = np.array(b)
c = [[5., 5., 5., 5., 5.]]
c = np.array(c)
d = [[[.1, .1, .1, .1, .1],
[.2, .2, .2, .2, .2],
[.3, .3, .3, .3, .3],
[.4, .4, .4, .4, .4],
[.5, .5, .5, .5, .5]]]
d = np.array(d)
def mul(x, y):
result = []
for i in range(len(x)):
result.append(x[i] @ y[i])
return np.array(result)
print(mul(a, b))
[[3. 3. 3. ]
[4.25 4.25 4.25]]
print(mul(c, d))
[[7.5 7.5 7.5 7.5 7.5]]
I think that makes it clear. I'm sure there is a better way of doing it, but so far I was unable to come up with one. I've been trying with apply_along_axis and multiply but I might be completely off track.
回答1:
You can use np.einsum -
np.einsum('ij,ijk->ik',array1,array2)
Or with np.matmul
or @
operator on Python 3.x
-
np.matmul(array1[:,None,:],array2)[:,0]
(array1[:,None,:] @ array2)[:,0]
来源:https://stackoverflow.com/questions/56070493/numpy-2-d-3-d-matrix-row-wise-multiplication