1. 程式人生 > >TensorFlow學習--CIFAR-10

TensorFlow學習--CIFAR-10

CIFAR-10資料集

CIFAR-10資料集包含10個類的60000張32x32的彩色影象,每個類有6000張影象.有50000張訓練影象和10000張測試影象.CIFAR-10資料集
10個分類明細及對應的部分圖片:
這裡寫圖片描述

教程程式碼

其中主要涉及的檔案:

檔案 作用
cifar10_input.py 讀取本地二進位制檔案
cifar10_input_test.py 輸入測試
cifar10.py 建立CIFAR-10模型
cifar10_train.py 在CPU或GPU上訓練模型
cifar10_eval.py 評估模型的預測效能
cifar10_multi_gpu_train.py 在多GPU上訓練模型

cifar10_input.py

cifar10_input.py的作用是讀取CIFAR-10的二進位制檔案.

cifar10_input.py中主要有4部分:

  • read_cifar10() 讀取二進位制CIFAR10資料
  • _generate_image_and_label_batch() 構建[images,labels]的佇列
  • distorted_inputs() 讀入並增廣資料為訓練構建輸入
  • inputs() 影象預處理併為預測構建輸入

其中

  1. read_cifar10()
    在CIFAR10資料的二進位制檔案中,第一個位元組是影象標籤是一個0-9的數字;接下來的3072個位元組是畫素值.由於每個圖片的儲存位元組數是固定的,因此函式read_cifar10(filename_queue)中使用tf.FixedLengthRecordReader每次從檔案中讀取固定長度的欄位.
    在畫素值的3072(3*1024)個位元組中,RGB通道分別1024個,以行優先順序儲存.
    二進位制檔案中,每個檔案都包含10000個3073位元組的行影象,沒有分隔行限制,每個檔案是30730000位元組長.檔案中沒有頁首頁尾,因此函式read_cifar10(filename_queue)中的tf.FixedLengthRecordReader()的引數header_bytes和footer_bytes都設為預設值0.
  2. _generate_image_and_label_batch()
    函式使用16個獨立執行緒,16個執行緒被連續的安排在一個佇列中;每次在執行讀取一個 batch_size數量的樣本[images,labels].分別在distorted_inputs()與inputs()中被呼叫,用來構建輸入佇列.
  3. distorted_inputs()
    distorted_inputs()為訓練構建輸入.在讀取影象資料後,依次對影象進行了以下操作:
    隨機裁剪大小為24*24的影象
    隨機水平翻轉影象
    隨機調整影象亮度
    隨機調整影象對比度
    標準化處理:減去均值除以方差,線性縮放為零均值的單位範數
    這樣,增加了訓練樣本的數量,實現了資料增廣.然後呼叫_generate_image_and_label_batch()構建影象和標籤的佇列.
        # 隨機裁剪[height, width]大小的影象
        distorted_image = tf.random_crop(reshaped_image, [height, width, 3])
        # 隨機水平翻轉影象
        distorted_image = tf.image.random_flip_left_right(distorted_image)
        # 隨機調整影象亮度與對比度(不可交換)
        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)
        # 減去均值除以方差,線性縮放為零均值的單位範數:白化/標準化處理
        float_image = tf.image.per_image_standardization(distorted_image)
  1. inputs()
    inputs()為預測構建輸入.通過以下操作:
    在影象的中心裁剪24*24大小的影象
    減去平均值併除以畫素的方差,保證資料均值為0,方差為1
    對影象進行預處理.然後呼叫_generate_image_and_label_batch()構建影象和標籤的佇列.
        # 用於評估的影象處理
        # 在影象的中心裁剪[height, width]大小的影象,裁剪中央區域用於評估
        resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, height, width)
        # 減去平均值併除以畫素的方差,保證資料均值為0,方差為1
        float_image = tf.image.per_image_standardization(resized_image)

cifar10.py

cifar10.py的作用是構建CIFAR-10模型.

cifar10.py中主要有4部分:

  • 模型輸入:distorted_inputs() inputs()
  • 模型訓練:loss() _add_loss_summaries() train()等
  • 模型預測:inference()等

