TensorFlow 变量共享

变量共享主要涉及到两个函数: tf.get_variable(<name>, <shape>, <initializer>) 和 tf.variable_scope(<scope_name>)。

为什么要共享变量?

例如如下代码:

复制代码
def my_image_filter(input_images):
    conv1_weights = tf.Variable(tf.random_normal([5, 5, 32, 32]),
        name="conv1_weights")
    conv1_biases = tf.Variable(tf.zeros([32]), name="conv1_biases")
    conv1 = tf.nn.conv2d(input_images, conv1_weights,
        strides=[1, 1, 1, 1], padding='SAME')
    return  tf.nn.relu(conv1 + conv1_biases)
复制代码

有两个变量(Variables)conv1_weighs, conv1_biases和一个操作(Op)conv1,如果你直接调用两次,不会出什么问题,但是会生成两套变量;

# First call creates one set of 2 variables.
result1 = my_image_filter(image1)
# Another set of 2 variables is created in the second call.
result2 = my_image_filter(image2)

如果把 tf.Variable 改成 tf.get_variable,直接调用两次,就会出问题了:

result1 = my_image_filter(image1)
result2 = my_image_filter(image2)
# Raises ValueError(... conv1/weights already exists ...)

为了解决这个问题,TensorFlow 又提出了 tf.variable_scope 函数:它的主要作用是,在一个作用域 scope 内共享一些变量,可以有如下用法:

1)

with tf.variable_scope("image_filters") as scope:
    result1 = my_image_filter(image1)
    scope.reuse_variables() # or 
    #tf.get_variable_scope().reuse_variables()
    result2 = my_image_filter(image2)

tf.get_variable() 是怎么工作?

 v=tf.get_variable(<name>, <shape>, <initializer>)

此调用做了有关作用域的两件事中的其中之一,方法调入 . 总的有两种情况 .

情况 1: 当 tf.get_variable_scope().reuse == False 时,作用域就是 为创建新变量所设置的 .这种情况下,v 将通过 tf.Variable 所提供的形状和数据类型来重新创建 . 创建
变量的全称将会由当前变量作用域名 + 所提供的名字所组成 , 并且还会检查来确保没 有任何变量使用这个全称 . 如果这个全称已经有一个变量使用了,那么方法将会抛出
ValueError 错误 .-----------------------------------------result1= my_image_filter(image1)

情况 2 :当 tf.get_variable_scope().reuse == True 时,作用域是为重 用变量所设置,这种情况下,调用就会搜索一个已经存在的变量,他的全称和当前变量的作用域名
+ 所提供的名字是否相等 . 如果不存在相应的变量,就会抛出 ValueError 错误 . 如果变量找到了,就返回这个变量 .

tf.variable_scope()是怎么工作?

tf.variable_scope(<scope_name>)

变量作用域的主方法带有一个名称,它将会作为前缀用于变量名 , 并且带有一个重用标签来区分以上的两种情况 .当前变量作用域可以用 tf.get_variable_scope() 进行检索并且 reuse 标签可以通过调用 tf.get_variable_scope().reuse_variables() 设置为 True

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章