gpt4 book ai didi

Tensorflow - tf.variable_scope,GAN 的重用参数

转载 作者:行者123 更新时间:2023-11-30 09:28:37 25 4
gpt4 key购买 nike

我正在尝试为一个项目构建一个 GAN,我真的很想了解 tensorflow 的变量范围中的变量共享是如何工作的。

为了构建 GAN,我有一个生成器网络和两个鉴别器网络:一个鉴别器接受真实图像,而一个鉴别器接受由生成器创建的假图像。重要的是,输入真实图像的鉴别器和输入假图像的鉴别器需要共享相同的权重。为了做到这一点,我需要共享权重。

我有一个鉴别器和生成器定义,可以说:

def discriminator(images, reuse=False):
with variable_scope("discriminator", reuse=reuse):

#.... layer definitions, not important here
#....
logits = tf.layers.dense(X, 1)
logits = tf.identity(logits, name="logits")
out = tf.sigmoid(logits, name="out")
# 14x14x64
return logits, out

def generator(input_z, reuse=False):
with variable_scope("generator", reuse=reuse):

#.. not so important
out = tf.tanh(logits)

return out

现在生成器和鉴别器函数被调用:

g_model = generator(input_z)
d_model_real, d_logits_real = discriminator(input_real)

#Here , reuse=True should produce the weight sharing between d_model_real, d_logits_real
#and d_model_fake and d_logits_fake.. why?
d_model_fake, d_logits_fake = discriminator(g_model, reuse=True)

为什么第二次调用中的reuse=True语句会产生权重共享?据我了解,您需要决定在第一次调用中重用变量,以便您可以在程序稍后的某个地方使用它们。

如果有人可以向我解释这一点,我会非常高兴,我没有找到这个主题的良好来源,而且对我来说这似乎非常令人困惑和复杂。谢谢!

最佳答案

在底层,变量是使用tf.get_variable()创建的。

该函数将在变量名前加上作用域前缀,并在创建新变量之前检查它是否存在。

例如,如果您在 "fc" 范围内并调用 tf.get_variable("w", [10,10]),则变量名称将为“fc/w:0”

现在,当您第二次执行此操作时,如果reuse=True,范围将再次为"fc",并且 get_variable 将重用变量"fc/w:0".

但是如果reuse=False,你会得到一个错误,因为变量"fc/w:0"已经存在,提示你使用不同的名称或者使用reuse=True

示例:

In [1]: import tensorflow as tf

In [2]: with tf.variable_scope("fc"):
...: v = tf.get_variable("w", [10,10])
...:

In [3]: v
Out[3]: <tf.Variable 'fc/w:0' shape=(10, 10) dtype=float32_ref>

In [4]: with tf.variable_scope("fc"):
...: v = tf.get_variable("w", [10,10])
...:
ValueError: Variable fc/w already exists, disallowed. Did you mean to set reuse=True or reuse=tf.AUTO_REUSE in VarScope?

In [5]: with tf.variable_scope("fc", reuse=True):
...: v = tf.get_variable("w", [10,10])
...:

In [6]: v
Out[6]: <tf.Variable 'fc/w:0' shape=(10, 10) dtype=float32_ref>

请注意,您可以仅实例化一个鉴别器,而不是共享权重。然后,您可以决定向其提供真实数据或使用 placeholder_with_default 生成的数据。

关于Tensorflow - tf.variable_scope,GAN 的重用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50991363/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com