1

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.

Michael Szczesny
  • 4,911
  • 5
  • 15
  • 32
Gaetano
  • 111
  • 2
  • I don't get what is the result you need. You want to multiply every (b,c) slice of T1 with T2 that has shape (d,b,c), do you want to perform a cross product? or the dot product? – imburningbabe Jan 20 '23 at 09:50
  • Hi imburningbabe, I need every slice (b,c) to be multiply by T2, it's equivalent to repeat 'd' times each slice (b,c) to have a (d,b,c) tensor, and then multiply it element by element with T2. And this for each (b,c) slice of T1. Thank you ! – Gaetano Jan 20 '23 at 10:14
  • So the final dimension of you tensor should be T3 = (a x d, b, c) ? – imburningbabe Jan 20 '23 at 10:17
  • No i want another dimension so that the final result is (a,d,b,c). – Gaetano Jan 20 '23 at 10:22
  • I have updated the post so that you can run the code, I hope it'll be more clear :) – Gaetano Jan 20 '23 at 10:24
  • 1
    `np.einsum('abc, dbc -> adbc', T1, T2)` – Michael Szczesny Jan 20 '23 at 13:01

2 Answers2

0

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]))
imburningbabe
  • 742
  • 1
  • 2
  • 13
  • Thank you very much ! But what I want is to avoid loops and compute this result using one vectorized function. I think it should be possible with np.tensordot (or another) and some good axis parameters. – Gaetano Jan 20 '23 at 10:54
  • Yeah, maybe you are right. But tensor products don't work that way, in your case what you can multiply are tensors of the shape (b,c,a) and (c,b,d), with that sequence of dimension. Moreover, in a tensordot product what you get is the dot product between matrices, that is completely different from an elementwise multiplication – imburningbabe Jan 20 '23 at 11:15
0

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.

hpaulj
  • 221,503
  • 14
  • 230
  • 353