1. 首页
  2. 主站
  3. 朋友
  4. 关于
  5. 后台

鹏鹏

Tensorflow学习笔记(一):手写数字识别

mnist_forward.py

#!/usr/bin/env python2.7
#coding: utf-8

import tensorflow as tf

INPUT_NODE = 784 #喂入数据的大小
OUTPUT_NODE = 10 #输出数据的大小
LAYER1_NODE = 500 #第一层隐藏层的大小

def get_weight(shape, regularizer): #生成形状为shape,正则化率为regularizer的w
    w = tf.Variable(tf.truncated_normal(shape, stddev = 0.1)) #定义w为形状为shape,标准差为0.1的截断的随机值
    if regularizer != None: tf.add_to_collection('losses', tf.contrib.layers.l2_regularizer(regularizer)(w)) :#将w以L2正则化的结果添加到集合losses中
    return w

def get_bias(shape): #生成形状为shape的b
    b = tf.Variable(tf.zeros(shape)) #以0填充的shape
    return b

def forward(x, regularizer): #正向传播
    #输入层到隐藏层
    w1 = get_weight([INPUT_NODE, LAYER1_NODE], regularizer)
    b1 = get_bias([LAYER1_NODE])
    y1 = tf.nn.relu(tf.matmul(x, w1) + b1) #对矩阵乘法的计算结果进行激活,即mat=max(mat, 0)
    #隐藏层到输出层
    w2 = get_weight([LAYER1_NODE, OUTPUT_NODE], regularizer)
    b2 = get_bias([OUTPUT_NODE])
    y = tf.matmul(y1, w2) + b2
    return y

mnist_backward.py

#!/usr/bin/env python2.7
#coding: utf-8

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data #导入mnist数据集
import mnist_forward
import os

BATCH_SIZE = 200 #每次喂入的数据组数
LEARNING_RATE_BASE = 0.1 #学习率基数
LEARNING_RATE_DECAY = 0.99 #学习率衰减率
REGULARIZER = 0.0001 #正则化率
STEPS = 50000 #训练次数
MOVING_AVERAGE_DECAY = 0.99 #滑动平均衰减率
MODEL_SAVE_PATH = './model/' #模型的保存位置
MODEL_NAME = 'mnist_model' #模型的名称

def backward(mnist): #反向传播
    x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE]) #待喂入数据,占位
    y_ = tf.placeholder(tf.float32, [None, mnist_forward.OUTPUT_NODE]) #计算所得数据,占位
    y = mnist_forward.forward(x, REGULARIZER) #正向传播,得到计算图
    global_step = tf.Variable(0, trainable = False) #不可训练的变量,作为计步器

    ce = tf.nn.sparse_softmax_cross_entropy_with_logits(logits = y , labels = tf.argmax(y_, 1))
    #用交叉熵归一化指数函数计算y和y_的差距
    cem = tf.reduce_mean(ce)
    #求平均
    loss = cem + tf.add_n(tf.get_collection('losses'))
    #总损失为交叉熵+正则化(从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)
    #定义线性下降的优化器作为训练步骤

    ema = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
    #求滑动平均
    ema_op = ema.apply(tf.trainable_variables())
    #把滑动平均应用到所有可训练变量
    with tf.control_dependencies([train_step, ema_op]): #将训练步骤和滑动平均操作绑定
        train_op = tf.no_op(name = 'train') #什么也不做
    
    saver = tf.train.Saver() #初始化保存器

    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer()) #初始化所有全局变量

        ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH) #检查模型目录是否已有模型,获取其状态
        if ckpt and ckpt.model_checkpoint_path: #如果存在且能获得模型路径
            saver.restore(sess, ckpt.model_checkpoint_path) #重现模型到当前会话

        for i in range(STEPS):
            xs, ys = mnist.train.next_batch(BATCH_SIZE) #从mnist中去下一撮数据
            _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict = {x: xs, y_: ys}) #训练,并得到损失和总步数
            if i % 1000 == 0:
                print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
                saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step = global_step) #暂存当前会话

def main():
    mnist = input_data.read_data_sets('./data/', one_hot = True) #读取数据集,如果没有会自动下载
    backward(mnist) #反向传播

if __name__ == '__main__':
    main()

mnist_app.py

#!/usr/bin/env python2.7
#coding: utf-8

import tensorflow as tf
import numpy as np
from PIL import Image
import mnist_forward
import mnist_backward

def restore_model(testPicArr): #传入图像像素值的列表,恢复模型,喂入图像,得到结果
    with tf.Graph().as_default() as tg: #打开默认图
        x = tf.placeholder(tf.float32, [None, mnist_forward.INPUT_NODE]) #要喂入的数据,占位
        y = mnist_forward.forward(x, None) #前向传播,得到计算图,y为输出
        preValue = tf.argmax(y, 1) #去y中最大元素的下表

        variable_averages = tf.train.ExponentialMovingAverage(mnist_backward.MOVING_AVERAGE_DECAY)
        #求滑动平均
        variables_to_restore = variable_averages.variables_to_restore()
        #获取所有可恢复的变量
        saver = tf.train.Saver(variables_to_restore)
        #初始化保存器

        with tf.Session() as sess:
            ckpt = tf.train.get_checkpoint_state(mnist_backward.MODEL_SAVE_PATH) #检查模型状态
            if ckpt and ckpt.model_checkpoint_path: #存在
                saver.restore(sess, ckpt.model_checkpoint_path) #恢复模型到当前会话

                preValue = sess.run(preValue, feed_dict = {x: testPicArr}) #喂入数据,得到结果
                return preValue
            else:
                print("No checkpoint file found")
                return -1

def pre_pic(picName): #传入图片路径,进行预处理
    img = Image.open(picName) #打开图片文件
    reIm = img.resize((28, 28), Image.ANTIALIAS) #抗锯齿地将图片重置到28×28
    im_arr = np.array(reIm.convert('L')) #将图像灰度化并存为列表
    threshold = 50 #阈值,超过则为白,没超过则为黑
    for i in range(28):
        for j in range(28):
            im_arr[i][j] = 255 - im_arr[i][j] #由于mnist存的是黑0白1,所以要反过来
            if im_arr[i][j] < threshold:
                im_arr[i][j] = 0
            else:
                im_arr[i][j] = 255
    nm_arr = im_arr.reshape([1, 784]) #将图像像素列表重新定型
    nm_arr = nm_arr.astype(np.float32) #将列表转换到float32类型
    img_ready = np.multiply(nm_arr, 1.0 / 255.0) #列表各元素除255

    return img_ready

def application():
    testNum = input("Inpt the number of test pictures: ")
    for i in range(testNum):
        testPic = raw_input("the path of test picture: ")
        testPicArr = pre_pic(testPic)
        preValue = restore_model(testPicArr)
        print "The prediction number is: ", preValue

def main():
    application()

if __name__ == '__main__':
    main()
Typecho强力驱动,鹏鹏享有并保留本站所有内容的权利。