TensorFlow – is_tensor() 方法
TensorFlow 是 Google 设计的一个开源Python库,用于开发机器学习模型和深度学习神经网络。
许多 Tensorflow 操作都使用张量。有时在使用之前检查给定变量是否是张量很重要。 is_tensor()方法可用于检查这一点。
- 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.
示例 1:如果给定变量是张量,此示例将打印 True,否则将打印 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
示例 2:此示例检查变量是否为张量,如果不是,则将变量转换为张量。
# 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:
tensor: tf.Tensor([1 2 3], shape=(3,), dtype=int64)