TensorFlow(4)-TFRecord

TFRecord

  • 1. tf.train.Example
    • 1.1 tfrecord 數據范式轉化
    • 1.2 demo 數據集構建
  • 2. TFRecord 讀寫
    • 2.1 寫入1-tf.io.TFRecordWriter()
    • 2.3 讀取-tf.data.TFRecordDataset()
    • 2.3 data -> dataset -> 存儲-tf.data.experimental.TFRecordWriter()

tfrecord 用于存儲二進制序列數據的一種范式,按順序存,按順序取。里面存的每一條數據都是一個 byte-string, 最常用的轉byte-string的方式是tf.train.Example 。tf.train.Example (or protobuf) 以字典{“string”: value}的形式存儲消息,這種消息存儲機制可讀性高。

demo1–tfrecord存儲

value can be a num / list / array              
pybyte_value = np.array(value).tobytes()                     # 0.轉Python字節數據
tfbyte_value = tf.train.BytesList(value=[pybyte_value])      # 1.轉tf.train 字節數據
feature_dict[key] = tf.train.Feature(bytes_list=tfbyte_value)# 2.轉tf.train.Feature()注意是tf.train.Feature()沒有s
..........
feature_example = tf.train.Example(features=tf.train.Features(feature=tffeature_dict)# 3.轉tf.train.Example()  注意tf.train.Features()s
exmp_serial = feature_example.SerializeToString()           # 序列化feature_example tf_writer = tf.python_io.TFRecordWriter(tfrecord_path)      # 構建tf寫句柄
tf_writer.write(exmp_serial)                                # 寫入tf文件
tf_writer.close()                                           # 關閉句柄

np.array().tobytes()構造包含數組中原始數據的Python字節數據

1. tf.train.Example

須將用戶數據轉化為tfrecord 約定的格式,才能使用tfrecord 格式存儲數據。

1.1 tfrecord 數據范式轉化

1-> tfrecord支持寫入三種格式的數據:string,int64,float32,分別通過tf.train.BytesList、tf.train.Int64List、tf.train.FloatList寫入tf.train.Feature中。【就是說數據要寫入tf.train.Feature前必須使用tf.train.BytesList,tf.train.Int64List,tf.train.FloatList必須使用強制類型轉換】

# python 數據類型轉tf.train.BytesList、tf.train.Int64List、tf.train.FloatList
# tf.train.BytesList:string、byte
# tf.train.FloatList:float (float32)、double (float64)
# tf.train.Int64List :bool、enum、int32、uint32、int64、uint64
# 強制類型轉換
value = 1
value_ed = tf.train.Int64List(value=[value])

2-> tf.train.Feature 接受tf.train.BytesList、tf.train.Int64List、tf.train.FloatList 類型的數據。以下為scalar 轉 tf.train.Feature 的快捷函數。 not scalar 的數據只需要用np.array().tobytes()/tf.io.serialize_tensor 轉換成binary-strings,然后使用以下借口函數封裝成 tf.train.Feature 即可。

# input : a scalar input
# output: tf.train.Feature
def _bytes_feature(value):           """Returns a bytes_list from a string / byte."""if isinstance(value, type(tf.constant(0))):value = value.numpy() # BytesList won't unpack a string from an EagerTensor.return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))def _float_feature(value):"""Returns a float_list from a float / double."""return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))def _int64_feature(value):"""Returns an int64_list from a bool / enum / int / uint."""return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

3->tf.train.Feature 構成特征字典 -> 特征字典 轉 Features message -> Features message 轉 tf.train.Example -> tf.train.Example 序列化后可以存入tfrecord 文件。【 Note that the tf.train.Example message is just a wrapper around the Features message:】

1.2 demo 數據集構建

構建一個包含10000個觀測數據的數據集,每條數據包含4個特征:[bool, label_index, lable_string, random_score]

n_observations = int(1e4)              # The number of observations in the dataset.
feature0 = np.random.choice([False, True], n_observations)  #Boolean feature, encoded as False or True.
feature1 = np.random.randint(0, 5, n_observations) # Integer feature, random from 0 to 4.
strings = np.array([b'cat', b'dog', b'chicken', b'horse', b'goat']) # String feature.
feature2 = strings[feature1]
feature3 = np.random.randn(n_observations) # Float feature, from a standard normal distribution.

單個樣本轉tf.train.Feature-> tf.train.Features -> tf.train.Example()->SerializeToString() 接口函數

def serialize_example(feature0, feature1, feature2, feature3):#  Create a Feature dict : {key: tf.train.Feature}feature = {'feature0': _int64_feature(feature0),'feature1': _int64_feature(feature1),'feature2': _bytes_feature(feature2),'feature3': _float_feature(feature3),}#  Create a Features message and conver to tf.train.Example.example_proto = tf.train.Example(features=tf.train.Features(feature=feature))return example_proto.SerializeToString()

觀測序列化[serialized_example ]和反序列化[tf.train.Example()]的結果

for i in range(n_observations):f0, f1, f2, f3 = feature0[i], feature1[i], feature2[i], feature3[i]# 序列化 tf.train.Example 消息serialized_example = serialize_example(f0, f1, f2, f3) # b'\nR\n\x14\n\x08feature2\x12\x08\n\x06\.....# 反序列化 tf.train.Exampleexample_proto = tf.train.Example.FromString(serialized_example) '''features {feature {key: "feature0"value {int64_list {value: 0}}}feature {key: "feature1"value {int64_list {value: 4}}}feature {key: "feature2"value {bytes_list {value: "goat"}}}feature {key: "feature3"value {float_list {value: 0.9876000285148621}}}
}'''

2. TFRecord 讀寫

tfrecord 中每一條record按照下面的范式存儲。tfrecord 文件中并非只能存tf.train.Example 序列化的結果,tf.train.Example 只是將字典序列化的一種方法。任何 byte-string都能夠存入TFRecord file。

uint64 length
uint32 masked_crc32_of_length
byte   data[length]
uint32 masked_crc32_of_data

2.1 寫入1-tf.io.TFRecordWriter()

# Write the `tf.train.Example` observations to the file.
with tf.io.TFRecordWriter(filename) as writer:     # 獲取寫入句柄for i in range(n_observations):example = serialize_example(feature0[i], feature1[i], feature2[i], feature3[i])writer.write(example)

2.3 讀取-tf.data.TFRecordDataset()

# 讀取tfrecord文件, 獲取序列化的樣本
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)  # tf.data.Dataset 對象
for raw_record in raw_dataset.take(10):           # 讀取前10 條print(repr(raw_record))                         # raw_record序列化的樣本# 序列化樣本反序列化
# tf.data.Dataset 在圖中執行,feature_description能夠建立數據集shape和type的signature。
feature_description = {'feature0': tf.io.FixedLenFeature([], tf.int64, default_value=0),'feature1': tf.io.FixedLenFeature([], tf.int64, default_value=0),'feature2': tf.io.FixedLenFeature([], tf.string, default_value=''),'feature3': tf.io.FixedLenFeature([], tf.float32, default_value=0.0),
}  
def _parse_function(example_proto):# Parse the input `tf.train.Example` proto using the dictionary above.# 一次只解析一條數據: use tf.parse example 可以一次解析一個batch的數據return tf.io.parse_single_example(example_proto, feature_description)# 利用tf.data.Dataset.map 函數將_parse_function 應用于數據集raw_dataset中的每一個元素parsed_dataset = raw_dataset.map(_parse_function)      # 可以用的數據
# {'feature0': <tf.Tensor: shape=(), dtype=int64, numpy=0>, 'feature1': <tf.Tensor: shape=(), dtype=int64, numpy=4>, 'feature2': <tf.Tensor: shape=(), dtype=string, numpy=b'goat'>, 'feature3': <tf.Tensor: shape=(), dtype=float32, numpy=0.5251196>}
# 讀取
filenames = [filename]
raw_dataset = tf.data.TFRecordDataset(filenames)
# tf.train.Example.ParseFromString反序列化 得到的是tf.train.Example features, 很難直接使用
for raw_record in raw_dataset.take(1):example = tf.train.Example()example.ParseFromString(raw_record.numpy())
# tf.train.Example features 轉 dict of numpy array
result = {}
for key, feature in example.features.feature.items():# The values are the Feature objects which contain a `kind` which contains:# one of three fields: bytes_list, float_list, int64_listkind = feature.WhichOneof('kind')result[key] = np.array(getattr(feature, kind).value)

2.3 data -> dataset -> 存儲-tf.data.experimental.TFRecordWriter()

from_tensor_slices 將data 轉成dataset-> 序列化dataset 中的每一個元素-> 存入tf record 文件

features_dataset = tf.data.Dataset.from_tensor_slices((feature0, feature1, feature2, feature3))
for f0,f1,f2,f3 in features_dataset.take(1):    # 逐個獲取數據print(f0, f1, f2, f3)# tf.Tensor(False, shape=(), dtype=bool),tf.Tensor(4, shape=(), dtype=int64),tf.Tensor(b'goat', shape=(), dtype=string),tf.Tensor(0.5251196235602504, shape=(), dtype=float64)# 序列化方式1:tf.data.Dataset.map 映射數據集中的每一個元素
# 對于自定義的序列化操作函數serialize_example。為了使其成為TensorFlow graph 的節點,須使用 tf.py_function封裝;之后再使用tf.data.Dataset.map 映射序列化數據集中的每一個元素。
def tf_serialize_example(f0,f1,f2,f3):# (自定義函數,函數輸入,函數輸出)tf_string = tf.py_function(serialize_example,(f0, f1, f2, f3),tf.string)return tf.reshape(tf_string, ()) # The result is a scalar.
serialized_features_dataset = features_dataset.map(tf_serialize_example)# 序列化方式2:tf.data.Dataset.from_generator()映射數據集中的每一個元素
def generator():for features in features_dataset:yield serialize_example(*features)
serialized_features_dataset = tf.data.Dataset.from_generator(generator, output_types=tf.string, output_shapes=())

整個序列化的數據集寫入tfrecord.

# 整個寫入tfrecord
filename = 'test.tfrecord'
writer = tf.data.experimental.TFRecordWriter(filename)    # 與1.0 的接口有些不太一樣
writer.write(serialized_features_dataset)

參考資料:TFRecord and tf.train.Example

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/444634.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/444634.shtml
英文地址,請注明出處:http://en.pswp.cn/news/444634.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

Playfab開發(一)如何調用PlayFab接口

本人從事海外游戲制作和發行,參與了不少海外研發團隊studio的項目,這里我將個人接觸到的一些使用Playfab開發的項目心得分享給大家。 PlayFab簡介 playfab是一家主要為游戲開發人員提供游戲開發和管理的跨平臺工具及服務的公司, PlayFab正在構建當今游戲所需的所有基于云的…

PlayFab(二)如何通過Demo應用來進一步熟悉Playfab

有時候剛開始接觸新的平臺會兩眼一麻黑,不過這個文章希望能給讀者一些啟示,Playfab默認會給開發者提供一個應用,這里我暫且叫他”我的游戲“; 我通過官網提供的DEMO測試地址: https://www.vanguardoutrider.com/#/ 來為該應用配置服務器。 如果你是第一次進入這個頁面想為…

leetcode718 最長重復子數組

給兩個整數數組 A 和 B &#xff0c;返回兩個數組中公共的、長度最長的子數組的長度。 示例 1: 輸入: A: [1,2,3,2,1] B: [3,2,1,4,7] 輸出: 3 解釋: 長度最長的公共子數組是 [3, 2, 1]。 說明: 1 < len(A), len(B) < 1000 0 < A[i], B[i] < 100 思路&#xf…

PaperNotes(20)-TGAN-DeliGAN

GAN的文章2篇1.從RS-GAN說起2.TGANAbstract1 Reviews of GANs2.3 Relate to Turing Test3 Related Works4 Experiments4.1 Design of Discriminator5.Conclusion3 DeliGANAbstract1. Introduction2. Related Work3.GAN4.本文方法5.實驗5.1. Modified Inception Score5.2. Toy D…

ubuntu apache配置負載均衡篇(一)

首先下載apache2服務器 apt-get install apache2 使得代理生效: a2enmod proxy proxy_ajp proxy_balancer proxy_connect proxy_ftp proxy_http 修改配置 sudo vi /etc/apache2/mods-enabled/proxy.conf ProxyRequests Off <Proxy *> Order deny,allow Deny …

leetcode108 將有序數組轉換為二叉搜索樹

將一個按照升序排列的有序數組&#xff0c;轉換為一棵高度平衡二叉搜索樹。 本題中&#xff0c;一個高度平衡二叉樹是指一個二叉樹每個節點 的左右兩個子樹的高度差的絕對值不超過 1。 示例: 給定有序數組: [-10,-3,0,5,9], 一個可能的答案是&#xff1a;[0,-3,9,-10,null,…

ubuntu apache配置負載均衡篇(二)

上篇文章說到了基本的負載均衡配置,這次再說下負載均衡里的反向代理配置項參數:ProxyPass與ProxyPassReverse及ProxyPassMatch 1、ProxyPass: 語法:ProxyPass [path] !|url 它主要是用作URL前綴匹配,不能有正則表達式,它里面配置的Path實際上是一個虛擬的路徑,在反向…

MachineLearning(12)- RNN-LSTM-tf.nn.rnn_cell

RNN-LSTM1.RNN2.LSTM3. tensorflow 中的RNN-LSTM3.1 tf.nn.rnn_cell.BasicRNNCell()3.2 tf.nn.rnn_cell.BasicLSTMCell()3.3 tf.nn.dynamic_rnn()--多步執行循環神經網絡1.RNN RNN-Recurrent Neural Network-循環神經網絡 RNN用來處理序列數據。多層感知機MLP層間節點全聯接&…

判斷微信小游戲用戶是否真的分享

作為開發者,傳統的微信分享拿到分享的狀態碼并不能完全確定玩家是否分享到好友或群。 因此一部分開發者給分享做一個定時器,超過5秒就判定玩家分享成功,實際上很容易被玩家利用。 因此我們可以利用微信分享過程中的圖片url鏈接做文章: 1.需要一個web服務器,提供給客戶端…

Leaf服務器框架從入門到放棄(一)認識Leaf和安裝Leaf環境

首先我簡單介紹下Leaf服務器,下面這段描述是我摘自github官方README說明: Leaf 游戲服務器框架簡介 Leaf 是一個由 Go 語言(golang)編寫的開發效率和執行效率并重的開源游戲服務器框架。Leaf 適用于各類游戲服務器的開發,包括 H5(HTML5)游戲服務器。 Leaf 的關注點:…

Linux Command List

Linux Command ListLinux Command List)todops auxsednohupnvidia-smisnaptorch.cuda.is_available()Linux Command List) Linux(1)-touch,mkdir,rm,mv,cp,ls,cd,cat Linux(2)-tar,find,grep,xargs Linux(3)-網-ifconfig,ping,ssh Linux(4)-資源-du,top,free,gnome Linux(…

JS演示圖論匯總

BFS.js var BFSClass function () {this.isVisit new Array();this.adj new Array();this.vQueue new Array();this.curV;this.temp new Array();this.init function (beginV) {this.curV null;this.temp [];//初始化頂點訪問數組this.isVisit [];for (var i 0; i &…

Shell腳本自動監控docker容器的狀態

首先我們來寫一個腳本rootserver:~# cat docker_monitor.sh #!/bin/bash #監控容器的運行狀態 #容器名稱 傳入參數 containerName$1 #當前時間 nowdate "%Y-%m-%d %H:%M:%S"# 查看進程是否存在 existdocker inspect --format {{.State.Running}} ${containerNam…

Python模塊(9)-Time,Json 簡易使用教程

Time,Json簡易使用教程1 Time1.1 獲取時間1.2 程序計時2 Json1 Time Python中內置了一些與時間處理相關的庫&#xff0c;如time、datatime和calendar庫。其中time庫是Python中處理時間的標準庫&#xff0c;是最基礎的時間處理庫&#xff0c;提供如下功能功&#xff1a; &#…

AWS的VPC使用經驗(一)

Amazon VPC 概念 Amazon VPC 是 Amazon EC2 的網絡化階層。如果您是首次使用 Amazon EC2,請參閱 Amazon EC2 用戶指南(適用于 Linux 實例) 中的什么是 Amazon EC2?以獲取簡要概述。 以下是 VPC 的主要概念: Virtual Private Cloud (VPC) 是僅適用于您的 AWS 賬戶的虛擬網…

AWS的VPC使用經驗(二)

上文說了如何創建自定義VPC網絡的EC2實例&#xff0c;這節說如何在多個VPC之間創建對等連接。 這里分別填寫自己的VPC和對方的VPC的ID信息&#xff0c;然后在對方的VPC里就能看到有連接請求&#xff0c;在對方的連接請求里選擇 “操作”->接受。 到這里已經快要收尾了&…

ML Tools List

文章目錄1.Pyorch2.TensorFlow3. Other1.Pyorch Pytorch(1)-內置/自己設計的損失函數使用 Pytorch(2)-tensor常用操作 Pytorch(3)–數據載入接口&#xff1a;Dataloader、datasets Pytorch(4)-模型保存-載入-eval() Pytorch(5)-梯度反向傳播 Pytorch(6)–設置隨機種子&am…

ubuntu nginx配置負載均衡篇(一)

Nginx 代理服務的配置說明 1、設置 404 頁面導向地址 error_page 404 https://www.runnob.com; #錯誤頁 proxy_intercept_errors on; #如果被代理服務器返回的狀態碼為400或者大于400,設置的error_page配置起作用。默認為off。 2、如果我們的代理只允許接受get,post請求…

坦克大戰

效果 map.js var map4 [[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[0,2,2,0,0,2,2,0,0,0,2,2,0,0,2,2,0,0,2,2,0,2,2,0],[0,2,2,0,0,2,2,0,0,0,2,2,3,3,2,2…

ubuntu nginx配置負載均衡篇(二)

這里提供部分我的配置文件: nginx.conf: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf;events {worker_connections 768;# multi_accept on; }http {### Basic Settings##sendfile on;tcp_nopush on;tcp_nodelay…