Create fixed tensors
Represent fixed numeric data such as lookup values, masks, coefficients, or small inputs in a TensorFlow computation.
TensorFlow · Function
Creates a TensorFlow tensor from a tensor-like value, optionally choosing its dtype and shape. Python-side values are embedded as constants during graph construction; eager tensors remain immutable.
tf.constant converts a tensor-like value into a TensorFlow tensor. TensorFlow infers the element type unless dtype is supplied, can reshape or broadcast values to a requested shape, and embeds Python-side constant values in graph construction.
tf.constant(value, dtype=None, shape=None, name='Const') -> Union[tf.Operation, ops._EagerTensorBase]| Name | Type | Description |
|---|---|---|
value | tensor-like object | A constant value or list of values of the output type. |
dtype | tf.DType, optional | The element type of the resulting tensor; inferred when omitted. |
shape | TensorShape or sequence of integers, optional | Optional dimensions for the resulting tensor. |
name | string, optional | Optional name for the tensor or graph node. |
A Constant Tensor.
import tensorflow as tf
values = tf.constant([[1, 2], [3, 4]], dtype=tf.float32)
print(values)
print(values.shape)
Creates a 2-by-2 float32 tensor from nested Python lists and prints its value and shape.
Represent fixed numeric data such as lookup values, masks, coefficients, or small inputs in a TensorFlow computation.
Ensure operations receive a predictable element type, such as float32 instead of an inferred integer type.
Build a tensor with repeated scalar contents or a specified multidimensional arrangement.
Embed Python values into a traced or graph-based computation as a Const node.
tf.constant creates a tensor from a tensor-like value. If dtype is omitted, TensorFlow infers it from value; specifying dtype casts the resulting values to that type.
Follow-up: How would you create a mutable parameter? Use tf.Variable rather than tf.constant, because eager tensors are immutable.
shape optionally determines the output dimensions. TensorFlow reshapes the value to that shape, and a scalar is expanded to populate all requested elements.
Follow-up: What should be checked when supplying a non-scalar value and shape? Its element arrangement and size must be compatible with the requested dimensions.
Python constants are embedded in a graph Const node during graph construction. An eager Tensor passed as value is not changed by tf.constant and can transmit gradients.
Follow-up: Why can symbolic tensors cause failure? A symbolic tensor is not a Python-side constant available for embedding when the graph is built.
tf.convert_to_tensortf.Variabletf.filltf.identitytf.Tensor