python讀取mnist數據集方法案例詳解
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個字節(jié) #這樣讀到的前兩個數據分別是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個字節(jié) #這樣讀到的前兩個數據分別是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數據集方法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python subprocess 殺掉全部派生的子進程方法
下面小編就為大家?guī)硪黄猵ython subprocess 殺掉全部派生的子進程方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-01-01