您的位置:首页 > 理论基础 > 计算机网络

Tensorflow实现卷积神经网络

2017-04-29 15:29 239 查看
如果不明白什么是卷积神经网络,请参考:计算机视觉与卷积神经网络 下面基于开源的实现简单梳理如何用tensorflow实现卷积神经网络.

实现卷积神经网络

加载数据集

# 加载数据集
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
sess = tf.InteractiveSession()


定义函数

对于一些常用到的参数,定义函数去简化他们,如权重和偏置的函数定义.其中
tf.truncated_normal
截断的正太分布加了噪声.
shape
是传进去的向量的大小.

# w,b,可以复用,因此设为函数
def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial)


定义卷积层的函数:

首先明确卷积核的参数有卷积核的尺寸,channel,和卷积核的个数,同时要定义步长的大小,和边界的处理情况.

w: [5,5,1,32]其含义为5*5的卷积核,1个通道,32个卷积核.

stride表示步长,即卷积内积时滑动的步长,都是1代表不会遗漏图片中的每一个点.

padding表示边界的处理方式.

以上都是卷积层重要的参数,是需要记住的重要的知识点.

# 卷积层
# x输入,W卷积参数[5,5,1,32]  5*5的卷积核,1个深度,32个卷积核
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')


定义池化层函数:

这里采用最大采样,尺度为2*2,即在2*2的窗口中取出最大的一个像素.滑动的步长为2

def max_pool_22(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')


实现过程

首先placehoder需要传入训练的数据:

这里是用的批量训练的方法,即
mini-batch
.所以如下定义x,y_,其中x为训练的样本,每一个样本为1*784的向量.x为若干个样本,y_为真实的样本类别,每个样本为一个1*10的向量,其中有一个为1,其余为0.

x = tf.placeholder(tf.float32,[None,784])
y_ = tf.placeholder(tf.float32,[None,10])


构建卷积,池化层:

卷积层+ReLU+最大池化层构成一个单元.这里第一个卷积层有32个卷积核,所以第二个卷积的参数w为
W_conv2 = weight_variable([5,5,32,64])
32个通道,输出64个卷积核.

# 卷积,relu,池化
W_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
#relu
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
h_pool1 = max_pool_22(h_conv1)
################第二个卷积层
W_conv2 = weight_variable([5,5,32,64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)
h_pool2 = max_pool_22(h_conv2)    # 7×7×64


本身图像的大小为28*28经过二次最大池化层变成了7*7,同时最后输出64个卷积核因此输出的tensor尺寸为
7*7*64
.

定义全连接层:

# 全连接层,输入是7*7*64,输出为1024个隐含层
W_fc1 = weight_variable([7*7*64,1024])    #1d
b_fc1 = bias_variable([1024])
# 将卷积层的输出变成一维的向量,这个才能链接全连接层.
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
# 采用dropout的trick
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
# 输出层,10个神经元,输入为1024
W_fc2 = weight_variable([1024,10])
b_fc2 = weight_variable([10])
# 输出用sotfmax
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)


定义损失函数,优化方式

# 定义loss,optimizer
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv),reduction_indices=[1]))
train_step  =tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)


训练即验证

##启动变了初始化
tf.global_variables_initializer().run()
correct_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))

#高维度的
acuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#要用reduce_mean
for i in range(30000):
batch_x,batch_y  = mnist.train.next_batch(50)
if i%1000==0:
train_accuracy = acuracy.eval({x:batch_x,y_:batch_y,keep_prob:1.0})
print("step %d,train_accuracy %g"%(i,train_accuracy))
train_step.run(feed_dict={x:batch_x,y_:batch_y,keep_prob:0.5})


测试集结果

#test
print acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})


运行结果为:

step 9000,train_accuracy 0.98
step 10000,train_accuracy 1
step 11000,train_accuracy 1
step 12000,train_accuracy 1
step 13000,train_accuracy 0.98
step 14000,train_accuracy 1
step 15000,train_accuracy 1
step 16000,train_accuracy 1
step 17000,train_accuracy 1
step 18000,train_accuracy 1
step 19000,train_accuracy 1
step 20000,train_accuracy 1
step 21000,train_accuracy 1
step 22000,train_accuracy 1
step 23000,train_accuracy 1
step 24000,train_accuracy 1
step 25000,train_accuracy 1
step 26000,train_accuracy 1
step 27000,train_accuracy 1
step 28000,train_accuracy 1
step 29000,train_accuracy 1
######测试的误差
0.9919


可以看到这样一个简单的卷积神经网络就可以达到了99%以上的精确度.完整的代码可以在我的github上:https://github.com/yqtaowhu/MachineLearning/

参考资料:

https://github.com/yqtaowhu/tensorflow

tensorflow实战
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  卷积神经网络