數(shù)據(jù)轉(zhuǎn)換TFRecord

轉(zhuǎn)自:http://blog.csdn.net/u012759136/article/details/52232266

參考代碼:https://github.com/ycszen/TensorFlowLaboratory/blob/master/reading_data/example_tfrecords.py

概述

關(guān)于Tensorflow讀取數(shù)據(jù),官網(wǎng)給出了三種方法:

供給數(shù)據(jù)(Feeding): 在TensorFlow程序運行的每一步, 讓Python代碼來供給數(shù)據(jù)。

從文件讀取數(shù)據(jù): 在TensorFlow圖的起始, 讓一個輸入管線從文件中讀取數(shù)據(jù)。

預(yù)加載數(shù)據(jù): 在TensorFlow圖中定義常量或變量來保存所有數(shù)據(jù)(僅適用于數(shù)據(jù)量比較小的情況)。

對于數(shù)據(jù)量較小而言,可能一般選擇直接將數(shù)據(jù)加載進內(nèi)存,然后再分batch輸入網(wǎng)絡(luò)進行訓(xùn)練(tip:使用這種方法時,結(jié)合yield使用更為簡潔,大家自己嘗試一下吧,我就不贅述了)。但是,如果數(shù)據(jù)量較大,這樣的方法就不適用了,因為太耗內(nèi)存,所以這時最好使用tensorflow提供的隊列queue,也就是第二種方法從文件讀取數(shù)據(jù)。對于一些特定的讀取,比如csv文件格式,官網(wǎng)有相關(guān)的描述,在這兒我介紹一種比較通用,高效的讀取方法(官網(wǎng)介紹的少),即使用tensorflow內(nèi)定標(biāo)準(zhǔn)格式——TFRecords

TFRecords

TFRecords其實是一種二進制文件,雖然它不如其他格式好理解,但是它能更好的利用內(nèi)存,更方便復(fù)制和移動,并且不需要單獨的標(biāo)簽文件(等會兒就知道為什么了)… …總而言之,這樣的文件格式好處多多,所以讓我們用起來吧。

TFRecords文件包含了tf.train.Example協(xié)議內(nèi)存塊(protocol buffer)(協(xié)議內(nèi)存塊包含了字段Features)。我們可以寫一段代碼獲取你的數(shù)據(jù), 將數(shù)據(jù)填入到Example協(xié)議內(nèi)存塊(protocol buffer),將協(xié)議內(nèi)存塊序列化為一個字符串, 并且通過tf.python_io.TFRecordWriter寫入到TFRecords文件。

從TFRecords文件中讀取數(shù)據(jù), 可以使用tf.TFRecordReader的tf.parse_single_example解析器。這個操作可以將Example協(xié)議內(nèi)存塊(protocol buffer)解析為張量。

接下來,讓我們開始讀取數(shù)據(jù)之旅吧~

生成TFRecords文件

我們使用tf.train.Example來定義我們要填入的數(shù)據(jù)格式,然后使用tf.python_io.TFRecordWriter來寫入。

importosimporttensorflowastffromPILimportImagecwd = os.getcwd()'''

此處我加載的數(shù)據(jù)目錄如下:

0 -- img1.jpg

img2.jpg

img3.jpg

...

1 -- img1.jpg

img2.jpg

...

2 -- ...

這里的0, 1, 2...就是類別,也就是下文中的classes

classes是我根據(jù)自己數(shù)據(jù)類型定義的一個列表,大家可以根據(jù)自己的數(shù)據(jù)情況靈活運用

...

'''writer = tf.python_io.TFRecordWriter("train.tfrecords")forindex, nameinenumerate(classes):? ? class_path = cwd + name +"/"forimg_nameinos.listdir(class_path):? ? ? ? img_path = class_path + img_name? ? ? ? ? ? img = Image.open(img_path)? ? ? ? ? ? img = img.resize((224,224))? ? ? ? img_raw = img.tobytes()#將圖片轉(zhuǎn)化為原生bytesexample = 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()

關(guān)于ExampleFeature的相關(guān)定義和詳細內(nèi)容,我推薦去官網(wǎng)查看相關(guān)API。

基本的,一個Example中包含F(xiàn)eatures,F(xiàn)eatures里包含F(xiàn)eature(這里沒s)的字典。最后,F(xiàn)eature里包含有一個FloatList, 或者ByteList,或者Int64List

就這樣,我們把相關(guān)的信息都存到了一個文件中,所以前面才說不用單獨的label文件。而且讀取也很方便。

接下來是一個簡單的讀取小例子:

forserialized_exampleintf.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# 可以做一些預(yù)處理之類的printimage, label


使用隊列讀取

一旦生成了TFRecords文件,為了高效地讀取數(shù)據(jù),TF中使用隊列(queue)讀取數(shù)據(jù)。

defread_and_decode(filename):#根據(jù)文件名生成一個隊列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.5label = tf.cast(features['label'], tf.int32)returnimg, label

之后我們可以在訓(xùn)練的時候這樣使用

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()withtf.Session()assess:? ? sess.run(init)? ? threads = tf.train.start_queue_runners(sess=sess)foriinrange(3):? ? ? ? val, l= sess.run([img_batch, label_batch])#我們也可以根據(jù)需要對val, l進行處理#l = to_categorical(l, 12)print(val.shape, l)


至此,tensorflow高效從文件讀取數(shù)據(jù)差不多完結(jié)了。

恩?等等…什么叫差不多?對了,還有幾個注意事項

第一,tensorflow里的graph能夠記住狀態(tài)(state),這使得TFRecordReader能夠記住tfrecord的位置,并且始終能返回下一個。而這就要求我們在使用之前,必須初始化整個graph,這里我們使用了函數(shù)tf.initialize_all_variables()來進行初始化。

第二,tensorflow中的隊列和普通的隊列差不多,不過它里面的operation和tensor都是符號型的(symbolic),在調(diào)用sess.run()時才執(zhí)行。

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容