其中,

  1. 模型輸入部分
    distorted_inputs()通過呼叫cifar10_input.yp中的distorted_inputs()為CIFAR-10訓練構建輸入;inputs()通過呼叫cifar10_input.yp中的inputs()為CIFAR-10預測構建輸入.
  2. 模型訓練部分
    loss()將L2損失新增到所有可訓練變數.在計算logits和labels之間的交叉熵時,使用函式tf.nn.sparse_softmax_cross_entropy_with_logits()可在函式內部將labels稀疏化,因此loss()可以直接輸入非稀疏的標籤.
    即原來使用函式tf.nn.softmax_cross_entropy_with_logits()計算交叉熵時,輸入標籤需要先稀疏化,常用one-hot編碼,即標籤[0,1,2]對應的稀疏化編碼為[1 0 0][0 1 0][0 0 1];現在函式tf.nn.sparse_softmax_cross_entropy_with_logits()內部包含將labels稀疏化的操作,因此支援唯一值 labels.
def loss(logits, labels):
    labels = tf.cast(labels, tf.int64)
    # 計算logits和labels之間的交叉熵
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
      labels=labels, logits=logits, name='cross_entropy_per_example')
    # 計算整個批次的平均交叉熵損失
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
    # 把變數放入一個集合
    tf.add_to_collection('losses', cross_entropy_mean)
    # 總損失定義為交叉熵損失加上所有的權重衰減項(L2損失)
    return tf.add_n(tf.get_collection('losses'), name='total_loss')

_add_loss_summaries()中計算單個損失和總損失,並將指數移動平均應用於單個損失.
train()訓練CIFAR-10模型,使用指數衰減學習率並對損失進行移動平均.最後採用滑動平均的方法更新引數,這樣可以在評估過程中提升模型的效能.

    # 跟蹤所有可訓練變數的移動均值
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
  1. 模型預測部分
    inference()構建的CIFAR-10模型,依次由以下部分組成:
    卷積層1 (實現卷積)
    池化層 (max polling)
    lrn層 (區域性響應歸一化:增強大的抑制小的,增強泛化能力)
    卷積層2 (實現卷積)
    lrn層 (區域性響應歸一化:增強大的抑制小的,增強泛化能力)
    池化層 (max polling)
    全連線層3 (新增L2正則化約束,防止過擬合)
    全連線層4 (新增L2正則化約束,防止過擬合)
    線性層 ((WX+b) 進行線性變換以輸出 logits)

線性層中不使用softmax,因為loss()函式中的tf.nn.sparse_softmax_cross_entropy_with_logits接受非稀疏的logits並在內部執行softmax以提高效率.

    # 線性層 (WX+b)
    with tf.variable_scope('softmax_linear') as scope:
        weights = _variable_with_weight_decay('weights', [192, NUM_CLASSES], stddev=1/192.0, wd=None)
        # biases初始化為0
        biases = _variable_on_cpu('biases', [NUM_CLASSES], tf.constant_initializer(0.0))
        # (WX+b) 進行線性變換以輸出 logits
        softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)
        # 彙總
        _activation_summary(softmax_linear)

在TensorBoard 可檢視模型結構:
這裡寫圖片描述

cifar10_eval.py

cifar10_eval.py用於評估CIFAR-10模型的預測效能.
cifar10_train.py主要有兩部分:

  • eval_once() 單次評估
  • evaluate()  評估CIFAR-10模型

cifar10_train.py週期性的在checkpoint檔案中儲存模型中的所有引數,但不對模型進行評估.cifar10_eval.py中的eval_once()函式使用checkpoint檔案在另一部分資料集上測試預測效能.
cifar10_eval.py中的evaluate()函式利用cifar10.py中的inference() 函式進行重構模型.然後使用評估資料集(10000張圖片)進行測試.

部分程式碼及註釋

cifar10.py及註釋:

#!/usr/bin/python
# coding:utf-8

# 建立CIFAR-10的模型
# pylint: disable=missing-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import re
import sys
import tarfile

from six.moves import urllib
import tensorflow as tf
import cifar10_input

FLAGS = tf.app.flags.FLAGS
# 基本模型引數
tf.app.flags.DEFINE_integer('batch_size', 128,
                            """Number of images to process in a batch.""")
tf.app.flags.DEFINE_string('data_dir', '/home/w/mycode/data/cifar10_data',
                           """Path to the CIFAR-10 data directory.""")
tf.app.flags.DEFINE_boolean('use_fp16', False,# 半精度浮點數
                            """Train the model using fp16.""")
