Python – tensorflow.constant()
TensorFlow 是由 Google 设计的开源Python库,用于开发机器学习模型和深度学习神经网络。
constant()用于从像列表这样的张量对象创建张量。
Syntax: tensorflow.constant( value, dtype, shape, name )
Parameters:
- value: It is the value that needed to be converted to Tensor.
- dtype(optional): It defines the type of the output Tensor.
- shape(optional): It defines the dimension of output Tensor.
- 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.constant(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.constant(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.constant(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)