没事撸点神经网络----简单卷积神经网络
- 什么是卷积神经网络
卷积神经网络是在传统的全连接神经网络前,加入卷积层以及池化层,提取特征的一种神经网络。其大概的流程是输入原始图像-卷积-池化-卷积-池化(可能有N层)将卷积池化提取的深度特征作为新的特征进行全连接,接入传统的全连接神经网络来进行识别与分类操作。
卷积(Convolution)-池化(pooling/Subsampling)-全连接(Full Connection)
2.案例
这里的案例使用的是经典的MNIST 数据集进行手写数字识别,交代一下数据集的基本信息。
训练集:
Train:55000*738 图像(28*28)
Label:55000*10(10*1) one-hot
测试集:
10000*738 图像 Label:10000*10
3.神经网络设计:
卷积层1
一共有32个卷积核,每一个卷积核是5*5的模板大小,步长移动为1
卷积层2
输入为32层的Feature
一共有64个卷积核,设计,每一个卷积核为5*5的模板,补偿移动为1
池化层 我们设计为最大池化
池化卷积为 2*2的patch 步长移动为2,目的是为了重采样 降维处理
全连接层
全连接层 我们设计1024个感知神经元
Softmax层 10个神经元 one-hot型
这个图,可以好好看看,加强理解,主要也就是这一张图了。看图说话嘛!
4.Tensorflow 实现
第一层卷积:
W_conv1=WeightInitialized([5,5,1,32])#设计卷积核 5*5的patch 32 个卷积核 b_conv1=BiasInitialized([32]) h_conv1=tf.nn.relu(Conv(x_image,W_conv1)+b_conv1) #池化 h_pool1=Pooling(h_conv1)
第二层卷积
W_conv2=WeightInitialized([5,5,32,64])#设计卷积核 5*5的patch 64 个卷积核 b_conv2=BiasInitialized([64]) h_conv2=tf.nn.relu(Conv(h_pool1,W_conv2)+b_conv2) h_pool2=Pooling(h_conv2)
全连接 (1024个感知神经元)
#全连接 W_fullConnected=WeightInitialized([7*7*64,1024])#全连接权重矩阵 b_fullConnected=BiasInitialized([1024])#偏置单元 h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])#将矩阵扁平化 #前向传播第一层 h_fullContected=tf.nn.relu(tf.matmul(h_pool2_flat,W_fullConnected)+b_fullConnected)
Dropout层,用于全连接神经网络中的防止过拟合,原理是让一部分神经元的权重停止更新,保持不变
keep_prob=tf.placeholder("float") h_fullContected_drop=tf.nn.dropout(h_fullContected,keep_prob)#x,keep_drop 设置神经元被选中的概率
Softmax:
W_fullConnected2=WeightInitialized([1024,10]) b_fullConnected2=BiasInitialized([10]) y_=tf.nn.softmax(tf.matmul(h_fullContected_drop,W_fullConnected2)+b_fullConnected2)
到现在所有的前向传播网络已经构建完成了。交给tensorflow去后向传播最优化参数就好了,损失函数我们使用的是交叉熵进行表示。
#损失函数 交叉熵设计 cross_entropy=-tf.reduce_sum(y*tf.log(y_)) #梯度下降训练 使损失函数最小 train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float")) sess.run(tf.initialize_all_variables()) for i in range(20000): batch=mnist.train.next_batch(50) if(i%100==0): train_accuracy=accuracy.eval(feed_dict={x:batch[0],y:batch[1],keep_prob:1.0}) print("step {0},training accuracy {1}".format(i,train_accuracy)) train_step.run(feed_dict={x: batch[0], y: batch[1], keep_prob: 0.5}) print("test accuracy %g"%accuracy.eval(feed_dict={ x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0}))
我也是初步接触并实现一些简单网络,如果有错误,敬请批评指教,相互学习。
完整代码:
上一篇:
JS实现多线程数据分片下载