TensorFlow手写数字识别

1 . 保存为图片

使用mnist数据集:

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)

one hot=True ,表示将样本标签转化为one hot 编码。
one_hot 编码: 只有一个位为1 , 1 所在的位置就代表着第几类。例如:一共10 类。0 的one_hot 为1000000000,1 的one_hot为0100000000 , 2 的one hot 为0010000000 , 3 的one hot 为0001000000 ..…·依此类推。

查看大小:

#查看训练数据集的大小
print('训练图像形状', mnist.train.images.shape)
print('标签形状', mnist.train.labels.shape)
#查看验证集的大小
print('验证图像形状', mnist.validation.images.shape)
print('标签形状', mnist.validation.labels.shape)
#查看测试集的大小
print('测试图像形状', mnist.test.images.shape)
print('标签形状', mnist.test.labels.shape)

 其中每张图片均为784维的向量,其实也就是一个28X28的矩阵,可以将向量转化为图片。此外对于one-hot形式的label也可以加以转换,代码如下所示:

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
import os
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
from PIL import Image

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

#查看训练数据集的大小
print('训练图像形状', mnist.train.images.shape)
print('标签形状', mnist.train.labels.shape)
#查看验证集的大小
print('验证图像形状', mnist.validation.images.shape)
print('标签形状', mnist.validation.labels.shape)
#查看测试集的大小
print('测试图像形状', mnist.test.images.shape)
print('标签形状', mnist.test.labels.shape)

save_dir = 'MNIST_data/raw/'
if os.path.exists(save_dir) is False:
    os.makedirs(save_dir)

for i in range(20):
    image_array = mnist.train.images[i, :]
    image_array = image_array.reshape(28, 28)
    # 保存文件格式
    filename = save_dir + 'mnist_train_%d.jpg' % i
    # 转换文件格式
    # image.imsave(filename,image_array,cmap='gray')
    Image.fromarray((image_array * 255).astype('uint8'), mode='L').convert('RGB').save(filename)

# 独热表示
for i in range(20):
    lable_array = mnist.train.labels[i, :]
    # 取出最大值所在的索引
    lable = np.argmax(lable_array)
    print('mnist_train_%d.jpg lable: %d' % (i,lable))

2. 利用softmax回归识别MNIST

2.1 softmax

利用softmax的方法,来实现对手写数字识别这样一个多分类的问题,相关的原理见文章的2.5部分:卷积神经网络基础_清榎的博客-CSDN博客

在进行计算时要先计算各个节点的输出值Logit:

Logit = W^{T} x + b

此时的x是手写数字识别的数据,784维的向量。W则是一个784X10的矩阵,b是一个10维的向量。

然后再使用softmax函数得到各个类别的概率:

y = softmax(Logit)

在编程时遵循TensorFlow编程框架基础_清榎的博客-CSDN博客

中总结部分所提到的用法,输入数据使用占位符来进行存储,神经网络参数使用变量存储并初始化为全0

2.2 交叉熵

        关于交叉熵的相关知识见:损失函数|交叉熵损失函数 - 知乎        

L=\frac{1}{N} \sum_{i} L_{i}=-\frac{1}{N} \sum_{i} \sum_{c=1}^{M} y_{i c} \log \left(p_{i c}\right)

用交叉熵损失来衡量真实值和预测值之间相似性。

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))

tf.reduce_mean():用于计算tensor(张量)沿着指定的数轴(即tensor的某一维度)上的平均值,用作降维或者计算tensor的平均值。 用法tf.reduce_mean(input_tensor, axis=None, keepdims=False, name=None)

tf.reduce_sum():用于计算tensor(张量)沿着指定的数轴(即tensor的某一维度)上的和

2.3 计算梯度,优化 

计算完损失后,再用梯度下降法进行优化,减小损失。

2.4 执行会话,计算准确度

在session中执行,构建好计算图后还需要执行会话才会进行计算,会话可以视为计算的上下文(变量就是保存在会话中)

TensorFlow实际上对应的是一个C++后端,TensorFlow使用会话(Session)与后端连接。通常,我们都会先创建一个图,然后再在会话(Session)中启动它。InteractiveSession给了我们一个交互式会话的机会,使得我们可以在运行图(Graph)的时候再插入计算图,否则就要在启动会话之前构建整个计算图

计算准确度时先用tf.argmax()从独热表示中取出数字,然后比较二者是否相同,相同为TRUE,否则为FALSE,然后转换类型计算准确度即可。

tf.cast():执行 tensorflow 中张量数据类型转换,比如读入的图片如果是int8类型的,一般在要在训练前把图像的数据格式转换为float32。

