概述
本篇博文利用mnist数据集,利用一个简单的卷积神经网络识别手写数字。正确率比一般神经网络高很多。
网络结构
本博文使用了一个简单的卷积神经网络结构,其网络结构如下:
图只能截这么大了,下面来段文字描述:整个网络由输入层、两个卷积层、两个池化层、一个全连接层、输出层组成。卷积核大小为55,池化采用最大值池化。两个reshape需要特殊指出以下,输入层数据不能直接进行卷积,要转换为2828*batch大小的矩阵才能进行卷积;最后一次池化结束要把结果reshape以便能够进行全连接。
代码实现
# -*- coding: utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#载入数据集
minist = input_data.read_data_sets("minist",one_hot=True)
#定义批次大小
batch_size = 100
batch_n = minist.train.num_examples//batch_size
def weight_init(shape):
return tf.Variable(tf.truncated_normal(shape,stddev=0.1))
def biase_init(shape):
return tf.Variable(tf.constant(0.1,shape=shape))
def conv2(x,W):
#strides:定义步长
#x batch 高宽 通道数
#w 过滤器高 宽 输入通道 输出通道
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")
def max_pool_2x2(x):
#ksize=[1,x,y,1] x和y是池化窗口大小
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding="SAME")
with tf.name_scope('input'):
x = tf.placeholder(tf.float32,[None,784],name='x_input')
y = tf.placeholder(tf.float32,[None,10],name='y_input')
keep_drop = tf.placeholder(tf.float32)
x_image = tf.reshape(x,[-1,28,28,1]) #-1是批次 等下会自动变成100 1是通道数
#初始化参数
W_conv_l1 = weight_init([5,5,1,32]) #输入通道数为1的【5x5】卷机核 输出32通道 采样完会得到32通道 32是卷积核数目
b_conv_l1 = biase_init([32])
conv_l1 = tf.nn.relu(conv2(x_image,W_conv_l1)+b_conv_l1) #卷积激活
pool_l1 = max_pool_2x2(conv_l1) #对卷积结果进行最大值pool操作
W_conv_l2 = weight_init([5,5,32,64])
b_conv_l2 = biase_init([64])
conv_l2 = tf.nn.relu(conv2(pool_l1,W_conv_l2)+b_conv_l2)
pool_l2 = max_pool_2x2(conv_l2)
#最终得到64张7*7的图片
#全连接层
#定义权值
ful_w1 = weight_init([7*7*64,1024])
ful_b1 = biase_init([1024])
#将池化层结果转化为一维,以便能够和全连接层进行连接
pool_reshape = tf.reshape(pool_l2,[-1,7*7*64]) #-1是批次
ful_l1 = tf.nn.relu(tf.matmul(pool_reshape,ful_w1)+ful_b1)
output_l1 = tf.nn.dropout(ful_l1,keep_drop)
ful_w2 = weight_init([1024,10])
ful_b2 = biase_init([10])
prediction = tf.nn.softmax(tf.matmul(output_l1,ful_w2)+ful_b2)
#代价函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))
#优化器
train = tf.train.AdamOptimizer(0.0001).minimize(loss)
#准确率
correct_prediction = tf.equal(tf.arg_max(y,1),tf.arg_max(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
sess = tf.Session()
sess.run(tf.global_variables_initializer())
writer=tf.summary.FileWriter("logs/",sess.graph)
for step in range(10):
for _ in range(batch_n):
batch_xs, batch_ys = minist.train.next_batch(batch_size)
sess.run(train, feed_dict={x: batch_xs, y: batch_ys, keep_drop:0.7})
acc = sess.run(accuracy, feed_dict={x: minist.test.images, y: minist.test.labels, keep_drop:1.0})
print "Iter" + str(step) + ":" + str(acc)
sess.close()
结果和小结
卷积神经网络能够更好地学习图像特征,最终得到的正确率在98%以上 。这里笔者第一次运行忘记截图了,电脑发热实在厉害,只迭代了两次,大家可以看到结果明显优于一般神经网络。大家可以再试试其他参数比如取卷积核大小为3*3,迭代次数增加,改变批次大小等等。