TensorFlow数据读取

在官方给出的文档中,提到了三种数据读取方式:

  1. 供给数据(Feeding): 在TensorFlow程序运行的每一步, 让Python代码来供给数据。
  2. 从文件读取数据: 在TensorFlow图的起始, 让一个输入管线从文件中读取数据。
  3. 预加载数据: 在TensorFlow图中定义常量或变量来保存所有数据(仅适用于数据量比较小的情况)。

第一种方法是通过placeholeder创建变量,然后在运行是通过feed来把变量传进去,这个方法比较麻烦。

第三种方法是在运行前读取数据集中所有的数据存储到内存中,数据集很小的时候才可以使用,否则会占用大量内存

因此一般使用第二种方法,通过pipeline从文件中读取数据。详细介绍一下这种方法。

标准的tensorflow数据格式是TFRecords,这是一种二进制文件。图像信息与标签信息存在同一个文件里,不需要单独的存储标签。TFRecords文件包含了tf.train.Example 协议内存块(protocol buffer)(协议内存块包含了字段 Features)。

生成TFRecords文件:将数据填入到Example协议内存块(protocol buffer),将协议内存块序列化为一个字符串, 并且通过tf.python_io.TFRecordWriterclass写入到TFRecords文件。

从TFRecords文件中读取数据:可以使用tf.TFRecordReadertf.parse_single_example解析器。这个parse_single_example操作可以将Example协议内存块(protocol buffer)解析为张量。
下面来看一个例子:
此处我加载的数据目录如下:

1— 000001.jpg 
 000002.jpg 
 000003.jpg 
 000004.jpg 
 000005.jpg 
 2— 000006.jpg 
 000007.jpg 
 000008.jpg 
 000009.jpg 
 000010.jpg 
 3—- 
 ············ 
 4—-

1,2,3为文件夹名,也代表着图片所属类别。

import tensorflow as tf
import numpy as np
from PIL import Image

import os

cwd = os.getcwd()


root = cwd+"/data/my_data"

TFwriter = tf.python_io.TFRecordWriter("./data/xxxxTF.tfrecords")

for className in os.listdir(root):

    label = int(className[0])
    classPath = root+"/"+className+"/"
    for parent, dirnames, filenames in os.walk(classPath):
        for filename in filenames:
            imgPath = classPath+"/"+filename
            print (imgPath)
            img = Image.open(imgPath)
            print (img.size,img.mode)
            imgRaw = img.tobytes()
            example = tf.train.Example(features=tf.train.Features(feature={
                "label":tf.train.Feature(int64_list = tf.train.Int64List(value=[label])),
                "img_raw":tf.train.Feature(bytes_list = tf.train.BytesList(value=[imgRaw]))
            }) )
            TFwriter.write(example.SerializeToString())

TFwriter.close()

结果如下

tensorflow2读取 npy tensorflow读取数据集_数据

现在就生成了tfrecorder文件

tensorflow2读取 npy tensorflow读取数据集_TensorFlow_02

接下来从tfrecorder文件中读取,使用tf.train.shuffle_batch 函数来对队列中的样本进行乱序处理

def read_and_decode(filename):
    #根据文件名生成一个队列
    filename_queue = tf.train.string_input_producer([filename])

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)   #返回文件名和文件
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.int64),
                                           'img_raw' : tf.FixedLenFeature([], tf.string),
                                       })

    img = features['img_raw']

    label = features['label']

    return img, label


img, label = read_and_decode("./data/xxxxTF.tfrecords")

#使用shuffle_batch可以随机打乱输入
batch_size=6
min_after_dequeue = 50
capacity = min_after_dequeue + 3 * batch_size
img_batch, label_batch = tf.train.shuffle_batch([img, label],batch_size=batch_size, capacity=capacity,min_after_dequeue=min_after_dequeue)

#init = tf.initialize_all_variables()
init=tf.global_variables_initializer()

with tf.Session() as sess:

    threads = tf.train.start_queue_runners(sess=sess)
    sess.run(init)
    for i in range(4):
        val, l= sess.run([img_batch, label_batch])
        #我们也可以根据需要对val, l进行处理
        #l = to_categorical(l, 12) 
        print(val.shape, l)

结果如下:

(6,) [5 4 2 1 2 2] 
 (6,) [6 5 3 6 6 4] 
 (6,) [3 4 1 6 1 1] 
 (6,) [2 1 1 2 2 2]

这只是做分类任务时的数据集读取方式,若做object detection时,流程类似,加上从xml文件读取信息。