1. 程式人生 > >Tensorflow學習第1課——從本地載入MNIST以及FashionMNIST資料

Tensorflow學習第1課——從本地載入MNIST以及FashionMNIST資料

很多Tensorflow第一課的教程都是使用MNIST或者FashionMNIST資料集作為示例資料集,但是其給的例程基本都是從網路上用load_data函式直接載入,該函式封裝程度比較高,如果網路出現問題,資料集很難實時從網上下載(筆者就多次遇到這種問題,忍無可忍),而且資料是如何解碼的也一無所知,不利於後續的學習和理解,因此本文主要介紹對下載到本地的MNIST或FashionMNIST資料集如何載入解析的問題。

下載到本地的資料集一般有兩種格式:numpy的壓縮格式.npz,以及gzip壓縮格式.gz,下面我們分別介紹,在以下介紹中,均假設讀者已經將資料集下載到本地了,如果不知道從哪裡下載,請百度。

  1. npz格式資料集的載入程式碼非常簡單,直接用numpy的load函式即可
import numpy as np

# 假設資料儲存在'./datasets/'資料夾下
try:
    data = np.load('./datasets/mnist.npz')
    x_train, y_train, x_test, y_test = data['x_train'],data['y_train'],data['x_test'],data['y_test']
    
    # 可以將其中一條資料儲存成txt檔案,檢視一下,會對這組資料有個直觀的感受
    # np.savetxt('test.txt',x_train[0],fmt='%3d',newline='\n\n')
    
    # 將資料歸一化
    x_train, x_test = x_train/255.0, x_test/255.0
except Exception as e:
    print('%s' %e)
  1. gz格式資料集的載入
import numpy as np
import os
import gzip

# 定義載入資料的函式,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('./datasets/fashion/')

這樣,無論是npz格式還是gz格式,都可以輕鬆載入解碼,每次啟動測試都沒必要從網上下載,增加不必要的麻煩。