我正在尝试使用管道来读取图像到CNN中。我使用了string_input_producer()
来获取文件名的队列,但它似乎卡在那里什么也没做。以下是我的代码,请给我一些建议,让它能够正常工作。
def read_image_file(filename_queue, labels): reader = tf.WholeFileReader() key, value = reader.read(filename_queue) image = tf.image.decode_png(value, channels=3) image = tf.cast(image, tf.float32) resized_image = tf.image.resize_images(image, [224, 112]) with tf.Session() as sess: label = getLabel(labels, key.eval()) return resized_image, labeldef input_pipeline(filename_queue, queue_names, batch_size, num_epochs, labels): image, label = read_image_file(filename_queue, labels) min_after_dequeue = 10 * batch_size capacity = 20 * batch_size image_batch, label_batch = tf.train.shuffle_batch( [image, label], batch_size=batch_size, num_threads=1, capacity=capacity, min_after_dequeue=min_after_dequeue) return image_batch, label_batchtrain_queue = tf.train.string_input_producer(trainnames, shuffle=True, num_epochs=epochs)train_batch, train_label = input_pipeline(train_queue, trainnames, batch_size, epochs, labels)prediction = AlexNet(x)#训练with tf.name_scope("cost_function") as scope: cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=train_label, logits=prediction(train_batch))) tf.summary.scalar("cost_function", cost) train_step = tf.train.MomentumOptimizer(learning_rate, 0.9).minimize(cost)#准确率with tf.name_scope("accuracy") as scope: correct_prediction = tf.equal(tf.argmax(prediction,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) tf.summary.scalar("accuracy", accuracy) merged = tf.summary.merge_all()#会话with tf.Session() as sess: print('已启动') sess.run(tf.global_variables_initializer()) coord = tf.train.Coordinator() threads = tf.train.start_queue_runners(sess=sess, coord=coord, start=True) sess.run(threads) try: for step in range(steps_per_epch * epochs): print('步骤: %d' %step) sess.run(train_step) except tf.errors.OutOfRangeError as ex: pass coord.request_stop() coord.join(threads)
回答:
你的代码并不是完全自包含的,因为get_label
方法没有定义。
但很可能你的问题出自read_image_file
方法中的这些行:
with tf.Session() as sess: label = getLabel(labels, key.eval())
key.eval
部分试图从尚未启动的队列中取出一个元素。在你的输入管道定义之前,你不应该创建任何会话(也不应该尝试对key
(和可能的labels
)进行评估)。get_label
方法应该仅对labels
和key
执行张量操作,并返回一个label
张量。
例如,你可以使用这些tensor
字符串操作,这样它们将成为图的一部分。