github地址:https://github.com/tensorflow/models.git

本文分析tutorial/image/cifar10教程项目的cifar10_input.py代码。

给外部调用的方法是:

  1. distorted_inputs()和inputs()
    cifar10.py文件调用了此文件中定义的方法。
  1. """Routine for decoding the CIFAR-10 binary file format."""
  2.  
  3. from __future__ import absolute_import
  4. from __future__ import division
  5. from __future__ import print_function
  6.  
  7. import os
  8.  
  9. from six.moves import xrange # pylint: disable=redefined-builtin
  10. import tensorflow as tf
  11.  
  12. # 定义图片的像素,原生图片32 x 32
  13. # Process images of this size. Note that this differs from the original CIFAR
  14. # image size of 32 x 32. If one alters this number, then the entire model
  15. # architecture will change and any model would need to be retrained.
  16. # IMAGE_SIZE = 24
  17. IMAGE_SIZE = 32
  18. # Global constants describing the CIFAR-10 data set.
  19. # 分类数量
  20. NUM_CLASSES = 10
  21. # 训练集大小
  22. NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000
  23. # 评价集大小
  24. NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000
  25.  
  26. # 从CIFAR10数据文件中读取样例
  27. # filename_queue一个队列的文件名
  28. def read_cifar10(filename_queue):
  29.  
  30. class CIFAR10Record(object):
  31. pass
  32.  
  33. result = CIFAR10Record()
  34.  
  35. # Dimensions of the images in the CIFAR-10 dataset.
  36. # See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the
  37. # input format.
  38. # 分类结果的长度,CIFAR-100长度为2
  39. label_bytes = 1 # 2 for CIFAR-100
  40. result.height = 32
  41. result.width = 32
  42. # 3位表示rgb颜色(0-255,0-255,0-255)
  43. result.depth = 3
  44. image_bytes = result.height * result.width * result.depth
  45. # Every record consists of a label followed by the image, with a
  46. # fixed number of bytes for each.
  47. # 单个记录的总长度=分类结果长度+图片长度
  48. record_bytes = label_bytes + image_bytes
  49.  
  50. # Read a record, getting filenames from the filename_queue. No
  51. # header or footer in the CIFAR-10 format, so we leave header_bytes
  52. # and footer_bytes at their default of 0.
  53. # 读取
  54. reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
  55. result.key, value = reader.read(filename_queue)
  56.  
  57. # Convert from a string to a vector of uint8 that is record_bytes long.
  58. record_bytes = tf.decode_raw(value, tf.uint8)
  59.  
  60. # 第一位代表lable-图片的正确分类结果,从uint8转换为int32类型
  61. # The first bytes represent the label, which we convert from uint8->int32.
  62. result.label = tf.cast(
  63. tf.strided_slice(record_bytes, [0], [label_bytes]), tf.int32)
  64.  
  65. # 分类结果之后的数据代表图片,我们重新调整大小
  66. # The remaining bytes after the label represent the image, which we reshape
  67. # from [depth * height * width] to [depth, height, width].
  68. depth_major = tf.reshape(
  69. tf.strided_slice(record_bytes, [label_bytes],
  70. [label_bytes + image_bytes]),
  71. [result.depth, result.height, result.width])
  72. # 格式转换,从[颜色,高度,宽度]--》[高度,宽度,颜色]
  73. # Convert from [depth, height, width] to [height, width, depth].
  74. result.uint8image = tf.transpose(depth_major, [1, 2, 0])
  75.  
  76. return result
  77.  
  78. # 构建一个排列后的一组图片和分类
  79. def _generate_image_and_label_batch(image, label, min_queue_examples,
  80. batch_size, shuffle):
  81.  
  82. # Create a queue that shuffles the examples, and then
  83. # read 'batch_size' images + labels from the example queue.
  84. # 线程数
  85. num_preprocess_threads = 8
  86. if shuffle:
  87. images, label_batch = tf.train.shuffle_batch(
  88. [image, label],
  89. batch_size=batch_size,
  90. num_threads=num_preprocess_threads,
  91. capacity=min_queue_examples + 3 * batch_size,
  92. min_after_dequeue=min_queue_examples)
  93. else:
  94. images, label_batch = tf.train.batch(
  95. [image, label],
  96. batch_size=batch_size,
  97. num_threads=num_preprocess_threads,
  98. capacity=min_queue_examples + 3 * batch_size)
  99.  
  100. # Display the training images in the visualizer.
  101. tf.summary.image('images', images)
  102.  
  103. return images, tf.reshape(label_batch, [batch_size])
  104.  
  105. # 为CIFAR评价构建输入
  106. # data_dir路径
  107. # batch_size一个组的大小
  108. def distorted_inputs(data_dir, batch_size):
  109.  
  110. filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)
  111. for i in xrange(1, 6)]
  112. for f in filenames:
  113. if not tf.gfile.Exists(f):
  114. raise ValueError('Failed to find file: ' + f)
  115.  
  116. # Create a queue that produces the filenames to read.
  117. filename_queue = tf.train.string_input_producer(filenames)
  118.  
  119. # Read examples from files in the filename queue.
  120. read_input = read_cifar10(filename_queue)
  121. reshaped_image = tf.cast(read_input.uint8image, tf.float32)
  122.  
  123. height = IMAGE_SIZE
  124. width = IMAGE_SIZE
  125.  
  126. # Image processing for training the network. Note the many random
  127. # distortions applied to the image.
  128. # 随机裁剪图片
  129. # Randomly crop a [height, width] section of the image.
  130. distorted_image = tf.random_crop(reshaped_image, [height, width, 3])
  131. # 随机旋转图片
  132. # Randomly flip the image horizontally.
  133. distorted_image = tf.image.random_flip_left_right(distorted_image)
  134.  
  135. # Because these operations are not commutative, consider randomizing
  136. # the order their operation.
  137. # 亮度变换
  138. distorted_image = tf.image.random_brightness(distorted_image,
  139. max_delta=63)
  140. # 对比度变换
  141. distorted_image = tf.image.random_contrast(distorted_image,
  142. lower=0.2, upper=1.8)
  143.  
  144. # Subtract off the mean and divide by the variance of the pixels.
  145. # Linearly scales image to have zero mean and unit norm
  146. # 标准化
  147. float_image = tf.image.per_image_standardization(distorted_image)
  148.  
  149. # Set the shapes of tensors.
  150. # 设置张量的型
  151. float_image.set_shape([height, width, 3])
  152. read_input.label.set_shape([1])
  153.  
  154. # Ensure that the random shuffling has good mixing properties.
  155. # 确保洗牌的随机性
  156. min_fraction_of_examples_in_queue = 0.4
  157. min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *
  158. min_fraction_of_examples_in_queue)
  159. print('Filling queue with %d CIFAR images before starting to train. '
  160. 'This will take a few minutes.' % min_queue_examples)
  161.  
  162. # Generate a batch of images and labels by building up a queue of examples.
  163. return _generate_image_and_label_batch(float_image, read_input.label,
  164. min_queue_examples, batch_size,
  165. shuffle=True)
  166.  
  167. # 为CIFAR评价构建输入
  168. # eval_data使用训练还是评价数据集
  169. # data_dir路径
  170. # batch_size一个组的大小
  171. def inputs(eval_data, data_dir, batch_size):
  172.  
  173. if not eval_data:
  174. filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)
  175. for i in xrange(1, 6)]
  176. num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN
  177. else:
  178. filenames = [os.path.join(data_dir, 'test_batch.bin')]
  179. num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL
  180.  
  181. for f in filenames:
  182. if not tf.gfile.Exists(f):
  183. raise ValueError('Failed to find file: ' + f)
  184.  
  185. # Create a queue that produces the filenames to read.
  186. # 文件名队列
  187. filename_queue = tf.train.string_input_producer(filenames)
  188.  
  189. # Read examples from files in the filename queue.
  190. # 从文件中读取解析出的图片队列
  191. read_input = read_cifar10(filename_queue)
  192. # 转换为float
  193. reshaped_image = tf.cast(read_input.uint8image, tf.float32)
  194.  
  195. height = IMAGE_SIZE
  196. width = IMAGE_SIZE
  197.  
  198. # Image processing for evaluation.
  199. # Crop the central [height, width] of the image.
  200. # 剪切图片的中心
  201. resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image,
  202. height, width)
  203.  
  204. # Subtract off the mean and divide by the variance of the pixels.
  205. # 标准化图片
  206. float_image = tf.image.per_image_standardization(resized_image)
  207.  
  208. # Set the shapes of tensors.
  209. # 设置张量的型
  210. float_image.set_shape([height, width, 3])
  211. read_input.label.set_shape([1])
  212.  
  213. # Ensure that the random shuffling has good mixing properties.
  214. # 确保洗牌的随机性
  215. min_fraction_of_examples_in_queue = 0.4
  216. min_queue_examples = int(num_examples_per_epoch *
  217. min_fraction_of_examples_in_queue)
  218.  
  219. # Generate a batch of images and labels by building up a queue of examples.
  220. return _generate_image_and_label_batch(float_image, read_input.label,
  221. min_queue_examples, batch_size,
  222. shuffle=False)

