1. 程式人生 > >載入本地MNIST資料集

載入本地MNIST資料集

import numpy as np
import os
import gzip
import tensorflow as tf
from PIL import Image

def img_show(img):
    pil_img = Image.fromarray(np.uint8(img))#Image.fromarray影象資料轉換為PIL資料物件
    pil_img.show()#顯示圖片
# 定義載入資料的函式,data_folder為儲存gz資料的資料夾,該資料夾下有4個檔案
# 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz',
# 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz' def load_data(data_folder): files = [ 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz', 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz' ] paths = [] for fname in files: paths.append(os.path.join(data_folder,
fname)) with gzip.open(paths[0], 'rb') as lbpath: y_train = np.frombuffer(lbpath.read(), np.uint8, offset=8) with gzip.open(paths[1], 'rb') as imgpath: x_train = np.frombuffer( imgpath.read(), np.uint8, offset=16).reshape(len(y_train), 28, 28) with gzip.open(paths[2], 'rb') as
lbpath: y_test = np.frombuffer(lbpath.read(), np.uint8, offset=8) with gzip.open(paths[3], 'rb') as imgpath: x_test = np.frombuffer( imgpath.read(), np.uint8, offset=16).reshape(len(y_test), 28, 28) return (x_train, y_train), (x_test, y_test) (train_images, train_labels), (test_images, test_labels) = load_data('C:\\Users\\Administrator\\MNIST_data\\') img = train_images[0]#訓練影象賦給img label = train_labels[0]#訓練標籤賦給label print(label) # 5 print(img.shape) # (784,) img = img.reshape(28, 28) # 把影象的形狀變為原來的尺寸 print(img.shape) # (28, 28) img_show(img)#函式