Tensorflow实现卷积神经网络

来源:互联网 发布:知乎怎么推送到kindle 编辑:程序博客网 时间:2024/05/29 06:43



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

实现卷积神经网络

加载数据集

# 加载数据集import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/",one_hot=True)sess = tf.InteractiveSession()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

定义函数

对于一些常用到的参数,定义函数去简化他们,如权重和偏置的函数定义.其中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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

  1. w: [5,5,1,32]其含义为5*5的卷积核,1个通道,32个卷积核.
  2. stride表示步长,即卷积内积时滑动的步长,都是1代表不会遗漏图片中的每一个点.
  3. 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')
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

定义池化层函数: 
这里采用最大采样,尺度为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')
  • 1
  • 2
  • 1
  • 2

实现过程

首先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])
  • 1
  • 2
  • 1
  • 2

构建卷积,池化层: 
卷积层+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])#reluh_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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

# 全连接层,输入是7*7*64,输出为1024个隐含层W_fc1 = weight_variable([7*7*64,1024])    #1db_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的trickkeep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)# 输出层,10个神经元,输入为1024W_fc2 = weight_variable([1024,10])b_fc2 = weight_variable([10])# 输出用sotfmaxy_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

定义损失函数,优化方式

# 定义loss,optimizercross_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)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

训练即验证

##启动变了初始化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_meanfor 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})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

测试集结果

#testprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})
  • 1
  • 2
  • 1
  • 2

运行结果为:

step 9000,train_accuracy 0.98step 10000,train_accuracy 1step 11000,train_accuracy 1step 12000,train_accuracy 1step 13000,train_accuracy 0.98step 14000,train_accuracy 1step 15000,train_accuracy 1step 16000,train_accuracy 1step 17000,train_accuracy 1step 18000,train_accuracy 1step 19000,train_accuracy 1step 20000,train_accuracy 1step 21000,train_accuracy 1step 22000,train_accuracy 1step 23000,train_accuracy 1step 24000,train_accuracy 1step 25000,train_accuracy 1step 26000,train_accuracy 1step 27000,train_accuracy 1step 28000,train_accuracy 1step 29000,train_accuracy 1######测试的误差0.9919
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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

参考资料:

  1. https://github.com/yqtaowhu/tensorflow
如果不明白什么是卷积神经网络,请参考:计算机视觉与卷积神经网络 下面基于开源的实现简单梳理如何用tensorflow实现卷积神经网络.

实现卷积神经网络

加载数据集

# 加载数据集import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets("MNIST_data/",one_hot=True)sess = tf.InteractiveSession()
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

定义函数

对于一些常用到的参数,定义函数去简化他们,如权重和偏置的函数定义.其中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)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

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

  1. w: [5,5,1,32]其含义为5*5的卷积核,1个通道,32个卷积核.
  2. stride表示步长,即卷积内积时滑动的步长,都是1代表不会遗漏图片中的每一个点.
  3. 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')
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

定义池化层函数: 
这里采用最大采样,尺度为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')
  • 1
  • 2
  • 1
  • 2

实现过程

首先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])
  • 1
  • 2
  • 1
  • 2

构建卷积,池化层: 
卷积层+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])#reluh_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
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

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

# 全连接层,输入是7*7*64,输出为1024个隐含层W_fc1 = weight_variable([7*7*64,1024])    #1db_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的trickkeep_prob = tf.placeholder(tf.float32)h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)# 输出层,10个神经元,输入为1024W_fc2 = weight_variable([1024,10])b_fc2 = weight_variable([10])# 输出用sotfmaxy_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

定义损失函数,优化方式

# 定义loss,optimizercross_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)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

训练即验证

##启动变了初始化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_meanfor 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})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

测试集结果

#testprint acuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0})
  • 1
  • 2
  • 1
  • 2

运行结果为:

step 9000,train_accuracy 0.98step 10000,train_accuracy 1step 11000,train_accuracy 1step 12000,train_accuracy 1step 13000,train_accuracy 0.98step 14000,train_accuracy 1step 15000,train_accuracy 1step 16000,train_accuracy 1step 17000,train_accuracy 1step 18000,train_accuracy 1step 19000,train_accuracy 1step 20000,train_accuracy 1step 21000,train_accuracy 1step 22000,train_accuracy 1step 23000,train_accuracy 1step 24000,train_accuracy 1step 25000,train_accuracy 1step 26000,train_accuracy 1step 27000,train_accuracy 1step 28000,train_accuracy 1step 29000,train_accuracy 1######测试的误差0.9919
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

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

参考资料:

  1. https://github.com/yqtaowhu/tensorflow
原创粉丝点击