文档
Keras MNIST 手写数字识别
目标
用 Keras Sequential API 构建一个简单 CNN,在 MNIST 数据集上达到 99%+ 准确率。
完整代码
import numpy as np
from tensorflow import keras
from tensorflow.keras import layers
# 1. 加载数据
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
# 2. 预处理:归一化 + reshape(增加 channel 维度)
x_train = x_train.astype("float32") / 255.0
x_test = x_test.astype("float32") / 255.0
x_train = np.expand_dims(x_train, -1) # (60000, 28, 28, 1)
x_test = np.expand_dims(x_test, -1)
# 3. One-hot 编码标签
y_train = keras.utils.to_categorical(y_train, 10)
y_test = keras.utils.to_categorical(y_test, 10)
# 4. 构建模型
model = keras.Sequential([
layers.Conv2D(32, (3, 3), activation="relu", input_shape=(28, 28, 1)),
layers.MaxPooling2D((2, 2)),
layers.Conv2D(64, (3, 3), activation="relu"),
layers.MaxPooling2D((2, 2)),
layers.Flatten(),
layers.Dropout(0.5),
layers.Dense(128, activation="relu"),
layers.Dense(10, activation="softmax"),
])
model.compile(
optimizer="adam",
loss="categorical_crossentropy",
metrics=["accuracy"],
)
# 5. 训练
model.fit(x_train, y_train, batch_size=128, epochs=5, validation_split=0.1)
# 6. 评估
score = model.evaluate(x_test, y_test, verbose=0)
print(f"测试准确率: {score[1]:.4f}")
运行步骤
pip install tensorflow numpy
python mnist_cnn.py
预期输出
Epoch 1/5
422/422 ━━━━━━━━ 15s ... accuracy: 0.9720
Epoch 5/5
422/422 ━━━━━━━━ 14s ... accuracy: 0.9938
测试准确率: 0.9912