TFRecord 是 tensorflow 内置的文件格式,它是一种二进制文件,具有以下优点:

1. 统一各种输入文件的操作

2. 更好的利用内存,方便复制和移动

3. 将二进制数据和标签(label)存储在同一个文件中

引言

在了解如下操作后进一步详细讲解TFRecord

tf.train.Int64List(value=list_data)

它的作用是 把 list 中每个元素转换成 key-value 形式,

注意,输入必须是 list,且 list 中元素类型要相同,且与 Int 保持一致;

  1. # value = tf.constant([1, 2]) ### 这会报错的
  2. ss = 1 ### Int64List 对应的元素只能是 int long,其他同理
  3. tt = 2
  4. out1 = tf.train.Int64List(value = [ss, tt])
  5. print(out1)
  6. # value: 1
  7. # value: 2
  8.  
  9. ss = [1 ,2]
  10. out2 = tf.train.Int64List(value = ss)
  11. print(out2)
  12. # value: 1
  13. # value: 2

同类型的 方法还有 2 个

  1. tf.train.FloatList
  2. tf.train.BytesList

tf.train.Feature(int64_list=)

它的作用是 构建 一种类型的特征集,比如 整型

  1. out = tf.train.Feature(int64_list=tf.train.Int64List(value=[33, 22]))
  2. print(out)
  3. # int64_list {
  4. # value: 33
  5. # value: 22
  6. # }

也可以是其他类型

  1. tf.train.Feature(float_list=tf.train.FloatList())
  2. tf.train.Feature(bytes_list=tf.train.BytesList())

tf.train.Features(feature=dict_data)

它的作用是 构建 多种类型 的特征集,可以 dict 格式表达 多种类型

  1. ut = tf.train.Features(feature={
  2. "suibian": tf.train.Feature(int64_list=tf.train.Int64List(value=[1, 2, 4])),
  3. "a": tf.train.Feature(float_list=tf.train.FloatList(value=[5., 7.]))
  4. })
  5. print(out)
  6. # feature {
  7. # key: "a"
  8. # value {
  9. # float_list {
  10. # value: 5.0
  11. # value: 7.0
  12. # }
  13. # }
  14. # }
  15. # feature {
  16. # key: "suibian"
  17. # value {
  18. # int64_list {
  19. # value: 1
  20. # value: 2
  21. # value: 4
  22. # }
  23. # }
  24. # }

tf.train.Example(features=tf.train.Features())

它的作用是创建一个 样本,Example 对应一个样本

  1. example = tf.train.Example(features=
  2. tf.train.Features(feature={
  3. 'a': tf.train.Feature(int64_list=tf.train.Int64List(value=range(2))),
  4. 'b': tf.train.Feature(bytes_list=tf.train.BytesList(value=[b'm',b'n']))
  5. }))
  6. print(example)
  7. # features {
  8. # feature {
  9. # key: "a"
  10. # value {
  11. # int64_list {
  12. # value: 0
  13. # value: 1
  14. # }
  15. # }
  16. # }
  17. # feature {
  18. # key: "b"
  19. # value {
  20. # bytes_list {
  21. # value: "m"
  22. # value: "n"
  23. # }
  24. # }
  25. # }
  26. # }

一幅图总结一下上面的代码

Example 协议块

它其实是一种 数据存储的 格式,类似于 xml、json 等;

用上述方法实现该格式;

一个 Example 协议块对应一个样本,一个样本有多种特征,每种特征下有多个元素,可参看上图;

  1. message Example{
  2. Features features = 1;
  3. }
  4. message Features{
  5. map<string,Features> feature = 1;
  6. }
  7. message Feature {
  8. oneof kind {
  9. BytesList bytes_list = 1;
  10. FloateList float_list = 2;
  11. Int64List int64_list = 3;
  12. }
  13. }

TFRecord 文件就是以 Example协议块 格式 存储的;

TFRecord 文件

该类文件具有写功能,且可以把其他类型的文件转换成该类型文件,其实相当于先读取其他文件,再写入 TFRecord 文件;

该类文件也具有读功能;

TFRecord 存储

存储分两步:

1.建立存储器

2. 构造每个样本的 Example 协议块

tf.python_io.TFRecordWriter(file_name)

构造存储器,存储器有两个常用方法

  • write(record):向文件中写入一个样本
  • close():关闭存储器

注意:此处的 record 为一个序列化的 Example,通过 Example.SerializeToString()来实现,它的作用是将 Example 中的 map 压缩为二进制,节约大量空间

