How to addition/add 2 Tensors in TensorFlow?

We will learn how to do addition in TensorFlow using tf.add() function.

tf.add() : Do Element wise Addition with x & y
It can add list, tuple, scaler, TensorFlow variable/constant/placeholder/SparceMatrix with each other and with scaler and with list/tuple.

Note: + operator can be use to add 2 tensors

Syntax: tf.add(x, y, name=None)

xtf.Tensor. Must be one of the following types: bfloat16, half, float32, float64, uint8, int8, int16, int32, int64, complex64, complex128, string.
ytf.Tensor. Must have the same type as x.
nameA name for the operation (optional)

Addition of 2 Variables with TensorFlow

import tensorflow as tf
import numpy as np

Scaler Adding

a = 10
b = 20

Add 2 List

l1 = [1,2,3,4]
l2 = [5,6,7,8]

tf.add(l1, l2)

Add List/Tuple with Scaler

l1 = [1,2,3,4]
a =10
tf.add(l1, a)

Addition of 2 list/Tuple with Diiferent Size

If the size of 2 variables is different then tf.add() function will through error. If any one of the variables contains only a single item then it will do the element-wise operation.

#this code will through error
l1 = [1,2,3,4]
l2 = [5,6]

tf.add(l1, l2)

Add 2 Numpy Array

npa1 = np.array([1,2,3,4,5])
npa2 = np.array([1,2,3,4,5])

tf.add(npa1, npa2)

Add Numpy array with Scaler

npa1 = np.array([1,2,3,4,5])
a = 10

tf.add(npa1, a)

Add Numpy array with single element np array

npa1 = np.array([1,2,3,4,5])
npa2 = np.array([[1]])

tf.add(npa1, npa2)

Add 2 TF Constant Tensor

tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])

tf.add(tf_ct1, tf_ct2)

Add TF Constant Tensor with Scaler

tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf.add(tf_ct1, a)

Add 2 TF Variable

tf_vr1 = tf.Variable([1,2,3,4])
tf_vr2 = tf.Variable([1,2,3,4])

tf.add(tf_vr1, tf_vr2)

Add TF Variable with Scaler

tf_vr1 = tf.Variable([1,2,3,4])
a = 10
tf.add(tf_vr1, a)

Add 2 Numpy array with different Shape

x = np.ones(6).reshape(1, 2, 1, 3) # (2,2,3,3)
print("x: ", x)
y = np.ones(6).reshape(2, 1, 3, 1)
print("y: ", y)

tf.add(x, y)

Leave a Reply