# 描述CIFAR-10資料集的全域性常量
IMAGE_SIZE = cifar10_input.IMAGE_SIZE
NUM_CLASSES = cifar10_input.NUM_CLASSES
NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN
NUM_EXAMPLES_PER_EPOCH_FOR_EVAL = cifar10_input.NUM_EXAMPLES_PER_EPOCH_FOR_EVAL

# 描述訓練過程的常量
MOVING_AVERAGE_DECAY = 0.9999     # 滑動平均衰減率
NUM_EPOCHS_PER_DECAY = 350.0      # 在學習速度衰退之後的Epochs
LEARNING_RATE_DECAY_FACTOR = 0.1  # 學習速率衰減因子
INITIAL_LEARNING_RATE = 0.1       # 初始學習率

# 如果模型使用多個GPU進行訓練,則使用tower_name將所有Op名稱加字首以區分操作
# 視覺化模型時從摘要名稱中刪除此字首
TOWER_NAME = 'tower'
DATA_URL = 'https://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'

# 啟用摘要建立助手
def _activation_summary(x):
    # 若多個GPU訓練,則從名稱中刪除'tower_[0-9]/',利於TensorBoard顯示
    tensor_name = re.sub('%s_[0-9]*/' % TOWER_NAME, '', x.op.name)
    # 提供啟用直方圖的summary
    tf.summary.histogram(tensor_name + '/activations', x)
    # 衡量啟用稀疏性的summary
    tf.summary.scalar(tensor_name + '/sparsity', tf.nn.zero_fraction(x))

# 建立儲存在CPU記憶體上的變數(變數的名稱,整數列表,變數的初始化程式)
def _variable_on_cpu(name, shape, initializer):
    with tf.device('/cpu:0'):
        dtype = tf.float16 if FLAGS.use_fp16 else tf.float32
        var = tf.get_variable(name, shape, initializer=initializer, dtype=dtype)
    return var

# 建立一個權重衰減的初始化變數(變數的名稱,整數列表,截斷高斯的標準差,加L2Loss權重衰減)
# 變數用截斷正態分佈初始化的.只有指定時才新增權重衰減
def _variable_with_weight_decay(name, shape, stddev, wd):
    dtype = tf.float16 if FLAGS.use_fp16 else tf.float32
    # 用截斷正態分佈進行初始化
    var = _variable_on_cpu(name, shape, tf.truncated_normal_initializer(stddev=stddev,dtype=dtype))
    if wd is not None:
        # wd用於向losses新增L2正則化,防止過擬合,提高泛化能力
        weight_decay = tf.multiply(tf.nn.l2_loss(var), wd, name='weight_loss')
        # 把變數放入一個集合
        tf.add_to_collection('losses', weight_decay)
    return var


# -------------------------模型輸入-----------------------------------
# 訓練輸入
# 返回:images:[batch_size, IMAGE_SIZE, IMAGE_SIZE, 3]; labels:[batch_size]
def distorted_inputs():
    if not FLAGS.data_dir:
        raise ValueError('Please supply a data_dir')
    data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')
    # 讀入並增廣資料
    images, labels = cifar10_input.distorted_inputs(data_dir=data_dir, batch_size=FLAGS.batch_size)
    if FLAGS.use_fp16:
        images = tf.cast(images, tf.float16)
        labels = tf.cast(labels, tf.float16)
    return images, labels

# 預測輸入
# 返回:images:[batch_size, IMAGE_SIZE, IMAGE_SIZE, 3]; labels:[batch_size]
def inputs(eval_data):
    if not FLAGS.data_dir:
        raise ValueError('Please supply a data_dir')
    data_dir = os.path.join(FLAGS.data_dir, 'cifar-10-batches-bin')
    # 影象預處理及輸入
    images, labels = cifar10_input.inputs(eval_data=eval_data,data_dir=data_dir,batch_size=FLAGS.batch_size)
    if FLAGS.use_fp16:
        images = tf.cast(images, tf.float16)
        labels = tf.cast(labels, tf.float16)
    return images, labels
# -------------------------------------------------------------------


