目录
- 图变量的初始化方法
- 两种定义图变量的方法
- scope如何划分命名空间
- 图变量的复用
- 图变量的种类
1.图变量的初始化方法
对于一般的Python代码,变量的初始化就是变量的定义,向下面这样:
In [1]: x = 3
In [2]: y = 3 * 5
In [3]: y
Out[3]: 15
- 1
- 2
- 3
- 4
如果我们模仿上面的写法来进行TensorFlow编程,就会出现下面的”怪现象”:
In [1]: import tensorflow as tf
In [2]: x = tf.Variable(3, name='x')
In [3]: y = x * 5
In [4]: print(y)
Tensor("mul:0", shape=(), dtype=int32)
- 1
- 2
- 3
- 4
- 5
y的值并不是我们预想中的15,而是一个莫名其妙的输出——”
In [1]: import tensorflow as tf
In [2]: x = tf.Variable(3, name='x')
In [3]: y = x * 5
In [4]: sess = tf.InteractiveSession()
In [5]: sess.run(tf.global_variables_initializer())
In [6]: sess.run(y)
Out[6]: 15
- 1
- 2
- 3
- 4
- 5
- 6
- 7
TensorFlow:变量的定义和初始化是分开的。
所有关于图变量的赋值和计算都要通过tf.Session的run来进行。想要将所有图变量进行集体初始化时应该使用tf.global_variables_initializer。
2.两种定义图变量的方法
tf.Variable
tf.Variable. init ( 初始值(必须), trainable=True, collections=None, validate_shape=True, name=None )虽然有一堆参数,但只有第一个参数initial_value是必需的,用法如下(assign函数用于给图变量赋值):
In [1]: import tensorflow as tf
In [2]: v = tf.Variable(3, trainable=True,name='v')
In [3]: v2 = v.assign(5)
In [4]: sess = tf.InteractiveSession()
In [5]: sess.run(v.initializer)
In [6]: sess.run(v)
Out[6]: 3
In [7]: sess.run(v2)
Out[7]: 5
tf.get_variable
tf.get_variable(name, shape, dtype,initializer) name必须initializer是变量初始化的方式,初始化的方式有以下几种:
tf.constant_initializer:常量初始化函数
tf.random_normal_initializer:正态分布
tf.truncated_normal_initializer:截取的正态分布
tf.random_uniform_initializer:均匀分布
tf.zeros_initializer:全部是0
tf.ones_initializer:全是1
tf.uniform_unit_scaling_initializer:满足均匀分布,但不影响输出数量级的随机值
当使用tf.get_variable定义变量时,如果出现同名的情况将会引起报错
In [1]: import tensorflow as tf
In [2]: with tf.variable_scope('scope'):
...: v1 = tf.get_variable('var', [1])
...: v2 = tf.get_variable('var', [1])
ValueError: Variable scope/var already exists, disallowed. Did you mean to set reuse=True in VarScope? Originally defined at:
- 1
- 2
- 3
- 4
- 5
而对于tf.Variable来说,却可以定义“同名”变量
In [1]: import tensorflow as tf
In [2]: with tf.variable_scope('scope'):
...: v1 = tf.Variable(1, name='var')
...: v2 = tf.Variable(2, name='var')
...:
In [3]: v1.name, v2.name
Out[3]: ('scope/var:0', 'scope/var_1:0')
tf.name_scope
当tf.get_variable遇上tf.name_scope,它定义的变量的最终完整名称将不受这个tf.name_scope的影响,如下:
In [1]: import tensorflow as tf
In [2]: with tf.variable_scope('v_scope'):
...: with tf.name_scope('n_scope'):
...: x = tf.Variable([1], name='x')
...: y = tf.get_variable('x', shape=[1], dtype=tf.int32)
...: z = x + y
...:
In [3]: x.name, y.name, z.name
Out[3]: ('v_scope/n_scope/x:0', 'v_scope/x:0', 'v_scope/n_scope/add:0')