概述
關(guān)于Tensorflow讀取數(shù)據(jù),官網(wǎng)給出了三種方法:
- 供給數(shù)據(jù)(Feeding): 在TensorFlow程序運(yùn)行的每一步谋逻, 讓Python代碼來供給數(shù)據(jù)针余。
- 從文件讀取數(shù)據(jù): 在TensorFlow圖的起始毙玻, 讓一個(gè)輸入管線從文件中讀取數(shù)據(jù)。
- 預(yù)加載數(shù)據(jù): 在TensorFlow圖中定義常量或變量來保存所有數(shù)據(jù)(僅適用于數(shù)據(jù)量比較小的情況)土居。
對(duì)于數(shù)據(jù)量較小而言,可能一般選擇直接將數(shù)據(jù)加載進(jìn)內(nèi)存嬉探,然后再分batch
輸入網(wǎng)絡(luò)進(jìn)行訓(xùn)練(tip:使用這種方法時(shí)装盯,結(jié)合yield
使用更為簡潔,大家自己嘗試一下吧甲馋,我就不贅述了)埂奈。但是,如果數(shù)據(jù)量較大定躏,這樣的方法就不適用了账磺,因?yàn)樘膬?nèi)存,所以這時(shí)最好使用tensorflow提供的隊(duì)列queue
痊远,也就是第二種方法 從文件讀取數(shù)據(jù)垮抗。對(duì)于一些特定的讀取,比如csv文件格式碧聪,官網(wǎng)有相關(guān)的描述冒版,在這兒我介紹一種比較通用,高效的讀取方法(官網(wǎng)介紹的少)逞姿,即使用tensorflow內(nèi)定標(biāo)準(zhǔn)格式——TFRecords
太長不看辞嗡,直接看源碼請(qǐng)猛戳我的github
TFRecords
TFRecords其實(shí)是一種二進(jìn)制文件,雖然它不如其他格式好理解滞造,但是它能更好的利用內(nèi)存续室,更方便復(fù)制和移動(dòng),并且不需要單獨(dú)的標(biāo)簽文件(等會(huì)兒就知道為什么了)… …總而言之谒养,這樣的文件格式好處多多挺狰,所以讓我們用起來吧。
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)存塊序列化為一個(gè)字符串, 并且通過tf.python_io.TFRecordWriter
寫入到TFRecords文件瞳购。
從TFRecords文件中讀取數(shù)據(jù)沉唠, 可以使用tf.TFRecordReader
的tf.parse_single_example
解析器。這個(gè)操作可以將Example
協(xié)議內(nèi)存塊(protocol buffer)解析為張量苛败。
接下來满葛,讓我們開始讀取數(shù)據(jù)之旅吧~
生成TFRecords文件
我們使用tf.train.Example
來定義我們要填入的數(shù)據(jù)格式,然后使用tf.python_io.TFRecordWriter
來寫入罢屈。
import os
import tensorflow as tf
from PIL import Image
cwd = os.getcwd()
此處我加載的數(shù)據(jù)目錄如下:
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() #將圖片轉(zhuǎn)化為原生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()
關(guān)于Example
Feature
的相關(guān)定義和詳細(xì)內(nèi)容嘀韧,我推薦去官網(wǎng)查看相關(guān)API。
基本的缠捌,一個(gè)Example
中包含Features
锄贷,Features
里包含Feature
(這里沒s)的字典。最后曼月,Feature
里包含有一個(gè) FloatList
谊却, 或者ByteList
,或者Int64List
就這樣哑芹,我們把相關(guān)的信息都存到了一個(gè)文件中炎辨,所以前面才說不用單獨(dú)的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
# 可以做一些預(yù)處理之類的
print image, label
使用隊(duì)列讀取
一旦生成了TFRecords文件碴萧,接下來就可以使用隊(duì)列(queue
)讀取數(shù)據(jù)了。
def read_and_decode(filename):
#根據(jù)文件名生成一個(gè)隊(duì)列
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
之后我們可以在訓(xùn)練的時(shí)候這樣使用
img, label = read_and_decode("train.tfrecords")
# 使用shuffle_batch可以隨機(jī)打亂輸入
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])
#我們也可以根據(jù)需要對(duì)val末购, l進(jìn)行處理
#l = to_categorical(l, 12)
print(val.shape, l)
|
至此破喻,tensorflow高效從文件讀取數(shù)據(jù)差不多完結(jié)了。
恩盟榴?等等…什么叫差不多曹质?對(duì)了,還有幾個(gè)注意事項(xiàng):
第一擎场,tensorflow里的graph能夠記住狀態(tài)(state
)羽德,這使得TFRecordReader
能夠記住tfrecord
的位置,并且始終能返回下一個(gè)顶籽。而這就要求我們?cè)谑褂弥巴姘悖仨毘跏蓟麄€(gè)graph,這里我們使用了函數(shù)tf.initialize_all_variables()
來進(jìn)行初始化礼饱。
第二,tensorflow中的隊(duì)列和普通的隊(duì)列差不多,不過它里面的operation
和tensor
都是符號(hào)型的(symbolic
)镊绪,在調(diào)用sess.run()
時(shí)才執(zhí)行匀伏。
第三, TFRecordReader
會(huì)一直彈出隊(duì)列中文件的名字蝴韭,直到隊(duì)列為空够颠。
總結(jié)
- 生成tfrecord文件
- 定義
record reader
解析tfrecord文件 - 構(gòu)造一個(gè)批生成器(
batcher
) - 構(gòu)建其他的操作
- 初始化所有的操作
- 啟動(dòng)
QueueRunner
例子代碼請(qǐng)戳我的github,如果覺得對(duì)你有幫助的話可以加個(gè)星哦榄鉴。