Creates a constant tensor.
Aliases:
tf.compat.v2.constant
tf.constant(
value,
dtype=None,
shape=None,
name='Const'
)
Used in the guide:
B
et
te
rp
e
rf
or
ma
nc
ew
i
th
t
f.
fu
nc
ti
on
a
nd
A
ut
oG
ra
ph
E
ag
er
e
xe
cu
ti
on
R
ag
ge
dt
e
ns
or
s``U
se
a
G
PU
U
si
ng
t
he
S
av
ed
Mo
de
lf
o
rm
at
Used in the tutorials:
A
ut
om
at
ic
d
if
fe
re
nt
ia
ti
on
a
nd
g
ra
di
en
tt
a
pe
B
et
te
rp
e
rf
or
ma
nc
ew
i
th
t
f.
fu
nc
ti
on
D
ee
pD
re
am
L
oa
da
p
a
nd
as
.D
at
aF
ra
me
N
eu
ra
ls
t
yl
et
r
an
sf
er
T
FR
ec
or
da
n
dt
f
.E
xa
mp
le
T
ra
ns
fo
rm
er
m
od
el
f
or
l
an
gu
ag
eu
n
de
rs
ta
nd
in
g``U
ni
co
de
s
tr
in
gs
W
or
de
m
be
dd
in
gs
The resulting tensor is populated withvalue
s of typedtype
, as specified by argumentsvalue
and (optionally)shape
(see examples below). The argumentvalue
can be a constantvalue
, or a list ofvalue
s of typedtype
. Ifvalue
is a list, then the length of the list must be less than or equal to the number of elements implied by theshape
argument (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 argumentshape
is optional. If present, it specifies the dimensions of the resulting tensor. If not present, theshape
ofvalue
is used. If the argumentdtype
is 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.constant
supports arbitrary constants, not just uniform scalar Tensors liketf.fill
.tf.constant
creates aConst
node in the computation graph with the exact value at graph construction time. On the other hand,tf.fill
creates an Op in the graph that is expanded at runtime.- Because
tf.constant
only embeds constant values in the graph, it does not support dynamic shapes based on other runtime Tensors, whereastf.fill
does.
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
: Optionalname
for the tensor.
Returns:
A Constant Tensor.
Raises:
TypeError
: if shape is incorrectly specified or unsupported.