一、MNIST 數據集簡介
- MNIST 數據集是機器學習領域中非常經典的一個數據集,由 60000 個訓練樣本和 10000 個測試樣本組成,每個樣本都是一張 28 * 28 像素的灰度手寫數字圖片,如下圖所示:

- MNIST 數據集可在 http://yann.lecun.com/exdb/mnist/ 獲取,它包含了四個部分:訓練集、訓練集標簽、測試集、測試集標簽。

- MNIST 中的每個圖像都具有相應的標簽,0 到 9 之間的數字表示圖像中繪制的數字, 用的是 one-hot 編碼 nn[0,0,0,0,0,0,1,0,0,0],mnist.train.labels[55000,10]。
二、加載 MNIST 數據集
- 直接下載下來的數據是無法通過解壓或者應用程序打開的,因為這些文件不是任何標准 的圖像格式而是以字節的形式進行存儲的,所以必須編寫程序來打開它。
- 使用 TensorFlow 來讀取數據及標簽
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
# 加載數據集
mnist = input_data.read_data_sets('e:/soft/MNIST_DATA',one_hot=True)
# 加載訓練集樣本
train_x = mnist.train.images
# 加載驗證集樣本
validation_x = mnist.validation.images
# 加載測試集樣本
test_x = mnist.test.images
# 加載訓練集標簽
train_y = mnist.train.labels
# 加載驗證集標簽
validation_y = mnist.validation.labels
# 加載測試集標簽
test_y =mnist.test.labels
print('train_x.shape:',train_x.shape,'train_y.shape:',train_y.shape)
# 查看訓練集中第一個樣本的內容和標簽
print(train_x[0])
print(train_y[0])
# 獲取訓練集數據的前200個
images,labels = mnist.train.next_batch(200)
print('images.shape:',images.shape,'labels.shape:',labels.shape)
import matplotlib.pyplot as plt
# 繪制訓練集前20個樣本
fig,ax = plt.subplots(nrows=4,ncols=5)
ax = ax.flatten()
for i in range(20):
img = train_x[i].reshape(28,28)
ax[i].imshow(img,cmap='Greys')
ax[0].set_xticks([])
ax[0].set_yticks([])
plt.show()
三、訓練結果
- 訓練集中前 40 個樣本圖形如下:
