tf.constant
Stay organized with collections
Save and categorize content based on your preferences.
Creates a constant tensor from a tensor-like object.
tf.constant(
value, dtype=None, shape=None, name='Const'
) -> Union[tf.Operation
, ops._EagerTensorBase]
Used in the notebooks
Used in the guide |
Used in the tutorials |
|
|
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]])>
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.])>
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)>
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)
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
will create tensors on the current device. Inputs which are
already tensors maintain their placements unchanged.
Args |
value
|
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
|
if shape is incorrectly specified or unsupported.
|
ValueError
|
if called on a symbolic tensor.
|
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates. Some content is licensed under the numpy license.
Last updated 2024-04-26 UTC.
[null,null,["Last updated 2024-04-26 UTC."],[],[],null,["# tf.constant\n\n\u003cbr /\u003e\n\n|-------------------------------------------------------------------------------------------------------------------------------------|\n| [View source on GitHub](https://github.com/tensorflow/tensorflow/blob/v2.16.1/tensorflow/python/framework/constant_op.py#L177-L277) |\n\nCreates a constant tensor from a tensor-like object. \n\n tf.constant(\n value, dtype=None, shape=None, name='Const'\n ) -\u003e Union[../tf/Operation, ops._EagerTensorBase]\n\n### Used in the notebooks\n\n| Used in the guide | Used in the tutorials |\n|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| - [Better performance with tf.function](https://www.tensorflow.org/guide/function) - [TF-NumPy Type Promotion](https://www.tensorflow.org/guide/tf_numpy_type_promotion) - [Introduction to Tensors](https://www.tensorflow.org/guide/tensor) - [Introduction to graphs and tf.function](https://www.tensorflow.org/guide/intro_to_graphs) - [Migrate \\`tf.feature_column\\`s to Keras preprocessing layers](https://www.tensorflow.org/guide/migrate/migrating_feature_columns) | - [DeepDream](https://www.tensorflow.org/tutorials/generative/deepdream) - [Load text](https://www.tensorflow.org/tutorials/load_data/text) - [Playing CartPole with the Actor-Critic method](https://www.tensorflow.org/tutorials/reinforcement_learning/actor_critic) - [Neural style transfer](https://www.tensorflow.org/tutorials/generative/style_transfer) - [Custom training loop with Keras and MultiWorkerMirroredStrategy](https://www.tensorflow.org/tutorials/distribute/multi_worker_with_ctl) |\n\n| **Note:** All eager [`tf.Tensor`](../tf/Tensor) values are immutable (in contrast to [`tf.Variable`](../tf/Variable)). There is nothing especially *constant* about the value returned from [`tf.constant`](../tf/constant). This function is not fundamentally different from [`tf.convert_to_tensor`](../tf/convert_to_tensor). The name [`tf.constant`](../tf/constant) comes from the `value` being embedded in a `Const` node in the [`tf.Graph`](../tf/Graph). [`tf.constant`](../tf/constant) is useful for asserting that the value can be embedded that way.\n\nIf the argument `dtype` is not specified, then the type is inferred from\nthe type of `value`. \n\n # Constant 1-D Tensor from a python list.\n tf.constant([1, 2, 3, 4, 5, 6])\n \u003ctf.Tensor: shape=(6,), dtype=int32,\n numpy=array([1, 2, 3, 4, 5, 6], dtype=int32)\u003e\n # Or a numpy array\n a = np.array([[1, 2, 3], [4, 5, 6]])\n tf.constant(a)\n \u003ctf.Tensor: shape=(2, 3), dtype=int64, numpy=\n array([[1, 2, 3],\n [4, 5, 6]])\u003e\n\nIf `dtype` is specified, the resulting tensor values are cast to the requested\n`dtype`. \n\n tf.constant([1, 2, 3, 4, 5, 6], dtype=tf.float64)\n \u003ctf.Tensor: shape=(6,), dtype=float64,\n numpy=array([1., 2., 3., 4., 5., 6.])\u003e\n\nIf `shape` is set, the `value` is reshaped to match. Scalars are expanded to\nfill the `shape`: \n\n tf.constant(0, shape=(2, 3))\n \u003ctf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[0, 0, 0],\n [0, 0, 0]], dtype=int32)\u003e\n tf.constant([1, 2, 3, 4, 5, 6], shape=[2, 3])\n \u003ctf.Tensor: shape=(2, 3), dtype=int32, numpy=\n array([[1, 2, 3],\n [4, 5, 6]], dtype=int32)\u003e\n\n[`tf.constant`](../tf/constant) has no effect if an eager Tensor is passed as the `value`, it\neven transmits gradients: \n\n v = tf.Variable([0.0])\n with tf.GradientTape() as g:\n loss = tf.constant(v + v)\n g.gradient(loss, v).numpy()\n array([2.], dtype=float32)\n\nBut, since [`tf.constant`](../tf/constant) embeds the value in the [`tf.Graph`](../tf/Graph) this fails for\nsymbolic tensors: \n\n with tf.compat.v1.Graph().as_default():\n i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32)\n t = tf.constant(i)\n Traceback (most recent call last):\n\n TypeError: ...\n\n[`tf.constant`](../tf/constant) will create tensors on the current device. Inputs which are\nalready tensors maintain their placements unchanged.\n\n#### Related Ops:\n\n- [`tf.convert_to_tensor`](../tf/convert_to_tensor) is similar but:\n\n - It has no `shape` argument.\n - Symbolic tensors are allowed to pass through.\n\n with tf.compat.v1.Graph().as_default():\n i = tf.compat.v1.placeholder(shape=[None, None], dtype=tf.float32)\n t = tf.convert_to_tensor(i)\n \n- [`tf.fill`](../tf/fill): differs in a few ways:\n\n - [`tf.constant`](../tf/constant) supports arbitrary constants, not just uniform scalar Tensors like [`tf.fill`](../tf/fill).\n - [`tf.fill`](../tf/fill) creates an Op in the graph that is expanded at runtime, so it can efficiently represent large tensors.\n - Since [`tf.fill`](../tf/fill) does not embed the value, it can produce dynamically sized outputs.\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Args ---- ||\n|---------|----------------------------------------------------|\n| `value` | A constant value (or list) of output type `dtype`. |\n| `dtype` | The type of the elements of the resulting tensor. |\n| `shape` | Optional dimensions of resulting tensor. |\n| `name` | Optional name for the tensor. |\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Returns ------- ||\n|---|---|\n| A Constant Tensor. ||\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n\u003cbr /\u003e\n\n| Raises ------ ||\n|--------------|---------------------------------------------------|\n| `TypeError` | if shape is incorrectly specified or unsupported. |\n| `ValueError` | if called on a symbolic tensor. |\n\n\u003cbr /\u003e"]]