上一次我们学习了张量的变量,在这一次来学习一下张量的常量,因为很多时候需要使用张量常量来初始化变量,并且产生一些常量是固定的初始化值,这样可以减少变量的出错,同时也提供很好的测试数据,比如产生一个正态分布的数据,又或者产生初始化为 0 值,或者 1 值等等。
tf.zeros(shape, dtype=tf.float32, name=None)产生零值常量的张量类。
参数 :
shape: 任何的整数列表对象,或者是 1 维的整数张量。
dtype: 产生元素的类型。
name: 产生元素的名称。
返回值 :
生成一个所有元素都是 0 的张量。
例子:
#python 3.5.3 蔡军生 #http://edu.csdn.net/course/detail/2592 # import tensorflow as tf #创建张量变量 x = tf.zeros([1], dtype=tf.float32) y = tf.zeros([3, 4], tf.int32) #显示它的值 init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(x.eval()) print(y.eval())输出结果:
====================== RESTART: D:/AI/sample/tf_1.17.py ======================
[ 0.] [[0 0 0 0] [0 0 0 0] [0 0 0 0]]>>>
创建两行十列的 0 常量
例子:
#python 3.5.3 蔡军生 #http://edu.csdn.net/course/detail/2592 # import tensorflow as tf #创建张量0常量 x = tf.zeros([2,10], dtype=tf.float32) #显示它的值 init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(x.eval())输出结果如下:
====================== RESTART: D:/AI/sample/tf_1.19.py ======================
[[ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.] [ 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]]>>>
tf.ones(shape, dtype=tf.float32, name=None)创建一个所有元素都为 1 的张量常量。
参数:
shape: 任何整数的列表对象,或者是 1 维的整数( int32 )张量。
dtype: 产生元素的数据类型。
name: 张量的名称。
返回值 :
一个所有元素设置为 1 的张量常量。
例子:
#python 3.5.3 蔡军生 #http://edu.csdn.net/course/detail/2592 # import tensorflow as tf #创建张量常量 x = tf.ones([2,10], dtype=tf.float32) #显示它的值 init_op = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init_op) print(x.eval())输出结果:

1. C++标准模板库从入门到精通 2.跟老菜鸟学C++