变量被重用,即使它的变量范围没有提到reuse=Tru

2024-06-14 19:54:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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])

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

^{pr2}$

我知道_linear()函数用于执行args * W + bias操作。此处重量(W)必须可重复使用。
但是他们在_linear()函数中使用get_variable()函数的方式,我认为每次都会创建一个新的变量。但是{}必须可重用才能使神经网络工作。在

我想知道这里发生了什么。在


Tags: 函数retruegetfootfwith教程
1条回答
网友
1楼 · 发布于 2024-06-14 19:54:00

他们使用以下事实记录here

Note that the reuse flag is inherited: if we open a reusing scope, then all its sub-scopes become reusing as well.

因此,如果您的作用域被嵌入到一个相应地设置重用标志的父作用域中,那么您就全部设置好了。例如:

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创建的。在

相关问题 更多 >