TensorFlowのtfrecordsファイルとqueueキューを組み合わせてデータを読み込む方法


TensorFlowのtfrecordsファイルとqueueキューを組み合わせてデータを読み込む方法


自分でデータセットを作ったのですが、読み方がなんとなく読めないので、以下の記事を参考にしてみました.https://blog.csdn.net/julialove102123/article/details/80085871
私のテストファイル:
import os
import tensorflow as tf
from PIL import Image


def read_tfRecord(file_tfRecord):  #  .tfrecords 
    queue = tf.train.string_input_producer([file_tfRecord])
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(queue)
    features = tf.parse_single_example(
        serialized_example,
        features={
            'img_raw': tf.FixedLenFeature([], tf.string),
            'label': tf.FixedLenFeature([], tf.int64)
        }
    )
    image = tf.decode_raw(features['img_raw'], tf.uint8)
    image = tf.reshape(image, [50, 50, 1])
    image = tf.cast(image, tf.float32)
    image = tf.image.per_image_standardization(image)
    label = tf.cast(features['label'], tf.int64)  #  
    return image, label


traindata, trainlabel = read_tfRecord("./tmp_train.tfrecords")
image_batch, label_batch = tf.train.shuffle_batch([traindata, trainlabel],
                        batch_size=100, capacity=2000, min_after_dequeue=1000)

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(sess=sess, coord=coord)
    train_steps = 10

    try:
        while not coord.should_stop():  #  True
            example, label = sess.run([image_batch, label_batch])
            print(example.shape, label)

            train_steps -= 1
            print(train_steps)
            if train_steps <= 0:
                coord.request_stop()  #  

    except tf.errors.OutOfRangeError:
        print('Done training -- epoch limit reached')
    finally:
        # When done, ask the threads to stop.  
        coord.request_stop()
        # And wait for them to actually do it.  
        coord.join(threads)