MNIST 数据集是机器学习领域中最常用的数据集之一,它包含了 60,000 个灰度手写数字图片,以及 10,000 个用于测试的图片。在这个教程中,我们将使用 TensorFlow 来构建一个简单的神经网络模型,用于识别手写数字。
1. 准备工作
在开始之前,请确保您已经安装了 TensorFlow。您可以使用以下命令进行安装:
pip install tensorflow
2. 加载 MNIST 数据集
TensorFlow 提供了方便的函数来加载 MNIST 数据集:
from tensorflow.keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
3. 数据预处理
在训练模型之前,我们需要对数据进行一些预处理:
- 将图像数据归一化到 [0, 1] 范围内。
- 将标签转换为独热编码。
train_images = train_images / 255.0
test_images = test_images / 255.0
from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
4. 构建模型
接下来,我们构建一个简单的神经网络模型:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
model = Sequential([
Flatten(input_shape=(28, 28)),
Dense(128, activation='relu'),
Dense(10, activation='softmax')
])
5. 编译和训练模型
现在,我们可以编译和训练模型:
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(train_images, train_labels, epochs=5)
6. 评估模型
最后,我们使用测试数据集来评估模型的性能:
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f"测试准确率: {test_acc:.4f}")
扩展阅读
如果您想了解更多关于 TensorFlow 的内容,可以访问我们的 TensorFlow 教程页面。
TensorFlow Logo