0

I have a tensor3 with shape (3, 4, 5) and another tensor4 with shape (3, 4, 7, 5). In numpy,

 result = np.einsum("ijk, ijmk->ijm", tensor3, tensor4)
 print result.shape 
 (3, 4, 7)

but in theano , how to do it .

Hungry fool
  • 27
  • 1
  • 6

1 Answers1

1

The first step is to transpose and reshape your tensor so that only the first dimension gets preserved. In that case it is quite simple, you just have to combine the first two dimensions:

x = tensor.tensor3()
y = tensor.tensor4()
i, j, m, k = y.shape

x_ = x.reshape((i * j, k))
y_ = y.reshape((i * j, m, k))

Then, you specify to batched_tensordot that you are going to sum axis 1 of x_ with axis 2 of y_:

z_ = tensor.batched_tensordot(x_, y_, (1, 2))  # shape (i * j, m)

Finally, reshape z_ to get the first two dimensions:

z = z_.reshape((i, j, m))
print(z.eval({x: np.zeros((3, 4, 5)), y: np.zeros((3, 4, 7, 5))}).shape)
# (3, 4, 7)
Pascal Lamblin
  • 356
  • 1
  • 3
  • thank you very much@Pascal Lamblin. You have solved my problem.But I just wonder why I tried tensor.batched_tensordot(x, y, (2, 3)) and got the shape (i, j, j, m) other than (i, j, i, j, m)??? – Hungry fool Dec 07 '16 at 14:37
  • With batched_tensordot, the first axis is preserved (iterated jointly), so the first shape is i. Then, k is eliminated (becaused it is summed over). The remaining dimensions are j for x, and (j, m) for y, which get concatenated. So finally, the shape is (i,) + (j,) + (j, m), or (i, j, j, m). tensordot(x, y, (2, 3)) (without the batch) would have given you (i, j, i, j, m) – Pascal Lamblin Jan 07 '17 at 18:50