Tensorflow – is_tensor() method

TensorFlow is an open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks. Tensors are used by many Tensorflow operations. Sometimes it is important to check whether given variable is a tensor or not before using it. is_tensor() method can be used to check this.
- is_tensor: This method takes a variable as input and returns True if variable is a Tensor or Tensor-like object otherwise it will return false.
Example 1: This example will print True if given variable is a Tensor otherwise it will print False.
python3
# importing the libraryimport tensorflow as tf# Initializing python strings = "GeeksForGeeks"# Checking if s is a Tensorres = tf.is_tensor(s)# Printing the resultprint('Result: ', res)# Initializing the input tensora = tf.constant([ [-5, -7],[ 2, 0]], dtype=tf.float64)# Checking if a is a Tensorres = tf.is_tensor(a)# Printing the resultprint('Result: ', res) |
Output:
Result: False Result: True
Example 2: This example checks if a variable is tensor or not, if not it will convert the variable into tensor.
python3
# importing the libraryimport tensorflow as tfimport numpy as np# Initializing numpy arrayarr = np.array([1, 2, 3])# Checking if s is a Tensorif not tf.is_tensor(arr): # Converting to tensor arr = tf.convert_to_tensor(arr)# Printing the dtype of resulting tensorprint("Dtype: ",arr.dtype)# Printing the resulting tensorprint("tensor: ",arr) |
Output:
Dtype: <dtype: 'int64'> tensor: tf.Tensor([1 2 3], shape=(3,), dtype=int64)



