1 # CNN神经网络的代码实现 2 import tensorflow as tf 3 # 导入数据集 4 from tensorflow.examples.tutorials.mnist import input_data 5 # number 1 to 10 data:读取数据 6 mnist = input_data.read_data_sets("MNIST_data", one_hot=True) 7 8 sess = tf.Session() 9 10 #计算准确率 11 def compute_accuracy(v_xs, v_ys): 12 global prediction 13 y_pre = sess.run(prediction, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 0.5}) # keep_prob的设置是为了防止发生过拟合的现象 14 correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1)) 15 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) 16 result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 0.5}) 17 return result 18 19 # 定义并初始化weight_variable 20 def weight_variable(shape): 21 initial = tf.truncated_normal(shape, stddev=0.1) 22 return tf.Variable(initial) 23 24 # 定义并初始化bias_variable 25 def bias_variable(shape): 26 initial = tf.constant(0.1, shape=shape) 27 return tf.Variable(initial) 28 29 #定义卷积层 30 def conv2d(x,W): 31 # strides=[1,x_movement,y_movement,1] 32 # strides[0] = strides[3] = 0 33 return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding="SAME") 34 35 #定义池化层 36 def max_pool_2x2(x): 37 # strides=[1,x_movement,y_movement,1] 38 # strides[0] = strides[3] = 0 39 # ksize=[1,x,x,1]:其中表示池化的大小 40 # 在池化得我过程中,不能有重叠,否则会出现报错 --栽沟里了!!! 41 return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME") 42 43 # 定义placeholder for inputs to network,None表示输入的样本数待定 44 xs = tf.placeholder(tf.float32, [None, 784]) # None表示输入的样本数待定(待定) 45 ys = tf.placeholder(tf.float32, [None, 10]) 46 keep_prob = tf.placeholder(tf.float32) 47 48 # 将输入的数据变换成矩阵的形式 49 # 此时x_image表示的是[n_samples,28,28,1],其中1表示channel 50 x_image = tf.reshape(xs, [-1, 28, 28, 1]) # -1表示输入的样本数待定(待定) 51 52 # 定义conv1 layer--卷积层1 53 # [5,5,1,32] 54 # 5*5:patch size 1:channel 32:filter的数量 55 W_conv1 = weight_variable([5, 5, 1, 32]) 56 b_conv1 = bias_variable([32]) 57 h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #output_size:28*28*32 58 h_pool1 = max_pool_2x2(h_conv1) #output_size:14*14*32 59 60 # 定义conv2 layer 61 # 32:第二层卷积中卷积核的深度 64:卷积核的个数 62 W_conv2 = weight_variable([5, 5, 32, 64]) 63 b_conv2 = bias_variable([64]) 64 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #output_size:14*14*64 65 h_pool2 = max_pool_2x2(h_conv2) #output_size:7*7*64 66 67 68 # 定义func1 layer:全卷积层1 69 W_fc1 = weight_variable([7*7*64, 1024]) #全连接层的in_size:7*7*64 out_size:1024 70 b_fc1 = bias_variable([1024]) 71 # 将con2 layer的输出拉平:[n_sample,7,7,64] ->> [n_sample,7*7*64] 72 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) # -1表示输入的样本数(待定) 73 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) 74 # 为了防止出现过拟合,使用tf.nn.dropout() 75 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) 76 77 # 定义func2 layer 78 W_fc2 = weight_variable([1024, 10]) #全连接层的in_size:1024 out_size:10(分类对应10个数据) 79 b_fc2 = bias_variable([10]) 80 # 将con2 layer的输出拉平:[n_sample,7,7,64] ->> [n_sample,7*7*64] 81 prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2)+b_fc2) 82 83 # the error between prediction and real data 84 cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1])) 85 # 优化器的选择 86 train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) 87 88 # 定义变量需要初始化所有的参数 -- very important 89 sess.run(tf.initialize_all_variables()) 90 91 # 数据的训练 92 for i in range(1000): 93 batch_xs, batch_ys = mnist.train.next_batch(100) 94 sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5}) 95 if i % 50 == 0: 96 # 每训练50次,计算一下准确略:函数需要自定义 97 print(compute_accuracy( 98 mnist.test.images, mnist.test.labels))
说明:
①在实现CNN过程中,定义池化层的时候,由于strides设置错误([1, 1, 1, 1] ->>[1, 2, 2, 1]),导致在进行MaxPooling时出现重叠进而导致后续的运算出现矩阵维度不匹配的错误。
②以上代码实在tensorflow1.13.0环境中运行的--采用的是符号式编程。