# -------------------------模型預測-----------------------------------
# 構建CIFAR-10模型
# 使用tf.get_variable()而不是tf.Variable()來例項化所有變數,以便跨多個GPU訓練執行共享變數
# 若只在單個GPU上執行,則可通過tf.Variable()替換tf.get_variable()的所有例項來簡化此功能
def inference(images):
    # 卷積層1
    with tf.variable_scope('conv1') as scope:
        # weight不進行L2正則化
        kernel = _variable_with_weight_decay('weights',shape=[5, 5, 3, 64],stddev=5e-2, wd=None)
        # 卷積
        conv = tf.nn.conv2d(images, kernel, [1, 1, 1, 1], padding='SAME')
        # biases初始化為0
        biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.0))
        pre_activation = tf.nn.bias_add(conv, biases)
        # 卷積層1的結果由ReLu啟用
        conv1 = tf.nn.relu(pre_activation, name=scope.name)
        # 彙總
        _activation_summary(conv1)
    # 池化層1
    pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool1')
    # lrn層1 區域性響應歸一化:增強大的抑制小的,增強泛化能力
    norm1 = tf.nn.lrn(pool1, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')
    # 卷積層2
    with tf.variable_scope('conv2') as scope:
        # weight不進行L2正則化
        kernel = _variable_with_weight_decay('weights', shape=[5, 5, 64, 64], stddev=5e-2, wd=None)
        conv = tf.nn.conv2d(norm1, kernel, [1, 1, 1, 1], padding='SAME')
        # biases初始化為0.1
        biases = _variable_on_cpu('biases', [64], tf.constant_initializer(0.1))
        pre_activation = tf.nn.bias_add(conv, biases)
        # 卷積層2的結果由ReLu啟用
        conv2 = tf.nn.relu(pre_activation, name=scope.name)
        # 彙總
        _activation_summary(conv2)
    # lrn層2
    norm2 = tf.nn.lrn(conv2, 4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')
    # 池化層2
    pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pool2')

    # 全連線層3
    with tf.variable_scope('local3') as scope:
        # 將樣本轉換為一維向量
        reshape = tf.reshape(pool2, [FLAGS.batch_size, -1])
        # 維數
        dim = reshape.get_shape()[1].value
        # 新增L2正則化約束,防止過擬合
        weights = _variable_with_weight_decay('weights', shape=[dim, 384], stddev=0.04, wd=0.004)
        # biases初始化為0.1
        biases = _variable_on_cpu('biases', [384], tf.constant_initializer(0.1))
        # ReLu啟用
        local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)
        _activation_summary(local3)

    # 全連線層4
    with tf.variable_scope('local4') as scope:
        # 新增L2正則化約束,防止過擬合
        weights = _variable_with_weight_decay('weights', shape=[384, 192], stddev=0.04, wd=0.004)
        # biases初始化為0.1
        biases = _variable_on_cpu('biases', [192], tf.constant_initializer(0.1))
        # ReLu啟用
        local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name=scope.name)
        _activation_summary(local4)

    # 線性層
    # (WX+b)不使用softmax,因為tf.nn.sparse_softmax_cross_entropy_with_logits接受未縮放的logits並在內部執行softmax以提高效率
    with tf.variable_scope('softmax_linear') as scope:
        weights = _variable_with_weight_decay('weights', [192, NUM_CLASSES], stddev=1/192.0, wd=None)
        # biases初始化為0
        biases = _variable_on_cpu('biases', [NUM_CLASSES], tf.constant_initializer(0.0))
        # (WX+b) 進行線性變換以輸出 logits
        softmax_linear = tf.add(tf.matmul(local4, weights), biases, name=scope.name)
        # 彙總
        _activation_summary(softmax_linear)
    return softmax_linear
# -------------------------------------------------------------------


# -------------------------模型訓練-----------------------------------
# 將L2損失新增到所有可訓練變數
def loss(logits, labels):
    labels = tf.cast(labels, tf.int64)
    # 計算logits和labels之間的交叉熵
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
      labels=labels, logits=logits, name='cross_entropy_per_example')
    # 計算整個批次的平均交叉熵損失
    cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
    # 把變數放入一個集合
    tf.add_to_collection('losses', cross_entropy_mean)
    # 總損失定義為交叉熵損失加上所有的權重衰減項(L2損失)
    return tf.add_n(tf.get_collection('losses'), name='total_loss')