示例代码1:将 MNIST 数据集保存成 TFRecord 文件

  1. import tensorflow as tf
  2. import numpy as np
  3. import input_data
  4.  
  5. # 生成整数型的属性
  6. def _int64_feature(value):
  7. return tf.train.Feature(int64_list = tf.train.Int64List(value = [value]))
  8.  
  9. # 生成字符串类型的属性,也就是图像的内容
  10. def _string_feature(value):
  11. return tf.train.Feature(bytes_list = tf.train.BytesList(value = [value]))
  12.  
  13. # 读取图像数据 和一些属性
  14. mniset = input_data.read_data_sets('../../../data/MNIST_data',dtype=tf.uint8, one_hot=True)
  15. images = mniset.train.images
  16. labels = mniset.train.labels
  17. pixels = images.shape[1] # (55000, 784)
  18. num_examples = mniset.train.num_examples #
  19.  
  20. file_name = 'output.tfrecords' ### 文件名
  21. writer = tf.python_io.TFRecordWriter(file_name) ### 写入器
  22.  
  23. for index in range(num_examples):
  24. ### 遍历样本
  25. image_raw = images[index].tostring() ### 图片转成 字符型
  26. example = tf.train.Example(features = tf.train.Features(feature = {
  27. 'pixel': _int64_feature(pixels),
  28. 'label': _int64_feature(np.argmax(labels[index])),
  29. 'image_raw': _string_feature(image_raw)
  30. }))
  31. writer.write(example.SerializeToString()) ### 写入 TFRecord
  32. writer.close()

示例代码2:将 csv 保存成 TFRecord 文件

  1. train_frame = pd.read_csv("../myfiles/xx3.csv")
  2. train_labels_frame = train_frame.pop(item="label")
  3. train_values = train_frame.values
  4. train_labels = train_labels_frame.values
  5. print("values shape: ", train_values.shape) # values shape: (2, 3)
  6. print("labels shape:", train_labels.shape) # labels shape: (2,)
  7.  
  8. writer = tf.python_io.TFRecordWriter("xx3.tfrecords")
  9.  
  10. for i in range(train_values.shape[0]):
  11. image_raw = train_values[i].tostring()
  12. example = tf.train.Example(
  13. features=tf.train.Features(
  14. feature={
  15. "image_raw": tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_raw])),
  16. "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[train_labels[i]]))
  17. }
  18. )
  19. )
  20. writer.write(record=example.SerializeToString())
  21. writer.close()

示例3:将 png 文件保存成 TFRecord 文件

  1. # filenames = tf.train.match_filenames_once('../myfiles/*.png')
  2. filenames = glob.iglob('..\myfiles\*.png')
  3.  
  4. writer = tf.python_io.TFRecordWriter('png.tfrecords')
  5.  
  6. for filename in filenames:
  7. img = Image.open(filename)
  8. img_raw = img.tobytes()
  9. label = 1
  10. example = tf.train.Example(
  11. features=tf.train.Features(
  12. feature={
  13. "image_raw": tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),
  14. "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[label]))
  15. }
  16. )
  17. )
  18. writer.write(record=example.SerializeToString())
  19. writer.close()

TFRecord 读取

读取文件 和 tensorflow 读取数据方法类似,参考我的博客 读取数据

tf.TFRecordReader()

建立读取器,有 read 和 close 方法

tf.parse_single_example(serialized,features=None,name= None)

解析单个 Example 协议块

  • serialized : 标量字符串的Tensor,一个序列化的Example,文件经过文件阅读器之后的value
  • features :字典数据,key为读取的名字,value为FixedLenFeature
  • return : 一个键值对组成的字典,键为读取的名字

features中的value还可以为tf.VarLenFeature(),但是这种方式用的比较少,它返回的是SparseTensor数据,这是一种只存储非零部分的数据格式,了解即可。

tf.FixedLenFeature(shape,dtype)

  • shape : 输入数据的形状,一般不指定,为空列表
  • dtype : 输入数据类型,与存储进文件的类型要一致,类型只能是float32,int 64, string
  • return : 返回一个定长的 Tensor (即使有零的部分也存储)

示例代码

  1. filename = 'png.tfrecords'
  2. file_queue = tf.train.string_input_producer([filename], shuffle=True)
  3.  
  4. reader = tf.TFRecordReader()
  5. key, value = reader.read(file_queue)
  6.  
  7. ### features 的 key 必须和 写入时 一致,数据类型也必须一致,shape 可为 空
  8. dict_data= tf.parse_single_example(value, features={'label': tf.FixedLenFeature(shape=(1,1), dtype=tf.int64),
  9. 'image_raw': tf.FixedLenFeature(shape=(), dtype=tf.string)})
  10. label = tf.cast(dict_data['label'], tf.int32)
  11. img = tf.decode_raw(dict_data['image_raw'], tf.uint8) ### 将 string、bytes 转换成 int、float
  12.  
  13. image_tensor = tf.reshape(img, [500, 500, -1])
  14.  
  15. sess = tf.Session()
  16. sess.run(tf.local_variables_initializer())
  17. tf.train.start_queue_runners(sess=sess)
  18.  
  19. while 1:
  20. # print(sess.run(key)) # b'png.tfrecords:0'
  21. image = sess.run(image_tensor)
  22. img_PIL = Image.fromarray(image)
  23. img_PIL.show()

参考资料:

https://blog.csdn.net/chengshuhao1991/article/details/78656724

https://www.cnblogs.com/yanshw/articles/12419616.html

