即使变量范围没有提到reuse = True,也会重用变量

问题描述 投票:1回答:1

Sharing Variable教程中,它说明如何使用函数get_variable()重用以前创建的变量。

with tf.variable_scope("foo"):      # Creation
    v = tf.get_variable("v", [1])

with tf.variable_scope("foo", reuse=True):    # Re-using
    v1 = tf.get_variable("v", [1])

但是在_linear()中实现here函数时,get_variable()函数的用法如下。

with vs.variable_scope(scope) as outer_scope:
    weights = vs.get_variable(
        _WEIGHTS_VARIABLE_NAME, [total_arg_size, output_size],
        dtype=dtype,
        initializer=kernel_initializer)

据我所知,_linear()函数用于做args * W + bias操作。这里权重(W)必须是可重复使用的。 但是在他们在get_variable()函数中使用_linear()函数的方式中,我认为每次都会创建一个新变量。但W必须可以重复使用神经网络才能工作。

我正在寻求了解这里发生的事情。

python tensorflow
1个回答
0
投票

他们使用以下事实记录here

请注意,重用标志是继承的:如果我们打开一个重用范围,那么它的所有子范围也会重用。

因此,如果您的作用域嵌入到相应地设置重用标记的父作用域中,那么您已经完成了设置。例如:

import tensorflow as tf

def get_v():
  with tf.variable_scope("foo"):
      v = tf.get_variable("v", shape=(), initializer=tf.random_normal_initializer())
  return v

with tf.variable_scope("bar"):
  v = get_v()
with tf.variable_scope("bar", reuse=True):
  v1 = get_v()

sess = tf.Session()
sess.run(tf.global_variables_initializer())
sess.run(v)
sess.run(v1) # returns the same value

在本例中,父范围由父类tf.python.layers.Layer创建。

© www.soinside.com 2019 - 2024. All rights reserved.