Saturday, August 30, 2025
HomeLanguagesTensorflow – is_tensor() method

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 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)


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 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)


Output:

Dtype:  <dtype: 'int64'>
tensor:  tf.Tensor([1 2 3], shape=(3,), dtype=int64)
Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7013 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS