MNIST 是机器学习领域经典的数据集,包含 70,000 张 28x28 的手写数字图像(0-9),常用于入门深度学习和神经网络。以下是使用 Python 实现 MNIST 分类的步骤:
📌 1. 环境准备
- 安装 TensorFlow 或 PyTorch
- 导入必要库:
import tensorflow as tf from tensorflow.keras import layers, models
📊 2. 数据加载与预处理
# 加载 MNIST 数据集
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0 # 归一化处理
🧠 3. 构建模型
model = models.Sequential([
layers.Flatten(input_shape=(28, 28)), # 展平输入
layers.Dense(128, activation='relu'), # 全连接层
layers.Dropout(0.2), # 防止过拟合
layers.Dense(10, activation='softmax') # 输出层
])
🚀 4. 训练与评估
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test, verbose=2)
📚 扩展阅读
想深入了解 TensorFlow 的使用?点击这里查看 TensorFlow 教程 获取更多实战案例!