神经网络训练图片数据集读取方法—TFRecords

神经网络训练图片数据集读取方法—TFRecords(python)

      之前学习过神经网络的建模过程,以及做过一些简单的练习,但是直到最近我要训练自己的数据才意识到我不知道怎么把图片输入到神经网络模型中进行训练。

     我们在学习神经网络的时候,一般都会用MNIST数据集,这是一个经过处理的的数据集,所以怎么训练我们自己的图片数据集呢?

     我想记录学习的过程。

    前期有一部分理论知识,关于tensorflow读取机制我推荐一篇文章,介绍的很详细,也很好理解:https://blog.csdn.net/shenziheng1/article/details/84960746

     我们要先知道一个单词就是tfrecords,tfrecords是一种tensorflow方便快速读取数据的一种二进制文件,frecords文件方便复制和移动,能够很好的利用内存,无需单独标记文件,适用于大量数据的处理。

主要代码介绍:

1.   writer = tf.python_io.TFRecordWriter(path, options=None)

path:TFRecord文件的存放路径;

option:TFRecordOptions对象,定义TFRecord文件保存的压缩格式;

        有三种文件压缩格式可选,分别为TFRecordCompressionType.ZLIB、TFRecordCompressionType.GZIP以及TFRecordCompressionType.NONE,默认为最后一种,即不做任何压缩,定义方法如下:

option = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.ZLIB)

2.   tf.train.Feature 编码封装列表类型和字典类型

          注意:内层用的是tf.train.Feature而外层用的是tf.train.Features。tf.train.Feature是对单一数据编码成单元feature,而tf.train.Features是将包含多个单元feature的字典数据再编码为集成的features。

tf.train.BytesList(value=[value]) # value转化为字符串(二进制)列表

tf.train.FloatList(value=[value]) # value转化为浮点型列表

tf.train.Int64List(value=[value]) # value转化为整型列表

example = tf.train.Example(features=tf.train.Features(feature={
        "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
        'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
    }))  # example对象对label和image数据进行封装

3.使用tf.train.Example将features编码数据封装成特定的PB协议格式

 

下面的程序是如何将我们自己的图片数据集转换成tfrecords格式。

程序:python

#coding:utf-8
#作者:ChenQiDan
import os
import tensorflow as tf
from PIL import Image  # 注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np

cwd = 'F:/pychram_lianxi/'  #图片数据集的位置
classes = {'0','1','2','3'}  # 图片设定 4 类
writer = tf.python_io.TFRecordWriter("./train_data.tfrecords")  # 要生成的文件

for index, name in enumerate(classes):
    class_path = cwd + name + '\\'
    for img_name in os.listdir(class_path):
        img_path = class_path + img_name  # 每一个图片的地址
    img = Image.open(img_path)
    img = img.resize((28, 28)) #图片尺寸
    img_raw = img.tobytes()  # 将图片转化为二进制格式
    example = tf.train.Example(features=tf.train.Features(feature={
        "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
        'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
    }))  # example对象对label和image数据进行封装
    writer.write(example.SerializeToString())  #将example序列化为字符串并写入
writer.close()

            之后你就会发现你的本地文件夹中出现一个*.tfrecords文件。

           我们的图片数据变成tfrecord格式之后,我们的神经网络模型才能进行读取和继续进行以后工作。

ps:大家互相学习,有问题互相讨论,我也在学习阶段,欢迎大家指点!

感慨一下,今天重庆的天气真的太好了,不出去玩太可惜了,劳逸结合的时间到了。

猜你喜欢

转载自blog.csdn.net/qq_41120234/article/details/88394991