gpt4 book ai didi

TensorFlow:varscope.reuse_variables()

转载 作者:行者123 更新时间:2023-12-02 04:55:15 27 4
gpt4 key购买 nike

如何在 TensorFlow 中重用变量?我想重用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()时,没有什么可以重用的,因为这些是新变量。

尝试做这样的事情

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(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40536665/

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