基于手写识别的卷积神经网络的代码实现(学习过程)

以下所有注释均为:代码在上,解释在下

首先:

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf

第一句表示的是:
使用tensorflow.examples.tutorials.mnist来加载 input_data(就是运用mnist数据库)
基于手写识别的卷积神经网络的代码实现(学习过程)_第1张图片

def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1);#tf.truncated_normal产生正态分布 stddev为标准差 shape表示张量的维度
    return tf.Variable(initial)

即设定一个函数,用来初始化权重

def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

即设定一个函数,用来初始化偏置

def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

定义卷积函数:
关于卷积函数:见详解https://blog.csdn.net/u010177286/article/details/80207747?utm_source=blogxgwz4
tf.nn.conv2d
(1)函数原型
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)

(2)参数介绍
第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一

第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维

第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4
补充:步长不为1的情况,文档里说了对于图片,因为只有两维,通常strides取[1,stride,stride,1]
重点补充:这四维到底是哪四维呢?
这些地方说的四维永远是:
batch一维(一张图一个batch)
宽一维
高度一维
通道一维

即[batch, height, width, channels]这种形式。
第四个参数padding:string类型的量,只能是”SAME”,”VALID”其中之一,这个值决定了不同的卷积方式(后面会介绍)

第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true

结果返回一个Tensor,这个输出,就是我们常说的feature map,shape仍然是[batch, height, width, channels]这种形式。

因此这里的

def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')

含义是:
return一个结果,什么结果呢,是对x高度,w宽度的图片,步长为1,并用padding保持same的卷积结果(存疑?????)

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

定义池化层
运用最大池化,见https://blog.csdn.net/jningwei/article/details/73557932
即 需要池化的参数是x,ksize是池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1,这里池化窗口是2乘2,strides步长与上面相同。最后依然选择same填充。

if __name__ == "__main__":#存疑问
x = tf.placeholder("float", shape=[None, 784])#定义输入变量

定义输入变量为28乘28乘1的灰度图片,784列

y_ = tf.placeholder("float", shape=[None, 10])#定义输出变量

输出为十个概率数

 w_conv1 = weight_variable([5, 5, 1, 32])#5乘5的卷积核,1个深度(灰度通道),32个卷积核

初始化权重,第一层卷积,32的意思代表的是输出32个通道
其实,也就是设置32个卷积,每一个卷积都会对图像进行卷积操作(32个卷积和)
32个下图卷积核

基于手写识别的卷积神经网络的代码实现(学习过程)_第2张图片

 b_conv1 = bias_variable([32])

初始化偏置项:仿佛在每一个通道做完卷积后都要进行一次加偏置(存疑)

x_image = tf.reshape(x, [-1, 28, 28, 1])

将输入的x转成一个4D向量,第2、3维对应图片的宽高,最后一维代表图片的颜色通道数

牵扯到tf.shape和reshape的用法:
https://blog.csdn.net/chinacmt/article/details/78548420
https://blog.csdn.net/apengpengpeng/article/details/80579658
tf.reshape看来可以理解为将一维矩阵转化为多维度:
https://blog.csdn.net/sangreallilith/article/details/80285229

h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)

卷积并激活,注意这里用的是relu修正线性单元,conv2d是上面定义的卷积函数,那么卷积的内容为x_image(28×28)与卷积核(5×5)进行卷积,卷积后的所有元素均加上一个biases

h_pool1 = max_pool_2_2(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_2_2(h_conv2)

注意的是 卷积核为5×5,32个深度(因为第一层的输出是32个深度),做64个卷积

开始设置全连接层(一个隐藏层)

w_fc1 = weight_variable([7 * 7 * 64, 1024])# 设置全连接层的权重

设置全连接层的权重,那在这里要看看全连接层的输入是多少
从头开始捋:
输入一个28×28×1的图片
一开始我是这么想的:
第一次卷积:32个卷积(n-f)/s+1,n=28,f=5,s=1,得到24×24×32
进行maxpooling依然是24×24×32,因为是padding=‘same’
第二次卷积:64个卷积,n=24,f=5,s=1,得到20×20×64
进行maxpooling依然是20×20×64,因为是padding=‘same’

这里存疑

疑难解决了:记住,padding用于卷积conv和池化均用。然后呢,每次卷积填充以后尺寸不变,然而每次pooling都要使得输入减少一半,因此记得maxpooling之后矩阵要减小一半。 因此上面的废话改为

第一次卷积:32个卷积(n-f)/s+1,n=28,f=5,s=1,但是是same卷积故不变,得到28×28×32
进行maxpooling是14×14×32,因为是padding=‘same’
第二次卷积:64个卷积,n=24,f=5,s=1,但是是same池化故减小一半
进行maxpooling是7×7×64,因为是padding=‘same’

b_fc1 = bias_variable([1024])

设置全连接层的偏置

h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])

将第二层卷积池化后的结果,转成一个7×7×64的数组

h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, w_fc1) + b_fc1)#通过全连接之后并激活

激活

keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

dropout防止过拟合
防止过拟合就这么两句???

# 输出层
    w_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