cast(x, dtype, name=None)
第一个参数 x:   待转换的数据(张量)
第二个参数 dtype: 目标数据类型
第三个参数 name: 可选参数,定义操作的名称

2.5 完整代码: 

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data

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

#占位符对应输入,此处指可输入任意多张图片
x = tf.placeholder(tf.float32, [None, 784])
#神经网络中的参数使用变量进行存储
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))

y = tf.nn.softmax(tf.matmul(x, W) + b)
#y_是实际图像的标签
y_ = tf.placeholder(tf.float32, [None, 10])

#然后计算实际与分类结果之间的差异,二者越小越好
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y)))

#梯度下降法优化损失,学习率为0.01,此时会更新变量w,b
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)

#在会话中进行执行
sess = tf.InteractiveSession()
#初始化所有变量
tf.global_variables_initializer().run()
#使用训练数据训练1000次,每次取100个
for _ in range(1000):
    #每次取100个训练数据
    batch_xs, batch_ys = mnist.train.next_batch(100)
    #运行时将x,y_的占位符中的数据填上
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

#检测模型的训练结果
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
#类型转换后求精确度
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
#使用测试数据计算准确度
print('准确度为:', sess.run(accuracy, feed_dict={x:mnist.test.images, y_:mnist.test.labels}))

3. 卷积网络分类

3.1 初始化权重和偏置

对权重进行初始化时采用截断的正态分布产生随机数进行初始化,对于偏置采用一个小常量0.1进行初始化 。

此处需要额外注意的是由于我们采用的是ReLu激活函数,为防止出现“神经元死亡”,这里用一个较小的正数来初始化偏置项,避免神经元节点输出恒为0的问题

具体见2.2激活函数部分,卷积神经网络基础_清榎的博客-CSDN博客

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)

3.2 第一层卷积

采用Same Padding,使用32个大小为5X5的卷积核,步长为1,得到32个大小为28X28的特征图;此时偏置应该也为32X1。做完卷积后进行2X2的最大池化,步长为2,无重叠项,32X28x28->32X14x14。

tf.nn.maxpool():

        h : 输入通常是feature map,shape:[batch_size, height, width, channels]
        k_size : 池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
        strides : 窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
        padding: 填充的方法,SAME或VALID,SAME表示添加全0填充,VALID表示不添加
这里的k_size 维度是[1, 2, 2, 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)

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

#第一层卷积
w_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1)
h_pool1 = max_pool_2X2(h_conv1)

3.3 第二层卷积

对第一次池化后的h_pool1再次进行了卷积、池化操作。

3.4 全连接层

 此时,大小为7x7X64。加入一个有1024个神经元的全连接层。把刚才池化后输出的张量reshape成一个一维向量,再将其与权重相乘,加上偏置项,再通过一个ReLU激活函数。

然后再使用dropout防止过拟合,dropout会以一定的概率去掉网络中的一些连接,但是不是永久性去除,只是这一步中进行了去除,每一次的去除都是随机的。

#全连接层,输出为1024维的向量
w_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
#将池化后输出的张量reshape成一个一维向量,再将其与权重相乘,加上偏置项
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防止过拟合
keep_prob = tf.placeholder("float")
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

3.5 第二层全连接层

 用于输出10个类别,然后再计算交叉熵并进行优化即可,最终的准确度在99%以上。

完整代码:

import tensorflow.compat.v1 as tf
tf.disable_eager_execution()
from tensorflow.examples.tutorials.mnist import input_data


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

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

#784维的向量转化为28X28的矩阵图片,-1表示由x自动确定
x_image = tf.reshape(x, [-1,28,28,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)

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

#第一层卷积
w_conv1 = weight_variable([5,5,1,32])
b_conv1 = bias_variable([32])
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)

#全连接层,输出为1024维的向量
w_fc1 = weight_variable([7*7*64, 1024])
b_fc1 = bias_variable([1024])
#将池化后输出的张量reshape成一个一维向量,再将其与权重相乘,加上偏置项
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防止过拟合
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.matmul(h_fc1_drop, w_fc2) + b_fc2

#交叉熵&优化
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=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, tf.float32))

#创建会话,初始化变量
sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())

for i in range(20000):
    batch = mnist.train.next_batch(50)
    #每隔100次输出一次准确度
    if i % 100 == 0:
        train_accuracy = accuracy.eval(feed_dict = {x:batch[0], y_:batch[1], keep_prob:0.5})
        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('accuracy %g' %accuracy.eval(feed_dict = {x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0}))

 

 

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值