test04.py 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. # -*- coding: utf-8 -*-
  2. import tensorflow as tf
  3. import tensorflow.examples.tutorials.mnist.input_data as input_data
  4. mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 下载并加载mnist数据
  5. x = tf.placeholder(tf.float32, [None, 784]) # 输入的数据占位符
  6. y_actual = tf.placeholder(tf.float32, shape=[None, 10]) # 输入的标签占位符
  7. # 定义一个函数,用于初始化所有的权值 W
  8. def weight_variable(shape):
  9. initial = tf.truncated_normal(shape, stddev=0.1)
  10. return tf.Variable(initial)
  11. # 定义一个函数,用于初始化所有的偏置项 b
  12. def bias_variable(shape):
  13. initial = tf.constant(0.1, shape=shape)
  14. return tf.Variable(initial)
  15. # 定义一个函数,用于构建卷积层
  16. def conv2d(x, W):
  17. return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  18. # 定义一个函数,用于构建池化层
  19. def max_pool(x):
  20. return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
  21. # 构建网络
  22. x_image = tf.reshape(x, [-1, 28, 28, 1]) # 转换输入数据shape,以便于用于网络中
  23. W_conv1 = weight_variable([5, 5, 1, 32])
  24. b_conv1 = bias_variable([32])
  25. h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) # 第一个卷积层
  26. h_pool1 = max_pool(h_conv1) # 第一个池化层
  27. W_conv2 = weight_variable([5, 5, 32, 64])
  28. b_conv2 = bias_variable([64])
  29. h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 第二个卷积层
  30. h_pool2 = max_pool(h_conv2) # 第二个池化层
  31. W_fc1 = weight_variable([7 * 7 * 64, 1024])
  32. b_fc1 = bias_variable([1024])
  33. h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64]) # reshape成向量
  34. h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # 第一个全连接层
  35. keep_prob = tf.placeholder("float")
  36. h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) # dropout层
  37. W_fc2 = weight_variable([1024, 10])
  38. b_fc2 = bias_variable([10])
  39. y_predict = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) # softmax层
  40. cross_entropy = -tf.reduce_sum(y_actual * tf.log(y_predict)) # 交叉熵
  41. train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy) # 梯度下降法
  42. correct_prediction = tf.equal(tf.argmax(y_predict, 1), tf.argmax(y_actual, 1))
  43. accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) # 精确度计算
  44. sess = tf.InteractiveSession()
  45. sess.run(tf.initialize_all_variables())
  46. for i in range(20000):
  47. batch = mnist.train.next_batch(50)
  48. if i % 100 == 0: # 训练100次,验证一次
  49. train_acc = accuracy.eval(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 1.0})
  50. print('step', i, 'training accuracy', train_acc)
  51. train_step.run(feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
  52. test_acc = accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
  53. print("test accuracy", test_acc)