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

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

给外部调用的方法是:

distorted_inputs()和inputs()
cifar10.py文件调用了此文件中定义的方法。
"""Routine for decoding the CIFAR-10 binary file format."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function import os from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf # 定义图片的像素,原生图片32 x 32
# Process images of this size. Note that this differs from the original CIFAR
# image size of 32 x 32. If one alters this number, then the entire model
# architecture will change and any model would need to be retrained.
# IMAGE_SIZE = 24
IMAGE_SIZE = 32
# Global constants describing the CIFAR-10 data set.
# 分类数量
NUM_CLASSES = 10
# 训练集大小
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000
# 评价集大小
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = 10000 # 从CIFAR10数据文件中读取样例
# filename_queue一个队列的文件名
def read_cifar10(filename_queue): class CIFAR10Record(object):
pass result = CIFAR10Record() # Dimensions of the images in the CIFAR-10 dataset.
# See http://www.cs.toronto.edu/~kriz/cifar.html for a description of the
# input format.
# 分类结果的长度,CIFAR-100长度为2
label_bytes = 1 # 2 for CIFAR-100
result.height = 32
result.width = 32
# 3位表示rgb颜色(0-255,0-255,0-255)
result.depth = 3
image_bytes = result.height * result.width * result.depth
# Every record consists of a label followed by the image, with a
# fixed number of bytes for each.
# 单个记录的总长度=分类结果长度+图片长度
record_bytes = label_bytes + image_bytes # Read a record, getting filenames from the filename_queue. No
# header or footer in the CIFAR-10 format, so we leave header_bytes
# and footer_bytes at their default of 0.
# 读取
reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
result.key, value = reader.read(filename_queue) # Convert from a string to a vector of uint8 that is record_bytes long.
record_bytes = tf.decode_raw(value, tf.uint8) # 第一位代表lable-图片的正确分类结果,从uint8转换为int32类型
# The first bytes represent the label, which we convert from uint8->int32.
result.label = tf.cast(
tf.strided_slice(record_bytes, [0], [label_bytes]), tf.int32) # 分类结果之后的数据代表图片,我们重新调整大小
# The remaining bytes after the label represent the image, which we reshape
# from [depth * height * width] to [depth, height, width].
depth_major = tf.reshape(
tf.strided_slice(record_bytes, [label_bytes],
[label_bytes + image_bytes]),
[result.depth, result.height, result.width])
# 格式转换,从[颜色,高度,宽度]--》[高度,宽度,颜色]
# Convert from [depth, height, width] to [height, width, depth].
result.uint8image = tf.transpose(depth_major, [1, 2, 0]) return result # 构建一个排列后的一组图片和分类
def _generate_image_and_label_batch(image, label, min_queue_examples,
batch_size, shuffle): # Create a queue that shuffles the examples, and then
# read 'batch_size' images + labels from the example queue.
# 线程数
num_preprocess_threads = 8
if shuffle:
images, label_batch = tf.train.shuffle_batch(
[image, label],
batch_size=batch_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_size,
min_after_dequeue=min_queue_examples)
else:
images, label_batch = tf.train.batch(
[image, label],
batch_size=batch_size,
num_threads=num_preprocess_threads,
capacity=min_queue_examples + 3 * batch_size) # Display the training images in the visualizer.
tf.summary.image('images', images) return images, tf.reshape(label_batch, [batch_size]) # 为CIFAR评价构建输入
# data_dir路径
# batch_size一个组的大小
def distorted_inputs(data_dir, batch_size): filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)
for i in xrange(1, 6)]
for f in filenames:
if not tf.gfile.Exists(f):
raise ValueError('Failed to find file: ' + f) # Create a queue that produces the filenames to read.
filename_queue = tf.train.string_input_producer(filenames) # Read examples from files in the filename queue.
read_input = read_cifar10(filename_queue)
reshaped_image = tf.cast(read_input.uint8image, tf.float32) height = IMAGE_SIZE
width = IMAGE_SIZE # Image processing for training the network. Note the many random
# distortions applied to the image.
# 随机裁剪图片
# Randomly crop a [height, width] section of the image.
distorted_image = tf.random_crop(reshaped_image, [height, width, 3])
# 随机旋转图片
# Randomly flip the image horizontally.
distorted_image = tf.image.random_flip_left_right(distorted_image) # Because these operations are not commutative, consider randomizing
# the order their operation.
# 亮度变换
distorted_image = tf.image.random_brightness(distorted_image,
max_delta=63)
# 对比度变换
distorted_image = tf.image.random_contrast(distorted_image,
lower=0.2, upper=1.8) # Subtract off the mean and divide by the variance of the pixels.
# Linearly scales image to have zero mean and unit norm
# 标准化
float_image = tf.image.per_image_standardization(distorted_image) # Set the shapes of tensors.
# 设置张量的型
float_image.set_shape([height, width, 3])
read_input.label.set_shape([1]) # Ensure that the random shuffling has good mixing properties.
# 确保洗牌的随机性
min_fraction_of_examples_in_queue = 0.4
min_queue_examples = int(NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN *
min_fraction_of_examples_in_queue)
print('Filling queue with %d CIFAR images before starting to train. '
'This will take a few minutes.' % min_queue_examples) # Generate a batch of images and labels by building up a queue of examples.
return _generate_image_and_label_batch(float_image, read_input.label,
min_queue_examples, batch_size,
shuffle=True) # 为CIFAR评价构建输入
# eval_data使用训练还是评价数据集
# data_dir路径
# batch_size一个组的大小
def inputs(eval_data, data_dir, batch_size): if not eval_data:
filenames = [os.path.join(data_dir, 'data_batch_%d.bin' % i)
for i in xrange(1, 6)]
num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN
else:
filenames = [os.path.join(data_dir, 'test_batch.bin')]
num_examples_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_EVAL for f in filenames:
if not tf.gfile.Exists(f):
raise ValueError('Failed to find file: ' + f) # Create a queue that produces the filenames to read.
# 文件名队列
filename_queue = tf.train.string_input_producer(filenames) # Read examples from files in the filename queue.
# 从文件中读取解析出的图片队列
read_input = read_cifar10(filename_queue)
# 转换为float
reshaped_image = tf.cast(read_input.uint8image, tf.float32) height = IMAGE_SIZE
width = IMAGE_SIZE # Image processing for evaluation.
# Crop the central [height, width] of the image.
# 剪切图片的中心
resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image,
height, width) # Subtract off the mean and divide by the variance of the pixels.
# 标准化图片
float_image = tf.image.per_image_standardization(resized_image) # Set the shapes of tensors.
# 设置张量的型
float_image.set_shape([height, width, 3])
read_input.label.set_shape([1]) # Ensure that the random shuffling has good mixing properties.
# 确保洗牌的随机性
min_fraction_of_examples_in_queue = 0.4
min_queue_examples = int(num_examples_per_epoch *
min_fraction_of_examples_in_queue) # Generate a batch of images and labels by building up a queue of examples.
return _generate_image_and_label_batch(float_image, read_input.label,
min_queue_examples, batch_size,
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. Android view状态保存

    为什么我们需要保存View的状态? 这个问题问的好!我坚信移动应用应该帮助你解决问题,而不是制造问题. 想象一下一个非常复杂的设置页面: 这并不是从一个移动应用的截图(这不是典型的win32程序吗.. ...

  2. java-03 变量与运算符

    1.java中的变量与常量 1.1 变量的定义: 变量,顾名思义就是会变的量,这种思想来源于数学,指的是一个不确定的量或者随时会改变的量. 在我们进行编程的过程中,有一些东西是会随着实际情况而发生变化 ...

  3. [LeetCode 题解]: Search a 2D Matrix

    Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the follo ...

  4. 使用ContentPresenter,不使用ContentControl

    参考: https://wpf.2000things.com/2017/04/06/1204-using-a-datatrigger-to-change-content-in-a-contentpre ...

  5. [js]利用闭包向post回调函数传参数

    最近在闲逛校园XX站的时候,打算搞个破坏,试试有多少人还是用初始密码登陆.比较懒,所以直接打开控制台来写. 所以问题可以描述为: 向后端不断的post数据,id从1~5000自增,后端会根据情况来返回 ...

  6. android ART-逆向研究者的福音?

    android 4.4起,提供了一种与Dalvik截然不同的运行环境-ART(Android Runtime)的支持.目前用户可以选择设备的运行环境,在不久的将来ART肯定会替代Dalvik Runt ...

  7. ASP.NET MVC 控制器通过继承控制器来达到 过滤 并且多了一个IAuthenticationFilter

    暂时没有用到过这个IAuthenticationFilter接口,毕竟已经有三个具体实现类了,所以这个还不知道用在哪,以后看看 20190324 需要注意!!!控制器重写方法都是被protected修 ...

  8. C#线程和异步

    C#Thread学习 C#ThreadPool学习 C#Task学习 C#backgroundWorker c# 锁的使用 C#前台线程和后台线程区别 C#Async,await异步简单介绍 C#委托 ...

  9. 基于.net standard 的动态编译实现

    在前文[基于.net core 微服务的另类实现]结尾处,提到了如何方便自动的生成微服务的客户端代理,使对于调用方透明,同时将枯燥的东西使用框架集成,以提高使用便捷性.在尝试了基于 Emit 中间语言 ...

  10. 「HNOI 2015」亚瑟王

    \(Description\) 有\(n\)张卡牌,每一张卡牌有\(p_i\)的概率发动,并造成\(d_i\)点伤害.一共有\(r\)轮,每一轮按照编号从小到大依次考虑,如果这张牌已经发动过则跳过该牌 ...