python讀取mnist數(shù)據(jù)集方法案例詳解
mnist手寫(xiě)數(shù)字?jǐn)?shù)據(jù)集在機(jī)器學(xué)習(xí)中非常常見(jiàn),這里記錄一下用python從本地讀取mnist數(shù)據(jù)集的方法。
數(shù)據(jù)集格式介紹
這部分內(nèi)容網(wǎng)絡(luò)上很常見(jiàn),這里還是簡(jiǎn)明介紹一下。網(wǎng)絡(luò)上下載的mnist數(shù)據(jù)集包含4個(gè)文件:
前兩個(gè)分別是測(cè)試集的image和label,包含10000個(gè)樣本。后兩個(gè)是訓(xùn)練集的,包含60000個(gè)樣本。.gz表示這個(gè)一個(gè)壓縮包,如果進(jìn)行解壓的話,會(huì)得到.ubyte格式的二進(jìn)制文件。
上圖是訓(xùn)練集的label和image數(shù)據(jù)的存儲(chǔ)格式。兩個(gè)文件最開(kāi)始都有magic number和number of images/items兩個(gè)數(shù)據(jù),有用的是第二個(gè),表示文件中存儲(chǔ)的樣本個(gè)數(shù)。另外要注意的是數(shù)據(jù)的位數(shù),有32位整型和8位整型兩種。
讀取方法
.gz格式的文件讀取
需要import gzip
讀取訓(xùn)練集的代碼如下:
def load_mnist_train(path, kind='train'): '‘' path:數(shù)據(jù)集的路徑 kind:值為train,代表讀取訓(xùn)練集 ‘'‘ 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打開(kāi)文件 with gzip.open(labels_path, 'rb') as lbpath: #使用struct.unpack方法讀取前兩個(gè)數(shù)據(jù),>代表高位在前,I代表32位整型。lbpath.read(8)表示一次從文件中讀取8個(gè)字節(jié) #這樣讀到的前兩個(gè)數(shù)據(jù)分別是magic number和樣本個(gè)數(shù) magic, n = struct.unpack('>II',lbpath.read(8)) #使用np.fromstring讀取剩下的數(shù)據(jù),lbpath.read()表示讀取所有的數(shù)據(jù) 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
讀取測(cè)試集的代碼類(lèi)似。
非壓縮文件的讀取
如果在本地對(duì)四個(gè)文件解壓縮之后,得到的就是.ubyte格式的文件,這時(shí)讀取的代碼有所變化。
def load_mnist_train(path, kind='train'): '‘' path:數(shù)據(jù)集的路徑 kind:值為train,代表讀取訓(xùn)練集 ‘'‘ labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind) images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind) #不再用gzip打開(kāi)文件 with open(labels_path, 'rb') as lbpath: #使用struct.unpack方法讀取前兩個(gè)數(shù)據(jù),>代表高位在前,I代表32位整型。lbpath.read(8)表示一次從文件中讀取8個(gè)字節(jié) #這樣讀到的前兩個(gè)數(shù)據(jù)分別是magic number和樣本個(gè)數(shù) magic, n = struct.unpack('>II',lbpath.read(8)) #使用np.fromfile讀取剩下的數(shù)據(jù) 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的長(zhǎng)度,確認(rèn)讀取是否正確。
到此這篇關(guān)于python讀取mnist數(shù)據(jù)集方法案例詳解的文章就介紹到這了,更多相關(guān)python讀取mnist數(shù)據(jù)集方法內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。