ML Community Day is November 9! Join us for updates from TensorFlow, JAX, and more Learn more

tf.math.add

Returns x + y element-wise.

Used in the notebooks

Used in the guide Used in the tutorials

Example usages below.

Add a scalar and a list:

x = [1, 2, 3, 4, 5]
y = 1
tf.add(x, y)
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([2, 3, 4, 5, 6],
dtype=int32)>

Note that binary + operator can be used instead:

x = tf.convert_to_tensor([1, 2, 3, 4, 5])
y = tf.convert_to_tensor(1)
x + y
<tf.Tensor: shape=(5,), dtype=int32, numpy=array([2, 3, 4, 5, 6],
dtype=int32)>

Add a tensor and a list of same shape:

x = [1, 2, 3, 4, 5]
y = tf.constant([1, 2, 3, 4, 5])
tf.add(x, y)
<tf.Tensor: shape=(5,), dtype=int32,
numpy=array([ 2,  4,  6,  8, 10], dtype=int32)>

For example,

x = tf.constant([1, 2], dtype=tf.int8)
y = [2**7 + 1, 2**7 + 2]
tf.add(x, y)
<tf.Tensor: shape=(2,), dtype=int8, numpy=array([-126, -124], dtype=int8)>

When adding two input values of different shapes, Add follows NumPy broadcasting rules. The two input array shapes are compared element-wise. Starting with the trailing dimensions, the two dimensions either have to be equal or one of them needs to be 1.

For example,

x = np.ones(6).reshape(1, 2, 1, 3)
y = np.ones(6).reshape(2, 1, 3, 1)
tf.add(x, y).shape.as_list()
[2, 2, 3, 3]

Another example with two arrays of different dimension.