python神經(jīng)網(wǎng)絡(luò)tfrecords文件的寫入讀取及內(nèi)容解析
學(xué)習(xí)前言
前一段時(shí)間對(duì)SSD預(yù)測(cè)與訓(xùn)練的整體框架有了一定的了解,但是對(duì)其中很多細(xì)節(jié)還是把握的不清楚。今天我決定好好了解以下tfrecords文件的構(gòu)造。
tfrecords格式是什么
tfrecords是一種二進(jìn)制編碼的文件格式,tensorflow專用。能將任意數(shù)據(jù)轉(zhuǎn)換為tfrecords。更好的利用內(nèi)存,更方便復(fù)制和移動(dòng),并且不需要單獨(dú)的標(biāo)簽文件。
之所以使用到tfrecords格式是因?yàn)楫?dāng)今數(shù)據(jù)爆炸的情況下,使用普通的數(shù)據(jù)格式不僅麻煩,而且速度慢,這種專門為tensorflow定制的數(shù)據(jù)格式可以大大增快數(shù)據(jù)的讀取,而且將所有內(nèi)容規(guī)整,在保證速度的情況下,使得數(shù)據(jù)更加簡(jiǎn)單明晰。
tfrecords的寫入
這個(gè)例子將會(huì)講述如何將MNIST數(shù)據(jù)集寫入到tfrecords,本次用到的MNIST數(shù)據(jù)集會(huì)利用tensorflow原有的庫(kù)進(jìn)行導(dǎo)入。
from tensorflow.examples.tutorials.mnist import input_data
# 讀取MNIST數(shù)據(jù)集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)
對(duì)于MNIST數(shù)據(jù)集而言,其中的訓(xùn)練集是mnist.train,而它的數(shù)據(jù)可以分為images和labels,可通過(guò)如下方式獲得。
# 獲得image,shape為(55000,784) images = mnist.train.images # 獲得label,shape為(55000,10) labels = mnist.train.labels # 獲得一共具有多少?gòu)垐D片 num_examples = mnist.train.num_examples
接下來(lái)定義存儲(chǔ)TFRecord文件的地址,同時(shí)創(chuàng)建一個(gè)writer來(lái)寫TFRecord文件。
# 存儲(chǔ)TFRecord文件的地址 filename = 'record/output.tfrecords' # 創(chuàng)建一個(gè)writer來(lái)寫TFRecord文件 writer = tf.python_io.TFRecordWriter(filename)
此時(shí)便可以按照一定的格式寫入了,此時(shí)需要對(duì)每一張圖片進(jìn)行循環(huán)并寫入,在tf.train.Features中利用features字典定義了數(shù)據(jù)保存的方式。以image_raw為例,其經(jīng)過(guò)函數(shù)_float_feature處理后,存儲(chǔ)到tfrecords文件的’image/encoded’位置上。
# 將每張圖片都轉(zhuǎn)為一個(gè)Example,并寫入
for i in range(num_examples):
image_raw = images[i] # 讀取每一幅圖像
image_string = images[i].tostring()
example = tf.train.Example(
features=tf.train.Features(
feature={
'image/class/label': _int64_feature(np.argmax(labels[i])),
'image/encoded': _float_feature(image_raw),
'image/encoded_tostring': _bytes_feature(image_string)
}
)
)
print(i,"/",num_examples)
writer.write(example.SerializeToString()) # 將Example寫入TFRecord文件
在最終存入前,數(shù)據(jù)還需要經(jīng)過(guò)處理,處理方式如下:
# 生成整數(shù)的屬性
def _int64_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮點(diǎn)數(shù)的屬性
def _float_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的屬性
def _bytes_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
tfrecords的讀取
tfrecords的讀取首先要?jiǎng)?chuàng)建一個(gè)reader來(lái)讀取TFRecord文件中的Example。
# 創(chuàng)建一個(gè)reader來(lái)讀取TFRecord文件中的Example reader = tf.TFRecordReader()
再創(chuàng)建一個(gè)隊(duì)列來(lái)維護(hù)輸入文件列表。
# 創(chuàng)建一個(gè)隊(duì)列來(lái)維護(hù)輸入文件列表 filename_queue = tf.train.string_input_producer(['record/output.tfrecords'])
利用reader讀取輸入文件列表隊(duì)列,并用parse_single_example將讀入的Example解析成tensor
# 從文件中讀出一個(gè)Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example將讀入的Example解析成tensor
features = tf.parse_single_example(
serialized_example,
features={
'image/class/label': tf.FixedLenFeature([], tf.int64),
'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
}
)
此時(shí)我們得到了一個(gè)features,實(shí)際上它是一個(gè)類似于字典的東西,我們額可以通過(guò)字典的方式讀取它內(nèi)部的內(nèi)容,而字典的索引就是我們?cè)賹懭雝frecord文件時(shí)所用的feature。
# 將字符串解析成圖像對(duì)應(yīng)的像素?cái)?shù)組 labels = tf.cast(features['image/class/label'], tf.int32) images = tf.cast(features['image/encoded'], tf.float32) images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)
最后利用一個(gè)循環(huán)輸出:
# 每次運(yùn)行讀取一個(gè)Example。當(dāng)所有樣例讀取完之后,在此樣例中程序會(huì)重頭讀取
for i in range(5):
label, image = sess.run([labels, images])
images_tostring = sess.run(images_tostrings)
print(np.shape(image))
print(np.shape(images_tostring))
print(label)
print("#########################")
測(cè)試代碼
1、tfrecords文件的寫入
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 生成整數(shù)的屬性
def _int64_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
# 生成浮點(diǎn)數(shù)的屬性
def _float_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
# 生成字符串型的屬性
def _bytes_feature(value):
if not isinstance(value,list) and not isinstance(value,np.ndarray):
value = [value]
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
# 讀取MNIST數(shù)據(jù)集
mnist = input_data.read_data_sets('./MNIST_data', dtype=tf.float32, one_hot=True)
# 獲得image,shape為(55000,784)
images = mnist.train.images
# 獲得label,shape為(55000,10)
labels = mnist.train.labels
# 獲得一共具有多少?gòu)垐D片
num_examples = mnist.train.num_examples
# 存儲(chǔ)TFRecord文件的地址
filename = 'record/Mnist_Out.tfrecords'
# 創(chuàng)建一個(gè)writer來(lái)寫TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
# 將每張圖片都轉(zhuǎn)為一個(gè)Example,并寫入
for i in range(num_examples):
image_raw = images[i] # 讀取每一幅圖像
image_string = images[i].tostring()
example = tf.train.Example(
features=tf.train.Features(
feature={
'image/class/label': _int64_feature(np.argmax(labels[i])),
'image/encoded': _float_feature(image_raw),
'image/encoded_tostring': _bytes_feature(image_string)
}
)
)
print(i,"/",num_examples)
writer.write(example.SerializeToString()) # 將Example寫入TFRecord文件
print('data processing success')
writer.close()
運(yùn)行結(jié)果為:
……
54993 / 55000
54994 / 55000
54995 / 55000
54996 / 55000
54997 / 55000
54998 / 55000
54999 / 55000
data processing success
2、tfrecords文件的讀取
import tensorflow as tf
import numpy as np
# 創(chuàng)建一個(gè)reader來(lái)讀取TFRecord文件中的Example
reader = tf.TFRecordReader()
# 創(chuàng)建一個(gè)隊(duì)列來(lái)維護(hù)輸入文件列表
filename_queue = tf.train.string_input_producer(['record/Mnist_Out.tfrecords'])
# 從文件中讀出一個(gè)Example
_, serialized_example = reader.read(filename_queue)
# 用parse_single_example將讀入的Example解析成tensor
features = tf.parse_single_example(
serialized_example,
features={
'image/class/label': tf.FixedLenFeature([], tf.int64),
'image/encoded': tf.FixedLenFeature([784], tf.float32, default_value=tf.zeros([784], dtype=tf.float32)),
'image/encoded_tostring': tf.FixedLenFeature([], tf.string)
}
)
# 將字符串解析成圖像對(duì)應(yīng)的像素?cái)?shù)組
labels = tf.cast(features['image/class/label'], tf.int32)
images = tf.cast(features['image/encoded'], tf.float32)
images_tostrings = tf.decode_raw(features['image/encoded_tostring'], tf.float32)
sess = tf.Session()
# 啟動(dòng)多線程處理輸入數(shù)據(jù)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
# 每次運(yùn)行讀取一個(gè)Example。當(dāng)所有樣例讀取完之后,在此樣例中程序會(huì)重頭讀取
for i in range(5):
label, image = sess.run([labels, images])
images_tostring = sess.run(images_tostrings)
print(np.shape(image))
print(np.shape(images_tostring))
print(label)
print("#########################")
運(yùn)行結(jié)果為:
#########################
(784,)
(784,)
7
#########################
#########################
(784,)
(784,)
4
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
1
#########################
#########################
(784,)
(784,)
9
#########################
以上就是python神經(jīng)網(wǎng)絡(luò)tfrecords文件的寫入讀取及內(nèi)容解析的詳細(xì)內(nèi)容,更多關(guān)于python神經(jīng)網(wǎng)絡(luò)tfrecords寫入讀取的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python利用dir函數(shù)查看類中所有成員函數(shù)示例代碼
這篇文章主要給大家介紹了關(guān)于python如何利用dir函數(shù)查看類中所有成員函數(shù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)下吧。2017-09-09
django傳值給模板, 再用JS接收并進(jìn)行操作的實(shí)例
今天小編就為大家分享一篇django傳值給模板, 再用JS接收并進(jìn)行操作的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-05-05
使用Python在Windows下獲取USB PID&VID的方法
今天小編就為大家分享一篇使用Python在Windows下獲取USB PID&VID的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-07-07
python實(shí)現(xiàn)掃描局域網(wǎng)指定網(wǎng)段ip的方法
這篇文章主要介紹了python實(shí)現(xiàn)掃描局域網(wǎng)指定網(wǎng)段ip的方法,非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04

