Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Restoring Model in Tensorflow After Changing the Optimizer Paramter

I have trained a model in Tensorflow. During the training process, I was setting a var_list in the optimizer, in other words, I was training a GRU on top of a CNN. Here is the code for the optimizer:

with tf.name_scope('optimizer'):
    update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    with tf.control_dependencies(update_ops):
        optimizer = tf.train.AdamOptimizer(0.0001).minimize(MSE, var_list=gru_output_var_list)

Then, after training, and saving the variables in checkpoints, I was trying to remove the var_list from the optimizer in order to be able to fine tune the whole network, conv layers with GRU. But, that is raising an error:

Key weight_fc_sig/Adam_1 not found in checkpoint

where weight_fc_sig is the name of one of the variables in the model.

I have read through github, and I found that the state of the optimizer is saved as well as variables in the checkpoint. So, I would like to know how to solve this issue, in other words, I need to know how to reset the state of the optimizer.

Any help is much appreciated!!

like image 890
I. A Avatar asked Mar 08 '23 04:03

I. A


1 Answers

To begin with, I build a model in tensorflow, and then I saved the graph, with variables... into a checkpoint through:

saver = tf.train.Saver()
saver.save(sess, model_path + "ckpt")

So when I inspect the list of variables stored through:

from tensorflow.python import pywrap_tensorflow
model_path = 'C:/Users/user/PycharmProjects/TensorflowDifferentProjects/MNIStDataset/tensorlogs/ckpt'
reader = pywrap_tensorflow.NewCheckpointReader(model_path)
var_to_shape_map = reader.get_variable_to_shape_map()

for key in sorted(var_to_shape_map):
    print("tensor_name: ", key)

I got the following list of variables:

tensor_name:  Adam_optimizer/beta1_power
tensor_name:  Adam_optimizer/beta2_power
tensor_name:  conv1/biases
tensor_name:  conv1/biases/Adam
tensor_name:  conv1/biases/Adam_1
tensor_name:  conv1/weights
tensor_name:  conv1/weights/Adam
tensor_name:  conv1/weights/Adam_1
tensor_name:  conv2/biases
tensor_name:  conv2/biases/Adam
tensor_name:  conv2/biases/Adam_1
tensor_name:  conv2/weights
tensor_name:  conv2/weights/Adam
tensor_name:  conv2/weights/Adam_1
tensor_name:  fc1/biases
tensor_name:  fc1/biases/Adam
tensor_name:  fc1/biases/Adam_1
tensor_name:  fc1/weights
tensor_name:  fc1/weights/Adam
tensor_name:  fc1/weights/Adam_1
tensor_name:  fc2/biases
tensor_name:  fc2/biases/Adam
tensor_name:  fc2/biases/Adam_1
tensor_name:  fc2/weights
tensor_name:  fc2/weights/Adam
tensor_name:  fc2/weights/Adam_1

And when I trained the same model another time, but this time, I passed to the saver only the list of the weights and biases as: saver = tf.train.Saver(var_list=lst_vars), and then I printed out the list of weights and biases saved, I got the following list:

tensor_name:  conv1/biases
tensor_name:  conv1/weights
tensor_name:  conv2/biases
tensor_name:  conv2/weights
tensor_name:  fc1/biases
tensor_name:  fc1/weights
tensor_name:  fc2/biases
tensor_name:  fc2/weights

Now, when I tried to run the same model again, but with removing the list of variables to restore, So I have this saver now:

saver = tf.train.Saver(), 

I ran into the following error:

Key fc2/weights/Adam_1 not found in checkpoint.

Therefore, the solution was to mention explicitly the list of variables I need to restore. In other words, even when I only saved the list of weights and biases I need to store, when importing them, I should mention them specifically, so I should say:

saver = tf.train.Saver(var_list=lst_vars) 

where lst_vars is the list of variables I need to restore which is the same as the one printed above.

So in general what happens is that whenever we try to restore the graph, if I didnt mention the list of variables to restore, tensorflow will look and see that there are some variables that are not stored yet, I other words, whenever there is no list, tensorflow assumes that we are trying to restore the whole graph, which is not true. I am only restoring the part responsible for weights and biases. So once this is mentioned, tensorflow will know that I am not initializing the whole graph, but part of it.

Now even if I was truly mentioning the list of variables I need to restore, as follows:

saver = tf.train.Saver(var_list=lst_vars)

This will not cause any problem

Also, I can add/modify the var_list passed to the optimizer, that will not cause any problem as well.

At the same time, even if I passed the list of variables for the optimizer to work on as:

