MNIST 数据集是机器学习领域中最常用的数据集之一,它包含了 60,000 个灰度手写数字图片,每个数字图片的大小为 28x28 像素。本教程将介绍如何使用 Python 和 TensorFlow 来加载、处理和训练 MNIST 数据集。
安装 TensorFlow
在开始之前,请确保你已经安装了 TensorFlow。你可以通过以下命令进行安装:
pip install tensorflow
加载数据集
使用 TensorFlow 的 tf.keras.datasets
模块可以轻松地加载 MNIST 数据集:
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
数据预处理
在训练模型之前,需要对数据进行一些预处理:
- 归一化像素值:将像素值从 [0, 255] 范围缩放到 [0, 1] 范围。
- 扁平化图像:将图像从 28x28 的二维数组转换为 784 的一维数组。
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255
train_labels = train_labels.astype('int32')
test_labels = test_labels.astype('int32')
构建模型
接下来,我们可以构建一个简单的卷积神经网络模型:
from tensorflow.keras import layers, models
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
编译和训练模型
现在,我们可以编译和训练模型:
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
评估模型
最后,我们可以使用测试数据集来评估模型的性能:
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"Test accuracy: {test_acc}")
MNIST 手写数字图片
更多关于 MNIST 数据集和 TensorFlow 的信息,请访问 TensorFlow 官方文档。
如果你对深度学习感兴趣,可以继续阅读 深度学习基础教程。