使用TFRecord存取多个数据案例


Posted in Python onFebruary 17, 2020

TensorFlow提供了一种统一的格式来存储数据,就是TFRecord,它可以统一不同的原始数据格式,并且更加有效地管理不同的属性。

TFRecord格式

TFRecord文件中的数据都是用tf.train.Example Protocol Buffer的格式来存储的,tf.train.Example可以被定义为:

message Example{
  Features features = 1
}

message Features{
  map<string, Feature> feature = 1
}

message Feature{
  oneof kind{
    BytesList bytes_list = 1
    FloatList float_list = 1
    Int64List int64_list = 1
  }
}

可以看出Example是一个嵌套的数据结构,其中属性名称可以为一个字符串,其取值可以是字符串BytesList、实数列表FloatList或整数列表Int64List。

将数据转化为TFRecord格式

以下代码是将MNIST输入数据转化为TFRecord格式:

# -*- coding: utf-8 -*-

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np


# 生成整数型的属性
def _int64_feature(value):
  return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

# 生成浮点型的属性
def _float_feature(value):
  return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))  
#若想保存为数组,则要改成value=value即可


# 生成字符串型的属性
def _bytes_feature(value):
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))


mnist = input_data.read_data_sets("/tensorflow_google", dtype=tf.uint8, one_hot=True)
images = mnist.train.images
# 训练数据所对应的正确答案,可以作为一个属性保存在TFRecord中
labels = mnist.train.labels
# 训练数据的图像分辨率,这可以作为Example中的一个属性
pixels = images.shape[1]
num_examples = mnist.train.num_examples

# 输出TFRecord文件的地址
filename = "/tensorflow_google/mnist_output.tfrecords"
# 创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):
  # 将图像矩阵转换成一个字符串
  image_raw = images[index].tostring()
  # 将一个样例转化为Example Protocol Buffer, 并将所有的信息写入这个数据结构
  example = tf.train.Example(features=tf.train.Features(feature={
    'pixels': _int64_feature(pixels),
    'label': _int64_feature(np.argmax(labels[index])),
    'image_raw': _bytes_feature(image_raw)}))

  # 将一个Example写入TFRecord文件
  writer.write(example.SerializeToString())
writer.close()

本程序将MNIST数据集中所有的训练数据存储到了一个TFRecord文件中,若数据量较大,也可以存入多个文件。

从TFRecord文件中读取数据

以下代码可以从上面代码中的TFRecord中读取单个或多个训练数据:

# -*- coding: utf-8 -*-
import tensorflow as tf

# 创建一个reader来读取TFRecord文件中的样例
reader = tf.TFRecordReader()
# 创建一个队列来维护输入文件列表
filename_queue = tf.train.string_input_producer(["/Users/gaoyue/文档/Program/tensorflow_google/chapter7"
                         "/mnist_output.tfrecords"])

# 从文件中读出一个样例,也可以使用read_up_to函数一次性读取多个样例
# _, serialized_example = reader.read(filename_queue)
_, serialized_example = reader.read_up_to(filename_queue, 6) #读取6个样例
# 解析读入的一个样例,如果需要解析多个样例,可以用parse_example函数
# features = tf.parse_single_example(serialized_example, features={
# 解析多个样例
features = tf.parse_example(serialized_example, features={
  # TensorFlow提供两种不同的属性解析方法
  # 第一种是tf.FixedLenFeature,得到的解析结果为Tensor
  # 第二种是tf.VarLenFeature,得到的解析结果为SparseTensor,用于处理稀疏数据
  # 解析数据的格式需要与写入数据的格式一致
  'image_raw': tf.FixedLenFeature([], tf.string),
  'pixels': tf.FixedLenFeature([], tf.int64),
  'label': tf.FixedLenFeature([], tf.int64),
})

# tf.decode_raw可以将字符串解析成图像对应的像素数组
images = tf.decode_raw(features['image_raw'], tf.uint8)
labels = tf.cast(features['label'], tf.int32)
pixels = tf.cast(features['pixels'], tf.int32)

sess = tf.Session()
# 启动多线程处理输入数据
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

# 每次运行可以读取TFRecord中的一个样例,当所有样例都读完之后,会重头读取
# for i in range(10):
#   image, label, pixel = sess.run([images, labels, pixels])
#   # print(image, label, pixel)
#   print(label, pixel)

# 读取TFRecord中的前6个样例,若加入循环,则会每次从上次输出的地方继续顺序读6个样例
image, label, pixel = sess.run([images, labels, pixels])
print(label, pixel)

