Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Tensorflow – is_tensor() method

  • Last Updated : 05 Sep, 2020

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 give variable is a Tensor otherwise it will print False.

# importing the library
import tensorflow as tf
# Initializing python string
s = "GeeksForGeeks"
# Checking if s is a Tensor
res = tf.is_tensor(s)
# Printing the result
print('Result: ', res)
# Initializing the input tensor
a = tf.constant([ [-5, -7],[ 2, 0]], dtype=tf.float64)
# Checking if a is a Tensor
res = tf.is_tensor(a)
# Printing the result
print('Result: ', res)


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.

# importing the library
import tensorflow as tf
import numpy as np
# Initializing numpy array
arr = np.array([1, 2, 3])
# Checking if s is a Tensor
if not tf.is_tensor(arr):
  # Converting to tensor
  arr = tf.convert_to_tensor(arr)
# Printing the dtype of resulting tensor
print("Dtype: ",arr.dtype)
# Printing the resulting tensor
print("tensor: ",arr)


Dtype:  <dtype: 'int64'>
tensor:  tf.Tensor([1 2 3], shape=(3,), dtype=int64)

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!