首先要了解constant的元素
constant(
value,
dtype=None,
shape=None,
name='Const',
verify_shape=False
)
参数说明:
value:这个必须填写,可以是一个值也可以是一个列表
对于一个值
num = tf.constant(1)
如果想查看num的值,需要创建一个会话,由会话去启动。会话的创建在使用之后需要释放资源,可以用with代码块来自动完成关闭动作。
num = tf.constant(1)
with tf.Session() as sess:
print(sess.run(num))
对于一个列表
list = tf.constant([2, 3, 4])
with tf.Session() as sess:
print(sess.run(list)) # [2 3 4]
dtype:选填。如果不填默认类型为value的类型,传入参数为(float32,float64....)
list = tf.constant([2, 3, 4], dtype=tf.float32)
with tf.Session() as sess:
print(sess.run(list)) # [2. 3. 4.]
注意这时候的输出,变成了[2. 3. 4.],因为将类型改为了float32
shape:选填。如果不填默认为value的shape,在设置shape的时候不得比value的shape小(大小就是shape各维度的乘积),可以更高。如果shape的设置高于value的shape,多余的部分会用value的最后一个元素填充
list = tf.constant([2, 3], dtype=tf.float32, shape=[3, 3])
with tf.Session() as sess:
print(sess.run(list))
'''
[[2. 3. 3.]
[3. 3. 3.]
[3. 3. 3.]]
'''