TensorFlow之实现卷积神经网络(9)
示例:
1 # -*- encoding:utf-8 -*- 2 3 import numpy as np 4 import tensorflow as tf 5 6 #下载并载入 MNIST 手写数字库(55000 * 28 * 28) 55000张训练图像 7 from tensorflow.examples.tutorials.mnist import input_data 8 mnist = input_data.read_data_sets('mnist_data', one_hot=True) 9 10 #one_hot 独热码的编码(encoding)形式 11 #0,1,2,3,4,5,6,7,8,9 的十位数字 12 # 0 : 1000 000 000 13 # 1 : 0100 000 000 14 # 2 : 0010 000 000 15 # 3 : 0001 000 000 16 # 4 : 0000 100 000 17 # 5 : 0000 010 000 18 # 6 : 0000 001 000 19 # 7 : 0000 000 100 20 # 8 : 0000 000 010 21 # 9 : 0000 000 001 22 23 # None 表示张量(Tensor)的第一个维度可以是任何长度 24 input_x = tf.placeholder(tf.float32, [None, 28 * 28]) / 255. 25 output_y = tf.placeholder(tf.int32, [None, 10]) #输出:10个数字的标签 26 input_x_images = tf.reshape(input_x, [-1, 28, 28, 1]) #改变形状之后的输入 27 28 # 从 Test(测试)数据集选取 3000 个手写数字的图片和对应标签 29 test_x = mnist.test.images[:3000] # 图片 30 test_y = mnist.test.labels[:3000] #标签 31 32 # 构建我们的卷积神经网络 33 # 第 1 层卷积 34 conv1 = tf.layers.conv2d( 35 inputs=input_x_images, #形状 [28, 28, 1] 36 filters = 32, #32个过滤器,输出的深度(depth)是32 37 kernel_size=[5, 5], #过滤器在二维的大小是(5 * 5) 38 strides = 1, #步长是1 39 padding = 'same', #same表示输出的大小不变,因此需要在外围补零 2 圈 40 activation=tf.nn.relu #激活函数是 Relu 41 ) #形状 [28, 28, 32] 42 43 # 第 1 层池化(亚采样) 44 pool1 = tf.layers.max_pooling2d( 45 inputs = conv1, #形状 [28, 28, 32] 46 pool_size = [2, 2], #过滤器在二维的大小是(2 * 2) 47 strides = 2 #步长是 2 48 ) #形状 [14, 14, 32] 49 50 # 第 2 层卷积 51 conv2 = tf.layers.conv2d( 52 inputs=pool1, #形状 [14, 14, 32] 53 filters = 64, #64个过滤器,输出的深度(depth)是64 54 kernel_size=[5, 5], #过滤器在二维的大小是(5 * 5) 55 strides = 1, #步长是1 56 padding = 'same', #same表示输出的大小不变,因此需要在外围补零 2 圈 57 activation=tf.nn.relu #激活函数是 Relu 58 ) #形状 [14, 14, 64] 59 60 # 第 2 层池化(亚采样) 61 pool2 = tf.layers.max_pooling2d( 62 inputs = conv2, #形状 [14, 14, 64] 63 pool_size = [2, 2], #过滤器在二维的大小是(2 * 2) 64 strides = 2 #步长是 2 65 ) #形状 [7, 7, 64] 66 67 # 平坦化(flat) 68 flat = tf.reshape(pool2, [-1, 7 * 7 * 64]) #形状 [7 * 7 * 64] 69 70 # 1024 个神经元的全连接层 71 dense = tf.layers.dense(inputs=flat, units=1024, activation=tf.nn.relu) 72 73 # Dropout : 丢弃 50%, rate=0.5 74 dropout = tf.layers.dropout(inputs=dense, rate=0.5) 75 76 # 10 个神经元的全连接层,这里不用激活函数来做非线性化了 77 logits = tf.layers.dense(inputs=dropout, units=10) # 输出。 形状[1,1,10] 78 79 #计算误差(计算 Cross entropy(交叉熵),再用 Softmax 计算百分比概率) 80 loss = tf.losses.softmax_cross_entropy(onehot_labels=output_y, logits=logits) 81 82 #用 Adam 优化器来最小化误差,学习率 0.001 83 train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss) 84 85 # 精度。计算 预测值 和 实际标签 的匹配程度 86 # 返回 (accuracy, undate_op), 会创建两个局部变量 87 accuracy = tf.metrics.accuracy( 88 labels = tf.argmax(output_y, axis=1), 89 predictions=tf.argmax(logits, axis=1),)[1] 90 91 # 创建会话 92 sess = tf.Session() 93 # 初始化变量:全局 和 局部 94 init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer()) 95 sess.run(init) 96 97 for i in range(20000): 98 batch = mnist.train.next_batch(50) #从 Train(训练) 数据集里取下一个 50 个样本 99 train_loss, train_op_ = sess.run([loss, train_op], {input_x: batch[0], output_y: batch[1]}) 100 101 if i % 100 == 0: 102 test_accuracy = sess.run(accuracy, {input_x: test_x, output_y: test_y}) 103 print ("Step=%d, Train loss=%.4f, [Test accuracy=%.2f]") % (i, train_loss, test_accuracy) 104 105 # 测试:打印 20 个预测值 和 真实值 的对 106 test_output = sess.run(logits, {input_x:test_x[:20]}) 107 inferenced_y = np.argmax(test_output, 1) 108 print (inferenced_y, 'Inferenced numbers') # 推测的数字 109 print (np.argmax(test_y[:20], 1), 'Real numbers') # 真实的数字