main.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. # coding: utf-8
  2. # In[2]:
  3. from nt import chdir
  4. mdir="C:/Users/dell/workspace/firstPython/mnist"
  5. chdir(mdir)
  6. import tensorflow as tf
  7. import numpy as np
  8. import input_data
  9. mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
  10. # In[3]:
  11. #启动.Tensorflow依赖于一个高效的C++后端来进行计算。与后端的这个连接叫做session。
  12. sess = tf.InteractiveSession()
  13. #TensorBoard读取的log文件
  14. file_writer = tf.summary.FileWriter('%s%s' % (mdir,'/mnist_logs'), sess.graph)
  15. #占位符
  16. x = tf.placeholder("float", shape=[None, 784])
  17. y_ = tf.placeholder("float", shape=[None, 10])
  18. #变量
  19. W = tf.Variable(tf.zeros([784,10]))
  20. b = tf.Variable(tf.zeros([10]))
  21. #run
  22. sess.run(tf.initialize_all_variables())
  23. #类别预测与损失函数
  24. y = tf.nn.softmax(tf.matmul(x,W) + b)
  25. cross_entropy = -tf.reduce_sum(y_*tf.log(y))
  26. #训练模型
  27. train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
  28. for i in range(1000):
  29. batch = mnist.train.next_batch(50)
  30. train_step.run(feed_dict={x: batch[0], y_: batch[1]})
  31. #评估模型
  32. correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
  33. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  34. print(accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels}))
  35. # In[4]:
  36. #权重初始化
  37. def weight_variable(shape):
  38. initial = tf.truncated_normal(shape, stddev=0.1)
  39. return tf.Variable(initial)
  40. def bias_variable(shape):
  41. initial = tf.constant(0.1, shape=shape)
  42. return tf.Variable(initial)
  43. #卷积和池化
  44. def conv2d(x, W):
  45. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  46. def max_pool_2x2(x):
  47. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
  48. strides=[1, 2, 2, 1], padding='SAME')
  49. #第一层卷积
  50. W_conv1 = weight_variable([5, 5, 1, 32])
  51. b_conv1 = bias_variable([32])
  52. x_image = tf.reshape(x, [-1,28,28,1])
  53. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
  54. h_pool1 = max_pool_2x2(h_conv1)
  55. #第二层卷积
  56. W_conv2 = weight_variable([5, 5, 32, 64])
  57. b_conv2 = bias_variable([64])
  58. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
  59. h_pool2 = max_pool_2x2(h_conv2)
  60. #密集连接层
  61. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  62. b_fc1 = bias_variable([1024])
  63. h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
  64. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
  65. #Dropout
  66. # In[5]:
  67. keep_prob = tf.placeholder("float")
  68. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
  69. #输出层
  70. W_fc2 = weight_variable([1024, 10])
  71. b_fc2 = bias_variable([10])
  72. y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
  73. #训练和评估模型
  74. cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
  75. train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
  76. correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
  77. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
  78. sess.run(tf.initialize_all_variables())
  79. # In[8]:
  80. #for i in range(20000):
  81. for i in range(100):
  82. batch = mnist.train.next_batch(50)
  83. if i%100 == 0:
  84. train_accuracy = accuracy.eval(feed_dict={
  85. x:batch[0], y_: batch[1], keep_prob: 1.0})
  86. # print("step %d, training accuracy %g"%(i, train_accuracy))
  87. train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
  88. # In[7]:
  89. print("test accuracy %g"%accuracy.eval(feed_dict={
  90. x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))