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: 測試集標簽