with tf.name_scope('Adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy, var_list=lst_vars[:3])

saver = tf.train.Saver(var_list=lst_vars)

Then I can run the same model another time but without the var_list parameter in the optimizer. So that would be the case with fine tuning.


Now, to go the extra mile, I can modify the model, add maybe more layers, but I should keep in mind, since I have only the following variables stored in the checkpoint:

tensor_name:  conv1/biases
tensor_name:  conv1/weights
tensor_name:  conv2/biases
tensor_name:  conv2/weights
tensor_name:  fc1/biases
tensor_name:  fc1/weights
tensor_name:  fc2/biases
tensor_name:  fc2/weights
    

I should mention to the saver that these are the variables that I am restoring. So I said the following:

saver = tf.train.Saver(var_list=[lst_vars[0], lst_vars[1], lst_vars[2], lst_vars[3],
                             lst_vars[6], lst_vars[7], lst_vars[8], lst_vars[9]])

In this case, there would be no problem and the code will run fine!!! and I can ask the optimizer as well to train the new model, maybe train certain parameters, I mean weights and biases and so on...

Also, note that I can save the whole model as:

saver = tf.train.Saver()

and then restore part of the model (by running the model another time, and pass:

saver = tf.train.Saver(var_list=lst_vars))

Also, I can modify the model and maybe add more conv layer. So I can fine tune the model as long as I mention exactly what variables I am restoring. Ex:

saver = tf.train.Saver(var_list=[lst_vars[0], lst_vars[1], lst_vars[2], lst_vars[3],
                             lst_vars[6], lst_vars[7], lst_vars[8], lst_vars[9]])

all this explanation came because I though there might some problems with the optimizer, and I needed to know how to rest it. An issue was raised on github, exactly on how to rest the optimizer, and that it why I came up with all this conclusion


Here is the code for whomever is interested:

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os


def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial, name=name)


def bias_variable(shape, name):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)


def deepnn(x):
    with tf.name_scope('reshape'):
        x_image = tf.reshape(x, [-1, 28, 28, 1])

    # First convolutional layer, maps one grayscale image to 32 feature maps.
    with tf.name_scope('conv1'):
        w_conv1 = weight_variable([5, 5, 1, 32], name='weights')
        b_conv1 = bias_variable([32], name='biases')
        h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)

    # Pooling layer, downsampling by 2X
    with tf.name_scope('pool1'):
        h_pool1 = max_pool_2x2(h_conv1)

    # Second convolutional layer -- maps 32 feature maps to 64
    with tf.name_scope('conv2'):
        w_conv2 = weight_variable([5, 5, 32, 64], name='weights')
        b_conv2 = bias_variable([64], name='biases')
        h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)

    # Second pooling layer
    with tf.name_scope('pool2'):
        h_pool2 = max_pool_2x2(h_conv2)

    # Fully connected layer 1 -- after 2 round of downsampling, our 28 x 28 image is
    # down to 7 x 7 x 64 feature maps -- maps this to 1024 features.
    with tf.name_scope('fc1'):
        w_fc1 = weight_variable([7 * 7 * 64, 1024], name='weights')
        b_fc1 = bias_variable([1024], name='biases')

        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
        h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)

    # Dropout - control the complexity of the model, prevents co-adaptation of features
    with tf.name_scope('dropout'):
        keep_prob = tf.placeholder(tf.float32)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # Map the 1024 features to 10 classes, one for each digit.
    with tf.name_scope('fc2'):
        w_fc2 = weight_variable([1024, 10], name='weights')
        b_fc2 = bias_variable([10], name='biases')

        y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2

    return y_conv, keep_prob


mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

# Build the graph for the deep net
y_conv, keep_prob = deepnn(x)

with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)

cross_entropy = tf.reduce_mean(cross_entropy)

# Note that this list of variables only include the weights and biases in the model.
lst_vars = []
for v in tf.global_variables():
    lst_vars.append(v)
    print(v.name, '....')

with tf.name_scope('Adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)

accuracy = tf.reduce_mean(correct_prediction)

model_path = 'C:/Users/user/PycharmProjects/TensorflowDifferentProjects/MNIStDataset/tensorlogs/'

saver = tf.train.Saver(var_list=lst_vars)

train_writer = tf.summary.FileWriter(model_path + "EventsFile/")
train_writer.add_graph(tf.get_default_graph())

for v in tf.global_variables():
    print(v.name)

# Note that a session is created within a with block so that it is destroyed
# once the block has been exited.
with tf.Session() as sess:
    print('all variables initialized!!')

    sess.run(tf.global_variables_initializer())

    ckpt = tf.train.get_checkpoint_state(
        os.path.dirname(model_path))
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print('checkpoints are saved!!!')
    else:
        print('No stored checkpoints')

    for i in range(700):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print('step %d, training accuracy %g' % (i, train_accuracy))

        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    save_path = saver.save(sess, model_path + "ckpt")

And the modified model (Where I added another convlolutional layer):

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import os

def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial, name=name)

