Introduction
Broadcasting lets TensorFlow do math on arrays of different shapes easily, like stretching smaller arrays to match bigger ones without copying data.
Jump into concepts and practice - no test required
result = tensor1 + tensor2
import tensorflow as tf # tensor1 shape: (3, 4) tensor1 = tf.constant([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]) # tensor2 shape: (4,) tensor2 = tf.constant([1, 0, 1, 0]) result = tensor1 + tensor2 print(result)
import tensorflow as tf # tensor1 shape: (2, 3, 1) tensor1 = tf.constant([[[1], [2], [3]], [[4], [5], [6]]]) # tensor2 shape: (3,) tensor2 = tf.constant([10, 20, 30]) result = tensor1 + tensor2 print(result)
import tensorflow as tf # Define a 2D tensor (matrix) of shape (2, 3) matrix = tf.constant([[1, 2, 3], [4, 5, 6]]) # Define a 1D tensor (vector) of shape (3,) vector = tf.constant([10, 20, 30]) # Add vector to each row of matrix using broadcasting result = matrix + vector # Print shapes and result print(f"matrix shape: {matrix.shape}") print(f"vector shape: {vector.shape}") print("result:") print(result) # Calculate mean of result tensor mean_value = tf.reduce_mean(result) print(f"mean of result: {mean_value.numpy():.2f}")
import tensorflow as tf x = tf.constant([[1, 2, 3]]) # shape (1, 3) y = tf.constant([4, 5, 6, 7]) # shape (4,) z = x + y
a = tf.constant([[1, 2, 3], [4, 5, 6]]) (shape (2, 3))b = tf.constant([1, 2]) (shape (2,))a + b raise an error, and how can you fix it?t of shape (5, 1, 3), you want to add a bias tensor b of shape (3,) to each element along the last dimension. Which code correctly applies broadcasting to add b to t?