什么是 MNIST?

MNIST 是一个经典的手写数字数据集,包含 70,000 张 28x28 像素的灰度图像,常用于训练和测试机器学习模型。

mnist_dataset

环境准备

  1. 安装 TensorFlow:pip install tensorflow
  2. 导入必要库:
    import tensorflow as tf
    from tensorflow.keras import layers, models
    
  3. 加载 MNIST 数据集:
    (train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()
    

代码实现

# 构建模型
model = models.Sequential([
    layers.Flatten(input_shape=(28, 28)),
    layers.Dense(128, activation='relu'),
    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, verbose=2)
neural_network_structure

训练结果

  • 训练准确率可达 98% 以上 ✅
  • 测试准确率通常在 97% 左右 📈
  • 可通过 model.predict() 查看预测结果 🔍

扩展学习

想要深入了解卷积神经网络(CNN)在 MNIST 上的应用?
👉 点击这里查看 TensorFlow CNN 实现教程

training_process_mnist