TF数据读取队列机制详解

一、TFR文件多线程队列读写操作

TFRecod文件写入操作

  1. import tensorflow as tf
  2. def _int64_feature(value):
  3. # value必须是可迭代对象
  4. # 非int的数据使用bytes取代int64即可
  5. return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
  6. num_shards = 2
  7. instance_perPshard = 2
  8. for i in range(num_shards):
  9. filename = ('FTR/data.tfrecords-%.5d-of-%.5d' % (i, num_shards))
  10. writer = tf.python_io.TFRecordWriter(filename) #<---------书写器打开
  11. for j in range(instance_perPshard):
  12. example = tf.train.Example(features=tf.train.Features(feature={ #<---------书写入缓冲区
  13. 'i':_int64_feature(i),
  14. 'j':_int64_feature(j)
  15. }))
  16. writer.write(example.SerializeToString()) #<---------书写入实际文件
  17. writer.close() #<---------书写器关闭

TFRecod文件读取操作

默认多线程,这个默认的多线程过程用于维护文件名队列

  1. '''读取TFR'''
  2.  
  3. files = ["FTR/data.tfrecords-00000-of-00002","FTR/data.tfrecords-00001-of-00002"]
  4. # files = tf.train.match_filenames_once("FTR/data.tfrecords-*")
  5.  
  6. # 输入文件名列表
  7. # 返回QueueRunner & FIFOQueue
  8. # 打乱顺序&加入队列 和 输出队列获取文件 属于单独的线程
  9. filename_queue = tf.train.string_input_producer(files, shuffle=False) #<---------输入文件队列
  10. reader = tf.TFRecordReader() #<---------读取器打开
  11. _,serialized_example = reader.read(filename_queue) #<---------读取原始文件
  12. features = tf.parse_single_example( #<---------读取解析后文件
  13. serialized_example,
  14. features={
  15. 'i':tf.FixedLenFeature([],tf.int64),
  16. 'j':tf.FixedLenFeature([],tf.int64)
  17. })
  18.  
  19. with tf.Session() as sess:
  20. tf.global_variables_initializer().run()
  21. coord = tf.train.Coordinator() #<---------多线程
  22. threads = tf.train.start_queue_runners(sess=sess,coord=coord) #<---------文件名队列填充线程启动
  23. for i in range(6):
  24. print(sess.run([features['i'],features['j']])) #<---------实际会话中启动读取过程
  25. coord.request_stop() #<---------多线程
  26. coord.join(threads) #<---------多线程

TFRecod文件打包操作

打包机制:

——————多线程调用前面的节点计算入队

——————批量出队并打包

所以不需要修改解析读取数据过程为循环之类的,可以说很是方便

  1. example_batch, label_batch = tf.train.batch([example, label], #<---------多线程batch生成
  2. batch_size=batch_size,
  3. num_threads=3,
  4. capacity=capacity)
  5.  
  6. example_batch, label_batch = tf.train.shuffle_batch([example, label], #<---------多线程随机batch生成
  7. batch_size=batch_size,
  8. num_threads=3,
  9. capacity=capacity,
  10. min_after_dequeue=30) 由于元素太少随机意义就不大了,所以多了个参数

使用范例,

  1. files = ["FTR/data.tfrecords-00000-of-00002","FTR/data.tfrecords-00001-of-00002"]
  2. # files = tf.train.match_filenames_once("FTR/data.tfrecords-*")
  3.  
  4. # 输入文件名列表
  5. # 返回QueueRunner & FIFOQueue
  6. # 打乱顺序&加入队列 和 输出队列获取文件 属于单独的线程
  7. filename_queue = tf.train.string_input_producer(files, shuffle=False) #<---------输入文件队列
  8. reader = tf.TFRecordReader() #<---------读取
  9. _,serialized_example = reader.read(filename_queue) #<---------读取
  10. features = tf.parse_single_example( #<---------读取
  11. serialized_example,
  12. features={
  13. 'i':tf.FixedLenFeature([],tf.int64),
  14. 'j':tf.FixedLenFeature([],tf.int64)
  15. })
  16.  
  17. example, label = features['i'], features['j']
  18. batch_size = 2
  19. capacity = 1000 + 3 * batch_size
  20.  
  21. # 入队单个样例,出队batch
  22. # 可以指定多个线程同时执行入队操作
  23. example_batch, label_batch = tf.train.batch([example, label], #<---------多线程batch生成
  24. batch_size=batch_size,
  25. num_threads=3,
  26. capacity=capacity)
  27. with tf.Session() as sess:
  28. tf.global_variables_initializer().run()
  29. coord = tf.train.Coordinator() #<---------多线程管理器
  30. threads = tf.train.start_queue_runners(sess=sess,coord=coord) #<---------文件名队列填充线程启动
  31. for i in range(3):
  32. cur_example_batch, cur_label_batch = sess.run([example_batch, label_batch])
  33. print(cur_example_batch, cur_label_batch)
  34. coord.request_stop() #<---------多线程关闭
  35. coord.join(threads)

