Variable与命名空间scope

参考文档: http://www.cnblogs.com/studyDetail/p/6576017.html


1. 变量声明方式:

tensorflow中有两种声明变量的方式,tf.get_variable()和 `tf.Variable()

  • tf.Variable用于创建一个新变量,在同一个name_scope下面,可以创建相同名字的变量,底层实现会自动引入别名机制,两次调用产生了其实是两个不同的变量。

  • tf.get_variable用于获取一个变量,并且不受name_scope的约束。当这个变量已经存在时,则自动获取;如果不存在,则自动创建一个变量。

variable_scope情况下如果没有将shape=[1]传入,则会报错。

name_scope默认


Variable与命名空间scope_第1张图片
image.png
Variable与命名空间scope_第2张图片
image.png
生成一个2*3的矩阵,矩阵中的元素均值是0,标准差为2的随机数。
weights = tf.Variable(tf.random_normal([2,3],seed=1,mean=4,stddev=2))
# mean 平均数,stddev是方差,random_normal生成随机矩阵

with tf.Session() as sess:
    #不要忘记了初始化
    sess.run(tf.initialize_all_variables())
    print(sess.run(weights))
生成常数:
weights=tf.ones([2,3])
weights=tf.zeros([2,3])
Variable与命名空间scope_第3张图片
image.png
生成给定数字的数组:
tf.fill([2,3],9)
Variable与命名空间scope_第4张图片
image.png
想单独初始化向量可以:
sess.run(weights.initializer)

打印所有变量:tf.global_variables

Variable与命名空间scope_第5张图片
image.png


2. 变量作用域:

name_scope对于tf.get_variable()无效,只在tf.Variable()中起作用

name_scope 作用于操作,variable_scope 可以通过设置reuse 标志以及初始化方式来影响域下的变量。

with tf.variable_scope("variable的作用域,不申明就是空",reuse=True):
     print(sess.run(tf.get_variable("v")))
Variable与命名空间scope_第6张图片
image.png

  1. name_scope()

使用tf.Variable()这种方式创建变量时,首先会检查是否有此时要创建的变量name,如果存在则自动分配一个不同的变量name。

name_scope模式不利于共享变量。
Variable与命名空间scope_第7张图片
image.png
  1. variable_scope()

variable_scope对于tf.get_variable()和tf.Variable()都起作用

要共享变量,需要使用tf.variable_scope()
Variable与命名空间scope_第8张图片
image.png

你可能感兴趣的:(Variable与命名空间scope)