Попытка использовать неинициализированное значение InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0b_1x

Я модифицирую сеть Inception V3 (удаляю некоторые модули слоев) и создаю данные поезда 6 классов, по 1 изображению на класс. Когда я выполняю обучение, я получаю сообщение об ошибке

tensorflow.python.framework.errors_impl.FailedPreconditionError: Попытка использовать неинициализированное значение InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0b_1x1 / weights [[Node: InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0b_1x1 / WentOclights / Conv2d_0b_1x1] loc: / Branch_3 / Conv2d_0

Код поезда:

import tensorflow as tf
import inception
import create_record
import numpy as np
import inception_utils
width, height = 299, 299
classes = 6
batch_size = 6
learning_rate = 0.01
max_step = 1
image_dir = '/home/xzy/test/images/'
path = '/home/xzy/test/train.tfrecords'
logs_dir = '/home/xzy/test/logs/'
# %% Training
def train():
    filename_queue = tf.train.string_input_producer([path])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw': tf.FixedLenFeature([], tf.string),
                                       })
    image = tf.decode_raw(features['img_raw'], tf.uint8)
    image = tf.reshape(image, [299, 299, 3])
    label = tf.cast(features['label'], tf.int32)
    image_batch, label_batch = tf.train.batch([image, label],
                                              batch_size=6, num_threads=64, capacity=300)
    label_batch = tf.one_hot(label_batch, depth=classes)
    label_batch = tf.cast(label_batch, dtype=tf.int32)
    label_batch = tf.reshape(label_batch, [batch_size, classes])
    x = tf.placeholder(tf.float32, shape=[batch_size, width, height, 3])
    y_ = tf.placeholder(tf.int16, shape=[batch_size, classes])
    init_op = tf.initialize_all_variables()
    logits = inception.inference(x, num_classes=classes)
    loss = inception.loss(logits, y_)
    my_global_step = tf.Variable(0, name='global_step', trainable=False)
    optimizer = tf.train.GradientDescentOptimizer(learning_rate)
    train_op = optimizer.minimize(loss, global_step=my_global_step)
    saver = tf.train.Saver(tf.global_variables())
    summary_op = tf.summary.merge_all()
    with tf.Session() as sess:
        sess.run(init_op)
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(coord=coord)
        train_summary_writer = tf.summary.FileWriter(logs_dir, sess.graph)
        try:
            for step in np.arange(max_step):
                if coord.should_stop():
                    break
                example, lab = sess.run([image_batch, label_batch])
                example = tf.to_float(example)
                _, train_loss = sess.run([train_op, loss], feed_dict={x: example.eval(), y_: lab})
                if step == 0 or (step + 1) == max_step:
                    print ('Step: %d, loss: %.4f' % (step, train_loss))
                    summary_str = sess.run(summary_op)
                    train_summary_writer.add_summary(summary_str, step)
                    if step % 2000 == 0 or (step + 1) == max_step:
                        checkpoint_path = os.path.join(train_log_dir, 'model.ckpt')
                        saver.save(sess, checkpoint_path, global_step=step)
        except tf.errors.OutOfRangeError:
            print('Done training -- epoch limit reached')
        coord.request_stop()
        coord.join(threads)
        sess.close()
train()

Трассировка стека ошибок:

Отслеживание (последний вызов последний):

Файл "/home/xzy/PycharmProjects/network/train_inception.py", строка 89, в train ()

Файл "/home/xzy/PycharmProjects/network/train_inception.py", строка 71, in train ()
_, train_loss = sessions.run ([train_op, loss], feed_dict = {x: example.eval () , y_: lab})

Файл "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", строка 889, при запуске run_metadata_ptr)

Файл "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", строка 1120, в _run feed_dict_tensor, options, run_metadata)

Файл "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", строка 1317, в параметрах _do_run, run_metadata)

Файл "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", строка 1336, в типе повышения _do_call (e) (node_def, op, message)

tensorflow.python.framework.errors_impl.FailedPreconditionError: Попытка использовать неинициализированное значение InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0b_1x1 / weights [[Node: InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0b_1x1 / WentOclights / Conv2d_0b_1x1] loc: @ InceptionV3 / Mixed_6d / Branch_3 / Conv2d_0

Что случилось? может кто-нибудь дать мне несколько идей, спасибо?

Версия Tensorflow: 1.5.0-dev20171206, python 2.7, Ubuntu 16.04.


person zhiyou    schedule 09.01.2018    source источник
comment
Вы забыли об этом - tensorflow.org/api_docs/python/tf/global_variables_initializer   -  person Maxim    schedule 09.01.2018
comment
@ Maxim.Спасибо за ответ. Я меняю свой код с init_op = tf.initialize_all_variables() на init_op = tf.global_variables_initializer(). Но я получаю аналогичную ошибку. Только различие подсказок ошибок изменяет смещение неинициализированной ошибки от неинициализированной ошибки веса. Деталь Attempting to use uninitialized value InceptionV3/Mixed_6d/Branch_3/Conv2d_0b_1x1/biases   -  person zhiyou    schedule 10.01.2018
comment
Если проблема связана с gcloud, проверьте этот ответ: stackoverflow.com/a/60384189/4137497   -  person tsveti_iko    schedule 25.02.2020


Ответы (1)


Ваш init_op определен слишком рано:

init_op = tf.initialize_all_variables()

# BAD! All the ops below won't get initialized!
logits = inception.inference(x, num_classes=classes)
loss = inception.loss(logits, y_)
my_global_step = tf.Variable(0, name='global_step', trainable=False)
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train_op = optimizer.minimize(loss, global_step=my_global_step)

Решение:

logits = inception.inference(x, num_classes=classes)
loss = inception.loss(logits, y_)
my_global_step = tf.Variable(0, name='global_step', trainable=False)
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train_op = optimizer.minimize(loss, global_step=my_global_step)

# Now it's OK.
init_op = tf.global_variables_initializer()
person Maxim    schedule 10.01.2018
comment
Большое тебе спасибо. Ваше решение хорошее! Теперь это работает. Спасибо - person zhiyou; 10.01.2018