Функция TensorFlow random_shuffle_queue закрыта и имеет недостаточные элементы

Я читаю партию изображений, получая идею здесь от tfrecords (преобразованный этим)

Мои изображения - изображения cifar, [32, 32, 3], и, как вы можете видеть при чтении и прохождении изображений, формы нормальны (batch_size=100)

две наиболее заметные проблемы, указанные в журнале, насколько мне известно,

  • Форма 12228, о которой я не знаю, откуда я это получаю. Все мои тензоры имеют форму [32, 32, 3] или [Нет, 3072].
  • Запуск образца

Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

Как я могу это решить?

Logs:

1- image shape is  TensorShape([Dimension(3072)])
1.1- images batch shape is  TensorShape([Dimension(100), Dimension(3072)])
2- images shape is  TensorShape([Dimension(100), Dimension(3072)])

W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72abc89a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ab9d080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa7285e55a0 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/kernels/queue_ops.cc:79] Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72aadb080 Compute status: Invalid argument: Shape mismatch in tuple component 0. Expected [3072], got [12288]
     [[Node: input/shuffle_batch/random_shuffle_queue_enqueue = QueueEnqueue[Tcomponents=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/sub, input/Cast_1)]]
W tensorflow/core/common_runtime/executor.cc:1027] 0x7fa72ad499a0 Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Traceback (most recent call last):
  File "/Users/HANEL/Documents/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 76, in train
    _, loss_value = sess.run([train_op, loss])
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 345, in run
    results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/client/session.py", line 419, in _do_run
    e.code)
tensorflow.python.framework.errors.OutOfRangeError: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)
     [[Node: input/shuffle_batch = QueueDequeueMany[component_types=[DT_FLOAT, DT_INT32], timeout_ms=-1, _device="/job:localhost/replica:0/task:0/cpu:0"](input/shuffle_batch/random_shuffle_queue, input/shuffle_batch/n)]]
Caused by op u'input/shuffle_batch', defined at:
  File "/Users/HANEL/my_cifar_train.py", line 110, in <module>
    tf.app.run()
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/platform/default/_app.py", line 11, in run
    sys.exit(main(sys.argv))
  File "/Users/HANEL/my_cifar_train.py", line 107, in main
    train()
  File "/Users/HANEL/my_cifar_train.py", line 39, in train
    images, labels = my_input.inputs()
  File "/Users/HANEL/my_input.py", line 157, in inputs
    min_after_dequeue=200)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/input.py", line 453, in shuffle_batch
    return queue.dequeue_many(batch_size, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/data_flow_ops.py", line 245, in dequeue_many
    self._queue_ref, n, self._dtypes, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/gen_data_flow_ops.py", line 319, in _queue_dequeue_many
    timeout_ms=timeout_ms, name=name)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
    op_def=op_def)
  File "/Users
/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
    original_op=self._default_original_op, op_def=op_def)
  File "/Users/HANEL/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 988, in __init__
    self._traceback =

_extract_stack()

Ответ 1

У меня была аналогичная проблема. Копаясь в Интернете, выяснилось, что если вы используете какой-то аргумент num_epochs, вы должны инициализировать все переменные local, поэтому ваш код должен выглядеть следующим образом:

with tf.Session() as sess:
    sess.run(tf.local_variables_initializer())
    sess.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # do your stuff here

    coord.request_stop()
    coord.join(threads)

Если вы разместите еще какой-нибудь код, возможно, я смогу глубже изучить его. Тем временем HTH.

Ответ 2

Чтобы суммировать комментарии,

Compute status: Out of range: RandomSuffleQueue '_2_input/shuffle_batch/random_shuffle_queue' is closed and has insufficient elements (requested 100, current size 0)

был вызван тем, что очередь заканчивается из данных. Это часто объясняется тем, что у вас достаточно данных для N итераций, когда на самом деле у вас достаточно только для M итераций, где M < N.

Одно из предположений для определения того, сколько данных вы действительно имеете, - это подсчет количества раз, когда вы можете читать данные до того, как очередь OutOfRangeError будет выбрана очередью.

Ответ 3

Вероятно, вы неправильно обработали обработанный пример TFRecord. Например. пытаясь изменить тензор на несовместимый размер. Вы можете отлаживать с помощью tf_record_iterator, чтобы подтвердить, что данные, которые вы читаете, хранятся так, как вы думаете:

import tensorflow as tf
import numpy as np

tfrecords_filename = '/path/to/some.tfrecord'
record_iterator = tf.python_io.tf_record_iterator(path=tfrecords_filename)

for string_record in record_iterator:
    # Parse the next example
    example = tf.train.Example()
    example.ParseFromString(string_record)

    # Get the features you stored (change to match your tfrecord writing code)
    height = int(example.features.feature['height']
                                 .int64_list
                                 .value[0])

    width = int(example.features.feature['width']
                                .int64_list
                                .value[0])

    img_string = (example.features.feature['image_raw']
                                  .bytes_list
                                  .value[0])
    # Convert to a numpy array (change dtype to the datatype you stored)
    img_1d = np.fromstring(img_string, dtype=np.float32)
    # Print the image shape; does it match your expectations?
    print(img_1d.shape)

Ответ 4

У меня была точно такая же проблема сегодня, и позже я обнаружил, что это файл входных данных, который я загрузил из "известного набора данных" (например, https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data), которые вызвали ошибку: в конце файла есть несколько пустых строк. Удалите пустые строки, ошибка исчезла!

Ответ 5

Это также может быть вызвано неправильным именем файла tf, которое вообще не существует. Перед выполнением других проверок убедитесь, что у вас есть правильные пути к файлам.

Ответ 6

У меня была такая же проблема, и ни один из предыдущих ответов, казалось, не разрешил ее, поэтому я тоже буду звонить.

Для меня проблема оказалась в списке функций, который я передавал parse_single_example. По какой-либо причине (поскольку я использую float_list?) В моем файле tfrecords мне нужно было указать длину массива в списке моих функций или использовать tf.VarLenFeature, т.е.:

feature_structure = {'features': tf.FixedLenFeature([FEATURE_SIZE], tf.float32),
           'outputs': tf.FixedLenFeature([OUTPUT_SIZE], tf.float32)}
d_features = tf.parse_single_example(serialized_example, features=feature_structure)

Без этого я продолжал получать ошибку "random_shuffle_queue закрыта и имеет недостаточные элементы", о которой я предполагаю, потому что в моем анализируемом примере не было данных.