使用Tensorflow在我自己的图像数据集上进行训练

时间:2016-12-21 18:48:40

标签: tensorflow

我有一些代码,我基本上是从网上不同的地方拼凑而成的,我老实说不确定到底发生了什么。

import tensorflow as tf


filename_queue = tf.train.string_input_producer(
    tf.train.match_filenames_once("/testimages/*.jpg"), name="filename_queue")

image_reader = tf.WholeFileReader(name="image_reader")

image_name, image_file = image_reader.read(filename_queue)

image = tf.image.decode_jpeg(image_file, channels=3)
batch_size=10

#resize the image
image = tf.image.resize_image_with_crop_or_pad(image, 128, 128)
image.set_shape((128, 128, 3))

# Generate batch
num_preprocess_threads = 1
min_queue_examples = 10
images = tf.train.shuffle_batch(
    [image],
    batch_size=batch_size,
    num_threads=num_preprocess_threads,
    capacity=min_queue_examples + 3 * batch_size,
    min_after_dequeue=min_queue_examples,
    name="images")
print_images = tf.Print(images.get_shape(),[images])
print(images.get_shape())

# Start a new session to show example output.
with tf.Session() as sess:
    summary_writer = tf.summary.FileWriter('/logdir', sess.graph)
    # Required to get the filename matching to run.
    tf.global_variables_initializer().run()

    # Coordinate the loading of image files.
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)

    # Get an image tensor and print its value.
    for x in range(20):
        print(x)
        image_tensor= sess.run(images)
        sess.run(print_images)

    # Finish off the filename queue coordinator.
    coord.request_stop()
    coord.join(threads)

我的问题是,当我呼叫sess.run(images)时,for循环中发生了什么?它是否排队一批10张图片?当我这样做20次会发生什么?我在目录中只有100个图像,但它似乎仍然有效?我应该在这里使用for循环吗?另外,我现在如何使用这些图像训练模型?我为听起来如此困惑而道歉。我一直试图通过查看其他问题和教程来解决这个问题。

谢谢!

1 个答案:

答案 0 :(得分:1)

  

当我调用sess.run(图像)时for循环中发生了什么?

当你运行一堆TensorFlow函数时,实际上一开始并没有计算任何东西。你真的在设置一个计算图。当你将某些东西传递给sess.run时,那就是当你的东西实际被计算出来的时候。也许您可以将TensorFlow函数视为自己的语言,并将sess.run视为其解释器。

  

是否排队一批10张图片?当我这样做20次会发生什么?我在目录中只有100个图像,但它似乎仍然有效?我应该在这里使用for循环吗?

这些代码都没有必要来训练任何东西 - 这是你自己可以做的设置。到目前为止,我自己加载的图像效果很好。

  

另外,我现在如何使用这些图像训练模型?

这取决于你想要训练它做什么。一般来说,你会做这样的事情:用变量和损失函数定义一些计算图,使用tf.train.AdamOptimizer之类的东西自动调整变量的值,使你的损失函数(衡量你做得多好)倒下了。

  

我为听起来如此困惑而道歉。我一直试图通过查看其他问题和教程来解决这个问题。

不用担心!在开始使用TensorFlow之前,您可能希望找到一些入门机器学习课程或书籍来解决这个问题。 This tutorial可能是了解TensorFlow的好地方。