TensorFlow学习_(4)MNIST数字识别问题

索引:
1. 什么是MNIST
2. 给出程序前的准备工作
3. 神经网络模型训练解决MNIST问题(完整程序)

什么是MNIST

MNIST是一个非常有名的手写体数字识别数据集,被当做深度学习的HelloWorld。

MNIST数据集包含70,000张图片,图片上都是0~9的手写体数字,大小为28*28,且数字都出现在图片正中间。其中:

  • 55,000张作为训练数据集(train);
  • 5,000张作为验证数据集(validation)
  • 10,000张作为测试数据集(test)。
    为了防止过拟合,训练集和测试集互不可见。

此数据集可以从 http://yann.lecun.com/exdb/mnist/ 下载,界面如下:
MNIST
红框内为下载链接

为了方便使用,TensorFlow提供了一个类来处理MNIST数据。这个类会自动下载并转化MNIST数据的格式。样例程序:

from tensorflow.examples.tutorials.mnist import input_data

# 载入MNIST数据集,如果指定地址路径下没有下载好的数据,TensorFlow会自动从上述网址下载数据
# one_hot可以简单理解为将标签定义为一个长度为n的数组,只有一个元素是1.0,其余都是0.0。
# 如,在n为4的情况下,标签2对应的onehot标签就是 [0.0, 0.0, 1.0, 0.0]
mnist = input_data.read_data_sets("MNIST/", one_hot = True)

# 打印训练集数据大小
print("Training data size: ", mnist.train.num_examples)

# 打印验证集数据大小
print("Validating data size: ", mnist.validation.num_examples)

# 打印测试集数据大小
print("Testing data size: ", mnist.test.num_examples)

# 打印训练集第一组数据28*28数组
print("Examples training data: \n", mnist.train.images[0])

# 打印训练集第一组数据标准答案
print("Example training data label: ", mnist.train.labels[0])

执行结果:

Extracting MNIST/train-images-idx3-ubyte.gz
Extracting MNIST/train-labels-idx1-ubyte.gz
Extracting MNIST/t10k-images-idx3-ubyte.gz
Extracting MNIST/t10k-labels-idx1-ubyte.gz
Training data size:  55000
Validating data size:  5000
Testing data size:  10000
Examples training data: 
 ...(太长了自己跑了看吧)
Example training data label:  [ 0.  0.  0.  0.  0.  0.  0.  1.  0.  0.]

给出程序前的准备工作

  1. 变量管理

    TensorFlow提供了根据变量名称来创建或者获取一个变量的机制,通过 tf.get_variabletf.variable_scope 函数实现。

    tf.get_variable 用于创建变量时,和 tf.Variable 的功能是基本等价的,如下:

    
    # 以下两个定义等价
    
    v = tf.get_variable("v", shape = [1], initializer = tf.constant_initializer(1.0))
    v = tf.Variable(tf.constant(1.0, shape = [1], name = "v"))

    初始化函数也基本对应相同,如下:
    初始化
    如果需要获取一个已经创建的变量,需要通过 tf.variable_scope 函数
    生成一个上下文管理器。实例:

    with tf.variable_scope("foo"):
        tf.get_variable("v", [1], initializer = tf.constant_initializer(1, 0))
    
    
    # 在生成上下文管理器时,将参数 reuse 设置为 true,
    
    
    # 则上下文管理器中所有tf.get_variable 将直接获取已经声明的变量。
    
    with tf.variable_scope("foo", reuse = true):
        v1 = tf.get_variable("v", [1])
    
  2. TensorFlow模型持久化实现断点续训

    TensorFlow提供了 tf.train.Saver 类保存和还原神经网络模型。保存实例:

    import tensorflow as tf
    
    v1 = tf.Variable(tf.constant(1.0, shape = [1]), name = "v1")
    v2 = tf.Variable(tf.constant(2.0, shape = [1]), name = "v2")
    result = v1 + v2
    
    init_op = tf.initialize_all_variable()
    
    # 声明 tf.train.Saver 类用于保存模型
    
    saver = tf.train.Saver()
    
    with tf.Session() as sess:
        sess.run(init_op)
        # 将模型保存到.ckpt文件
        saver.save(sess, "yourPath/model.ckpt")

    运行后TensorFlow将保存3个文件:

    • model.ckpt.meta:TensorFlow计算图的结构
    • model.ckpt:TensorFlow程序中每一个变量的取值
    • checkpoint:目录下所有模型的模型文件列表

    加载模型实例:

    import tensorflow as tf
    
    
    # 声明变量
    
    v1 = tf.Variable(tf.constant(1.0, shape = [1]), name = "v1")
    v2 = tf.Variable(tf.constant(2.0, shape = [1]), name = "v2")
    result = v1 + v2
    
    saver = tf.train.Saver()
    
    with tf.Session() as sess:
        # 加载已经保存的模型,并通过已经保存的模型中变量的值来计算加法
        saver.restore(sess, "yourPath/model.ckpt")

    此代码只是加载了变量的值,计算图需要重新定义。若不希望重复定义,可以直接加载已经持久化的图。同时,还可以只保存和加载部分变量,也可以在保存和加载变量时给变量重命名。针对滑动平均变量,有特定的函数生成tf.train.Saver类所需要的变量重命名字典。以上问题截图展示如下,如有需要请自取。

    • 直接加载已经持久化的图
      这里写图片描述

    • 只保存和加载部分变量
      加载模型时提供列表参数,如 saver = tf.train.Saver([v1]) 只会加载v1变量

    • 在保存和加载变量时给变量重命名
      这里写图片描述

    • 针对滑动平均变量生成字典
      这里写图片描述
      这里写图片描述

  3. 用到的其他函数等

    • 数据类型转换

      tf.cast(x, dtype)
      
    • 返回a数组最大值坐标

      tf.argmax(a, axis)
      
    • 拼接路径,返回home/name

      OS.path.join("home", "name")
      
    • 计算图可以有好多个,with块内定义的节点为计算图g内的

      with tf.Graph().as_default() as g:
          ...
      

