由淺入深之Tensorflow(3)----數據讀取之TFRecords

轉載自http://blog.csdn.net/u012759136/article/details/52232266 原文做者github地址python

概述

關於Tensorflow讀取數據,官網給出了三種方法:git

  • 供給數據(Feeding): 在TensorFlow程序運行的每一步, 讓Python代碼來供給數據。
  • 從文件讀取數據: 在TensorFlow圖的起始, 讓一個輸入管線從文件中讀取數據。
  • 預加載數據: 在TensorFlow圖中定義常量或變量來保存全部數據(僅適用於數據量比較小的狀況)。

對於數據量較小而言,可能通常選擇直接將數據加載進內存,而後再分batch輸入網絡進行訓練(tip:使用這種方法時,結合yield 使用更爲簡潔,你們本身嘗試一下吧,我就不贅述了)。可是,若是數據量較大,這樣的方法就不適用了,由於太耗內存,因此這時最好使用tensorflow提供的隊列queue,也就是第二種方法 從文件讀取數據。對於一些特定的讀取,好比csv文件格式,官網有相關的描述,在這兒我介紹一種比較通用,高效的讀取方法(官網介紹的少),即便用tensorflow內定標準格式——TFRecordsgithub

TFRecords

TFRecords實際上是一種二進制文件,雖然它不如其餘格式好理解,可是它能更好的利用內存,更方便複製和移動,而且不須要單獨的標籤文件(等會兒就知道爲何了)… …總而言之,這樣的文件格式好處多多,因此讓咱們用起來吧。網絡

TFRecords文件包含了tf.train.Example 協議內存塊(protocol buffer)(協議內存塊包含了字段 Features)。咱們能夠寫一段代碼獲取你的數據, 將數據填入到Example協議內存塊(protocol buffer),將協議內存塊序列化爲一個字符串, 而且經過tf.python_io.TFRecordWriter 寫入到TFRecords文件。函數

從TFRecords文件中讀取數據, 可使用tf.TFRecordReadertf.parse_single_example解析器。這個操做能夠將Example協議內存塊(protocol buffer)解析爲張量。ui

接下來,讓咱們開始讀取數據之旅吧~spa

生成TFRecords文件

咱們使用tf.train.Example來定義咱們要填入的數據格式,而後使用tf.python_io.TFRecordWriter來寫入。.net

import os
import tensorflow as tf 
from PIL import Image

cwd = os.getcwd()

'''
此處我加載的數據目錄以下:
0 -- img1.jpg
     img2.jpg
     img3.jpg
     ...
1 -- img1.jpg
     img2.jpg
     ...
2 -- ...
...
'''
writer = tf.python_io.TFRecordWriter("train.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((224, 224))
        img_raw = img.tobytes()              #將圖片轉化爲原生bytes
        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]))
        }))
        writer.write(example.SerializeToString())  #序列化爲字符串
writer.close()

 

關於Example Feature的相關定義和詳細內容,我推薦去官網查看相關API。code

基本的,一個Example中包含FeaturesFeatures裏包含Feature(這裏沒s)的字典。最後,Feature裏包含有一個 FloatList, 或者ByteList,或者Int64Listblog

就這樣,咱們把相關的信息都存到了一個文件中,因此前面才說不用單獨的label文件。並且讀取也很方便。

for serialized_example in tf.python_io.tf_record_iterator("train.tfrecords"):
    example = tf.train.Example()
    example.ParseFromString(serialized_example)

    image = example.features.feature['image'].bytes_list.value
    label = example.features.feature['label'].int64_list.value
    # 能夠作一些預處理之類的
    print image, label

使用隊列讀取

一旦生成了TFRecords文件,接下來就可使用隊列(queue)讀取數據了。

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 = tf.decode_raw(features['img_raw'], tf.uint8)
    img = tf.reshape(img, [224, 224, 3])
    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5
    label = tf.cast(features['label'], tf.int32)

    return img, label

以後咱們能夠在訓練的時候這樣使用

img, label = read_and_decode("train.tfrecords")

#使用shuffle_batch能夠隨機打亂輸入
img_batch, label_batch = tf.train.shuffle_batch([img, label],
                                                batch_size=30, capacity=2000,
                                                min_after_dequeue=1000)
init = tf.initialize_all_variables()

with tf.Session() as sess:
    sess.run(init)
    threads = tf.train.start_queue_runners(sess=sess)
    for i in range(3):
        val, l= sess.run([img_batch, label_batch])
        #咱們也能夠根據須要對val, l進行處理
        #l = to_categorical(l, 12) 
        print(val.shape, l)

至此,tensorflow高效從文件讀取數據差很少完結了。

恩?等等…什麼叫差很少?對了,還有幾個注意事項

第一,tensorflow裏的graph可以記住狀態(state),這使得TFRecordReader可以記住tfrecord的位置,而且始終能返回下一個。而這就要求咱們在使用以前,必須初始化整個graph,這裏咱們使用了函數tf.initialize_all_variables()來進行初始化。

第二,tensorflow中的隊列和普通的隊列差很少,不過它裏面的operationtensor都是符號型的(symbolic),在調用sess.run()時才執行。

第三, TFRecordReader會一直彈出隊列中文件的名字,直到隊列爲空。


總結

  1. 生成tfrecord文件
  2. 定義record reader解析tfrecord文件
  3. 構造一個批生成器(batcher
  4. 構建其餘的操做
  5. 初始化全部的操做
  6. 啓動QueueRunner
相關文章
相關標籤/搜索