Mnist最佳样例程序

下面介绍mnist最佳样例程序:

add_to_collection

表示将一个张量加入一个集合
2.

tf.get_variable
 tf.Variable()

的区别
https://blog.csdn.net/u012223913/article/details/78533910
3.

 initializer=tf.constant_initializer(0.0)

就是初始化为一个常数0.0
tf.constant_initializer可以简化为tf.Constant()

regularizer=tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)

REGULARAZTION_RATE即正则化项目里面 入 的大小

mnist.train.num_examples / BATCH_SIZE

这个前面的是怎么来的?存疑

    with tf.control_dependencies([train_step,variable_averages_op]):
        train_op=tf.no_op(name='train')

保证计算顺序的正确性
https://blog.csdn.net/abiggg/article/details/79019098

7.发现这个自己按照书上的有问题!!!

以下是mnist_train

#author MJY

#mnist_train.py
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


#加载mnist_inference.py中定义的常量和前向传播的函数
import mnist_inference

#配置神经网络参数
BATCH_SIZE=100
LEARNING_RATE_BASE=0.8
LEARNING_RATE_DECAY=0.99
REGULARAZTION_RATE=0.0001
TRAINING_STEPS=30000
MOVING_AVERAGE_DECAY=0.99
#模型保存的路径和名称
MODEL_SAVE_PATH="path/"
MODEL_NAME="model.ckpt"

#d定义训练函数
def train(mnist):
    #定义输入输出的placeholder
    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")
    regularizer=tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)

    #使用mnist_inference.py中定义的前向传播函数
    y=mnist_inference.inference(x,regularizer)
    global_step=tf.Variable(0,trainable=False)#初始化钟表0


    #定义损失函数 学习率 滑动平均操作和训练过程
    variable_averages=tf.train.ExponentialMovingAverage(
        MOVING_AVERAGE_DECAY,global_step)
    variable_averages_op=variable_averages.apply(
        tf.trainable_variables())#可更新的变量全部更新
    cross_entropy=tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=y,labels=tf.argmax(y_,1))
    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)
    train_step=tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
    with tf.control_dependencies([train_step,variable_averages_op]):
        train_op=tf.no_op(name='train')#保证train之前参数被刷新


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


        #在训练过程中不再测试模型在验证集上的表现,验证和测试的过程将会有一个独立的程序完成
        for i in range(TRAINING_STEPS):
            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:
                #输出当前训练batch上的损失函数大小
                print("After %d training steps,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(argv=None):
    mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
    train(mnist)

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





以下是我的mnist_inference(含错误)

#author MJY

#mnist_inference.py
import tensorflow as tf

#定义神经网络有关参数
INPUT_NODE=784
OUTPUT_NODE=10
LAYER1_NODE=500


#通过tf.get_variable函数获取变量
def get_weight_variable(shape,regularizer):
    weights=tf.get_variable(
        "weights",shape,
        initializer=tf.truncated_normal_initializer(stddev=0.1))#意思是:从截断的正态分布中输出随机值。生成的值服从具有指定平均值和标准偏差的正态分布,如果生成的值大于平均值2个标准偏差的值则丢弃重新选择。
    if regularizer != None:
        tf.add_to_collection('losses',regularizer(weights))#将一个张量加入一个集合
    return weights


#定义前向传播过程
def inference(input_tensor,regularizer):
    #声明第一层神经网络的变量并完成前向传播过程
    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))#就是把b初始化为0.0;tf.constant_initializer可以简化为tf.Constant()
        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.nn.relu(tf.matmul(layer1, weights) + biases)

    return layer2


经过对比发现是我的mnist_infenrence有问题
对比发现:
我写的是

layer2 = tf.nn.relu(tf.matmul(layer1, weights) + biases)

实际上第二层代码并没有进行relu处理
原因是第二层是输出层 是需要用softmax函数处理的
还有就是 没有写出来的 在train程序里面的LEARNING_RATE_BASE = 0.8太大了
一般基础学习率是0.1 0.01之类的

以下是mnist_eval

对于variables_to_restore需要了解一下:
https://blog.csdn.net/sinat_29957455/article/details/78508793?utm_source=blogxgwz0
自己的还是有错 如下:

#author MJY

#mnist_eval测试程序
import time
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

import mnist_inference
import mnist_train


#每十秒加载一次最新的模型 并在测试数据上测试最新模型的正确率
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}

        #通过封装好的函数(mnist_inference)来计算前向传播的结果。因为测试时不关注正则化损失的值,故计算正则化损失的函数被设置为None
        y=mnist_inference.inference(x,None)
        correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))#相等则返回True
        accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))


        #通过变量重命名的方式加载模型
        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)#先学会用法吧

        #每隔EVAL_INTERVAL_SECS秒调用一次计算正确率的过程以检测训练过程中正确率的变化
        while True:
            with tf.Session() as sess:
                ckpt=tf.train.get_checkpoint_state(
                    mnist_train.MODEL_SAVE_PATH)#tf.train.get_checkpoint_state函数自动找到这个时间最新模型的ckpt
                if ckpt and ckpt.model_checkpoint_path:
                    #加载模型
                    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 steps,validation accuracy = %g" % (global_step,accuracy_score))
                else:
                    print('No checkpoint file found')
                    return
            time.sleep(EVAL_INTERVAL_SECS)#延迟函数


def main(argv=None):
    mnist=input_data.read_data_sets("MNIST_data",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、付费专栏及课程。

余额充值