神经网络模型训练解决MNIST问题(完整程序)

将整个工程分为3个程序:

  • mnist_inference.py
  • mnist_train.py
  • mnist_eval.py

如下:

mnist_inference.py

# 本程序定义前向传播的过程和神经网络中的参数

#coding:utf-8
import tensorflow as tf

# 定义输入层节点数(28 * 28)
INPUT_NODE = 784
# 定义输出层节点数(0~9共10个数字)
OUTPUT_NODE = 10
# 定义隐藏层节点数
LAYER1_NODE = 500

# 定义函数,得到正则化参数
def get_weight_variable(shape, regularizer):
    # tf.get_variable 函数获取变量在训练神经网络时会创建这些变量,
    # 在测试时会通过保存的模型加载这些变量的取值。
    # 因为可以在变量加载时将滑动平均变量重命名,所以可以直接通过同样的名称在训练时使用变量自身,
    # 而在测试时使用变量的滑动平均值。
    weights = tf.get_variable("weights",
                              shape,
                              initializer=tf.truncated_normal_initializer(stddev=0.1))
    # 若定义了正则化函数,将变量的正则化损失加入损失函数集合
    if regularizer != None:
        tf.add_to_collection('losses', regularizer(weights))
    return weights

# 定义神经网络的前向传播过程,返回值为前向传播结果
def inference(input_tensor, regularizer):
    # 在命名空间内创建变量
    # 若在同一程序中多次调用,则需要第一次调用后将 reuse 参数设为 true
    with tf.variable_scope('layer1'):

        weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
        biases = tf.get_variable("biases",
                                 [LAYER1_NODE],
                                 initializer=tf.constant_initializer(0.0))
        layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)

    with tf.variable_scope('layer2'):
        weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer)
        biases = tf.get_variable("biases",
                                 [OUTPUT_NODE],
                                 initializer=tf.constant_initializer(0.0))
        layer2 = tf.matmul(layer1, weights) + biases

    return layer2

mnist_train.py

# 本程序定义神经网络的训练过程

#coding:utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 加载定义好的前向传播函数
import mnist_inference
import os

# 配置神经网络参数
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001
TRAINING_STEPS = 39000
MOVING_AVERAGE_DECAY = 0.99
# 模型保存的路径和文件名
MODEL_SAVE_PATH="ckpt"
MODEL_NAME="model.ckpt"

