1. import os
  2. import tensorflow as tf
  3. from tensorflow.examples.tutorials.mnist import input_data
  4.  
  5. INPUT_NODE = 784
  6. OUTPUT_NODE = 10
  7. LAYER1_NODE = 500
  8.  
  9. def get_weight_variable(shape, regularizer):
  10. weights = tf.get_variable("weights", shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
  11. if regularizer != None:
  12. tf.add_to_collection('losses', regularizer(weights))
  13. return weights
  14.  
  15. def inference(input_tensor, regularizer):
  16. with tf.variable_scope('layer1'):
  17. weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
  18. biases = tf.get_variable("biases", [LAYER1_NODE], initializer=tf.constant_initializer(0.0))
  19. layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)
  20.  
  21. with tf.variable_scope('layer2'):
  22. weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer)
  23. biases = tf.get_variable("biases", [OUTPUT_NODE], initializer=tf.constant_initializer(0.0))
  24. layer2 = tf.matmul(layer1, weights) + biases
  25. return layer2
  26.  
  27. BATCH_SIZE = 100
  28. LEARNING_RATE_BASE = 0.8
  29. LEARNING_RATE_DECAY = 0.99
  30. REGULARIZATION_RATE = 0.0001
  31. TRAINING_STEPS = 30000
  32. MOVING_AVERAGE_DECAY = 0.99
  33. MODEL_SAVE_PATH = "E:\\MNIST_model\\"
  34. MODEL_NAME = "mnist_model"
  35.  
  36. def train(mnist):
  37. # 定义输入输出placeholder。
  38. x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
  39. y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')
  40.  
  41. regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
  42. y = inference(x, regularizer)
  43. global_step = tf.Variable(0, trainable=False)
  44.  
  45. # 定义损失函数、学习率、滑动平均操作以及训练过程。
  46. variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY, global_step)
  47. variables_averages_op = variable_averages.apply(tf.trainable_variables())
  48. cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
  49. cross_entropy_mean = tf.reduce_mean(cross_entropy)
  50. loss = cross_entropy_mean + tf.add_n(tf.get_collection('losses'))
  51. learning_rate = tf.train.exponential_decay(
  52. LEARNING_RATE_BASE,
  53. global_step,
  54. mnist.train.num_examples / BATCH_SIZE, LEARNING_RATE_DECAY,
  55. staircase=True)
  56. train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
  57. with tf.control_dependencies([train_step, variables_averages_op]):
  58. train_op = tf.no_op(name='train')
  59.  
  60. # 初始化TensorFlow持久化类。
  61. saver = tf.train.Saver()
  62. with tf.Session() as sess:
  63. tf.global_variables_initializer().run()
  64. for i in range(TRAINING_STEPS):
  65. xs, ys = mnist.train.next_batch(BATCH_SIZE)
  66. _, loss_value, step = sess.run([train_op, loss, global_step], feed_dict={x: xs, y_: ys})
  67. if i % 1000 == 0:
  68. print("After %d training step(s), loss on training batch is %g." % (step, loss_value))
  69. saver.save(sess, os.path.join(MODEL_SAVE_PATH, MODEL_NAME), global_step=global_step)
  70.  
  71. def main(argv=None):
  72. mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True)
  73. train(mnist)
  74.  
  75. if __name__ == '__main__':
  76. main()

  1. import os
  2. import time
  3. import tensorflow as tf
  4. from tensorflow.examples.tutorials.mnist import input_data
  5.  
  6. INPUT_NODE = 784
  7. OUTPUT_NODE = 10
  8. LAYER1_NODE = 500
  9.  
  10. BATCH_SIZE = 100
  11. LEARNING_RATE_BASE = 0.8
  12. LEARNING_RATE_DECAY = 0.99
  13. REGULARIZATION_RATE = 0.0001
  14. TRAINING_STEPS = 30000
  15. MOVING_AVERAGE_DECAY = 0.99
  16. MODEL_SAVE_PATH = "E:\\MNIST_model\\"
  17. MODEL_NAME = "mnist_model"
  18.  
  19. def get_weight_variable(shape, regularizer):
  20. weights = tf.get_variable("weights", shape, initializer=tf.truncated_normal_initializer(stddev=0.1))
  21. if regularizer != None:
  22. tf.add_to_collection('losses', regularizer(weights))
  23. return weights
  24.  
  25. def inference(input_tensor, regularizer):
  26. with tf.variable_scope('layer1'):
  27. weights = get_weight_variable([INPUT_NODE, LAYER1_NODE], regularizer)
  28. biases = tf.get_variable("biases", [LAYER1_NODE], initializer=tf.constant_initializer(0.0))
  29. layer1 = tf.nn.relu(tf.matmul(input_tensor, weights) + biases)
  30.  
  31. with tf.variable_scope('layer2'):
  32. weights = get_weight_variable([LAYER1_NODE, OUTPUT_NODE], regularizer)
  33. biases = tf.get_variable("biases", [OUTPUT_NODE], initializer=tf.constant_initializer(0.0))
  34. layer2 = tf.matmul(layer1, weights) + biases
  35. return layer2
  36.  
  37. # 加载的时间间隔。
  38. EVAL_INTERVAL_SECS = 10
  39.  
  40. def evaluate(mnist):
  41. with tf.Graph().as_default() as g:
  42. x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input')
  43. y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input')
  44. validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
  45.  
  46. y = inference(x, None)
  47. correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  48. accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  49.  
  50. variable_averages = tf.train.ExponentialMovingAverage(MOVING_AVERAGE_DECAY)
  51. variables_to_restore = variable_averages.variables_to_restore()
  52. saver = tf.train.Saver(variables_to_restore)
  53.  
  54. while True:
  55. with tf.Session() as sess:
  56. ckpt = tf.train.get_checkpoint_state(MODEL_SAVE_PATH)
  57. if ckpt and ckpt.model_checkpoint_path:
  58. saver.restore(sess, ckpt.model_checkpoint_path)
  59. global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]
  60. accuracy_score = sess.run(accuracy, feed_dict=validate_feed)
  61. print("After %s training step(s), validation accuracy = %g" % (global_step, accuracy_score))
  62. else:
  63. print('No checkpoint file found')
  64. return
  65. time.sleep(EVAL_INTERVAL_SECS)
  66.  
  67. def main(argv=None):
  68. mnist = input_data.read_data_sets("E:\\MNIST_data\\", one_hot=True)
  69. evaluate(mnist)
  70.  
  71. if __name__ == '__main__':
  72. main()

