Tensorflow使用tfrecord输入数据格式


Posted in Python onJune 19, 2018

Tensorflow 提供了一种统一的格式来存储数据,这个格式就是TFRecord,上一篇文章中所提到的方法当数据的来源更复杂,每个样例中的信息更丰富的时候就很难有效的记录输入数据中的信息了,于是Tensorflow提供了TFRecord来统一存储数据,接下来我们就来介绍如何使用TFRecord来同意输入数据的格式。

1. TFRecord格式介绍

TFRecord文件中的数据是通过tf.train.Example Protocol Buffer的格式存储的,下面是tf.train.Example的定义

message Example {
 Features features = 1;
};

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

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

从上述代码可以看到,ft.train.Example 的数据结构相对简洁。tf.train.Example中包含了一个从属性名称到取值的字典,其中属性名称为一个字符串,属性的取值可以为字符串(BytesList ),实数列表(FloatList )或整数列表(Int64List )。例如我们可以将解码前的图片作为字符串,图像对应的类别标号作为整数列表。

2. 将自己的数据转化为TFRecord格式

准备数据

在上一篇中,我们为了像伟大的MNIST致敬,所以选择图像的前缀来进行不同类别的分类依据,但是大多数的情况下,在进行分类任务的过程中,不同的类别都会放在不同的文件夹下,而且类别的个数往往浮动性又很大,所以针对这样的情况,我们现在利用不同类别在不同文件夹中的图像来生成TFRecord.

我们在Iris&Contact这个文件夹下有两个文件夹,分别为iris,contact。对于每个文件夹中存放的是对应的图片

转换数据

数据准备好以后,就开始准备生成TFRecord,具体代码如下:

import os 
import tensorflow as tf 
from PIL import Image 
import matplotlib.pyplot as plt 

cwd='/home/ruyiwei/Documents/Iris&Contact/'
classes={'iris','contact'} 
writer= tf.python_io.TFRecordWriter("iris_contact.tfrecords") 

for index,name in enumerate(classes):
  class_path=cwd+name+'/'
  for img_name in os.listdir(class_path): 
    img_path=class_path+img_name 
    img=Image.open(img_path)
    img= img.resize((512,80))
    img_raw=img.tobytes()
    #plt.imshow(img) # if you want to check you image,please delete '#'
    #plt.show()
    example = tf.train.Example(features=tf.train.Features(feature={
      "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
      'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
    })) 
    writer.write(example.SerializeToString()) 

writer.close()

3. Tensorflow从TFRecord中读取数据

def read_and_decode(filename): # read iris_contact.tfrecords
  filename_queue = tf.train.string_input_producer([filename])# create a queue

  reader = tf.TFRecordReader()
  _, serialized_example = reader.read(filename_queue)#return file_name and file
  features = tf.parse_single_example(serialized_example,
                    features={
                      'label': tf.FixedLenFeature([], tf.int64),
                      'img_raw' : tf.FixedLenFeature([], tf.string),
                    })#return image and label

  img = tf.decode_raw(features['img_raw'], tf.uint8)
  img = tf.reshape(img, [512, 80, 3]) #reshape image to 512*80*3
  img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 #throw img tensor
  label = tf.cast(features['label'], tf.int32) #throw label tensor
  return img, label

4. 将TFRecord中的数据保存为图片

filename_queue = tf.train.string_input_producer(["iris_contact.tfrecords"]) 
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue)  #return file and file_name
features = tf.parse_single_example(serialized_example,
                  features={
                    'label': tf.FixedLenFeature([], tf.int64),
                    'img_raw' : tf.FixedLenFeature([], tf.string),
                  }) 
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [512, 80, 3])
label = tf.cast(features['label'], tf.int32)
with tf.Session() as sess: 
  init_op = tf.initialize_all_variables()
  sess.run(init_op)
  coord=tf.train.Coordinator()
  threads= tf.train.start_queue_runners(coord=coord)
  for i in range(20):
    example, l = sess.run([image,label])#take out image and label
    img=Image.fromarray(example, 'RGB')
    img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#save image
    print(example, l)
  coord.request_stop()
  coord.join(threads)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