tensorflow-TFRecord 文件详解的更多相关文章

  1. web.xml文件详解

      web.xml文件详解 Table of Contents 1 listener. filter.servlet 加载顺序 2 web.xml文件详解 3 相应元素配置 1 listener. f ...

  2. Linux中/proc目录下文件详解

    转载于:http://blog.chinaunix.net/uid-10449864-id-2956854.html Linux中/proc目录下文件详解(一)/proc文件系统下的多种文件提供的系统 ...

  3. SUBLIME TEXT 2 设置文件详解

    SUBLIME TEXT 2 设置文件详解 Preferences.sublime-settings文件: // While you can edit this file, it’s best to ...

  4. [转]AndroidManifest.xml文件详解

    转自:http://www.cnblogs.com/greatverve/archive/2012/05/08/AndroidManifest-xml.html AndroidManifest.xml ...

  5. delphi 资源文件详解

    delphi资源文件详解 一.引子: 现在的Windows应用程序几乎都使用图标.图片.光标.声音等,我们称它们为资源(Resource).最简单的使用资源的办法是把这些资源的源文件打入软件包,以方便 ...

  6. VSFTPD全攻略(/etc/vsftpd/vsftpd.conf文件详解)

    /etc/vsftpd/vsftpd.conf文件详解,分好类,方便大家查找与学习 #################匿名权限控制############### anonymous_enable=YE ...

  7. jni.h头文件详解二

    作者:左少华 博客:http://blog.csdn.net/shaohuazuo/article/details/42932813 转载请注明出处:http://blog.csdn.net/shao ...

  8. 【转】 jni.h头文件详解(二)

    原文网址:http://blog.csdn.net/shaohuazuo/article/details/42932813 作者:左少华 博客:http://blog.csdn.net/shaohua ...

  9. Android.mk文件详解(转)

    源:Android.mk文件详解 从对Makefile一无所知开始,折腾了一个多星期,终于对Android.mk有了一个全面些的了解.了解了标准的Makefile后,发现Android.mk其实是把真 ...

  10. PE文件详解(八)

    本文转载自小甲鱼PE文件详解系列教程原文传送门 当应用程序需要调用DLL中的函数时,会由系统将DLL中的函数映射到程序的虚拟内存中,dll中本身没有自己的栈,它是借用的应用程序的栈,这样当dll中出现 ...

随机推荐

  1. Verilog代码和FPGA硬件的映射关系(二)

    大家可能会有这样的疑问,我们编写的Verilog代码最终会在FPGA上以怎样的映射关系来实现功能呢?我们以一个最简单的组合逻辑与门为例来向大家说明.RTL代码如下所示: //------------- ...

  2. pip命令报错“no perl script found in input”

    windows10,命令行下使用pip命令时报错,python运行成功,且环境变量已经设置,可能是更新了新版本pip所导致 解决方案: 一.使用pip.exe+命令可解决这个问题 二.进行python ...

  3. 面试中很值得聊的二叉树遍历方法——Morris遍历

    Morri遍历 通过利用空闲指针的方式,来节省空间.时间复杂度O(N),额外空间复杂度O(1).普通的非递归和递归方法的额外空间和树的高度有关,递归的过程涉及到系统压栈,非递归需要自己申请栈空间,都具 ...

  4. linux-offen-used-commands

    文件系统 cd 进入目录 ls 列出目录信息,ls -al (或 ll)列出详细信息 touch 新建文件 mkdir 新建目录 rm 删除文件或目录 cp 复制 mv 移动(或重命名) 搜索.查找. ...

  5. 中国电信中兴F412光猫——IPTV与网络单线复用

    标题: 中国电信中兴F412光猫--IPTV与网络单线复用 作者: 梦幻之心星 347369787@QQ.com 标签: [光猫, IPTV] 目录: 路由器 日期: 2019-2-30 目录 第一步 ...

  6. ASP.NET Core WebAPI实现本地化(单资源文件)

    在Startup ConfigureServices 注册本地化所需要的服务AddLocalization和 Configure<RequestLocalizationOptions> p ...

  7. Linux passwd 提权

    利用条件,passwd 可写 ls -al /etc/passwd 利用方式: 生成密钥  openssl passwd -1 -salt test 123456 写入passwd echo 'tes ...

  8. 【Storm】与Hadoop的区别

    1)Storm用于实时计算,Hadoop用于离线计算. 2)Storm处理的数据保存在内存中,源源不断:Hadoop处理的数据保存在文件系统中,一批一批处 理. 3)Storm的数据通过网络传输进来: ...

  9. Java实现 LeetCode 107 二叉树的层次遍历 II(二)

    107. 二叉树的层次遍历 II 给定一个二叉树,返回其节点值自底向上的层次遍历. (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历) 例如: 给定二叉树 [3,9,20,null,null, ...

  10. Java实现 洛谷 P1583 魔法照片

    import java.util.*; class Main{ public static void main(String[] args) { Scanner in = new Scanner(Sy ...