这个输出每一行前为image(代指),后为label,第一行的数据对实际为0-0,0-1:

  1. [0 0] [0 1]
  2. [1 1] [0 1]
  3. [0 0] [0 1]

二、图片文件使用TFR读写测试

read的二进制数据直接进行_bytes_feature化就可以写入文件,使用tf.string类型读出图片数据后可以直接decode解码之(推测tf中string对应二进制数据类型)。

把一张图片写入TFR中:

  1. import tensorflow as tf
  2. import matplotlib.pyplot as plt
  3.  
  4. def _bytes_feature(value):
  5. return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
  6. def _int64_feature(value):
  7. return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
  8. img_raw = tf.gfile.FastGFile('123123.jpeg','rb').read()
  9.  
  10. filename = ('FTR/image.tfrecords')
  11. writer = tf.python_io.TFRecordWriter(filename) #<---------书写
  12. example = tf.train.Example(features=tf.train.Features(feature={ #<---------书写
  13. 'image':_bytes_feature(img_raw),
  14. 'label':_int64_feature(1)
  15. }))
  16. writer.write(example.SerializeToString()) #<---------书写
  17. writer.close()

从TFR中读取图片数据并解码绘制出来:

  1. filename_queue = tf.train.string_input_producer(['FTR/image.tfrecords'], shuffle=False) #<---------输入文件队列
  2. reader = tf.TFRecordReader() #<---------读取
  3. _,serialized_example = reader.read(filename_queue) #<---------读取
  4. features = tf.parse_single_example( #<---------读取
  5. serialized_example,
  6. features={
  7. 'image':tf.FixedLenFeature([],tf.string),
  8. 'label':tf.FixedLenFeature([],tf.int64)
  9. })
  10. img = tf.image.decode_jpeg(features['image'])
  11. with tf.Session() as sess:
  12. tf.global_variables_initializer().run()
  13.  
  14. coord = tf.train.Coordinator() # <---------多线程
  15. threads = tf.train.start_queue_runners(sess=sess, coord=coord) # <---------文件名队列填充线程启动
  16. # img_raw, label = sess.run([features['image'], features['label']])
  17. image = sess.run(img)
  18. plt.imshow(image)
  19. plt.show()
  20. coord.request_stop() # <---------多线程
  21. coord.join(threads) # <---------多线程

三、图片文件直接使用队列读写操作

仅仅示范了维护图片文件名队列的读写,没有过多的其他操作

reader = tf.WholeFileReader():新的读取器,应该是范用性二进制文件读取器

  1. # 导入tensorflow
  2. import tensorflow as tf
  3.  
  4. # 新建一个Session
  5. with tf.Session() as sess:
  6. # 我们要读三幅图片A.jpg, B.jpg, C.jpg
  7. filename = ['123.png', '123123.jpeg']
  8. # string_input_producer会产生一个文件名队列
  9. filename_queue = tf.train.string_input_producer(filename, shuffle=False, num_epochs=5)
  10. # reader从文件名队列中读数据。对应的方法是reader.read
  11. reader = tf.WholeFileReader() #<---------注意读取器不一样了
  12. key, value = reader.read(filename_queue)
  13. # tf.train.string_input_producer定义了一个epoch变量,要对它进行初始化
  14. tf.local_variables_initializer().run()
  15. # 使用start_queue_runners之后,才会开始填充队列
  16. threads = tf.train.start_queue_runners(sess=sess)
  17. i = 0
  18. while True:
  19. i += 1
  20. # 获取图片数据并保存
  21. image_data = sess.run(value)
  22. with open('test_%d.jpg' % i, 'wb') as f:
  23. f.write(image_data)