# 新增損失的summary;計算所有單個損失的移動均值和總損失
def _add_loss_summaries(total_loss):
    # 指數移動平均
    loss_averages = tf.train.ExponentialMovingAverage(0.9, name='avg')
    losses = tf.get_collection('losses')
    # 將指數移動平均應用於單個損失
    loss_averages_op = loss_averages.apply(losses + [total_loss])
    # 單個損失損失和全部損失的標量summary
    for l in losses + [total_loss]:
        # 將每個損失命名為raw,並將損失的移動平均命名為原始損失
        tf.summary.scalar(l.op.name + ' (raw)', l)
        tf.summary.scalar(l.op.name, loss_averages.average(l))
    return loss_averages_op

# 訓練CIFAR-10模型
# 建立一個優化器並應用於所有可訓練變數,為所有可訓練變數新增移動均值(全部損失,訓練步數)
def train(total_loss, global_step):
    # 影響學習率的變數
    num_batches_per_epoch = NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN / FLAGS.batch_size
    decay_steps = int(num_batches_per_epoch * NUM_EPOCHS_PER_DECAY)
    # 指數衰減學習率
    lr = tf.train.exponential_decay(INITIAL_LEARNING_RATE, global_step, decay_steps,
                                  LEARNING_RATE_DECAY_FACTOR, staircase=True)
    tf.summary.scalar('learning_rate', lr)
    # 對總損失進行移動平均
    loss_averages_op = _add_loss_summaries(total_loss)
    # 計算梯度
    with tf.control_dependencies([loss_averages_op]):
        opt = tf.train.GradientDescentOptimizer(lr)
        grads = opt.compute_gradients(total_loss)
    # 應用處理過後的梯度
    apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)
    # 為可訓練變數新增直方圖
    for var in tf.trainable_variables():
        tf.summary.histogram(var.op.name, var)
    # 為梯度新增直方圖
    for grad, var in grads:
        if grad is not None:
            tf.summary.histogram(var.op.name + '/gradients', grad)
    # 跟蹤所有可訓練變數的移動均值
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
    # 使用預設圖形的包裝器
    with tf.control_dependencies([apply_gradient_op, variables_averages_op]): train_op = tf.no_op(name='train')
    return train_op
# -------------------------------------------------------------------

# 下載並解壓資料
def maybe_download_and_extract():
    dest_directory = FLAGS.data_dir
    if not os.path.exists(dest_directory):
        os.makedirs(dest_directory)
    filename = DATA_URL.split('/')[-1]
    filepath = os.path.join(dest_directory, filename)
    if not os.path.exists(filepath):
        def _progress(count, block_size, total_size):
            sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
              float(count * block_size) / float(total_size) * 100.0))
            sys.stdout.flush()
        filepath, _ = urllib.request.urlretrieve(DATA_URL, filepath, _progress)
        print()
        statinfo = os.stat(filepath)
        print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
    extracted_dir_path = os.path.join(dest_directory, 'cifar-10-batches-bin')
    if not os.path.exists(extracted_dir_path):
        tarfile.open(filepath, 'r:gz').extractall(dest_directory)

cifar10_input.py及註釋:

#!/usr/bin/python
# coding:utf-8

# 讀取本地CIFAR-10的二進位制檔案

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
from six.moves import xrange
import tensorflow as tf

# 處理影象尺寸,與CIFAR原始影象大小32 x 32不同
IMAGE_SIZE = 24
# 全域性常量
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()
    # CIFAR-10資料集中影象的尺寸
    label_bytes = 1  # 2 for CIFAR-100
    result.height = 32
    result.width = 32
    result.depth = 3
    image_bytes = result.height * result.width * result.depth
    # 每條記錄都包含一個標籤,後面跟著影象,每個記錄都有固定的位元組數
    record_bytes = label_bytes + image_bytes
    # 從檔案輸出固定長度的欄位(每個圖片的儲存位元組數是固定的)
    reader = tf.FixedLengthRecordReader(record_bytes=record_bytes)
    # 返回reader生成的下一條記錄(key, value pair)
    result.key, value = reader.read(filename_queue)
    # 將字串轉換為uint8型別的向量
    record_bytes = tf.decode_raw(value, tf.uint8)
    # 將標籤從uint8轉換為int32
    result.label = tf.cast(tf.strided_slice(record_bytes, [0], [label_bytes]), tf.int32)
    # 標籤之後的位元組表示影象,將其從[depth*height*width]轉換為[depth,height,width]
    depth_major = tf.reshape(
      tf.strided_slice(record_bytes, [label_bytes], [label_bytes + image_bytes]),
      [result.depth, result.height, result.width])
    # 從[depth,height,width]轉換為[height,width,depth].
    result.uint8image = tf.transpose(depth_major, [1, 2, 0])
    return result

