TensorFlow基础篇(二)——tf.get_variable()和tf.get_variable_scope()

1、tf.get_variable()


tf.get_variable()用来创建变量时,和tf.Variable()函数的功能基本等价。

v = tf.get_variable("v", shape=[1], initializer=tf.ones_initializer(1.0))
v = tf.Variable(tf.constant(1.0, shape=[1]), name="v")


tf.get_variable函数调用时提供的维度(shape)信息以及初始化方法(initializer)的参数和tf.Variable函数调用时提供的初始化过程中的参数类似。

tf.get_variable函数与tf.Variable函数最大的区别在于指定变量名称的参数。对于tf.Variable函数,函数名称是一个可选的参数,通过name=“v”的形式给出。但是对于tf.get_variable函数,变量名称是一个必填的参数。

tf.get_variable只能创建新的参数,如果创建的参数已经存在,则会报错。如果想要通过tf.get_variable函数获取一个已经创建的变量,需要通过tf.variable_scope函数来生成一个上下文管理器,并明确指定在这个上下文管理器中,tf.get_variable将直接获取已经生成的变量。

2、tf.variable_scope()


tf.variable_scope可以控制tf.get_variable函数的语义。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import tensorflow as tf
 
# 在名字为foo的命名空间内创建名字为v的变量
with tf.variable_scope("foo"):
    v = tf.get_variable('v', [1], initializer=tf.constant_initializer(1.0))
 
# 因为在命名空间foo已经存在名为v的变量,所以以下代码将会报错:
# Variable foo/v already exists, disallowed. Did you mean tu set reuse=True in Varscope?
with tf.variable_scope("foo"):
    v = tf.get_variable('v', [1])
 
# 在生成上下文管理器时,将参数reuse设置为True。这样tf.get_variable函数将直接获取已经声明的变量
with tf.variable_scope("foo", reuse=True):
    v1 = tf.get_variable('v', [1], initializer=tf.constant_initializer(1.0))
    print(v == v1)     # 输出为True,代表v,v1代表的是相同的TensorFlow中变量
 
#  将参数reuse设置为True时,tf.variable_scope将只能获取已经创建过的变量。因为在命名空间bar中还没有v变量,
# 所以以下代码会报错:
# Variable bar/v dose not exist, disallowed. Did you mean tu set reuse=None in Varscope?
with tf.variable_scope("bar", reuse=True):
    v = tf.get_variable('v', [1])


上边例子说明当tf.variable_scope函数使用参数reuse=True生成上下文管理器时,这个上下文管理器内所有的tf.get_variable函数会直接获取已经创建的变量。如果变量不存在,则tf.get_variable函数将会报错;

相反,如果tf.variable_scope函数使用参数reuse=None或reuse=False创建上下文管理器,tf.get_variable操作将创建新的变量。如果同名的变量已经存在,则会报错。

3、tf.variable_scope() 函数嵌套


TensorFlow中tf.variable_scope函数是可以嵌套的,下边的程序来说明当tf.variable_scope函数嵌套时,reuse参数的取值是如何确定的。

import tensorflow as tf
 
with tf.variable_scope("root"):
    # 可以通过tf.get_variable_scope().reuse函数来获取当前上下文管理器中reuse参数的取值
    print(tf.get_variable_scope().reuse)  # 输出False,即最外层reuse是False
 
    with tf.variable_scope("foo", reuse=True):  #新建一个嵌套的上下文管理器,并指定reuse为True
        print(tf.get_variable_scope().reuse)  # 输出True
 
        with tf.variable_scope("bar"):   # 新建一个嵌套的上下文管理器,不指定reuse,这时reuse的取值与外面一层保持一致
            print(tf.get_variable_scope().reuse)  # 输出True
 
    print(tf.get_variable_scope().reuse)  # 输出False。5退出reuse设置为True的上下文管理器之后,reuse的值又回到了False


 

发布了352 篇原创文章 · 获赞 115 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/Aidam_Bo/article/details/103189695
今日推荐