1.簡介
MNIST 數據集來自美國國家標準與技術研究所, 是NIST(National Institute of Standards and Technology)的縮小版,訓練集 (training set) 由來自 250 個不同人手寫的數字構成, 其中 50% 是高中學生, 50% 來自人口普查局 (the Census Bureau) 的工作人員,測試集(test set) 也是同樣比例的手寫數字數據.
MNIST 數據集可在 http://yann.lecun.com/exdb/mnist/ 獲取, 圖片是以字節的形式進行存儲,它包含了四個部分:
- Training set images: train-images-idx3-ubyte.gz (9.9 MB, 解壓後 47 MB, 包含 60,000 個樣本)
- Training set labels: train-labels-idx1-ubyte.gz (29 KB, 解壓後 60 KB, 包含 60,000 個標籤)
- Test set images: t10k-images-idx3-ubyte.gz (1.6 MB, 解壓後 7.8 MB, 包含 10,000 個樣本)
- Test set labels: t10k-labels-idx1-ubyte.gz (5KB, 解壓後 10 KB, 包含 10,000 個標籤)
此數據集中,訓練樣本:共60000個,其中55000個用於訓練,另外5000個用於驗證。測試樣本:共10000個,驗證數據比例相同。
數據集中像素值
a)使用python讀取二進制文件方法讀取mnist數據集,則讀進來的圖像像素值爲0-255之間;標籤是0-9的數值。
b)採用TensorFlow的封裝的函數讀取mnist,則讀進來的圖像像素值爲0-1之間;標籤是0-1值組成的大小爲1*10的行向量。
2.讀取mnist到numpy
load_mnist 函數返回兩個數組, 第一個是一個 n x m 維的 NumPy array(images), 這裏的 n 是樣本數(行數), m 是特徵數(列數). 訓練數據集包含 60,000 個樣本, 測試數據集包含 10,000 樣本.
在 MNIST 數據集中的每張圖片由 28 x 28 個像素點構成, 每個像素點用一個灰度值表示. 在這裏, 我們將 28 x 28 的像素展開爲一個一維的行向量, 這些行向量就是圖片數組裏的行(每行 784 個值, 或者說每行就是代表了一張圖片).
load_mnist 函數返回的第二個數組(labels) 包含了相應的目標變量, 也就是手寫數字的類標籤(整數 0-9).
import os
import struct
import numpy as np
def load_mnist(path, kind='train'):
"""Load MNIST data from `path`"""
labels_path = os.path.join(path,'%s-labels-idx1-ubyte'% kind)
images_path = os.path.join(path,'%s-images-idx3-ubyte'% kind)
with open(labels_path, 'rb') as lbpath:
magic, n = struct.unpack('>II',lbpath.read(8))
labels = np.fromfile(lbpath,dtype=np.uint8)
#讀入magic是一個文件協議的描述,也是調用fromfile 方法將字節讀入NumPy的array之前在文件緩衝中的item數(n).
with 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
1.
>這是指大端(用來定義字節是如何存儲的,關於大小端, 更多內容可見<<深入理解計算機系統 – 2.1 節信息存儲>>)
2.
I: 這是指一個無符號整數.
3.查看tensorflow集成的mnist
from tensorflow.examples.tutorials.mnist import input_data
minit = input_data.read_data_sets("../MNIST_data")
#如果該路徑沒有會自動下載
print("Training data size",minit.train.num_examples)
#訓練數據
print("Training data size",minit.validatation.num_examples)
#驗證數據
print("Training data size",minit.test.num_examples)
#測試數據
print("Example training data size",minit.train.image[0])
#樣例訓練數據
print(“Example training data label”,minist.train.labels[0])
#樣例訓練數據標籤
batch_size = 100
x,y = mnist.train.next_batch(batch_size)
print('x shape:',x.shape)
print('y shape:',y.shape)
4.可視化
4.1 plt的方法
從 feature matrix 中將 784-像素值 的向量 reshape 爲之前的 28*28 的形狀, 然後通過 matplotlib 的 imshow 函數進行繪製,不能進行one-hot編碼:
- 讀單個圖片
import matplotlib.pyplot as plt
#from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
#mnist = read_data_sets('MNIST_data', one_hot=False)
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data",one_hot=False)
x, y = mnist.test.next_batch(1)
x = x.reshape([28, 28])
fig = plt.figure()
# Method1
ax1 = fig.add_subplot(221)
ax1.imshow(x, cmap=plt.cm.gray)
# Method2: 反轉色
ax2 = fig.add_subplot(222)
ax2.imshow(x, cmap=plt.cm.gray_r) # r表示reverse
# Method3(等價於Method1)
ax3 = fig.add_subplot(223)
ax3.imshow(x, cmap='gray')
# Method4(等價於Method2)
ax4 = fig.add_subplot(224)
ax4.imshow(x, cmap='gray_r')
plt.show()
- 讀多個圖片
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data",one_hot=False)
fig, ax_big = plt.subplots()
for i in range(100): #讀一百張
x,y = mnist.test.next_batch(1)
x = x.reshape([28,28])
ax = fig.add_subplot(10,10,i+1) #10行10列
ax.imshow(x, cmap=plt.cm.gray)
ax.set_xticks([])
ax.set_yticks([])
#隱藏子圖座標軸刻度
ax_big.set_xticks([])
# 隱藏座標軸刻度
ax_big.set_yticks([])
plt.show()
#plt.savefig("路徑.png", dpi=150)
4.2 torchvision&scipy方法
其實數據集裏的圖片就是一個帶有像素值的二維數組,可以畫出這個數組的庫有很多。機器學習庫torch,的torchvision也可以。具體方法如下:
import torchvision
import torch.utils.data as Data
import scipy.misc
import os
DOWNLOAD_MNIST = True
train_data = torchvision.datasets.MNIST(root='./MNIST_data2/',train=True,transform=torchvision.transforms.ToTensor(),download=DOWNLOAD_MNIST)
#把原始圖片保存至MNIST_data/raw/下
save_dir="mnist/raw/"
if os.path.exists(save_dir) is False:
os.makedirs(save_dir)
for i in range(20):
image_array,_=train_data[i]#打印第i個
image_array=image_array.resize(28,28)
filename=save_dir + 'mnist_train_%d.jpg' % i#保存文件的格式
print(filename)
print(train_data.train_labels[i])#打印出標籤
scipy.misc.toimage(image_array,cmin=0.0,cmax=1.0).save(filename)#保存圖像
結果輸出如下: