import keras
keras.__version__
‘2.7.0’
将手写数字的灰度图像(28 像素×28 像素)划分到 10 个类别中(0~9)
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()
# 查看手写数字灰度图像(28*28)
import matplotlib.pyplot as plt
plt.imshow(train_images[5][14:,14:], # 索引
cmap=plt.cm.binary) # 显示黑白图像
plt.show()
测试数据:
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激活函数使用):
根据公式我们可以发现,因为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.网络训练
- 每个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)