手写数字分类mnist--python深度学习

import keras
keras.__version__

‘2.7.0’

将手写数字的灰度图像(28 像素×28 像素)划分到 10 个类别中(0~9)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-a0fjyadV-1685105676354)(attachment:image.png)]

1.加载Keras 中的 MNIST 数据集

from keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

图像被编码为 Numpy 数组,而标签是数字数组,取值范围为 0~9。图像和标签一一对应。

训练数据:

train_images.shape

(60000, 28, 28)

len(train_labels)

60000

train_labels

array([5, 0, 4, …, 5, 6, 8], dtype=uint8)

train_images[5].shape

(28, 28)

train_images[5]
# 查看手写数字灰度图像(28*28)
import matplotlib.pyplot as plt
plt.imshow(train_images[5],
           cmap=plt.cm.binary)  # 显示黑白图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-C5sbNJ2Q-1685105676355)(output_11_0.png)]

# 查看手写数字灰度图像(28*28)
import matplotlib.pyplot as plt
plt.imshow(train_images[5][14:,14:],   # 索引
           cmap=plt.cm.binary)  # 显示黑白图像
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gWRHaeP0-1685105676356)(output_12_0.png)]

测试数据:

test_images.shape

(10000, 28, 28)

len(test_labels)

10000

test_labels
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)

2.模型构建

# 网路架构
from keras import models
from keras import layers

network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))

神经网络的核心组件是层(layer),你可以将它看成数据过滤器。
深度学习模型就像是数据处理的筛子,包含一系列越来越精细的
数据过滤器(即层)。

本例中的网络包含 2 个 Dense 层。第二层是一个 10 路 softmax 层,它将返回一个由 10 个概率值(总和为 1)组成的数组。
每个概率值表示当前数字图像属于 10 个数字类别中某一个的概率。

要想训练网络,我们还需要选择编译(compile)步骤的三个参数。

  • 损失函数(loss function):网络如何衡量在训练数据上的性能,即网络如何朝着正确的方向前进。
  • 优化器(optimizer):基于训练数据和损失函数来更新网络的机制。
  • 在训练和测试过程中需要监控的指标(metric):本例只关心精度,即正确分类的图像所占的比例。
# 编译步骤
network.compile(optimizer='rmsprop',    # 优化器(自适应学习率RMSProp)
                loss='categorical_crossentropy',    # 损失函数(多元交叉熵)
                metrics=['accuracy'])  # 监控的指标(精度)

https://blog.csdn.net/qq_40661327/article/details/107034575
categorical_crossentropy和binary_crossentropy

categorical_crossentropy损失函数的公式如下(一般搭配softmax激活函数使用):
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-VetVFDq2-1685105676356)(attachment:image.png)]

根据公式我们可以发现,因为yi,要么是0,要么是1。而当yi等于0时,结果就是0,当且仅当yi等于1时,才会有结果。也就是说categorical_crossentropy只专注与一个结果,因而它一般配合softmax做单标签分类。

3.准备图像数据

在开始训练之前,我们将对数据进行预处理,将其变换为网络要求的形状,并缩放到所有值都在 [0, 1] 区间。比如,之前训练图像保存在一个 uint8 类型的数组中,其形状为(60000, 28, 28),取值区间为 [0, 255]。我们需要将其变换为一个 float32 数组,其形状为 (60000, 28 * 28),取值范围为 0~1。

train_images = train_images.reshape((60000, 28 * 28))   # 形状(60000, 28, 28)改为(60000, 28 * 28)
train_images = train_images.astype('float32') / 255     # 数据类型转换为[0, 255],取值范围为 0~1

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255

4.对标签进行分类编码

from tensorflow.keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
train_labels.shape

(60000, 10)

5.网络训练

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-q3aHiKHq-1685105676357)(attachment:BE048CD52039AEB8272822FC2DBD9EC5.jpg)]

  • 每个batch大小为128,共有469个batch
  • 1 epoch = see all batch once
60000/128

468.75

network.fit(train_images, train_labels, epochs=5, batch_size=128)

在这里插入图片描述

test_loss, test_acc = network.evaluate(test_images, test_labels)

313/313 [==============================] - 0s 1ms/step - loss: 0.0766 - accuracy: 0.9771: 0s - loss: 0.0785 - accuracy: 0.

print('test_acc:', test_acc)

test_acc: 0.9771000146865845

预测

pred = network.predict(train_images)
pred.shape

(60000, 10)

pred[1]

array([9.9999940e-01, 1.0376198e-15, 4.1299447e-07, 1.1990192e-09,
1.3832399e-14, 1.8900495e-09, 8.1415124e-09, 1.0586651e-10,
5.9382103e-11, 9.5863918e-08], dtype=float32)

import numpy as np

np.max(pred[1])

0.9999994

train_labels[1]

array([1., 0., 0., 0., 0., 0., 0., 0., 0., 0.], dtype=float32)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值