I am trying to build a basic RNN, but I get errors trying to use the network after training.
I hold network architecture in a function inference
This is just speculation until you show us the SimpleRNN
implementation. However, I suspect that SimpleRNN
is very badly implemented. There is a different getween tf.get_variable
and tf.Variable
. I expect your SimpleRNN
to use tf.Variable
.
To reproduce this behaviour:
import tensorflow as tf
def inference(x):
w = tf.Variable(1., name='w')
layer = x + w
return layer
x = 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}))
This gives exactly the same error:
Attempting to use uninitialized value RNN_1/w
However the version with w = tf.get_variable('w', initializer=1.)
instead of w = tf.Variable(1., name='w')
makes it work.
Why? See the docs:
tf.get_variable:
Gets an existing variable with these parameters or create a new one. This function prefixes the name with the current variable scope and performs reuse checks.
edit Thank you for the question (I added the keras flag to your question). This is now becoming my favorite reason to show people why using Keras is the worst decision they ever made.
SimpleRNN creates it variables here:
self.kernel = self.add_weight(shape=(input_shape[-1], self.units),
name='kernel',...)
This executes the line
weight = K.variable(initializer(shape),
dtype=dtype,
name=name,
constraint=constraint)
which ends up here
v = tf.Variable(value, dtype=tf.as_dtype(dtype), name=name)
And this is an obvious flaw in the implementation.
Until Keras uses TensorFlow in the correct way (respecting at least scopes
and variable-collections
), you should look for alternatives. The best advice somebody can give you is to switch to something better like the official tf.layers
.
@Patwie made the correct diagnosis regarding the error — a possible bug in the reference Keras implementation.
However, in my opinion, the logical conclusion is not to dismiss Keras, but to use the Keras implementation that comes with tensorflow, that can be found in tf.keras
. You will find that variables are generated correctly in this implementation. tf.keras
is implemented specifically for tensorflow and should minimize this kind of interfacing error.
In fact, if you are already tensorflow, I don't see any particular benefit in using the reference Keras rather than tf.keras
, unless you are using its very latest features, tf.keras
being typically a bit behind in terms of versions (e.g. currently at 2.1.5 in TF 1.8 wheras Keras 2.2.0 has been out for about a month).