TensorFlow:varscope.reuse_variables() [英] TensorFlow: varscope.reuse_variables()

查看:98
本文介绍了TensorFlow:varscope.reuse_variables()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在TensorFlow中重用变量?我想重复使用 tf.contrib.layers.linear

How do I reuse variables in TensorFlow? I want to reuse the tf.contrib.layers.linear

with tf.variable_scope("root") as varscope:
    inputs_1 = tf.constant(0.5, shape=[2, 3, 4])
    inputs_2 = tf.constant(0.5, shape=[2, 3, 4])
    outputs_1 = tf.contrib.layers.linear(inputs_1, 5)
    varscope.reuse_variables()
    outputs_2 = tf.contrib.layers.linear(inputs_2, 5)

但这给了我以下结果

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-51-a40b9ec68e25> in <module>()
      5     outputs_1 = tf.contrib.layers.linear(inputs_1, 5)
      6     varscope.reuse_variables()
----> 7     outputs_2 = tf.contrib.layers.linear(inputs_2, 5)
...
ValueError: Variable root/fully_connected_1/weights does not exist, or was not created with tf.get_variable(). Did you mean to set reuse=None in VarScope?


推荐答案

问题是tf.contrib.layers.linear自动使用自己的范围创建一组新的线性层。调用scope.reuse()时,没有什么可重复使用的,因为它们是新变量。

The problem is tf.contrib.layers.linear automatically creates a new set of linear layers with its own scope. When calling scope.reuse() there's nothing to be reused because those are new variables.

尝试执行类似的操作

def function():
  with tf.variable_scope("root") as varscope:
    inputs = tf.constant(0.5, shape=[2, 3, 4])
    outputs = tf.contrib.layers.linear(inputs, 5)
    return outputs

result_1 = function()
tf.get_variable_scope().reuse_variables()
result_2 = function()

sess = tf.InteractiveSession()
sess.run(tf.initialize_all_variables())
a = sess.run(result_1)
b = sess.run(result_2)
np.all(a == b) # ==> True

这篇关于TensorFlow:varscope.reuse_variables()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