Home > OS >  Tensor multiplication in Keras
Tensor multiplication in Keras

Time:04-21

I have two tensors of size

A <tf.Tensor 'sequential_12/my_layer_56/add:0' shape=(?, 300, 2) dtype=float32>

and B <tf.Tensor 'input_82:0' shape=(?, 2, 2) dtype=float32>

Now, I would like to multiply them in the sense of the usual matrix row-column product to obtain

A * B of size (?, 300, 2), so I would be doing the matrix product only over the second and third dimension. How can I achieve this?

I tried to use tf.tensordot with different axes specifications, but it did not work so far. For example I tried

tf.tensordot(A,B,axes=[[2], [0]])

but this produces a tensor of the following form

<tf.Tensor 'Tensordot_10:0' shape=(?, 300, 2, 2) dtype=float32>

CodePudding user response:

Maybe try tf.matmul:

import tensorflow as tf

samples = 1
A = tf.random.normal((samples, 300, 2))
B = tf.random.normal((samples, 2, 2))

print(tf.matmul(A, B).shape)
# (1, 300, 2)
  • Related