TensorFlow学习_(5)0~9数字识别程序

用MNIST数据集训练,输入要识别的图片路径,首先预处理,将图片调成 28*28 ,转成灰度图,反色,取阈值二值化,变成 1*784 数组,输入模型,算出被预测数字。程序如下:

pre_pic.py

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

def pre_pic(path):
    im = Image.open(path)
    img = im.resize((28, 28), Image.ANTIALIAS)
    img = img.convert('L')
    arr = np.array(img)
    arr = 1 - arr * 1.0 / 255
    brr = arr.reshape(1, 784)
    xx = 0.2
    for i in range(784):
        if brr[0][i] > xx:
            brr[0][i] = 1
        else:
            brr[0][i] = 0
    return brr

def main(argv=None):
    path = input("Please input your pic's path: ")
    pre_pic(path)

if __name__ == '__main__':
    main()

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 = 30000
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()

judge_pic.py

#coding:utf-8
import time
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
import mnist_inference
import mnist_train
import changesize

def evaluate(nums):
    with tf.Graph().as_default() as g:
        # 定义输入
        x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')

        # 直接用封装好的函数计算前向传播结果
        # 因为这里不关心正则化损失的值,所以正则化函数被置为None
        y = tf.cast(mnist_inference.inference(x, None), tf.float32)
        preValue = tf.argmax(y, 1)

        # 通过变量重命名的方式加载模型,这样在前向传播过程中就不需要调用求滑动平均的函数获取平均值了
        # 可以完全共用 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)

        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)

                ans = sess.run(preValue, feed_dict={x: nums})
                print("Num in pic is: " + str(ans))
            else:
                print('No checkpoint file found')
                return
#主程序
def main(argv = None):
    path = input("Please input your pic's path: ")
    evaluate(changesize.pre_pic(path))

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值