1.placeholder 机制
网络的输入数据是一个矩阵,我们把多个这样的矩阵数据打包成一个很大的数据集,如果将这个数据集当作变量或常量一下子输入到网络中,那么就需要定义很多的网络输入常量,于是计算图上将会涌现大量的输入节点。这是不利的,这些节点的利用率很低。
placehoder 机制被设计用来解决这个问题。编程时只需要将数据通过 placeholder 传入 TensorFlow 计算图即可。
1 2 3 4 5 6 7 8 9
| import tensorflow as tf a = tf.placeholder(tf.float32,shape=(2),name="input") b = tf.placeholder(tf.float32,shape=(2),name="input") result = a+b
with tf.Session() as sess : sess.run(result,feed_dict={a:[1.0,2.0],b:[3.0,4.0]}) print(result) #输出[4.,6.]
|
在 placeholder 定义时,这个位置上的数据类型dtype
是需要指定且不可以改变的。 placeholder 中数据的维度信息shape
可以根据提供的数据推导得出,所以不一定要给出;或者对于不确定的维度,填入None
即可。
这里输入a
和b
定义为常量,这里将它们定义为一个tf.placeholder()
,在运行会话时需要通过sess.run()
函数的feed_dict
来提供a
和b
的取值。feed_dict
是一个字典dict
,在字典中需要给出每个用到的placeholder
的取值。
2.Varibale变量
1 2 3 4 5
| tf.Variable(initial_value, trainable=True, collections=None, validate_shape=True, name=None)
|
参数名称 |
参数类型 |
含义 |
initial_value |
所有可以转换为Tensor的类型 |
变量的初始值,一般是随机生成函数的值 |
trainable |
bool |
是否加入到GraphKeys.TRAINABLE_VARIABLES 被迭代优化 |
collections |
list |
指定该图变量的类型、默认为GraphKeys.GLOBAL_VARIABLES |
validate_shape |
bool |
是否进行类型和维度检查 |
name |
string |
变量的名称,如果没有指定则系统会自动分配一个唯一的值 |
1 2 3
| init = tf.global_variables_initializer() with tf.Session() as sess: sess.run(init)
|
1 2
| with tf.variable_scope("one") : a = tf.get_variable ("a",shape=[1],initializer=tf.constant_initializer(1.0))
|
- 以上代码在名为
one
的变量空间内创建名字为a
的变量;
- 因为
tf.variable_scope("one")
的参数默认reuse=False
,所以在one
这个变量空间内不能在创建名字为a
的变量;
- 若
reuse=True
则get_variable()
函数会直接获取name
属性相同的己经创建的变量,获取的变量没创建过则会报错(区别于指定initializer时为创建新变量)