pandas把dataframe转成Series,改变列中值的类型方法
Apr 10 Python
python flask实现分页的示例代码
Aug 02 Python
python 实现提取某个索引中某个时间段的数据方法
Feb 01 Python
11个Python Pandas小技巧让你的工作更高效(附代码实例)
Apr 30 Python
Python操作redis实例小结【String、Hash、List、Set等】
May 16 Python
django 中QuerySet特性功能详解
Jul 25 Python
python对Excel按条件进行内容补充(推荐)
Nov 24 Python
Python全局变量与global关键字常见错误解决方案
Oct 05 Python
利用Python pandas对Excel进行合并的方法示例
Nov 04 Python
Python jieba库分词模式实例用法
Jan 13 Python
python 第三方库paramiko的常用方式
Feb 20 Python
Python Django框架介绍之模板标签及模板的继承
May 27 Python
Tensorflow 训练自己的数据集将数据直接导入到内存
Jun 19 #Python
python如何爬取个性签名
Jun 19 #Python
详解TensorFlow查看ckpt中变量的几种方法
Jun 19 #Python
TensorFlow 滑动平均的示例代码
Jun 19 #Python
python3个性签名设计实现代码
Jun 19 #Python
TensorFlow 模型载入方法汇总(小结)
Jun 19 #Python
python3爬虫之设计签名小程序
Jun 19 #Python
You might like
PHP 自定义错误处理函数的使用详解
2013/05/10 PHP
探讨捕获php错误信息方法的详解
2013/06/09 PHP
php使用PDO方法详解
2014/12/27 PHP
php自定义函数实现JS的escape的方法示例
2016/07/07 PHP
php下载远程大文件(获取远程文件大小)的实例
2017/06/17 PHP
phpStudy配置多站点多域名和多端口的方法
2017/09/01 PHP
php+ajax实现商品对比功能示例
2019/04/13 PHP
node.js中的path.extname方法使用说明
2014/12/09 Javascript
js正则表达式中exec用法实例
2015/07/23 Javascript
jquery利用拖拽方式在图片上添加热链接
2015/11/24 Javascript
深入分析jQuery的ready函数是如何工作的(工作原理)
2015/12/17 Javascript
AngularJS单选框及多选框实现双向动态绑定
2016/01/13 Javascript
JS实现太极旋转思路分析
2016/12/09 Javascript
bootstrap配合Masonry插件实现瀑布式布局
2017/01/18 Javascript
Spring boot 和Vue开发中CORS跨域问题解决
2018/09/05 Javascript
解决layui富文本编辑器图片上传无法回显的问题
2019/09/18 Javascript
vue学习笔记之slot插槽基本用法实例分析
2020/02/01 Javascript
node.js中 mysql 增删改查操作及async,await处理实例分析
2020/02/11 Javascript
彻底搞懂并解决vue-cli4中图片显示的问题实现
2020/08/31 Javascript
在Python的web框架中中编写日志列表的教程
2015/04/30 Python
python使用urllib2提交http post请求的方法
2015/05/26 Python
浅谈Python Opencv中gamma变换的使用详解
2018/04/02 Python
Apache部署Django项目图文详解
2019/07/30 Python
浅谈在django中使用redirect重定向数据传输的问题
2020/03/13 Python
Python+Kepler.gl轻松制作酷炫路径动画的实现示例
2020/06/02 Python
css3动画过渡实现鼠标跟随导航效果
2018/02/08 HTML / CSS
中国领先的专业演出票务网:永乐票务
2016/08/29 全球购物
英国领先的高级美容和在线皮肤诊所:Face the Future
2020/06/17 全球购物
数学专业毕业生自荐信
2013/11/10 职场文书
校园创业策划书
2014/01/14 职场文书
体育教师自我鉴定
2014/02/12 职场文书
幼儿园健康教育方案
2014/06/14 职场文书
领导干部四风问题自我剖析材料
2014/09/25 职场文书
工程项目合作意向书
2015/05/08 职场文书
《角的度量》教学反思
2016/02/18 职场文书
晚会开幕词范文
2016/03/04 职场文书