tf.constant
tf.constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)
Defined in tensorflow/python/framework/constant_op.py.
See the guide: Constants, Sequences, and Random Values > Constant Value Tensors
Creates a constant tensor.
创建一个常数张量。
The resulting tensor is populated with values of type dtype, as specified by arguments value and (optionally) shape (see examples below).
生成的张量将填充dtype类型的值,该值由参数value和(可选)shape指定(请参见下面的示例)。
The argument value can be a constant value, or a list of values of type dtype. If value is a list, then the length of the list must be less than or equal to the number of elements implied by the shape argument (if specified). In the case where the list length is less than the number of elements specified by shape, the last element in the list will be used to fill the remaining entries.
参数值可以是常量值,也可以是dtype类型的值列表。
如果value是一个列表,则列表的长度必须小于或等于shape参数所隐含的元素数(如果指定)。
如果列表长度小于shape指定的元素数,则列表中的最后一个元素将用于填充其余条目。
The argument shape is optional. If present, it specifies the dimensions of the resulting tensor. If not present, the shape of value is used.
参数形状是可选的。 如果存在,它指定所得张量的尺寸。 如果不存在,则使用值的形状。
If the argument dtype is not specified, then the type is inferred from the type of value.
如果未指定参数dtype,则从值的类型推断类型。
For example:
# Constant 1-D Tensor populated with value list.
tensor = tf.constant([1, 2, 3, 4, 5, 6, 7]) => [1 2 3 4 5 6 7]
# Constant 2-D tensor populated with scalar value -1.
tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.]
[-1. -1. -1.]]
tf.constant differs from tf.fill in a few ways:
tf.constant与tf.fill在以下方面有所不同:
-
tf.constant supports arbitrary constants, not just uniform scalar Tensors like tf.fill.
tf.constant支持任意常量,而不仅仅是像tf.fill这样的统一标量张量。 -
tf.constant creates a Const node in the computation graph with the exact value at graph construction time. On the other hand, tf.fill creates an Op in the graph that is expanded at runtime.
tf.constant在计算图中使用图构建时的确切值创建一个Const节点。 另一方面,tf.fill在图形中创建一个Op,并在运行时对其进行扩展。 -
Because tf.constant only embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereas tf.fill does.
因为tf.constant仅将常数值嵌入到图形中,所以它不支持基于其他运行时Tensor的动态形状,而tf.fill则支持。
Args:
-
value: A constant value (or list) of output type dtype.
输出类型dtype的常量值(或列表)。 -
dtype: The type of the elements of the resulting tensor.
所得张量的元素类型。 -
shape: Optional dimensions of resulting tensor.
-
name: Optional name for the tensor.
张量的可选名称。 -
verify_shape: Boolean that enables verification of a shape of values.
布尔值,用于验证值的形状。
Returns:
- A Constant Tensor.
恒定张量。
Raises:
- TypeError: if shape is incorrectly specified or unsupported.
TypeError:如果形状指定不正确或不受支持。
20200212
tf.constant()返回的结果是一个Tensor对象
import tensorflow as tf
x = tf.constant([[1., 1.], [2., 2.]])
print(type(x))
结果:<class ‘tensorflow.python.framework.ops.Tensor’>