tf.constant


从类似张量(tensor-like)的对象创建一个常量张量。

Creates a constant tensor from a tensor-like object.

tf.constant(
    value, dtype=None, shape=None, name='Const'
)

定义

参数

Args
value

输出类型 dtype 的常量值(或列表)。

A constant value (or list) of output type dtype.

dtype

结果张量的元素类型。

The type of the elements of the resulting tensor.

shape

结果张量的可选尺寸。

Optional dimensions of resulting tensor.

name

张量的可选名称。

Optional name for the tensor.

返回

Returns

一个常量张量。

A Constant Tensor.

异常

Raises
TypeError

如果 shape 指定不正确或不受支持。

if shape is incorrectly specified or unsupported.

ValueError

如果调用符号张量。

if called on a symbolic tensor.

说明

如果未指定参数 dtype,则类型从 value 的类型中推断而来。

If the argument dtype is not specified, then the type is inferred from the type of value.

  >>> # Constant 1-D Tensor from a python list.
  >>> tf.constant([1, 2, 3, 4, 5, 6])
  <tf.Tensor: shape=(6,), dtype=int32,
      numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)>
  >>> # Or a numpy array
  >>> a = np.array([[1, 2, 3], [4, 5, 6]])
  >>> tf.constant(a)
  <tf.Tensor: shape=(2, 3), dtype=int64, numpy=
    array([[1, 2, 3],
           [4, 5, 6]])>

如果指定了 dtype,则生成的张量值将转换为请求的 dtype

If dtype is specified, the resulting tensor values are cast to the requested dtype.

  >>> tf.constant([1, 2, 3, 4, 5, 6], dtype=tf.float64)
  <tf.Tensor: shape=(6,), dtype=float64,
      numpy=array([1., 2., 3., 4., 5., 6.])>

如果设置了 shape,则重新调整(reshape)以匹配该设置 value。标量(scalar)被扩展以填充该 shape

If shape is set, the value is reshaped to match. Scalars are expanded to fill the shape:

  >>> tf.constant(0, shape=(2, 3))
    <tf.Tensor: shape=(2, 3), dtype=int32, numpy=
    array([[0, 0, 0],
           [0, 0, 0]], dtype=int32)>
  >>> tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])
  <tf.Tensor: shape=(2, 3), dtype=int32, numpy=
    array([[1, 2, 3],
           [4, 5, 6]], dtype=int32)>

如果一个 eager 模式下的 Tensor 对象作为 value 传递,tf.constant 无效,它甚至传输梯度:

tf.constant has no effect if an eager Tensor is passed as the value, it even transmits gradients:

  >>> v = tf.Variable([0.0])
  >>> with tf.GradientTape() as g:
  ...     loss = tf.constant(v + v)
  >>> g.gradient(loss, v).numpy()
  array([2.], dtype=float32)

但是,由于 tf.constant 将值嵌入到 tf.Graph 中,因此符号张量(symbolic tensor)失败:

But, since tf.constant embeds the value in the tf.Graph this fails for symbolic tensors:

  >>> with tf.compat.v1.Graph().as_default():
  ...   i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32)
  ...   t = tf.constant(i)
  Traceback (most recent call last):
  ...
  TypeError: ...

tf.constant 将在当前设备上创建张量。已经是张量的输入保持其占位不变。

tf.constant will create tensors on the current device. Inputs which are already tensors maintain their placements unchanged.

相关操作(Related Ops):

  • tf.convert_to_tensor 类似,但是:(tf.convert_to_tensor is similar but:)
    • 它没有 shape 参数。(It has no shape argument.)
    • 允许传递符号张量(symbolic tensor)。(Symbolic tensors are allowed to pass through.)
    >>> with tf.compat.v1.Graph().as_default():
    ...   i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32)
    ...   t = tf.convert_to_tensor(i)
  • tf.fill :在几个方面有所不同:(tf.fill : differs in a few ways)
    • tf.constant 支持任意常量,而不仅仅是像 tf.fill 这样的统一标量张量。(tf.constant supports arbitrary constants, not just uniform scalar Tensors like tf.fill.)
    • tf.fill 在图中创建一个在运行时扩展的 Op,因此它可以有效地表示大张量。(tf.fill creates an Op in the graph that is expanded at runtime, so it can efficiently represent large tensors.)
    • 由于 tf.fill 没有嵌入值,它可以产生动态大小的输出。(Since tf.fill does not embed the value, it can produce dynamically sized outputs.)