Python – tensorflow.convert_to_tensor()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
convert_to_tensor()用于将给定值转换为张量
Syntax: tensorflow.convert_to_tensor( value, dtype, dtype_hint, name )
Parameters:
- value: It is the value that needed to be converted to Tensor.
- dtype(optional): It defines the type of the output Tensor.
- dtype_hint(optional): It is used when dtype is None. In some cases, a caller may not have a dtype in mind when converting to a tensor, so dtype_hint can be used as a soft preference. If the conversion to dtype_hint is not possible, this argument has no effect.
- name(optiona): It defines the name for the operation.
Returns: It returns a Tensor.
示例 1:来自Python列表
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
l = [1, 2, 3, 4]
# Printing the input
print('l: ', l)
# Calculating result
x = tf.convert_to_tensor(l)
# Printing the result
print('x: ', x)
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
l = (1, 2, 3, 4)
# Printing the input
print('l: ', l)
# Calculating result
x = tf.convert_to_tensor(l, dtype = tf.float64)
# Printing the result
print('x: ', x)
输出:
l: [1, 2, 3, 4]
x: tf.Tensor([1 2 3 4], shape=(4, ), dtype=int32)
示例 2:来自Python元组
Python3
# Importing the library
import tensorflow as tf
# Initializing the input
l = (1, 2, 3, 4)
# Printing the input
print('l: ', l)
# Calculating result
x = tf.convert_to_tensor(l, dtype = tf.float64)
# Printing the result
print('x: ', x)
输出:
l: (1, 2, 3, 4)
x: tf.Tensor([1. 2. 3. 4.], shape=(4, ), dtype=float64)