How to Calculate Square Root of Tensors in TensorFlow?

In TensorFlow 2.0 Python Tutorial, We will Learn about the TensorFlow Math Module tf.sqrt() function. We will learn how to calculate the square root of tensors in TensorFlow using tf.sqrt() function.

tf.sqrt() : Calculate Element wise square root of numpy array and TF tensor,
It can be give sqrt of list, tuple, scaler
It allow tf variable/constant/placeholder/SparceMatrix with Specific datatype

Data Type : bfloat16, half, float32, float64, complex64, complex128.

Note: Don’t give ‘int’ data type, tf.sqrt() will through error

Syntax: tf.sqrt(x, name=None)

Args
xtf.Tensor of type bfloat16halffloat32float64complex64complex128
nameA name for the operation (optional).
Returns
tf.Tensor of same size, type and sparsity as x.If x is a SparseTensor, returns SparseTensor(x.indices, tf.math.sqrt(x.values, ...), x.dense_shape)

Calculate the Square Root using TensorFlow

import tensorflow as tf
import numpy as np

Square Root of Scaler

a = 9.0
tf.sqrt(a)

Square Root of List

l1 = [4.0,9.0,16.0]

tf.sqrt(l1)

Square Root of Tuple

t1 = (4.0,9.0,16.0)

tf.sqrt(t1)

Square Root of Numpy Array

npa1 = np.array([4,9,16], dtype = np.float64)

tf.sqrt(npa1)
y = np.ones(6).reshape(2, 1, 3, 1)*4
print("Y: " , y)
tf.sqrt(y)

Square Root of TensorFlow Tensor

tf.sqrt(tf.convert_to_tensor(4, dtype='float')) # using scaler value
tf.sqrt(tf.convert_to_tensor([4,9,16], dtype='float')) # using list

Square Root of TF Constant Tensor

tf_ct1 = tf.constant([4,9,16], dtype='float')

tf.sqrt(tf_ct1)

Square Root of TF Variable

tf_vr1 = tf.Variable([4,9,16], dtype='half')

tf.sqrt(tf_vr1)

Leave a Reply