Tensorflow常量constant

首先要了解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.]]
'''

name:常量名,选填,只要是字符串不重复就行

verify_shape:是否验证value的shape和指定的shape相匹配,默认为false。若设为true,不相符的时候会报错

猜你喜欢

转载自blog.csdn.net/qq_33193309/article/details/99671822