def bias_variable(shape, name):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)

def deepnn(x):

    with tf.name_scope('reshape'):
        x_image = tf.reshape(x, [-1, 28, 28, 1])

    # First convolutional layer, maps one grayscale image to 32 feature maps.
    with tf.name_scope('conv1'):
        w_conv1 = weight_variable([5, 5, 1, 32], name='weights')
        b_conv1 = bias_variable([32], name='biases')
        h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)

    # Pooling layer, downsampling by 2X
    with tf.name_scope('pool1'):
        h_pool1 = max_pool_2x2(h_conv1)

    # Second convolutional layer -- maps 32 feature maps to 64
    with tf.name_scope('conv2'):
        w_conv2 = weight_variable([5, 5, 32, 64], name='weights')
        b_conv2 = bias_variable([64], name='biases')
        h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2)

    # Second pooling layer
    with tf.name_scope('pool2'):
        h_pool2 = max_pool_2x2(h_conv2)

    with tf.name_scope('conv3'):
        w_conv3 = weight_variable([1, 1, 64, 64], name='weights')
        b_conv3 = bias_variable([64], name='biases')
        h_conv3 = tf.nn.relu(conv2d(h_pool2, w_conv3) + b_conv3)

    # Fully connected layer 1 -- after 2 round of downsampling, our 28 x 28 image is
    # down to 7 x 7 x 64 feature maps -- maps this to 1024 features.
    with tf.name_scope('fc1'):
        w_fc1 = weight_variable([7 * 7 * 64, 1024], name='weights')
        b_fc1 = bias_variable([1024], name='biases')

        h_conv3_flat = tf.reshape(h_conv3, [-1, 7 * 7 * 64])
        h_fc1 = tf.nn.relu(tf.matmul(h_conv3_flat, w_fc1) + b_fc1)

    # Dropout - control the complexity of the model, prevents co-adaptation of features
    with tf.name_scope('dropout'):
        keep_prob = tf.placeholder(tf.float32)
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # Map the 1024 features to 10 classes, one for each digit.
    with tf.name_scope('fc2'):
        w_fc2 = weight_variable([1024, 10], name='weights')
        b_fc2 = bias_variable([10], name='biases')

        y_conv = tf.matmul(h_fc1_drop, w_fc2) + b_fc2

    return y_conv, keep_prob

mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

# Create the model
x = tf.placeholder(tf.float32, [None, 784])

# Define loss and optimizer
y_ = tf.placeholder(tf.float32, [None, 10])

# Build the graph for the deep net
y_conv, keep_prob = deepnn(x)

with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)

cross_entropy = tf.reduce_mean(cross_entropy)

# Note that this list of variables only include the weights and biases in the model.
lst_vars = []
for v in tf.global_variables():
    lst_vars.append(v)
    print(v.name, '....')

with tf.name_scope('Adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.arg_max(y_conv, 1), tf.arg_max(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)

accuracy = tf.reduce_mean(correct_prediction)

model_path = 'C:/Users/user/PycharmProjects/TensorflowDifferentProjects/MNIStDataset/tensorlogs/'

saver = tf.train.Saver(var_list=[lst_vars[0], lst_vars[1], lst_vars[2], lst_vars[3],
                                 lst_vars[6], lst_vars[7], lst_vars[8], lst_vars[9]])

train_writer = tf.summary.FileWriter(model_path + "EventsFile/")
train_writer.add_graph(tf.get_default_graph())

for v in tf.global_variables():
    print(v.name)

# Note that a session is created within a with block so that it is destroyed
# once the block has been exited.
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    print('all variables initialized!!')

    ckpt = tf.train.get_checkpoint_state(
        os.path.dirname(model_path))
    if ckpt and ckpt.model_checkpoint_path:
        saver.restore(sess, ckpt.model_checkpoint_path)
        print('checkpoints are saved!!!')
    else:
        print('No stored checkpoints')

    for i in range(700):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print('step %d, training accuracy %g' % (i, train_accuracy))

        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

    save_path = saver.save(sess, model_path + "ckpt")
like image 126
I. A Avatar answered May 19 '23 16:05

I. A