How to do division/divide of Tensors in TensorFlow?

In TensorFlow 2.0 Python Tutorial, We will Learn about the TensorFlow Math Module tf.divide() function. We will learn how to do the division of tensors in TensorFlow using tf.devide() function.

tf.divide() : Do Element wise division,
It can be divide scaler, Numpy array but not with list, tuple.
tf variable/constant/placeholder/SparceMatrix with each other and with scaler and with list/tuple

Note: / or // operator can be use to divide 2 tensors

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

Args
xTensor
yTensor
nameA name for the operation (optional).
Returns
Tensor with same shape as input

Division of 2 Variables with TensorFlow

import tensorflow as tf
import numpy as np

Scaler division

a = 10
b = 20
print(" a/b =", a/b)
print(" a/b =", a//b)

tf.divide(a,b) #0.5

tf.divide(b, a) #2.0

Divide 2 Numpy Array

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

tf.divide(npa1, npa2)

Divide Numpy array with Scaler

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

tf.divide(npa1, a)

Divide Numpy array with single element np array

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

tf.divide(npa1, npa2)

Divide 2 TF Constant Tensor

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

tf.divide(tf_ct1, tf_ct2)
# Division with operator /
tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])

tf_ct1 / tf_ct2
# Division with operator /
tf_ct1 = tf.constant([1,2,3,4])
tf_ct2 = tf.constant([1,2,3,4])

tf_ct1 // tf_ct2

Divide TF Constant Tensor with Scaler

tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf.divide(tf_ct1, a)
# division with operator /
tf_ct1 = tf.constant([1,2,3,4])
a = 10
tf_ct1 / a

Divide 2 TF Variable

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

tf.divide(tf_vr1, tf_vr2)

Divide TF Variable with Scaler

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

Divide 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.divide(x, y)

Leave a Reply

Top