当前位置:   article > 正文

Tensorflow训练mnist数据(完整版)_mnsit训练过程

mnsit训练过程

使用Tensorflow来对代码进行重构

重构之后的代码会被拆分成3个程序,第一个是mnist_inference.py,它定义了前向传播的过程以及神经网络中的参数。第二个程序是mnist_train.py,它定义了神经网络的训练过程。第三个程序是mnist_eval.py,它定义了测试过程。

代码如下:

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 25 10:04:39 2017
  4. @author: mnist_inference.py
  5. """
  6. import tensorflow as tf
  7. #定义神经网络结构相关的参数
  8. INPUT_NODE = 784
  9. OUTPUT_NODE = 10
  10. LAYER1_NODE = 500
  11. def get_weight_variable(shape, regularizer):
  12. weights = tf.get_variable("weights",shape,
  13. initializer = tf.truncated_normal_initializer(stddev=0.1))
  14. if regularizer !=None:
  15. tf.add_to_collection("losses", regularizer(weights))
  16. return weights
  17. #定义神经网络前向传播过程
  18. def inference(input_tensor, regularizer):
  19. #声明第一层神经网络的变量并完成前向传播过程
  20. with tf.variable_scope('layer1'):
  21. weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
  22. biases = tf.get_variable("biases", [LAYER1_NODE], initializer=tf.constant_initializer(0.0))
  23. layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)
  24. #声明第二层神经网络的变量并完成前向传播过程
  25. with tf.variable_scope('layer2' ):
  26. weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer)
  27. biases = tf.get_variable("biases", [OUTPUT_NODE], initializer=tf.constant_initializer(0.0))
  28. layer2 = tf.matmul(layer1,weights) + biases
  29. #返回最后前向传播的结果
  30. return layer2

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Tue Jul 25 14:00:16 2017
  4. @author: mnist_train.py
  5. """
  6. import os
  7. import tensorflow as tf
  8. from tensorflow.examples.tutorials.mnist import input_data
  9. #加载mnist_inference.py中定义的常量和前向传播的函数
  10. import mnist_inference
  11. #配置神经网络的参数
  12. BATCH_SIZE = 100
  13. LEARNING_RATE_BASE = 0.8
  14. LEARNING_RATE_DECAY = 0.99
  15. REGULARAZTION_RATE = 0.0001
  16. TRAINING_STEPS = 30000
  17. MOVING_AVERAGE_DECAY = 0.99
  18. #模型保存的路径和文件名
  19. MODEL_SAVE_PATH = r"C:\Users\alienware\Desktop\mnist2\ckpt"
  20. MODEL_NAME = "model.ckpt"
  21. def train(mnist):
  22. #定义输入输出placeholder
  23. x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE] , name = 'x-input')
  24. y_ = tf.placeholder(tf.float32,[None, mnist_inference.OUTPUT_NODE] , name = 'y-input')
  25. regularizer = tf.contrib.layers.l2_regularizer(REGULARAZTION_RATE)
  26. #前向传播
  27. y = mnist_inference.inference(x, regularizer)
  28. global_step = tf.Variable(0, trainable=False)
  29. #定义损失函数、学习率、滑动平滑操作以及训练过程
  30. variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
  31. variable_averages_op = variable_averages.apply(tf.trainable_variables())
  32. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.arg_max(y_,1))
  33. cross_entropy_mean = tf.reduce_mean(cross_entropy)
  34. loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))
  35. learning_rate = tf.train.exponential_decay(
  36. LEARNING_RATE_BASE,
  37. global_step,
  38. mnist.train.num_examples/BATCH_SIZE,
  39. LEARNING_RATE_DECAY)
  40. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step=global_step)
  41. with tf.control_dependencies([train_step, variable_averages_op]):
  42. train_op = tf.no_op(name='train')
  43. #初始化tensor持久化类
  44. saver = tf.train.Saver()
  45. with tf.Session() as sess:
  46. tf.initialize_all_variables().run()
  47. for i in range(TRAINING_STEPS):
  48. xs,ys = mnist.train.next_batch(BATCH_SIZE)
  49. _,loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x:xs, y_:ys})
  50. #每1000轮保存一次模型
  51. if i % 1000 == 0:
  52. #输出当前的训练情况
  53. print("After %d training step(s), loss on training "
  54. "batch is %g." % (step, loss_value))
  55. saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
  56. def main(argv=None):
  57. mnist = input_data.read_data_sets(r"F:\Tensor\MNIST_data", one_hot=True)
  58. train(mnist)
  59. if __name__ == '__main__':
  60. tf.app.run()