四、队列文件使用范式

文件名队列创建->读取解析文件->打包解析好的文件->多线程启动图训练(多线程指被使用的部分其实还是文件读取)

  1. import tensorflow as tf
  2.  
  3. '''创建文件列表'''
  4.  
  5. files = tf.train.match_filenames_once("Records/output.tfrecords")
  6. filename_queue = tf.train.string_input_producer(files, shuffle=False)
  7.  
  8. '''解析TFRecord文件里的数据'''
  9.  
  10. # 读取文件。
  11.  
  12. reader = tf.TFRecordReader()
  13. _,serialized_example = reader.read(filename_queue)
  14.  
  15. # 解析读取的样例。
  16. features = tf.parse_single_example(
  17. serialized_example,
  18. features={
  19. 'image_raw':tf.FixedLenFeature([],tf.string),
  20. 'pixels':tf.FixedLenFeature([],tf.int64),
  21. 'label':tf.FixedLenFeature([],tf.int64)
  22. })
  23.  
  24. decoded_images = tf.decode_raw(features['image_raw'],tf.uint8)
  25. retyped_images = tf.cast(decoded_images, tf.float32)
  26. labels = tf.cast(features['label'],tf.int32)
  27. #pixels = tf.cast(features['pixels'],tf.int32)
  28. images = tf.reshape(retyped_images, [784])
  29.  
  30. '''将文件以100个为一组打包'''
  31.  
  32. min_after_dequeue = 10000
  33. batch_size = 100
  34. capacity = min_after_dequeue + 3 * batch_size
  35.  
  36. image_batch, label_batch = tf.train.shuffle_batch([images, labels],
  37. batch_size=batch_size,
  38. capacity=capacity,
  39. min_after_dequeue=min_after_dequeue)
  40.  
  41. '''训练模型'''
  42.  
  43. def inference(input_tensor, weights1, biases1, weights2, biases2):
  44. layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
  45. return tf.matmul(layer1, weights2) + biases2
  46.  
  47. # 模型相关的参数
  48. INPUT_NODE = 784
  49. OUTPUT_NODE = 10
  50. LAYER1_NODE = 500
  51. REGULARAZTION_RATE = 0.0001
  52. TRAINING_STEPS = 5000
  53.  
  54. weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
  55. biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))
  56.  
  57. weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
  58. biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))
  59.  
  60. y = inference(image_batch, weights1, biases1, weights2, biases2)
  61.  
  62. # 计算交叉熵及其平均值
  63. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=label_batch)
  64. cross_entropy_mean = tf.reduce_mean(cross_entropy)
  65.  
  66. # 损失函数的计算
  67. regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
  68. regularaztion = regularizer(weights1) + regularizer(weights2)
  69. loss = cross_entropy_mean + regularaztion
  70.  
  71. # 优化损失函数
  72. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
  73.  
  74. # 初始化回话并开始训练过程。
  75. with tf.Session() as sess:
  76. tf.global_variables_initializer().run()
  77. coord = tf.train.Coordinator()
  78. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  79. # 循环的训练神经网络。
  80. for i in range(TRAINING_STEPS):
  81. if i % 1000 == 0:
  82. print("After %d training step(s), loss is %g " % (i, sess.run(loss)))
  83.  
  84. sess.run(train_step)
  85. coord.request_stop()
  86. coord.join(threads)

