Skip to content
Advertisement

Tensorflow Keras Tensor Multiplication with None as First Dimension

I’m using TensorFlow Keras backend and I have two tensors a, b of the same shape: (None, 4, 7), where None represents the batch dimension.

I want to do matrix multiplication, and I’m expecting a result of (None, 4, 4).
i.e. For each batch, do one matmul: (4,7)·(7,4) = (4,4)

Here’s my code —

JavaScript

This code gives a tensor of shape (None, 4, None, 4)

I’d like to know how does high-dimension matrix multiplication work? What’s the right way to do this?

Advertisement

Answer

IIUC, you can either use tf.matmul directly as part of your model and transpose b or explicitly wrap the operation in a Lambda layer:

JavaScript
JavaScript

Or

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement