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.mzph.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…