这只是猜测,直到您向我们展示
SimpleRNN实现方案为止。但是,我怀疑这
SimpleRNN是很不好实现的。有一个不同的getween
tf.get_variable和
tf.Variable。我希望您
SimpleRNN能使用
tf.Variable。
要重现此行为:
import tensorflow as tfdef inference(x): w = tf.Variable(1., name='w') layer = x + w return layerx = tf.placeholder(tf.float32)with tf.variable_scope('RNN'): output = inference(x)with tf.Session() as sess: sess.run(tf.global_variables_initializer()) print(sess.run(output, {x: 10})) with sess.as_default(): with tf.variable_scope('RNN', reuse=True): output2 = inference(x) print(sess.run(output2, {x: 10}))这给出了完全相同的错误:
尝试使用未初始化的值RNN_1 / w
但是,带有
w = tf.get_variable('w', initializer=1.)而不是的版本w = tf.Variable(1.,name='w')可以正常工作。
为什么?参见文档:
tf.get_variable:
使用这些参数获取现有变量或创建一个新变量。此函数在名称前加上当前变量作用域,并执行 重用检查 。
编辑 谢谢您的问题(我在您的问题中添加了keras标志)。现在,这正成为我最喜欢的向人们展示为什么使用Keras是他们做出的最糟糕决定的原因。
SimpleRNN在此处创建变量:
self.kernel = self.add_weight(shape=(input_shape[-1], self.units), name='kernel',...)
这执行行
weight = K.variable(initializer(shape), dtype=dtype, name=name, constraint=constraint)
它在这里结束了
v = tf.Variable(value, dtype=tf.as_dtype(dtype), name=name)
这是实施中的明显缺陷。在Keras以正确的方式使用TensorFlow之前(至少尊重
scopesand
variable-collections),您应该寻找替代方案。最好的建议是改用像官员这样的东西
tf.layers。



