TFRecord文件查看包含的所有Features代碼
TFRecord作為tensorflow中廣泛使用的數(shù)據(jù)格式,它跨平臺,省空間,效率高。因為 Tensorflow開發(fā)者眾多,統(tǒng)一訓練時數(shù)據(jù)的文件格式是一件很有意義的事情,也有助于降低學習成本和遷移成本。
但是TFRecord數(shù)據(jù)是二進制格式,沒法直接查看。因此,如何能夠方便的查看TFRecord格式和數(shù)據(jù),就顯得尤為重要了。
為什么需要查看TFReocrd數(shù)據(jù)?首先我們先看下常規(guī)的寫入和讀取TFRecord數(shù)據(jù)的關鍵過程。
# 1. 寫入過程
# 一張圖片,我寫入了其內(nèi)容,label,長和寬幾個信息
tf_example = tf.train.Example(
features=tf.train.Features(feature={
'encoded': bytes_feature(encoded_jpg),
'label': int64_feature(label),
'height': int64_feature(height),
'width': int64_feature(width)}))
# 2. 讀取過程
# 定義解析的TFRecord數(shù)據(jù)格式
def _parse_image(example_proto):
features = {'encoded':tf.FixedLenFeature((),tf.string),
'label': tf.FixedLenFeature((), tf.int64),
'height': tf.FixedLenFeature((), tf.int64),
'width': tf.FixedLenFeature((), tf.int64)
}
return tf.parse_single_example(example_proto, features)
# TFRecord數(shù)據(jù)按照Feature解析出對應的真實數(shù)據(jù)
ds = ds.map(lambda x : _parse_image(x), num_parallel_calls=4)
上面是一個標準的TFRecord數(shù)據(jù)的寫入和讀取部分過程,大家應該發(fā)現(xiàn)了,讀取TFRecord數(shù)據(jù)的時候,得知道TFRecord數(shù)據(jù)保存的屬性名和類型,任何一項不匹配,都會導致無法獲取數(shù)據(jù)。
如果數(shù)據(jù)的寫入和讀取都是自己一個人完成,那就沒問題。但是如果寫入和讀取是跨團隊合作時候,如果每次讀取數(shù)據(jù)都得讓對方給完整的屬性名和屬性類型,那效率就太低了。畢竟TFRecord數(shù)據(jù)已經(jīng)包含了一切,自己動手豐衣足食。
那么怎么查看TFRecord數(shù)據(jù)呢?使用python tf.train.Example.FromString(serialized_example)方法,方法的入?yún)⑹荰FRecord包含的數(shù)據(jù)字符串。
然后,我直接將上訴查看的過程寫成了一個py腳本,需要自取。
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
import tensorflow as tf
# 用法:python trackTFRecord.py True file1 file2
# trackTFRecord.py 就是當前這個py文件
# True 表示是否輸出具體的數(shù)據(jù)
# file1 file2 表示的是需要查看的TFRecord文件的絕對路徑
# 輸出說明:tf.float32對應TFRecord的FloatList,tf.int64對應Int64List,tf.string對應BytesList
def main():
print('TFRecord文件個數(shù)為{0}個'.format(len(sys.argv)-2))
for i in range(2, len(sys.argv)):
filepath = sys.argv[i]
with tf.Session() as sess:
filenames = [filepath]
# 加載TFRecord數(shù)據(jù)
ds = tf.data.TFRecordDataset(filenames)
ds = ds.batch(10)
ds = ds.prefetch(buffer_size=tf.contrib.data.AUTOTUNE)
iterator = ds.make_one_shot_iterator()
# 為了加快速度,僅僅簡單拿一組數(shù)據(jù)看下結構
batch_data = iterator.get_next()
res = sess.run(batch_data)
serialized_example = res[0]
example_proto = tf.train.Example.FromString(serialized_example)
features = example_proto.features
print('{0} 信息如下:'.format(filepath))
for key in features.feature:
feature = features.feature[key]
ftype = None
fvalue = None
if len(feature.bytes_list.value) > 0:
ftype = 'bytes_list'
fvalue = feature.bytes_list.value
if len(feature.float_list.value) > 0:
ftype = 'float_list'
fvalue = feature.float_list.value
if len(feature.int64_list.value) > 0:
ftype = 'int64_list'
fvalue = feature.int64_list.value
result = '{0} : {1}'.format(key, ftype)
if 'True' == sys.argv[1]:
result = '{0} : {1}'.format(result, fvalue)
print(result)
if __name__ == "__main__":
main()
下面給大家實例演示,首先先隨便找個圖片,寫入到TFRecord數(shù)據(jù)
import tensorflow as tf
filename = "/Users/zhanhaitao/Desktop/1.png"
# 使用tf.read_file讀進圖片數(shù)據(jù)
image = tf.read_file(filename)
# 主要是為了獲取圖片的寬高
image_jpeg = tf.image.decode_jpeg(image, channels=3, name="decode_jpeg_picture")
# reshape圖片到原始大小2500x2000x3
image_jpeg = tf.reshape(image_jpeg, shape=(2500,2000,3))
# 獲取圖片shape數(shù)據(jù)
img_shape = image_jpeg.shape
width = img_shape[0]
height = img_shape[1]
# 將原圖片tensor生成bytes對象, image將保存到tfrecord
sess = tf.Session()
image = sess.run(image)
sess.close()
# 定義TFRecords文件的保存路徑及其文件名
path_none = "/Users/zhanhaitao/Desktop/a.tfrecord"
# 定義不同壓縮選項的TFRecordWriter
writer_none = tf.python_io.TFRecordWriter(path_none, options=None)
# 將外層features生成特定格式的example
example_none = tf.train.Example(features=tf.train.Features(feature={
"float_val":tf.train.Feature(float_list=tf.train.FloatList(value=[9.99])),
"width":tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),
"height":tf.train.Feature(int64_list=tf.train.Int64List(value=[height])),
"image_raw":tf.train.Feature(bytes_list=tf.train.BytesList(value=[image]))
}))
# example系列化字符串
example_str_none = example_none.SerializeToString()
# 將系列化字符串寫入?yún)f(xié)議緩沖區(qū)
writer_none.write(example_str_none)
# 關閉TFRecords文件操作接口
writer_none.close()
print("finish to write data to tfrecord file!")
然后,使用上面的腳本看下這個TFRecord數(shù)據(jù)定義了哪些屬性,以及對應的格式,先進入到腳本的目錄下,因為圖像數(shù)據(jù)內(nèi)容太大,影響閱讀,就只看屬性名和type了:
python trackTFRecord.py False /Users/zhanhaitao/Desktop/a.tfrecord # 結果,其中bytes_list對應tf.string,int64_list對應tf.int64 float_list對應tf.float32 # image_raw : bytes_list # width : int64_list # float_val : float_list # height : int64_list
以上這篇TFRecord文件查看包含的所有Features代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
詳解pandas DataFrame的查詢方法(loc,iloc,at,iat,ix的用法和區(qū)別)
這篇文章主要介紹了詳解pandas DataFrame的查詢方法(loc,iloc,at,iat,ix的用法和區(qū)別),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08
詳解Python操作RabbitMQ服務器消息隊列的遠程結果返回
RabbitMQ是一款基于MQ的服務器,Python可以通過Pika庫來進行程序操控,這里我們將來詳解Python操作RabbitMQ服務器消息隊列的遠程結果返回:2016-06-06
使用Python中的Playwright制作測試視頻的實現(xiàn)步驟
Playwright 是一種流行的用于測試 Web 應用程序的自動化工具,它提供了多種功能來使測試更加高效和可靠,這些功能之一是能夠捕獲測試運行的視頻,在此博客中,田辛老師將探索如何使用 Python 中的 Playwright 制作測試視頻,感興趣的同學可以參考本文自己動手嘗試2023-10-10
python軟件測試Jmeter性能測試JDBC Request(結合數(shù)據(jù)庫)的使用詳解
這篇文章主要介紹了python軟件測試Jmeter性能測試JDBC Request(結合數(shù)據(jù)庫)的使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
Python的Django框架中的select_related函數(shù)對QuerySet 查詢的優(yōu)化
這篇文章主要介紹了Python的Django框架中的select_related函數(shù)對QuerySet查詢的優(yōu)化,以減少數(shù)據(jù)庫的查詢次數(shù)為目的,需要的朋友可以參考下2015-04-04

