1 # 导入数据 2 from tensorflow.examples.tutorials.mnist import input_data 3 # 读取数据 4 mnist=input_data.read_data_sets("MNIST_data/",one_hot=True) 5 import tensorflow as tf 6 7 # 定义卷积操作函数 8 def conv2d(name,x,w,b): 9 return tf.nn.relu(tf.nn.bias_add(tf.nn.conv2d(x,w,strides=[1,1,1,1],padding=‘SAME‘),b),name=name) 10 11 # 定义下采样操作函数 12 def max_pool(name,x,k): 13 return tf.nn.max_pool(x,ksize=[1,k,k,1],strides=[1,k,k,1],padding=‘SAME‘,name=name) 14 15 # 定义归一化函数 16 def norm(name,x,lsize=4): 17 return tf.nn.lrn(x,lsize,bias=1.0,alpha=0.001/9,beta=0.75,name=name) 18 19 # 正式定义alex_net网络结构 20 def alex_net(_X,_weights,_biases,_dropout): 21 # 对输入进行形变 22 _X=tf.reshape(_X,shape=[-1,28,28,1]) 23 24 # 构建第一个卷积层 25 conv1=conv2d(‘conv1‘,_X,_weights[‘wc1‘],_biases[‘bc1‘]) 26 pool1=max_pool(‘pool1‘,conv1,k=2) 27 norm1=norm(‘norm1‘,pool1,lsize=4) 28 drop1=tf.nn.dropout(norm1,_dropout) 29 30 # 构建第二个卷积层 31 conv2=conv2d(‘conv2‘,drop1,_weights[‘wc2‘],_biases[‘bc2‘]) 32 pool2=max_pool(‘pool2‘,conv2,k=2) 33 norm2=norm(‘norm2‘,pool2,lsize=4) 34 drop2=tf.nn.dropout(norm2,_dropout) 35 36 # 构建第三个卷积层 37 conv3=conv2d(‘conv3‘,drop2,_weights[‘wc3‘],_biases[‘bc3‘]) 38 pool3=max_pool(‘pool3‘,conv3,k=2) 39 norm3=norm(‘norm3‘,pool3,lsize=4) 40 drop3=tf.nn.dropout(norm3,_dropout) 41 42 # 对输出进行形变,然后连接三个全连接层 43 dense1=tf.reshape(drop3,shape=[-1,_weights[‘wd1‘].get_shape().as_list()[0]]) 44 dense1=tf.nn.relu(tf.matmul(dense1,_weights[‘wd1‘])+_biases[‘bd1‘],name=‘fc1‘) 45 dense2=tf.nn.relu(tf.matmul(dense1,_weights[‘wd2‘])+_biases[‘bd2‘],name=‘fc2‘) 46 out=tf.matmul(dense2,_weights[‘out‘]+_biases[‘out‘]) 47 return out 48 49 # 设置网络训练参数 50 learning_rate=0.001 51 training_iters=200000 52 batch_size=64 53 display_step=20 54 55 # 设置数据参数 56 n_input=784 57 n_classes=10 58 dropout=0.8 59 60 # 占位符输入 有的版本写成 tf.types.float32 61 x=tf.placeholder(tf.float32,[None,n_input]) 62 y=tf.placeholder(tf.float32,[None,n_classes]) 63 keep_prob=tf.placeholder(tf.float32) 64 65 # 设置网络核的大小,层数,采样步长等 66 weights={ 67 ‘wc1‘:tf.Variable(tf.random_normal([3,3,1,64])), 68 ‘wc2‘:tf.Variable(tf.random_normal([3,3,64,128])), 69 ‘wc3‘:tf.Variable(tf.random_normal([3,3,128,256])), 70 ‘wd1‘:tf.Variable(tf.random_normal([4*4*256,1024])), 71 ‘wd2‘:tf.Variable(tf.random_normal([1024,1024])), 72 ‘out‘:tf.Variable(tf.random_normal([1024,10])) 73 } 74 75 biases={ 76 ‘bc1‘:tf.Variable(tf.random_normal([64])), 77 ‘bc2‘:tf.Variable(tf.random_normal([128])), 78 ‘bc3‘:tf.Variable(tf.random_normal([256])), 79 ‘bd1‘:tf.Variable(tf.random_normal([1024])), 80 ‘bd2‘:tf.Variable(tf.random_normal([1024])), 81 ‘out‘:tf.Variable(tf.random_normal([n_classes])) 82 } 83 84 # 构建一个alex_net网络,并根据输入预测输出结果 85 pred=alex_net(x,weights,biases,keep_prob) 86 87 # 根据预测值pred和真实标签y,构建损失函数 88 cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y)) 89 // 设置优化函数,最小化损失函数 90 optimizer=tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) 91 92 # 设置测试网络 93 correct_pred=tf.equal(tf.argmax(pred,1),tf.argmax(y,1)) 94 accuracy=tf.reduce_mean(tf.cast(correct_pred,tf.float32)) 95 96 # 初始化网络所有对权重 有的版本写成 global_variables_initializer 97 init=tf.initialize_all_variables() 98 99 with tf.Session() as sess: 100 # 初始化网络权值 101 sess.run(init) 102 step = 1 103 104 # 开始训练网络,直到达到最大迭代次数 105 while step * batch_size < training_iters: 106 # 获取批数据 107 batch_xs, batch_ys = mnist.train.next_batch(batch_size) 108 109 # 根据批数据训练网络 110 sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout}) 111 112 # 打印输出 113 if step % display_step == 0: 114 # 计算精度 115 acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.}) 116 # 计算损失值 117 loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.}) 118 print "Iter " + str(step*batch_size) + ", Minibatch Loss= " + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc) 119 step += 1 120 121 print "Optimization Finished!" 122 # 计算测试精度 123 print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], y: mnist.test.labels[:256], keep_prob: 1.})
AlexNet:
获得里ILSVRC比赛分类项目的2012年冠军(top-5错误率16.4%,使用额外数据可达到15.3%,8层神经网络 3 conv+2 pooling+3 fc)
首次在CNN中成功应用里ReLU Dropout和LRN等Trick:
成功使用ReLU作为CNN的激活函数,并验证其效果在较深对网络超过里Sigmoid,成功解决里Sigmoid在网络较深时对梯度弥散问题。
虽然ReLU激活函数在很久之前就被提出,但是直到AlexNet的出现才将其发扬光大。
训练时使用
时间: 2024-11-05 12:30:09