For two 2D tensors, matmul() requires the number of columns in a to match the number of rows in b, and computes the standard matrix product. For higher-dimensional tensors, matmul() treats the leading dimensions as a batch, performing independent matrix multiplications between corresponding matrix pairs across the batch — this batched behavior is exactly what makes it possible to multiply an entire batch of examples through a layer's weight matrix in a single call, rather than looping over each example individually.
1Understanding tf.matmul()
For two 2D tensors, matmul() requires the number of columns in a to match the number of rows in b, and computes the standard matrix product. For higher-dimensional tensors, matmul() treats the leading dimensions as a batch, performing independent matrix multiplications between corresponding matrix pairs across the batch — this batched behavior is exactly what makes it possible to multiply an entire batch of examples through a layer's weight matrix in a single call, rather than looping over each example individually.
matmul()'s batched behavior for tensors with more than 2 dimensions lets you multiply an entire batch of matrices through another matrix, or batch of matrices, in one call — this is exactly the mechanism that lets a Dense layer process a whole batch of inputs simultaneously instead of one example at a time.
import tensorflow as tf
A = tf.constant([[1, 2], [3, 4]])
B = tf.constant([[5, 6], [7, 8]])
print(tf.matmul(A, B))2Practical Example
Here is a real-world application of tf.matmul() showing how it is used in production TensorFlow code.
import tensorflow as tf
batch_inputs = tf.ones([32, 10])
weights = tf.ones([10, 5])
output = tf.matmul(batch_inputs, weights)
print(output.shape)3Best Practices
Follow these guidelines when working with tf.matmul():
1. Use tf.matmul() or @ for true matrix multiplication, reserving * strictly for element-wise multiplication
2. Check that inner dimensions actually match, columns of the left matrix equal rows of the right, before multiplying, to catch shape errors early
3. Rely on matmul()'s batched behavior for processing an entire batch of examples through a weight matrix at once, instead of writing an explicit loop over the batch dimension
Tip: matmul()'s batched behavior for tensors with more than 2 dimensions lets you multiply an entire batch of matrices through another matrix, or batch of matrices, in one call — this is exactly the mechanism that lets a Dense layer process a whole batch of inputs simultaneously instead of one example at a time.
import tensorflow as tf
A = tf.constant([[1, 2], [3, 4]])
B = tf.constant([[5, 6], [7, 8]])
print(tf.matmul(A, B))