吴裕雄 python 神经网络——TensorFlow训练神经网络:MNIST最佳实践的更多相关文章

  1. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用滑动平均

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  2. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用隐藏层

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  3. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用激活函数

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  4. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用指数衰减的学习率

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  5. 吴裕雄 python 神经网络——TensorFlow训练神经网络:不使用正则化

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  6. 吴裕雄 python 神经网络——TensorFlow训练神经网络:全模型

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data INPUT_NODE = 784 ...

  7. TensorFlow入门之MNIST最佳实践

    在上一篇<TensorFlow入门之MNIST样例代码分析>中,我们讲解了如果来用一个三层全连接网络实现手写数字识别.但是在实际运用中我们需要更有效率,更加灵活的代码.在TensorFlo ...

  8. TensorFlow入门之MNIST最佳实践-深度学习

    在上一篇<TensorFlow入门之MNIST样例代码分析>中,我们讲解了如果来用一个三层全连接网络实现手写数字识别.但是在实际运用中我们需要更有效率,更加灵活的代码.在TensorFlo ...

  9. 吴裕雄 python 神经网络——TensorFlow训练神经网络:花瓣识别

    import os import glob import os.path import numpy as np import tensorflow as tf from tensorflow.pyth ...

随机推荐

  1. 转载:DRC

    https://cn.mathworks.com/help/audio/ug/dynamic-range-control.html?requestedDomain=cn.mathworks.com h ...

  2. Linux gd库安装步骤说明

    gd 库是 PHP 处理图形的扩展库,它提供了一系列用来处理图片的 API(应用程序编程接口),使用 gd 库可以处理图片或者生成图片.在网站上,gd 库通常用来生成缩略图,或者对图片加水印,或者生成 ...

  3. mybatis报错:A query was run and no Result Maps were found for the Mapped Statement

    转自:https://blog.csdn.net/u013399093/article/details/53087469 今天编辑mybatis的xml文件,出现如下错误: 程序出现异常[A quer ...

  4. 如何在项目中新建.gitignore文件

    1. 在需要创建 .gitignore 文件的文件夹, 右键选择 Git Bash 进入命令行,进入项目所在目录. 2. 输入 touch .gitignore 在文件夹就生成了一个“.gitigno ...

  5. 关于mybatis中多参数传值

    如果前台单独传递多个参数,并且未进行封装,在mybatis的sql映射文件中需要以下标的形式表示传递的参数,从0开始 即:where name=#{0} and password =#{1}:0表示第 ...

  6. 【SSH】spring 整合 hibernate

    spring-hibernate-1.2.9.jar applicationContext.xml <bean id="sessionFactory" class=" ...

  7. BufferedInputStream 介绍

    BufferedInputStream 介绍 BufferedInputStream 是缓冲输入流.它继承于FilterInputStream.BufferedInputStream 的作用是为另一个 ...

  8. Linux中Oracle启动侦听报错TNS:permission denied的解决方法

    最近在开发环境 oracle 启动侦听的时候,出现了 TNS:permission denied 的问题,通过网上和咨询朋友,最终找到了解决方案,现在共享出来给有需要的朋友. [oracle@orac ...

  9. Centos6.10-FastDFS-Storage.conf配置示例

    Centos610系列配置 # is this config file disabled # false for enabled # true for disabled disabled = fals ...

  10. 总结fiddler抓https包

    把fiddler工具>选项>https>勾选所有,点击actions,导出的证书导入到浏览器(打开右上角浏览器设置>选项>高级>证书>查看证书>证书机构 ...