# 構建[images,labels]的佇列
def _generate_image_and_label_batch(image, label, min_queue_examples, batch_size, shuffle):
    # 使用16個獨立執行緒,16個執行緒被連續的安排在一個佇列中
    # 每次在執行讀取一個 batch_size數量的樣本[images,labels]
    num_preprocess_threads = 16
    # 是否隨機打亂佇列
    if shuffle:
        # images:4D張量[batch_size, height, width, 3]; labels:[batch_size]大小的1D張量
        # 將佇列中資料打亂後取出
        images, label_batch = tf.train.shuffle_batch(
            [image, label],
            batch_size=batch_size,                         # 每批次的影象數量
            num_threads=num_preprocess_threads,            # 入隊tensor_list的執行緒數量
            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,            # 排列“tensor”的執行緒數量
            capacity=min_queue_examples + 3 * batch_size)  # 佇列中元素的最大數量
    # 在TensorBoard中顯示訓練影象
    tf.summary.image('images', images)
    return images, tf.reshape(label_batch, [batch_size])



# 讀入並增廣資料為訓練構建輸入(CIFAR-10資料的路徑,每批次的影象數量)
# 返回值 images:[batch_size,IMAGE_SIZE,IMAGE_SIZE,3];labels:[batch_size]
def distorted_inputs(data_dir, batch_size):
    # 獲取5個二進位制檔案所在路徑
    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)
    # 建立一個檔名的佇列
    filename_queue = tf.train.string_input_producer(filenames)
    with tf.name_scope('data_augmentation'):
        # 讀取檔名佇列中的檔案
        read_input = read_cifar10(filename_queue)
        # 轉換張量型別
        reshaped_image = tf.cast(read_input.uint8image, tf.float32)
        height = IMAGE_SIZE
        width = IMAGE_SIZE
        # 隨機裁剪[height, width]大小的影象
        distorted_image = tf.random_crop(reshaped_image, [height, width, 3])
        # 隨機水平翻轉影象
        distorted_image = tf.image.random_flip_left_right(distorted_image)
        # 隨機調整影象亮度與對比度(不可交換)
        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)
        # 減去均值除以方差,線性縮放為零均值的單位範數:白化/標準化處理
        float_image = tf.image.per_image_standardization(distorted_image)
        # 設定張量的形狀
        float_image.set_shape([height, width, 3])
        read_input.label.set_shape([1])
        # 確保隨機亂序具有良好的混合性能
        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)
    # 構建影象和標籤的佇列
    return _generate_image_and_label_batch(float_image, read_input.label, min_queue_examples, batch_size, shuffle=True)


# 影象預處理併為CIFAR預測構建輸入
# 輸入:(指示是否應該使用訓練或eval資料集,CIFAR-10資料的路徑,每批次的影象數量)
# 輸出:images:[batch_size, IMAGE_SIZE, IMAGE_SIZE, 3]; labels: [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)
    with tf.name_scope('input'):
        # 建立一個生成要讀取的檔名的佇列
        filename_queue = tf.train.string_input_producer(filenames)
        # 閱讀檔名佇列中檔案的示例
        read_input = read_cifar10(filename_queue)
        reshaped_image = tf.cast(read_input.uint8image, tf.float32)
        height = IMAGE_SIZE
        width = IMAGE_SIZE
        # 用於評估的影象處理
        # 在影象的中心裁剪[height, width]大小的影象,裁剪中央區域用於評估
        resized_image = tf.image.resize_image_with_crop_or_pad(reshaped_image, height, width)
        # 減去平均值併除以畫素的方差,保證資料均值為0,方差為1
        float_image = tf.image.per_image_standardization(resized_image)
        # 設定張量的形狀
        float_image.set_shape([height, width, 3])
        read_input.label.set_shape([1])
        # 確保隨機亂序具有良好的混合性能
        min_fraction_of_examples_in_queue = 0.4
        min_queue_examples = int(num_examples_per_epoch * min_fraction_of_examples_in_queue)
    # 通過建立一個示例佇列來生成一批影象和標籤
    return _generate_image_and_label_batch(float_image, read_input.label, min_queue_examples, batch_size, shuffle=False)

cifar10_eval.py及註釋

#!/usr/bin/python
# coding:utf-8

