Tensorflow – is_tensor() method
Last Updated :
09 Mar, 2023
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
import tensorflow as tf
s = "GeeksForGeeks"
res = tf.is_tensor(s)
print ( 'Result: ' , res)
a = tf.constant([ [ - 5 , - 7 ],[ 2 , 0 ]], dtype = tf.float64)
res = tf.is_tensor(a)
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
import tensorflow as tf
import numpy as np
arr = np.array([ 1 , 2 , 3 ])
if not tf.is_tensor(arr):
arr = tf.convert_to_tensor(arr)
print ("Dtype: ",arr.dtype)
print ("tensor: ",arr)
|
Output:
Dtype: <dtype: 'int64'>
tensor: tf.Tensor([1 2 3], shape=(3,), dtype=int64)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...