使用mnist数据集实现手写字体的识别

1.MNIST是一个入门级的计算机视觉数据集,它包含各种手写数字图片:
它也包含每一张图片对应的标签,告诉我们这个是数字几,该数据集包括60000行的训练数据集(mnist.train
)和10000行的测试数据集(mnist.test),每一张图片包含28X28个像素点

2.首先使用softmax回归实现手写字体的识别(代码)

import input_data#input_data下载用于训练和测试的MNIST数据集的源码
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
# mnist是一个轻量级的类。它以Numpy数组的形式存储着训练、校验和测试数据集。
# 同时提供了一个函数,用于在迭代中获得minibatch,后面我们将会用到。
# 构建Softmax 回归模型
import tensorflow as tf
#使用TensorFlow程序的流程是先创建一个图,然后在session中启动它。
sess = tf.InteractiveSession()
x=tf.placeholder("float",shape=[None,784]) #784是一张展平的MNIST图片的维度(28*28)
y_=tf.placeholder("float",shape=[None,10])
# 变量
W=tf.Variable(tf.zeros([784,10]))
b=tf.Variable(tf.zeros([10]))
#变量需要通过seesion初始化后,才能在session中使用
init=tf.global_variables_initializer()
sess.run(init)
# 把向量化后的图片x和权重矩阵W相乘,加上偏置b,然后计算每个分类的softmax概率值。
y=tf.nn.softmax(tf.matmul(x,W)+b)
#损失函数是目标类别和预测类别之间的交叉熵。
cross_entropy=-tf.reduce_sum(y_*tf.log(y))
#训练模型
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
#,返回的train_step操作对象,在运行时会使用梯度下降来更新参数。
# 整个模型的训练可以通过反复地运行train_step来完成。
for i in range(1000):
    batch=mnist.train.next_batch(50)
    #我们都会加载50个训练样本,然后执行一次train_step,
    # 并通过feed_dict将x 和 y_张量占位符用训练训练数据替代。
    train_step.run(feed_dict={x:batch[0],y_:batch[1]})

#返回一个布尔数组。为了计算我们分类的准确率,
# 我们将布尔值转换为浮点数来代表对、错,然后取平均值。
#评估模型
correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))
#我们可以计算出在测试数据上的准确率,大概是91%。
print(accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels}))
3.脚本用于自动下载mnist数据集(input.py)
"""Functions for downloading and reading MNIST data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# pylint: disable=unused-import
import gzip
import os
import tempfile

import numpy
from six.moves import urllib
from six.moves import xrange  # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
# pylint: enable=unused-import

结果准确率达到91%

4.下面采用卷积神经网络实现手写字体的识别,采用conv-pool-conv-pool-fc-dropout-softmax

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

#第一层,一个卷积接一个max pooling
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)

#dropout
#我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。
# 这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout
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.GradientDescentOptimizer(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.run(tf.initialize_all_variables())
for i in range(2000):
  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})

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

当迭代2000次训练时, training accuracy 0.96,test accuracy 0.963。显然比非卷积神经网络准确率高很多。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章