I want to multiply two 3D tensors in a specific way.
The two tensors have shapes T1 = (a,b,c)
and T2 = (d,b,c)
.
What I want is to multiply a
times T2
by the successive 'slices' (b,c)
of a
.
In other words, I want to have the same as this code :
import numpy as np
a=2
b=3
c=4
d=5
T1 = np.random.rand(a,b,c)
T2 = np.random.rand(d,b,c)
L= []
for j in range(a) :
L =[T1[j,:,:]*T2]
L = np.array(L)
L.shape
I have the iterative solution and I try with axes arguments but I didn't succeed in the second way.
CodePudding user response:
Ok, now I think I got the solution:
a=2
b=3
c=4
d=5
T1 = np.random.rand(a,b,c)
T2 = np.random.rand(d,b,c)
L = np.zeros(shape=(a,d,b,c))
for i1 in range(len(T1)):
for i2 in range(len(T2)):
L[i1,i2] = np.multiply(np.array(T1[i1]),np.array(T2[i2]))
CodePudding user response:
Since the shapes:
In [26]: T1.shape, T2.shape
Out[26]: ((2, 3, 4), (5, 3, 4))
produce a:
In [27]: L.shape
Out[27]: (2, 5, 3, 4)
Let's try a broadcasted
pair of arrays:
In [28]: res = T1[:,None]*T2[None,:]
Shape and values match:
In [29]: res.shape
Out[29]: (2, 5, 3, 4)
In [30]: np.allclose(L,res)
Out[30]: True
tensordot
, dot
, or matmul
don't apply; just plain elementwise multiplication, with broadcasting
.