We will learn how to do suntraction in TensorFlow using tf.subtract() function.
tf.subtract() : Do Element wise subtraction with x & y
It can subtract list, tuple, scaler, TensorFlow variable/constant/placeholder/SparceMatrix with each other and with scaler and with list/tuple.
Note: – operator can be used to subtract 2 tensors
Syntax: tf.subtract(x, y, name=None)
Args | |
---|---|
x | A Tensor . Must be one of the following types: bfloat16 , half , float32 , float64 , uint8 , int8 , uint16 , int16 , int32 , int64 , complex64 , complex128 , uint32 , uint64 . |
y | A Tensor . Must have the same type as x . |
name | A name for the operation (optional). |
Returns |
---|
A Tensor . Has the same type as x . |
Subtraction of 2 Variables with TensorFlow
import tensorflow as tf
import numpy as np
Scaler subtract
a = 10
b = 20
tf.subtract(a,b)
subtract 2 List
l1 = [1,2,3,4]
l2 = [5,6,7,8]
tf.subtract(l2, l1)
subtract 2 Tuple
t1 = (1,2,3,4)
t2 = (5,6,7,8)
tf.subtract(t1,t2)
subtract List/Tuple with Scaler
l1 = [1,2,3,4]
a =10
tf.subtract(l1, a)
subtract of 2 list/Tuple with Diiferent Size
If the size of 2 variables is different then tf.subtract() 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.subtract(l1, l2)
subtract 2 Numpy Array
npa1 = np.array([1,2,3,4,5])
npa2 = np.array([1,2,3,4,5])
tf.subtract(npa1, npa2)
subtract Numpy array with Scaler
npa1 = np.array([1,2,3,4,5])
a = 10
tf.subtract(npa1, a)
subtract Numpy array with single element np array
npa1 = np.array([1,2,3,4,5])
npa2 = np.array([[1]])
tf.subtract(npa1, npa2)
subtract 2 TF Constant Tensor
tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])
tf.subtract(tf_ct1, tf_ct2)
subtract TF Constant Tensor with Scaler
tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf.subtract(tf_ct1, a)
subtract 2 TF Variable
tf_vr1 = tf.Variable([1,2,3,4])
tf_vr2 = tf.Variable([1,2,3,4])
tf.subtract(tf_vr1, tf_vr2)
subtract TF Variable with Scaler
tf_vr1 = tf.Variable([1,2,3,4])
a = 10
tf.subtract(a, tf_vr1)
subtract 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.subtract(x, y)