|TensorFlow 1 version||View source on GitHub|
Creates a constant tensor.
tf.constant( value, dtype=None, shape=None, name='Const' )
Used in the guide:
- Better performance with tf.function and AutoGraph
- Eager execution
- Ragged tensors
- Use a GPU
- Using the SavedModel format
Used in the tutorials:
- Automatic differentiation and gradient tape
- Better performance with tf.function
- Load a pandas.DataFrame
- Neural style transfer
- TFRecord and tf.Example
- Transformer model for language understanding
- Unicode strings
- Word embeddings
The resulting tensor is populated with values of type
specified by arguments
value and (optionally)
shape (see examples
value can be a constant value, or a list of values of type
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.
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
# Constant 1-D Tensor populated with value list. tensor = tf.constant([1, 2, 3, 4, 5, 6]) => [1 2 3 4 5 6] # Constant 1-D Tensor populated with value list. tensor = tf.constant([1, 2, 3, 4, 5, 6], shape=(2,3)) => [[1 2 3], [4 5 6]] # Constant 2-D tensor populated with scalar value -1. tensor = tf.constant(-1.0, shape=[2, 3]) => [[-1. -1. -1.] [-1. -1. -1.]]
tf.constantsupports arbitrary constants, not just uniform scalar Tensors like
Constnode in the computation graph with the exact value at graph construction time. On the other hand,
tf.fillcreates an Op in the graph that is expanded at runtime.
tf.constantonly embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereas
value: A constant value (or list) of output type
dtype: The type of the elements of the resulting tensor.
shape: Optional dimensions of resulting tensor.
name: Optional name for the tensor.
A Constant Tensor.
TypeError: if shape is incorrectly specified or unsupported.