『TensorFlow』第十一弹_队列&多线程&TFRecod文件_我辈当高歌的更多相关文章

  1. 『TensorFlow』第七弹_保存&载入会话_霸王回马

    首更: 由于TensorFlow的奇怪形式,所以载入保存的是sess,把会话中当前激活的变量保存下来,所以必须保证(其他网络也要求这个)保存网络和载入网络的结构一致,且变量名称必须一致,这是caffe ...

  2. 『TensorFlow』第十弹_队列&多线程_道路多坎坷

    一.基本队列: 队列有两个基本操作,对应在tf中就是enqueue&dequeue tf.FIFOQueue(2,'int32') import tensorflow as tf '''FIF ...

  3. 『TensorFlow』第三弹_可视化框架介绍_悄悄问圣僧

    添加记录节点 -> 汇总记录节点 -> run汇总节点 -> [书写器生成]书写入文件 [-> 刷新缓冲区] 可视化关键点: 注意, 1.with tf.name_scope( ...

  4. 『MXNet』第十一弹_符号式编程初探

    一.符号分类 符号对我们想要进行的计算进行了描述, 下图展示了符号如何对计算进行描述. 我们定义了符号变量A, 符号变量B, 生成了符号变量C, 其中, A, B为参数节点, C为内部节点! mxne ...

  5. 『PyTorch』第十一弹_torch.optim优化器

    一.简化前馈网络LeNet import torch as t class LeNet(t.nn.Module): def __init__(self): super(LeNet, self).__i ...

  6. 『PyTorch』第十一弹_torch.optim优化器 每层定制参数

    一.简化前馈网络LeNet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 im ...

  7. 『TensorFlow』专题汇总

    TensorFlow:官方文档 TensorFlow:项目地址 本篇列出文章对于全零新手不太合适,可以尝试TensorFlow入门系列博客,搭配其他资料进行学习. Keras使用tf.Session训 ...

  8. 『TensorFlow』模型保存和载入方法汇总

    『TensorFlow』第七弹_保存&载入会话_霸王回马 一.TensorFlow常规模型加载方法 保存模型 tf.train.Saver()类,.save(sess, ckpt文件目录)方法 ...

  9. 『PyTorch x TensorFlow』第六弹_从最小二乘法看自动求导

    TensoFlow自动求导机制 『TensorFlow』第二弹_线性拟合&神经网络拟合_恰是故人归 下面做了三个简单尝试, 利用包含gradients.assign等tf函数直接构建图进行自动 ...

随机推荐

  1. BZOJ 4159 [Neerc2009]Business Center

    思路 简单的模拟,答案就是\(min\{(\lfloor\frac{d\times n}{u+d}\rfloor+1)\times(u+d)-d\times n\}\) 代码 #include < ...

  2. [LightOJ 1341] Aladdin and the Flying Carpet (算数基本定理(唯一分解定理))

    题目链接: https://vjudge.net/problem/LightOJ-1341 题目描述: 问有几种边长为整数的矩形面积等于a,且矩形的短边不小于b 算数基本定理的知识点:https:// ...

  3. [HDU 2520] 我是菜鸟,我怕谁(不一样的for循环)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2520 //学学不一样的for循环 #include<iostream> #include& ...

  4. 【译】第38节---EF6-基于代码的配置

    原文:http://www.entityframeworktutorial.net/entityframework6/code-based-configuration.aspx EF6引入了基于代码的 ...

  5. http协议的状态码解释

    一些常见的状态码为: 200 – 服务器成功返回网页 404 – 请求的网页不存在 503 – 服务器超时 下面提供 HTTP 状态码的完整列表.点击链接可了解详情.您也可以访问 HTTP 状态码上的 ...

  6. 用R创建Word和PowerPoint文档--转载

    https://www.jianshu.com/p/7df62865c3ed Rapp --简书 Microsoft的Office软件在办公软件领域占有绝对的主导地位,几乎每个职场人士都必须掌握Wor ...

  7. VirtualBox-- 虚拟机网络设置2--主机与虚拟机互相访问且均上外网

    转载自:http://blog.sina.com.cn/s/blog_7de9d5d80100t2uw.html   VirtualBox中有4中网络连接方式:NATBridged AdapterIn ...

  8. python tcp .demo

    client: # -*- coding: utf- -*- import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.co ...

  9. sklearn中的train_test_split (随机划分训练集和测试集)

    官方文档:http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html ...

  10. 力扣(LeetCode) 136. 只出现一次的数字

    给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次.找出那个只出现了一次的元素. 说明: 你的算法应该具有线性时间复杂度. 你可以不使用额外空间来实现吗? 示例 1: 输入: [ ...