使用TFRecord存取多个数据案例
作者:gaoyueace 发布时间:2023-07-14 22:26:34
标签:TFRecord,存取,数据
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个样例。
来源:https://blog.csdn.net/gaoyueace/article/details/79271747
0
投稿
猜你喜欢
- 装饰器本质上是一个Python函数,它可以让其他函数在不需要做任何代码变动的前提下增加额外功能,装饰器的返回值也是一个函数对象.经常用于有切
- 问:如何给导入文件加上时间戳标记?答:请参考下文中介绍的两种方法:1.在DOS下从系统获得时间戳利用Dos命令取得时间戳:C:\>ec
- 1.获取function形参个数functionName.length2.较适用的运算符delete:删除以前定义的对象属性或方法的引用vo
- 协程中未处理的异常会向上冒泡,传给 next 函数或 send 方法的调用方(即触发协程的对 象)。下面示例举例说明如何使用之前博客示例中由
- 在现代的 web 框架里面,基本都有实现了依赖注入的功能,可以让我们很方便地对应用的依赖进行管理,同时免去在各个地方 new 对象的麻烦。比
- 0.引言自己在下载dlib官网给的example代码时,一开始不知道怎么使用,在一番摸索之后弄明白怎么使用了;现分享下 face_
- 第一步,建立一个CPP的DLL工程,然后写如下代码,生成DLL#include <stdio.h> &nb
- python中,A object = B object 是一种赋值操作,赋的值不是一个对象在内存中的空间,而只是这个
- 调用 <script language="javascript" src="xxx.asp?m
- system默认:managersys默认:change_on_install使用SQL Plus登录数据库时,system使用密码mana
- 进入:直接输入python即可,如图所示退出:1:输入exit(),回车2:输入quit(),回车3:输入ctrl+z,回车来源:https
- 本文实例讲述了Python定时任务sched模块用法。分享给大家供大家参考,具体如下:通过sched模块可以实现通过自定义时间,自定义函数,
- 本文实例为大家分享了python发送邮件的具体代码,供大家参考,具体内容如下#!/usr/bin/env python # -*- codi
- 列表是什么?列表由一系列特定顺序排列的元素组成,你可以创建包含字母表中的所有字母、数字0~9、所有家庭成员姓名的列表等等,也可以将任何东西放
- python怎么查看数据类型?第一步我们首先需要知道在python中查看变量数据类型是使用type()函数,type函数的用法如下图所示:第
- 互联网时代数据是 * 式增长,我们常常需要把结构化数据和非结构化数据(如文档,演示文稿,视频,音频,图像)存储在一起。通常有几种方案: 1。在
- MySQL使用环境变量TMPDIR的值作为保存临时文件的目录的路径名。如果未设置TMPDIR,MySQL将使用系统的默认值,通常为/tmp、
- 结果然后直接放源码:import cv2 as cvsource = cv.imread("zhaopian.jpg")
- 原始结构:Column1 Column2----------- ----------1 A1 B2 C2 D2 E3 F查询效果:Colum
- 如下所示:import matplotlib.pyplot as plt import tkinter import numpy as np