def train(mnist):

    x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
    y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')

    # 使用L2正则化
    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
    # 前向传播
    y = mnist_inference.inference(x, regularizer)
    # 将训练轮数定义为不可训练的参数
    global_step = tf.Variable(0, trainable=False)

    # 滑动平均
    variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    # 在所有代表神经网络参数的变量上使用滑动平均,即所有没有指定 trainable=False 的参数
    variables_averages_op = variable_averages.apply(tf.trainable_variables())

    # 交叉熵做为损失函数
    # 当问题只有一个正确答案时可使用 tf.nn.sparse_softmax_cross_entropy_with_logits() 函数加速交叉熵的计算
    # tf.argmax() 函数得到正确答案 label 对应的类别编号
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    # 计算在当前batch中所有样例的交叉熵平均值
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))

    learning_rate = tf.train.exponential_decay(
        LEARNING_RATE_BASE,
        global_step,
        mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY,
        staircase=True)

    # 使用梯度下降算法优化损失函数
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)

    # 在训练NN模型时,每过一遍数据既要更新NN中的参数,又要更新每个参数的滑动平均值。
    # 为了一次完成多个操作,TensorFlow提供了 tf.control_dependencies 和 tf.group 两种机制,以下代码等价
    # train_op = tf.group(train_step, variables_averages_op)
    with tf.control_dependencies([train_step, variables_averages_op]):
        train_op = tf.no_op(name='train')

    # 初始化TensorFlow持久化类
    saver = tf.train.Saver()
    with tf.Session() as sess:

        # tf.train.get_checkpoint_state 函数会自动找到最新保存模型文件名
        ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
        if ckpt and ckpt.model_checkpoint_path:
            # 加载模型。
            # ckpt.model_checkpoint_path 表示模型存储的位置,
            # 不需要提供模型的名字,它会去查看checkpoint文件,看看最新的是谁,叫做什么。
            saver.restore(sess, ckpt.model_checkpoint_path)
            already_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
        else:
            tf.initialize_all_variables().run()
            already_step = 0

        # 训练过程
        for i in range(TRAINING_STEPS - int(already_step)):
            xs, ys = mnist.train.next_batch(BATCH_SIZE)
            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})

            if i % 1000 == 0:
                # 每1000轮输出当前batch上的损失函数大小
                print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
                # 每1000轮保存一次模型
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)


def main(argv=None):
    mnist = input_data.read_data_sets("MNIST", one_hot=True)
    train(mnist)

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

mnist_eval.py

# 本程序用来在测试集上测试模型效果

#coding:utf-8
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference
import mnist_train
#1. 每10秒加载一次最新的模型

# 加载的时间间隔。每10秒加载一次最新的模型,并在测试数据上测试最新模型的正确率
EVAL_INTERVAL_SECS = 10

def evaluate(mnist):
    with tf.Graph().as_default() as g:
        # 定义输入输出
        x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
        y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
        validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}

        # 直接用封装好的函数计算前向传播结果
        # 因为这里不关心正则化损失的值,所以正则化函数被置为None
        y = mnist_inference.inference(x, None)
        # 计算正确率
        # tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,相等返回True,不等返回False,返回值的矩阵维度和A相同
        # cast(x, dtype, name=None),将x的数据格式转化成dtype。
        # 原来x的数据格式是bool,那么将其转化成float以后,就能够将其转化成0和1的序列。
        correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

        # 通过变量重命名的方式加载模型,这样在前向传播过程中就不需要调用求滑动平均的函数获取平均值了
        # 可以完全共用 mnist_inference.py 中的前向传播过程
        variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
        variables_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variables_to_restore)

        while True:
            with tf.Session() as sess:
                # tf.train.get_checkpoint_state 函数会自动找到最新保存模型文件名
                ckpt = tf.train.get_checkpoint_state(mnist_train.MODEL_SAVE_PATH)
                if ckpt and ckpt.model_checkpoint_path:
                    # 加载模型。
                    # ckpt.model_checkpoint_path 表示模型存储的位置,
                    # 不需要提供模型的名字,它会去查看checkpoint文件,看看最新的是谁,叫做什么。
                    saver.restore(sess, ckpt.model_checkpoint_path)
                    # 通过文件名得到文件保存时迭代的轮数
                    global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
                    accuracy_score = sess.run(accuracy, feed_dict=validate_feed)
                    print("After %s training step(s), validation accuracy = %g" % (global_step, accuracy_score))
                else:
                    print('No checkpoint file found')
                    return
            # 每隔 EVAL_INTERVAL_SECS 秒调用一次检验正确率程序
            time.sleep(EVAL_INTERVAL_SECS)
#主程序
def main(argv=None):
    mnist = input_data.read_data_sets("MNIST", one_hot=True)
    evaluate(mnist)

if __name__ == '__main__':
    main()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值