I have the tensor
A =
[[[a,b],
[c,d]],
[[e,f],
[g,h]]]
and the matrix
B =
[[1,2],
[3,4]]
I need to get
C =
[[a*1+e*2,b*1+f*2],
[c*3+g*4,d*3+h*4]]
How can I do this using numpy in matrix form? I've looked into np.tensordot() but it doesn't seem to help in this case.
解决方案
You can try this:
>>> import numpy as np
>>> a = np.arange(1,9).reshape(2,2,2)
>>> a
array([[[1, 2],
[3, 4]],
[[5, 6],
[7, 8]]])
>>> b = np.arange(1,5).reshape(2,2)
>>> b
array([[1, 2],
[3, 4]])
>>> (a * b[None,:,:].T).sum(axis = 0)
array([[11, 14],
[37, 44]])
Intermediate steps look like this:
>>> b[None,:,:]
array([[[1, 2],
[3, 4]]])
>>> b[None,:,:].T
array([[[1],
[3]],
[[2],
[4]]])