sess.close()

>> [7 3 4 6 1 8] [784 784 784 784 784 784]

输出结果显示,从TFRecord文件中顺序读出前6个样例。

以上这篇使用TFRecord存取多个数据案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
在Python中使用__slots__方法的详细教程
Apr 28 Python
python列表操作之extend和append的区别实例分析
Jul 28 Python
Python基于ThreadingTCPServer创建多线程代理的方法示例
Jan 11 Python
详谈python在windows中的文件路径问题
Apr 28 Python
Python中asyncio与aiohttp入门教程
Oct 16 Python
python读取word文档,插入mysql数据库的示例代码
Nov 07 Python
python读取指定字节长度的文本方法
Aug 27 Python
python numpy数组中的复制知识解析
Feb 03 Python
python-docx文件定位读取过程(尝试替换)
Feb 13 Python
PyQt5如何将.ui文件转换为.py文件的实例代码
May 26 Python
Python 如何反方向迭代一个序列
Jul 28 Python
Python利用folium实现地图可视化
May 23 Python
从多个tfrecord文件中无限读取文件的例子
Feb 17 #Python
Python3连接Mysql8.0遇到的问题及处理步骤
Feb 17 #Python
python3连接MySQL8.0的两种方式
Feb 17 #Python
Win10下安装并使用tensorflow-gpu1.8.0+python3.6全过程分析(显卡MX250+CUDA9.0+cudnn)
Feb 17 #Python
Windows下实现将Pascal VOC转化为TFRecords
Feb 17 #Python
tensorflow生成多个tfrecord文件实例
Feb 17 #Python
tensorflow将图片保存为tfrecord和tfrecord的读取方式
Feb 17 #Python
You might like
php与XML、XSLT、Mysql的结合运用实现代码
2009/11/19 PHP
PHP print类函数使用总结
2010/06/25 PHP
php一行代码获取文件后缀名实例分析
2014/11/12 PHP
Laravel学习教程之model validation的使用示例
2017/10/23 PHP
Laravel框架实现定时发布任务的方法
2018/08/16 PHP
简介JavaScript中Math.LOG10E属性的使用
2015/06/14 Javascript
全面解析Bootstrap表单使用方法(表单按钮)
2015/11/24 Javascript
jQuery Validation PlugIn的使用方法详解
2015/12/18 Javascript
JavaScript中判断数据类型的方法总结
2016/05/24 Javascript
在Debian(Raspberry Pi)树莓派上安装NodeJS的教程详解
2017/09/19 NodeJs
vue的安装及element组件的安装方法
2018/03/09 Javascript
关于vue-router的那些事儿
2018/05/23 Javascript
JS实现星星海特效
2019/12/24 Javascript
微信小程序动态添加和删除组件的现实
2020/02/28 Javascript
Js生成随机数/随机字符串的方法小结【5种方法】
2020/05/27 Javascript
[03:02]安得倚天剑,跨海斩长鲸——中国军团出征DOTA2国际邀请赛
2018/08/14 DOTA
python 切片和range()用法说明
2013/03/24 Python
bat和python批量重命名文件的实现代码
2016/05/19 Python
python 捕获 shell/bash 脚本的输出结果实例
2017/01/04 Python
Python2.7.10以上pip更新及其他包的安装教程
2018/06/12 Python
在Python中获取两数相除的商和余数方法
2018/11/10 Python
python使用matplotlib绘制雷达图
2019/10/18 Python
python定时任务 sched模块用法实例
2019/11/04 Python
用Python实现校园通知更新提醒功能
2019/11/23 Python
使用python实现数组、链表、队列、栈的方法
2019/12/20 Python
python接口自动化如何封装获取常量的类
2019/12/24 Python
Windows下python3安装tkinter的问题及解决方法
2020/01/06 Python
什么是托管函数?托管函数有什么用?
2014/06/15 面试题
三个Unix的命令面试题
2015/04/12 面试题
我爱幼儿园演讲稿
2014/09/11 职场文书
国家机关领导干部民主生活会对照检查材料思想汇报
2014/09/17 职场文书
房产协议书范本2014
2014/09/30 职场文书
2014年挂职干部工作总结
2014/12/06 职场文书
企业2014年度工作总结
2014/12/10 职场文书
Html5生成验证码的示例代码
2021/05/10 Javascript
Python OpenGL基本配置方式
2022/05/20 Python