用卷积神经网络实现MINIST手写字识别

前言

学习了这么久的深度学习,基本上都是在学习一些理论,那么现在就来实践一下吧,今天实践的是用卷积神经网络实现MINIST手写字识别

代码分析

既然是实践,卷积神经网络的具体步骤就不在此赘述了,直接上代码

#导入MNIST数据集-创建模型-保存模型到指定路径

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

mnist = input_data.read_data_sets('E:/download/pycharm/PyCharm Community Edition 2018.2.1/program/tensorflow/MNIST_data', one_hot=True) #MNIST数据集所在路径

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

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


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)

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

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

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

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_2x2(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_2x2(h_conv2)

W_fc1 = weight_variable([7 * 7 * 64, 1024])
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)

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)

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"))

saver = tf.train.Saver() #定义saver

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    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 %d, training accuracy %g' % (i, train_accuracy))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    saver.save(sess, 'E:/Flow classification/Handwritten/model.ckpt') #模型储存位置

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

这段代码的主要作用是把MINIST数据集导入-创建模型-把模型保存到指定目录。现在来一段一段地分析。

库函数

如下这是运行这段代码需要的库函数,input_data就可以把MINIST数据集导入,tensorflow是必不可少的。

from tensorflow.examples.tutorials.mnist import input_data

import tensorflow as tf

input_data.read_data_sets导入数据集

mnist = input_data.read_data_sets('E:/download/pycharm/PyCharm Community Edition 2018.2.1/program/tensorflow/MNIST_data', one_hot=True) #MNIST数据集所在路径

占位符

这里的x,y都不是具体的值,相反,它们只是一个占位符,可以在tensorflow运行某一运算时根据该占位符输入具体的值。和一般的函数一样,x表示输入,y表示输出,其中784是一张展平的MNIST图片的维度,10表示输出的每一行为一个10维的one-hot向量,用于代表对应某一MNIST图片的类别。None表示其值大小不定,在这里作为第一个维度值,用以指代batch的大小,意即x的数量不定。

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

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

权重和偏置函数

这一段代码表示初始化权重和偏置,目的是为了不在建立模型的时候反复做初始化操作,所以就定义了两个函数用于初始化。这里有需要注意的一点,为了避免神经元输出恒为0的情况出现,就要使用一个较小的正数来初始化偏置值,这里用了0.1

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)

第一层卷积

这一段表示的是第一层卷积,包括定义权重和偏置的张量形状,把x变成灰度图,把x_image和权值向量进行卷积,加上偏置值,然后用ReLU激活函数,最后采用最大值池化的操作。
这里描述一下各个参数的作用
**[5, 5, 1, 32]**前两个参数是patch的大小,接着是输入通道的数目,最后是输出通道的数目
**[-1,28,28,1]**把x变成一个4d向量,第二三维表示图片对应的宽和高,最后一维表示颜色是灰度图,如果值为3,表示的是彩色图

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

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_2x2(h_conv1)

第二层卷积

第二个卷积层5*5的patch可以得到64个特征

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_2x2(h_conv2)

全连接层

全连接层代码,都知道全连接层的作用是把特征给整合到一起,现在图片的尺寸变成了7*7的,加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

W_fc1 = weight_variable([7 * 7 * 64, 1024])
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

这段代码代表Dropout,作用是为了减少过拟合。我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。

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

输出层

最后是输出层,添加了一个softmax函数

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)

至此卷积神经网络的所有流程就已经结束了,下面就需要对模型进行训练和评估了。

评估

既然一个神经网络已经形成了,我们就需要查看准确率是否可以达到我们满意的效果,使用的是训练集先训练,并查看准确率。在这里使用了ADAM进行梯度下降优,在feed_dict中加入额外的参数keep_prob来控制dropout比例。然后每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"))

saver = tf.train.Saver() #定义saver

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    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 %d, training accuracy %g' % (i, train_accuracy))
        train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    saver.save(sess, 'E:/Flow classification/Handwritten/model.ckpt') #模型储存位置

    print('test accuracy %g' % accuracy.eval(feed_dict={
        x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

最后的结果显示准确率达到了99.2%。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值