tf.add(a, b) adds corresponding elements of a and b, applying NumPy-style broadcasting when the two tensors have compatible but different shapes — for example, adding a scalar to a tensor applies that scalar to every element, and adding a 1D tensor to a compatible 2D tensor applies it to every row. Using the + operator directly on tensors is equivalent and far more common in everyday TensorFlow code; tf.add() itself is mainly useful when you need to reference the operation explicitly, such as inside a computational graph.
1Understanding tf.add()
tf.add(a, b) adds corresponding elements of a and b, applying NumPy-style broadcasting when the two tensors have compatible but different shapes — for example, adding a scalar to a tensor applies that scalar to every element, and adding a 1D tensor to a compatible 2D tensor applies it to every row. Using the + operator directly on tensors is equivalent and far more common in everyday TensorFlow code; tf.add() itself is mainly useful when you need to reference the operation explicitly, such as inside a computational graph.
Prefer the + operator over calling tf.add() directly for everyday code — they're functionally identical, and + is both more common and more readable.
import tensorflow as tf
a = tf.constant([1, 2, 3])
b = tf.constant([10, 20, 30])
print(tf.add(a, b))2Practical Example
Here is a real-world application of tf.add() showing how it is used in production TensorFlow code.
import tensorflow as tf
matrix = tf.constant([[1, 2, 3], [4, 5, 6]])
row = tf.constant([10, 20, 30])
print(matrix + row)3Best Practices
Follow these guidelines when working with tf.add():
1. Use the + operator for everyday element-wise addition instead of calling tf.add() explicitly
2. Understand TensorFlow's broadcasting rules, the same as NumPy's, before relying on adding tensors of different shapes, so an unintended broadcast doesn't silently produce a wrong result
3. Check that both tensors' dtypes match before adding them, since TensorFlow, unlike NumPy, generally requires an explicit tf.cast() rather than silently upcasting mismatched types
Tip: Prefer the + operator over calling tf.add() directly for everyday code — they're functionally identical, and + is both more common and more readable.
import tensorflow as tf
a = tf.constant([1, 2, 3])
b = tf.constant([10, 20, 30])
print(tf.add(a, b))