深度学习Tensor flow 学习回忆(二)

深度学习Tensor flow 学习回忆(二)

关于Tensorflow中的另一种变量使用方式。

所应该掌握的有 :

  • 学会 tf.get_variable 和 tf.variable_scope的使用

  • 1.了解scope划分空间的意义
      Tensorflow 可以通过获取一个变量的名字(name)属性,来获得或者创建这个变量,

一、创建和获取变量

所用方式为: tf.get_variable() 和tf.variable_scope()

用法:  
v2 = tf.get_variable('asv',shape=[3,3],
					  initializer=tf.constant_initializer(1.0))
v1 = tf.Variable(tf.constant(1.0,shape=[3,3],name='asv'))
Out[31]:
array([[ 1.,  1.,  1.],
       [ 1.,  1.,  1.],
       [ 1.,  1.,  1.]], dtype=float32)

以上两句的定义是一样的,创建了一个name=“asv”的变量
但是如果,在定义完之后,接着利用get_variable() 来定义另一个名字为asv的变量,那么会报错。
所以,为了利用get_variable 的获取功能,需要利用scope划分一个空间进行,生成一个上下文管理器,具体实现如下:

In [50]:
with tf.variable_scope("foo"):
	#创建 name为V1的变量。
    v = tf.get_variable("V1",[3,2],initializer=tf.random_normal_initializer(3,2))​
In [51]:
with tf.variable_scope("foo",reuse=True):
	# 获取name为V1的变量
    temp = tf.get_variable("V1",[3,2])
    with tf.Session() as se :
        se.run(temp.initializer)
        print(se.run(temp))
Out[51]: 
[[-0.02469587  4.02479935]
 [ 5.24179077  4.22152519]
 [ 0.24870992  2.37303066]]
  • tf.get_variable(name,shape,initializer = 定义的类型(随机、常数等))
  • with tf.variable_scope(name,reuse):
  • 只有设置scope中的reuse =True时,才可以在该空间里,获取已经定义过的变量

二、scope的属性特点

猜你喜欢

转载自blog.csdn.net/qq_41780650/article/details/83155140
今日推荐