Tensorflow读写TFRecords文件
在使用slim之类的tensorflow自带框架的时候一般默认的数据格式就是TFRecords,在训练的时候使用TFRecords中数据的流程如下:使用input pipeline读取tfrecords文件/其他支持的格式,然后随机乱序,生成文件序列,读取并解码数据,输入模型训练。
如果有一串jpg图片地址和相应的标签:images和labels
1. 生成TFrecords
存入TFRecords文件需要数据先存入名为example的protocol buffer,然后将其serialize成为string才能写入。example中包含features,用于描述数据类型:bytes,float,int64。
import tensorflow as tf
import cv2
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))
train_filename = 'train.tfrecords'
with tf.python_io.TFRecordWriter(train_filename) as tfrecord_writer:
for i in range(len(images)):
# read in image data by tf
img_data = tf.gfile.FastGFile(images[i], 'rb').read() # image data type is string
label = labels[i]
# get width and height of image
image_shape = cv2.imread(images[i]).shape
width = image_shape[1]
height = image_shape[0]
# create features
feature = {'train/image': _bytes_feature(img_data),
'train/label': _int64_feature(label), # label: integer from 0-N
'train/height': _int64_feature(height),
'train/width': _int64_feature(width)}
# create example protocol buffer
example = tf.train.Example(features=tf.train.Features(feature=feature))
# serialize protocol buffer to string
tfrecord_writer.write(example.SerializeToString())
tfrecord_writer.close()
2. 读取TFRecords文件
首先用tf.train.string_input_producer读取tfrecords文件的list建立FIFO序列,可以申明num_epoches和shuffle参数表示需要读取数据的次数以及时候将tfrecords文件读入顺序打乱,然后定义TFRecordReader读取上面的序列返回下一个record,用tf.parse_single_example对读取到TFRecords文件进行解码,根据保存的serialize example和feature字典返回feature所对应的值。此时获得的值都是string,需要进一步解码为所需的数据类型。把图像数据的string reshape成原始图像后可以进行preprocessing操作。此外,还可以通过tf.train.batch或者tf.train.shuffle_batch将图像生成batch序列。
由于tf.train函数会在graph中增加tf.train.QueueRunner类,而这些类有一系列的enqueue选项使一个队列在一个线程里运行。为了填充队列就需要用tf.train.start_queue_runners来为所有graph中的queue runner启动线程,而为了管理这些线程就需要一个tf.train.Coordinator来在合适的时候终止这些线程。
import tensorflow as tf
import matplotlib.pyplot as plt
data_path = 'train.tfrecords'
with tf.Session() as sess:
# feature key and its data type for data restored in tfrecords file
feature = {'train/image': tf.FixedLenFeature([], tf.string),
'train/label': tf.FixedLenFeature([], tf.int64),
'train/height': tf.FixedLenFeature([], tf.int64),
'train/width': tf.FixedLenFeature([], tf.int64)}
# define a queue base on input filenames
filename_queue = tf.train.string_input_producer([data_path], num_epoches=1)
# define a tfrecords file reader
reader = tf.TFRecordReader()
# read in serialized example data
_, serialized_example = reader.read(filename_queue)
# decode example by feature
features = tf.parse_single_example(serialized_example, features=feature)
image = tf.image.decode_jpeg(features['train/image'])
image = tf.image.convert_image_dtype(image, dtype=tf.float32) # convert dtype from unit8 to float32 for later resize
label = tf.cast(features['train/label'], tf.int64)
height = tf.cast(features['train/height'], tf.int32)
width = tf.cast(features['train/width'], tf.int32)
# restore image to [height, width, 3]
image = tf.reshape(image, [height, width, 3])
# resize
image = tf.image.resize_images(image, [224, 224])
# create bathch
images, labels = tf.train.shuffle_batch([image, label], batch_size=10, capacity=30, num_threads=1, min_after_dequeue=10) # capacity是队列的最大容量,num_threads是dequeue后最小的队列大小,num_threads是进行队列操作的线程数。
# initialize global & local variables
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
sess.run(init_op)
# create a coordinate and run queue runner objects
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for batch_index in range(3):
batch_images, batch_labels = sess.run([images, labels])
for i in range(10):
plt.imshow(batch_images[i, ...])
plt.show()
print "Current image label is: ", batch_lables[i]
# close threads
coord.request_stop()
coord.join(threads)
sess.close()
参考
- https://stackoverflow.com/questions/37151895/tensorflow-read-all-examples-from-a-tfrecords-at-once
- http://www.machinelearninguru.com/deep_learning/tensorflow/basics/tfrecord/tfrecord.html
Tensorflow读写TFRecords文件的更多相关文章
- Tensorflow 读写 tfrecord 文件(Python3)
TensorFlow笔记博客:https://blog.csdn.net/xierhacker/article/category/6511974 写入tfrecord文件 import tensorf ...
- tensorflow二进制文件读取与tfrecords文件读取
1.知识点 """ TFRecords介绍: TFRecords是Tensorflow设计的一种内置文件格式,是一种二进制文件,它能更好的利用内存, 更方便复制和移动,为 ...
- 使用Python读写csv文件的三种方法
Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗号分隔值(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是 ...
- python读写csv文件
文章链接:https://www.cnblogs.com/cloud-ken/p/8432999.html Python读写csv文件 觉得有用的话,欢迎一起讨论相互学习~Follow Me 前言 逗 ...
- TFRecords文件的生成和读取(1)
参考:https://blog.csdn.net/u012222949/article/details/72875281 参考:https://blog.csdn.net/chengshuhao199 ...
- tensorflow 使用tfrecords创建自己数据集
直接采用矩阵方式建立数据集见:https://www.cnblogs.com/WSX1994/p/10128338.html 制作自己的数据集(使用tfrecords) 为什么采用这个格式? TFRe ...
- (第二章第一部分)TensorFlow框架之文件读取流程
本章概述:在第一章的系列文章中介绍了tf框架的基本用法,从本章开始,介绍与tf框架相关的数据读取和写入的方法,并会在最后,用基础的神经网络,实现经典的Mnist手写数字识别. 有四种获取数据到Tens ...
- [转载]C#读写txt文件的两种方法介绍
C#读写txt文件的两种方法介绍 by 大龙哥 1.添加命名空间 System.IO; System.Text; 2.文件的读取 (1).使用FileStream类进行文件的读取,并将它转换成char ...
- 用opencsv文件读写CSV文件
首先明白csv文件长啥样儿: 用excel打开就变成表格了,看不到细节 推荐用其它简单粗暴一点儿的编辑器,比如Notepad++, csv文件内容如下: csv文件默认用逗号分隔各列. 有了基础的了解 ...
随机推荐
- MAC自动脚本
链接: crontab 详细用法 定时任务 Linux crontab命令 定时任务 用法详解以及no crontab for root解决办法
- 从零开始优雅的使用mongodb实例
基本连接 一.创建express工程testmon express testmon 二.精简app.js var express = require("express"); var ...
- Java中的语法糖
一.范型 1. C#和Java范型的区别 在C#中范型是切实存在的,List<int>和List<String>就是两种不同的类型,它们在系统运行期间生成,有自己的虚方法表和类 ...
- float:浮点型double:双精度实型decimal:数字型单精度浮点数(Single)双精度浮点数(double)
单精度浮点数(Single) 双精度浮点数(double) Decimal为SQL Server.MySql等数据库的一种数据类型,不属于浮点数类型,可以在定义时划定整数部分以及小 ...
- 浅谈压缩感知(二十四):压缩感知重构算法之子空间追踪(SP)
主要内容: SP的算法流程 SP的MATLAB实现 一维信号的实验与结果 测量数M与重构成功概率关系的实验与结果 SP与CoSaMP的性能比较 一.SP的算法流程 压缩采样匹配追踪(CoSaMP)与子 ...
- python2中在sqlite3中插入中文
# -*- coding: utf-8 -*- import sqlite3 conn = sqlite3.connect('SWC_Perf_Info.db') cur = conn.cursor( ...
- 摄像专用的SD卡推荐
此类SD卡主要需要满足快速写入:特别对于4K的支持,速度要有很高才能满足. 文章来源:刘俊涛的博客 欢迎关注,有问题一起学习欢迎留言.评论
- dubbo服务启动的方式
dubbo服务启动的方式: 1.dubbo自带的脚本, 2.直接用main方法启动dubbo的spring容器,参见dubbo-test里的各个例子 3.dubbo的spring boot start ...
- IntelliJ IDEA for Mac(Java 语言开发的集成环境)破解版安装
1.软件简介 IntelliJ IDEA 是 macOS 系统上一款 java 语言开发的集成环境,IntelliJ 在业界被公认为最好的 java 开发工具之一,尤其在智能代码助手.代码自动提 ...
- 11G新特性 -- 分区表和增量统计信息
对于分区表,优化器会在全局级别为整个表维护一份统计信息,也会在分区级别为分区表维护一份统计信息. 对于大多数分区,dml一般都是在最近的分区上执行.在11g中,数据库支持只对那些发生一定数据变化的分区 ...