Creates a constant tensor.
Aliases:
tf.compat.v2.constant
tf.constant(
value,
dtype=None,
shape=None,
name='Const'
)
Used in the guide:
Betterperformancewithtf.functionandAutoGraphEagerexecutionRaggedtensors``UseaGPUUsingtheSavedModelformat
Used in the tutorials:
AutomaticdifferentiationandgradienttapeBetterperformancewithtf.functionDeepDreamLoadapandas.DataFrameNeuralstyletransferTFRecordandtf.ExampleTransformermodelforlanguageunderstanding``UnicodestringsWordembeddingsThe resulting tensor is populated withvalues of typedtype, as specified by argumentsvalueand (optionally)shape(see examples below). The argumentvaluecan be a constantvalue, or a list ofvalues of typedtype. Ifvalueis a list, then the length of the list must be less than or equal to the number of elements implied by theshapeargument (if specified). In the case where the list length is less than the number of elements specified byshape, the last element in the list will be used to fill the remaining entries. The argumentshapeis optional. If present, it specifies the dimensions of the resulting tensor. If not present, theshapeofvalueis used. If the argumentdtypeis not specified, then the type is inferred from the type ofvalue.
For example:
# 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.constant differs from tf.fill in a few ways:
tf.constantsupports arbitrary constants, not just uniform scalar Tensors liketf.fill.tf.constantcreates aConstnode 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.- Because
tf.constantonly embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereastf.filldoes.
Args:
value: A constantvalue(or list) of output typedtype.dtype: The type of the elements of the resulting tensor.shape: Optional dimensions of resulting tensor.name: Optionalnamefor the tensor.
Returns:
A Constant Tensor.
Raises:
TypeError: if shape is incorrectly specified or unsupported.