main.py 3.2 KB

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