Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

python - Tensorflow creating new variables despite reuse set to true

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

def inference(inp):
    with tf.name_scope("inference"):
        layer = SimpleRNN(1, activation='sigmoid',   return_sequences=False)(inp)
        layer = Dense(1)(layer)

    return layer 

but everytime i call it, another set of variables gets created despite using the same scope in training:

def train(sess, seq_len=2, epochs=100):
    x_input, y_input = generate_data(seq_len)

    with tf.name_scope('train_input'):
        x = tf.placeholder(tf.float32, (None, seq_len, 1))
        y = tf.placeholder(tf.float32, (None, 1))

    with tf.variable_scope('RNN'):
        output = inference(x)

    with tf.name_scope('training'):
        loss = tf.losses.mean_squared_error(labels=y, predictions=output)
        train_op = tf.train.RMSPropOptimizer(learning_rate=0.1).minimize(loss=loss, global_step=tf.train.get_global_step())

    with sess.as_default():
        sess.run([tf.global_variables_initializer(), tf.local_variables_initializer()])

        for i in tqdm.trange(epochs):
            ls, res, _ = sess.run([loss, output, train_op], feed_dict={x:x_input, y:y_input})
            if i%100==0:
                print(f'{ls}: {res[10]} - {y_input[10]}')
            x_input, y_input = generate_data(seq_len)

and prediction:

def predict_signal(sess, x, seq_len):   
    # Preparing signal (omitted)
    # Predict
    inp = tf.convert_to_tensor(prepared_signal, tf.float32)
    with sess.as_default():
        with tf.variable_scope('RNN', reuse=True) as scope:
            output = inference(inp)
            result = output.eval()

    return result

I have spent couple of hours reading about variables scopes by now, but on running prediction I still get an error Attempting to use uninitialized value RNN_1/inference/simple_rnn_2/kernel, with the number by RNN_1 increasing with each call

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...