mnist手寫數字數據集在機器學習中非常常見,這里記錄一下用python從本地讀取mnist數據集的方法。
數據集格式介紹
這部分內容網絡上很常見,這里還是簡明介紹一下。網絡上下載的mnist數據集包含4個文件:

前兩個分別是測試集的image和label,包含10000個樣本。后兩個是訓練集的,包含60000個樣本。.gz表示這個一個壓縮包,如果進行解壓的話,會得到.ubyte格式的二進制文件。

上圖是訓練集的label和image數據的存儲格式。兩個文件最開始都有magic number和number of images/items兩個數據,有用的是第二個,表示文件中存儲的樣本個數。另外要注意的是數據的位數,有32位整型和8位整型兩種。
讀取方法
.gz格式的文件讀取
需要import gzip
讀取訓練集的代碼如下:
def load_mnist_train(path, kind='train'):
'‘'
path:數據集的路徑
kind:值為train,代表讀取訓練集
‘'‘
labels_path = os.path.join(path,'%s-labels-idx1-ubyte.gz'% kind)
images_path = os.path.join(path,'%s-images-idx3-ubyte.gz'% kind)
#使用gzip打開文件
with gzip.open(labels_path, 'rb') as lbpath:
#使用struct.unpack方法讀取前兩個數據,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次從文件中讀取8個字節
#這樣讀到的前兩個數據分別是magic number和樣本個數
magic, n = struct.unpack('>II',lbpath.read(8))
#使用np.fromstring讀取剩下的數據,lbpath.read()表示讀取所有的數據
labels = np.fromstring(lbpath.read(),dtype=np.uint8)
with gzip.open(images_path, 'rb') as imgpath:
magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
images = np.fromstring(imgpath.read(),dtype=np.uint8).reshape(len(labels), 784)
return images, labels
讀取測試集的代碼類似。
非壓縮文件的讀取
如果在本地對四個文件解壓縮之后,得到的就是.ubyte格式的文件,這時讀取的代碼有所變化。
def load_mnist_train(path, kind='train'):
'‘'
path:數據集的路徑
kind:值為train,代表讀取訓練集
‘'‘
labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind)
images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind)
#不再用gzip打開文件
with open(labels_path, 'rb') as lbpath:
#使用struct.unpack方法讀取前兩個數據,>代表高位在前,I代表32位整型。lbpath.read(8)表示一次從文件中讀取8個字節
#這樣讀到的前兩個數據分別是magic number和樣本個數
magic, n = struct.unpack('>II',lbpath.read(8))
#使用np.fromfile讀取剩下的數據
labels = np.fromfile(lbpath,dtype=np.uint8)
with gzip.open(images_path, 'rb') as imgpath:
magic, num, rows, cols = struct.unpack('>IIII',imgpath.read(16))
images = np.fromfile(imgpath,dtype=np.uint8).reshape(len(labels), 784)
return images, labels
讀取之后可以查看images和labels的長度,確認讀取是否正確。
到此這篇關于python讀取mnist數據集方法案例詳解的文章就介紹到這了,更多相關python讀取mnist數據集方法內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- Python rindex()方法案例詳解
- Python 實現靜態鏈表案例詳解
- Python 概率生成問題案例詳解
- Python 二叉樹的概念案例詳解
- Python實現堆排序案例詳解
- 超實用的 10 段 Python 案例