# 評估CIFAR-10模型的預測效能

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from datetime import datetime
import math
import time
import numpy as np
import tensorflow as tf

import cifar10

FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string('eval_dir', '/tmp/cifar10_eval',
                           """Directory where to write event logs.""")
tf.app.flags.DEFINE_string('eval_data', 'test',
                           """Either 'test' or 'train_eval'.""")
tf.app.flags.DEFINE_string('checkpoint_dir', '/tmp/cifar10_train',
                           """Directory where to read model checkpoints.""")
tf.app.flags.DEFINE_integer('eval_interval_secs', 60 * 5,
                            """How often to run the eval.""")
tf.app.flags.DEFINE_integer('num_examples', 10000,
                            """Number of examples to run.""")
tf.app.flags.DEFINE_boolean('run_once', False,
                         """Whether to run eval only once.""")
# 單次評估
def eval_once(saver, summary_writer, top_k_op, summary_op):
    with tf.Session() as sess:
        # checkpoint檔案會記錄儲存資訊,通過它可以定位最新儲存的模型
        ckpt = tf.train.get_checkpoint_state(FLAGS.checkpoint_dir)
        if ckpt and ckpt.model_checkpoint_path:
            # 從檢查點恢復
            saver.restore(sess, ckpt.model_checkpoint_path)
            # 假設model_checkpoint_path為/my-favorite-path/cifar10_train/model.ckpt-0從中提取global_step
            global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
        else:
            print('No checkpoint file found')
            return
        # 啟動佇列協調器
        coord = tf.train.Coordinator()
        try:
            threads = []
            for qr in tf.get_collection(tf.GraphKeys.QUEUE_RUNNERS):
                threads.extend(qr.create_threads(sess, coord=coord, daemon=True,start=True))
            num_iter = int(math.ceil(FLAGS.num_examples / FLAGS.batch_size))
            # 統計正確預測的數量
            true_count = 0
            total_sample_count = num_iter * FLAGS.batch_size
            step = 0
            # 檢查是否被請求停止
            while step < num_iter and not coord.should_stop():
                predictions = sess.run([top_k_op])
                true_count += np.sum(predictions)
                step += 1
            # 計算準確度 [email protected]
            precision = true_count / total_sample_count
            print('%s: precision @ 1 = %.3f' % (datetime.now(), precision))
            summary = tf.Summary()
            summary.ParseFromString(sess.run(summary_op))
            summary.value.add(tag='Precision @ 1', simple_value=precision)
            summary_writer.add_summary(summary, global_step)
        # pylint: disable=broad-except
        except Exception as e:
            coord.request_stop(e)
        # 請求執行緒結束
        coord.request_stop()
        # 等待執行緒終止
        coord.join(threads, stop_grace_period_secs=10)

# 評估CIFAR-10
def evaluate():
    with tf.Graph().as_default() as g:
        # 獲取CIFAR-10的影象和標籤
        eval_data = FLAGS.eval_data == 'test'
        images, labels = cifar10.inputs(eval_data=eval_data)
        # 構建一個圖表,用於計算推理模型中的logits預測
        logits = cifar10.inference(images)
        # 計算預測
        top_k_op = tf.nn.in_top_k(logits, labels, 1)
        # 為eval恢復學習變數的移動平均
        variable_averages = tf.train.ExponentialMovingAverage(cifar10.MOVING_AVERAGE_DECAY)
        variables_to_restore = variable_averages.variables_to_restore()
        # 建立一個saver物件,用於儲存引數到檔案中
        saver = tf.train.Saver(variables_to_restore)
        # 根據摘要TF集合構建摘要操作
        summary_op = tf.summary.merge_all()
        # 將Summary protocol buffers寫入事件檔案
        summary_writer = tf.summary.FileWriter(FLAGS.eval_dir, g)
        while True:
            eval_once(saver, summary_writer, top_k_op, summary_op)
            if FLAGS.run_once:
                break
            time.sleep(FLAGS.eval_interval_secs)

# pylint: disable=unused-argument
def main(argv=None):
    cifar10.maybe_download_and_extract()
    if tf.gfile.Exists(FLAGS.eval_dir):
        tf.gfile.DeleteRecursively(FLAGS.eval_dir)
    tf.gfile.MakeDirs(FLAGS.eval_dir)
    evaluate()

if __name__ == '__main__':
    tf.app.run()