上边为输出层

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)

准备好运用softmax处理最终结果(相当于定义输出层的激活函数为softmax)

在这里,最终的输出为一个行向量(1,10)

这里需要补充softmax函数:

https://blog.csdn.net/supercally/article/details/54234115

这个结果越大,证明概率越大,那么交叉熵loss越小

# 定义交叉熵为损失函数
    cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))

这里注意的有两点:

1.-tf.reduce_sum的用法:
https://blog.csdn.net/qq_27871973/article/details/82148376
单走一个x表示对所有元素求和
此处这个负号没看明白????,应该是吴恩达课程里面讲述过,回去看看

弄明白了 是交叉熵的定义
基于手写识别的卷积神经网络的代码实现(学习过程)_第3张图片
选自https://blog.csdn.net/supercally/article/details/54234115
2.(y_ * tf.log(y_conv)
交叉熵损失函数
交叉熵两种方式来实现:
1、tf.nn.softmax_cross_entropy_with_logits
2、-tf.reduce_sum(y_*tf.log(y))

https://blog.csdn.net/wenqiwenqi123/article/details/78933409

我们继续,定义训练函数

train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

学习率10^-4
庞大的数据集会用到优化器AdamOptimizer

 # 计算准确率
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())

以上是程式化

**mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)**

下载minist的手写数字的数据集
这项指令的详细解释
https://blog.csdn.net/qq_26593465/article/details/81026762

基于手写识别的卷积神经网络的代码实现(学习过程)_第4张图片

    for i in range(20000):
        batch = mnist.train.next_batch(50)
    

开始训练
batch = mnist.train.next_batch(50) 批次处理,每次拿50张图

        if i % 100 == 0:
            train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print("step %d,training accuracy %g" % (i, train_accuracy))
        train_step.run(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print("test accuracy %g" % accuracy.eval(session=sess, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
    # test accuracy 0.9919

accuracy.eval计算准确率
https://blog.csdn.net/zxyhhjs2017/article/details/82349535

存疑:为什么计算accuracy的keep_prob=1,而train_step的keep_prob=0.5

基本到这里就全部结束了 下附所有代码(源代码地址忘记了)

from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf


#以下是定义了两个函数用于初始化
# 初始化权重函数
def weight_variable(shape):
    initial = tf.truncated_normal(shape, stddev=0.1);#tf.truncated_normal产生正态分布 stddev为标准差 shape表示张量的维度
    return tf.Variable(initial)


# 初始化偏置项
def bias_variable(shape):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)



# 定义卷积函数
def conv2d(x, w):
    return tf.nn.conv2d(x, w, strides=[1, 1, 1, 1], padding='SAME')


# 定义一个2*2的最大池化层
def max_pool_2_2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')


if __name__ == "__main__":#?
    # 定义输入变量
    x = tf.placeholder("float", shape=[None, 784])#28乘28的图片
    # 定义输出变量
    y_ = tf.placeholder("float", shape=[None, 10])
    # 初始化权重,第一层卷积,32的意思代表的是输出32个通道
    # 其实,也就是设置32个卷积,每一个卷积都会对图像进行卷积操作(32个卷积和)
    w_conv1 = weight_variable([5, 5, 1, 32])#5乘5的卷积核,1个深度(灰度通道),32个卷积核
    # 初始化偏置项
    b_conv1 = bias_variable([32])
    # 将输入的x转成一个4D向量,第2、3维对应图片的宽高,最后一维代表图片的颜色通道数
    # 输入的图像为灰度图,所以通道数为1,如果是RGB图,通道数为3
    # tf.reshape(x,[-1,28,28,1])的意思是将x自动转换成28*28*1的数组
    # -1的意思是代表不知道x的shape,它会按照后面的设置进行转换
    x_image = tf.reshape(x, [-1, 28, 28, 1])
    # 卷积并激活
    h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
    # 池化
    h_pool1 = max_pool_2_2(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_2_2(h_conv2)
    # 设置全连接层的权重
    w_fc1 = weight_variable([7 * 7 * 64, 1024])
    # 设置全连接层的偏置
    b_fc1 = bias_variable([1024])
    # 将第二层卷积池化后的结果,转成一个7*7*64的数组
    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)
    # 防止过拟合
    keep_prob = tf.placeholder("float")
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

    # 输出层
    w_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2) + b_fc2)

    # 日志输出,每迭代100次输出一次日志
    # 定义交叉熵为损失函数
    cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))
    # 最小化交叉熵
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    # 计算准确率
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    sess = tf.Session()
    sess.run(tf.initialize_all_variables())
    # 下载minist的手写数字的数据集
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    for i in range(20000):
        batch = mnist.train.next_batch(50)
        if i % 100 == 0:
            train_accuracy = accuracy.eval(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 1.0})
            print("step %d,training accuracy %g" % (i, train_accuracy))
        train_step.run(session=sess, feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})

    print("test accuracy %g" % accuracy.eval(session=sess, feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
    # test accuracy 0.9919


你可能感兴趣的:(基于手写识别的卷积神经网络的代码实现(学习过程))