本文将带你一步步了解如何使用 MNIST 数据集进行手写数字识别。MNIST 是一个包含 70,000 个灰度手写数字图像的数据集,常用于图像识别和机器学习领域的入门教程。
1. 简介
MNIST 数据集包含以下特点:
- 28x28 像素的灰度图像
- 0 到 9 的数字
- 图像被标签化,每个图像都对应一个数字标签
2. 准备工作
在开始之前,请确保你已经安装了以下库:
- TensorFlow
- Keras
你可以通过以下命令安装:
pip install tensorflow
pip install keras
3. 加载数据集
使用 Keras 库,我们可以轻松地加载数据集:
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
4. 数据预处理
在训练模型之前,我们需要对数据进行一些预处理:
- 归一化图像数据,使其值介于 0 和 1 之间
- 将标签转换为独热编码
train_images = train_images / 255.0
test_images = test_images / 255.0
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
5. 构建模型
接下来,我们可以构建一个简单的卷积神经网络模型:
from keras.models import Sequential
from keras.layers import Dense, Conv2D, Flatten, MaxPooling2D
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(10, activation='softmax'))
6. 训练模型
现在,我们可以开始训练模型:
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5, batch_size=32)
7. 评估模型
最后,我们可以使用测试数据集来评估模型:
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc}")
8. 扩展阅读
想要了解更多关于 MNIST 数据集和深度学习的内容,请访问以下链接:
MNIST 数据集示例