MNIST 数据集是机器学习领域最著名的数据集之一,全称为"Modified National Institute of Standards and Technology"数据库。它包含了大量手写数字的图像,是入门机器学习和深度学习的经典数据集。
1. MNIST 数据集概述
60,000 张训练图像
10,000 张测试图像
每张图像是 28×28 像素的灰度图像
每个图像对应一个 0-9 的数字标签
2. .npz 格式
mnist.npz 文件是 MNIST 数据集的一种常见存储格式,它将四个 NumPy 数组打包在一个文件中:
x_train: 训练图像,形状为 (60000, 28, 28)
y_train: 训练标签,形状为 (60000,)
x_test: 测试图像,形状为 (10000, 28, 28)
y_test: 测试标签,形状为 (10000,)
3. 如何获取 MNIST 数据集
3.1. 使用 Keras/TensorFlow 内置函数
新建get_mnist.py
import numpy as np
from tensorflow.keras.datasets import mnist# 加载 MNIST 数据集
(x_train, y_train), (x_test, y_test) = mnist.load_data()# 保存为 .npz 文件# np.savez('mnist.npz', x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test)
np.savez_compressed('mnist.npz', x_train=x_train, y_train=y_train, x_test=x_test, y_test=y_test)
print("MNIST 数据集已保存为 mnist.npz 文件")
3.2 从官方网站下载
MNIST 数据集可以从官方网站在线获取:
http://yann.lecun.com/exdb/mnist/
官方网站提供了四个文件:
train-images-idx3-ubyte.gz: 训练集图像
train-labels-idx1-ubyte.gz: 训练集标签
t10k-images-idx3-ubyte.gz: 测试集图像
t10k-labels-idx1-ubyte.gz: 测试集标签