Tensorflow样例代码分析cifar10的更多相关文章

  1. TensorFlow入门之MNIST样例代码分析

    这几天想系统的学习一下TensorFlow,为之后的工作打下一些基础.看了下<TensorFlow:实战Google深度学习框架>这本书,目前个人觉得这本书还是对初学者挺友好的,作者站在初 ...

  2. amaze样例页面分析(一)

    amaze样例页面分析(一) 一.总结 1.从审查(inspect)中是很清楚的可以弄清楚这些part之间的结构关系的 2.一者在于弄清楚他们之间的结构关系,二者在于知道结构的每一部分是干嘛的 3.i ...

  3. 使用ffmpeg实现转码样例(代码实现)

    分类: C/C++ 使用ffmpeg实现转码样例(代码实现) 使用ffmpeg转码主要工作如下: Demux -> Decoding -> Encoding -> Muxing 其中 ...

  4. java 线程、线程池基本应用演示样例代码回想

    java 线程.线程池基本应用演示样例代码回想 package org.rui.thread; /** * 定义任务 * * @author lenovo * */ public class Lift ...

  5. ECharts组件应用样例代码

    一.从Echarts官网上下载最新版本组件 Echarts是百度开发的开源Web图表组件,界面美观,使用简单.组件下载地址:http://echarts.baidu.com/echarts2/doc/ ...

  6. java文件夹相关操作 演示样例代码

    java文件夹相关操作 演示样例代码 package org.rui.io; import java.io.File; import java.io.FilenameFilter; import ja ...

  7. 10分钟理解Android数据库的创建与使用(附具体解释和演示样例代码)

    1.Android数据库简单介绍. Android系统的framework层集成了Sqlite3数据库.我们知道Sqlite3是一种轻量级的高效存储的数据库. Sqlite数据库具有以下长处: (1) ...

  8. C#调用 Oracle 存储过程样例代码

    -- 建表 CREATE TABLE sale_report (      sale_date DATE NOT NULL ,      sale_item VARCHAR(2) NOT NULL , ...

  9. java 又一次抛出异常 相关处理结果演示样例代码

    java 又一次抛出异常 相关处理结果演示样例代码 package org.rui.ExceptionTest; /** * 又一次抛出异常 * 在某些情况下,我们想又一次掷出刚才产生过的违例,特别是 ...

随机推荐

  1. 深入浅出Java多线程(2)-Swing中的EDT(事件分发线程) [转载]

    本系列文章导航 深入浅出Java多线程(1)-方法 join 深入浅出Java多线程(2)-Swing中的EDT(事件分发线程) 深入浅出多线程(3)-Future异步模式以及在JDK1.5Concu ...

  2. 20、Semantic-UI之数据验证

    20.1 实现数据验证   在很多前端框架中都提供了数据验证的操作,比如jQuery的验证框架等,但是jQuery的验证框架js文件太多:在使用Semantic-UI框架的时候只需要导入semanti ...

  3. ListControl的用法

    ListControl 控件可在窗体中管理和显示列 表项.可控制列表内容的显示方式,能够以图标和表格的形式显示数据.打开ListControl控件的属性窗口,在Styles选项卡中的View属性中 可 ...

  4. 强大的CSS 属性选择符 配合 stylish 屏蔽新浪微博信息流广告

    新建一条微博域名下的规则: @-moz-document domain("weibo.com") { #v6_pl_rightmod_rank,#v6_pl_rightmod_ad ...

  5. 曲苑杂坛--查看CPU配置

    ​--===================================================--查看CPU配置SELECT cpu_count AS [Logical CPU Coun ...

  6. SQL 语句case when

    简介 case when 一般有两种书写方式,多用于查询判断 1. case 列名 when '' then '空' ' then '成功' ' then '失败' else '其他' end as ...

  7. 小修改,让mvc的验证锦上添点花(1)

    首先,mvc的客户端验证用的是jquery.validate.js, jquery.validate本身已经提供了很好的扩展功能,通过简单点配置就可以做得更好看些. 而Microsoft通过jquer ...

  8. Weekly Contest 121

    984. String Without AAA or BBB Given two integers A and B, return any string S such that: S has leng ...

  9. “全栈2019”Java第四十二章:静态代码块与初始化顺序

    难度 初级 学习时间 10分钟 适合人群 零基础 开发语言 Java 开发环境 JDK v11 IntelliJ IDEA v2018.3 文章原文链接 "全栈2019"Java第 ...

  10. PTA 7-2 深入虎穴 (30 分)

    著名的王牌间谍 007 需要执行一次任务,获取敌方的机密情报.已知情报藏在一个地下迷宫里,迷宫只有一个入口,里面有很多条通路,每条路通向一扇门.每一扇门背后或者是一个房间,或者又有很多条路,同样是每条 ...