执行训练过程:

Extracting F:\Tensor\MNIST_data\train-images-idx3-ubyte.gz
Extracting F:\Tensor\MNIST_data\train-labels-idx1-ubyte.gz
Extracting F:\Tensor\MNIST_data\t10k-images-idx3-ubyte.gz
Extracting F:\Tensor\MNIST_data\t10k-labels-idx1-ubyte.gz
WARNING:tensorflow:From C:/Users/alienware/Desktop/mnist2/mnist_train.py:54: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02.
Instructions for updating:
Use `tf.global_variables_initializer` instead.
After 1 training step(s), loss on training batch is 2.92491.
After 1001 training step(s), loss on training batch is 0.203112.
After 2001 training step(s), loss on training batch is 0.144644.
After 3001 training step(s), loss on training batch is 0.128094.
After 4001 training step(s), loss on training batch is 0.115793.
After 5001 training step(s), loss on training batch is 0.116484.
After 6001 training step(s), loss on training batch is 0.103938.
After 7001 training step(s), loss on training batch is 0.0879508.
After 8001 training step(s), loss on training batch is 0.0801202.
After 9001 training step(s), loss on training batch is 0.0764782.
After 10001 training step(s), loss on training batch is 0.0709977.
After 11001 training step(s), loss on training batch is 0.0680732.
After 12001 training step(s), loss on training batch is 0.0609194.

  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Wed Jul 26 13:58:24 2017
  4. @author: mnist_eval.py
  5. """
  6. import time
  7. import tensorflow as tf
  8. from tensorflow.examples.tutorials.mnist import input_data
  9. #加载mnist_inference.py和mnist_train.py中定义的常量和函数
  10. import mnist_inference
  11. import mnist_train
  12. #每10秒加载一次最新的模型, 并在测试数据上测试最新的正确率
  13. EVAL_INTERVAL_SECS = 10
  14. def evaluate(mnist):
  15. with tf.Graph().as_default() as g:
  16. #定义输入输出的格式
  17. x = tf.placeholder(tf.float32, [None, mnist_inference.INPUT_NODE], name='x-input')
  18. y_ = tf.placeholder(tf.float32, [None, mnist_inference.OUTPUT_NODE], name='y-input')
  19. validate_feed = {x:mnist.validation.images,
  20. y_:mnist.validation.labels}
  21. #前向传播
  22. y = mnist_inference.inference(x,None)
  23. #使用前向传播的结果计算正确率
  24. correct_prediction = tf.equal(tf.arg_max(y,1), tf.arg_max(y_,1))
  25. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  26. #通过变量重命名的方式来加载模型
  27. variable_averages = tf.train.ExponentialMovingAverage(mnist_train.MOVING_AVERAGE_DECAY)
  28. variables_to_restore = variable_averages.variables_to_restore()
  29. saver = tf.train.Saver(variables_to_restore)
  30. #每隔EVAL_INTERVAL_SECS秒调用一次计算正确率的过程以检测训练过程中正确率的变化
  31. while True:
  32. with tf.Session() as sess:
  33. ckpt = tf.train.get_checkpoint_state(mnist_train.MODEL_SAVE_PATH)
  34. if ckpt and ckpt.model_checkpoint_path:
  35. #加载模型
  36. saver.restore(sess, ckpt.model_checkpoint_path)
  37. #通过文件名得到模型保存时迭代的轮数
  38. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
  39. accuracy_score = sess.run(accuracy, feed_dict=validate_feed)
  40. print("After %s training step(s), validation ""accuracy = %g" % (global_step, accuracy_score))
  41. else:
  42. print('No checkpoint file found')
  43. return
  44. time.sleep(EVAL_INTERVAL_SECS)
  45. def main(argv=None):
  46. mnist = input_data.read_data_sets(r"F:\Tensor\MNIST_data", one_hot=True)
  47. evaluate(mnist)
  48. if __name__ == '__main__':
  49. tf.app.run()
执行测试过程:
Extracting F:\Tensor\MNIST_data\train-images-idx3-ubyte.gz
Extracting F:\Tensor\MNIST_data\train-labels-idx1-ubyte.gz
Extracting F:\Tensor\MNIST_data\t10k-images-idx3-ubyte.gz
Extracting F:\Tensor\MNIST_data\t10k-labels-idx1-ubyte.gz
INFO:tensorflow:Restoring parameters from C:\Users\alienware\Desktop\mnist2\ckpt\model.ckpt-29001
After 29001 training step(s), validation accuracy = 0.9854



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/350225
推荐阅读
相关标签
  

闽ICP备14008679号