den folgenden Beispielcode Versuchen Sie Bilder und Etiketten von Ihrem tfrecords zu lesen,
import os
import glob
import tensorflow as tf
from matplotlib import pyplot as plt
def read_and_decode_file(filename_queue):
# Create an instance of tf record reader
reader = tf.TFRecordReader()
# Read the generated filename queue
_, serialized_reader = reader.read(filename_queue)
# extract the features you require from the tfrecord using their corresponding key
# In my example, all images were written with 'image' key
features = tf.parse_single_example(
serialized_reader, features={
'image': tf.FixedLenFeature([], tf.string),
'labels': tf.FixedLenFeature([], tf.int16)
})
# Extract the set of images as shown below
img = features['image']
img_out = tf.image.resize_image_with_crop_or_pad(img, target_height=128, target_width=128)
# Similarly extract the labels, be careful with the type
label = features['labels']
return img_out, label
if __name__ == "__main__":
tf.reset_default_graph()
# Path to your tfrecords
path_to_tf_records = os.getcwd() + '/*.tfrecords'
# Collect all tfrecords present in the records folder using glob
list_of_tfrecords = sorted(glob.glob(path_to_tf_records))
# Generate a tensorflow readable filename queue by supplying it with
# a list of tfrecords, optionally it is recommended to shuffle your data
# before feeding into the network
filename_queue = tf.train.string_input_producer(list_of_tfrecords, shuffle=False)
# Supply the tensorflow generated filename queue to the custom function above
image, label = read_and_decode_file(filename_queue)
# Create a new tf session to read the data
sess = tf.Session()
tf.train.start_queue_runners(sess=sess)
# Arbitrary number of iterations
for i in range(50):
img =sess.run(image)
# Show image
plt.imshow(img)
Jetzt haben Sie auch eine Funktion namens tf.train.shuffle_batch Sie mehrere CPU-Threads erzeugen zu helfen, die diese Funktion ausführen und Bilder und Labels basierend auf der vom Benutzer angegebenen Stapelgröße zurückgeben. Sie müssten simultane Daten- und Trainingspipelines erstellen, damit sie gleichzeitig funktionieren.
Um Ihre zweite Frage zu beantworten, ja Sie können Ihr Modell mit CPU allein trainieren, aber es wäre langsam und könnte mehrere Stunden oder sogar Tage dauern, um anständige Ergebnisse zu erzielen. Entfernen Sie den with tf.device('/gpu:{0}'):
Dekorator vor der Erstellung Ihres Anfangsmodells und Tensorflow würde das Modell auf Ihrer CPU erstellen.
Ich hoffe, diese Erklärung hilft.