Skip to content
Rain Hu's Workspace
Go back

[AI] 2-1. 初試神經網路-手寫辨識 mnist

Rain Hu

1. 認識 MNIST 資料集

from tensorflow.keras.datasets import mnist

(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images.shape
len(train_labels)
test_images.shape
test_labels
min(test_labels), max(test_labels)
結果
(60000, 28, 28)     # 代表 train_images 是 60000 張 28*28 的圖片 
60000               # 代表 train_labels 同樣也有 60000 份
(10000, 28, 28)     # 代表 test_images 有 10000 張 28*28 的圖片
array([7, 2, 1, ..., 4, 5, 6], dtype=uint8)
(0, 9)              # 代表 test_labels 是 0-9 的數字,資料型別是 uint8

2. 神經網路架構

from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(512, activation="relu")
    layers.Dense(10, activation="softmax")
])
model.compile(optimizer='adam',
    loss='sparse_categorical_crossentropy',
    metrics=['accuracy'])
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255

test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
model.fit(train_images, train_labels, epochs=5, batch_size=128)
test_digits = test_images[0:20]
predictions = model.predict(test_digits)
predictions.argmax(axis=1)   # 列出每行中最大值的索引值
結果
array([7, 2, 1, 0, 4, 1, 4, 9, 5, 9, 0, 6, 9, 0, 1, 5, 9, 7, 3, 4])
  • 嘗試把手寫圖片畫出來,比較一下
import matplotlib.pyplot as plt

n = 20
for i in range(n):
plt.subplot(1, n, i+1)
plt.imshow(test_images_pic[i], cmap='gray')
plt.axis('off')

plt.tight_layout()
plt.show()

mnist_20

+ 最後我們把模型拿來測試全部 10000 張測資,看一下準確度是多少 ```python test_loss, test_acc = model.evaluate(test_images, test_labels) print(f'test_acc: {test_acc}') ```
結果
test_acc: 0.9810000061988831
  • 代表正確率為 98.1%
+ 比較訓練集的準確度為 0.9904,測試集的準確度為 0.981,這樣的差距稱為**過度配適(overfitting)**,意指模型對新資料的表現比訓練資料還要差。

3. 摘要

在本篇做了以下的事

  1. 載入 mnist 資料集
  2. 用 Dense Layer 建構了一個神經網路
  3. 用 model.compile 來編譯神經網路,需要指定 opimizer, loss, metric 三個參數
  4. 對資料集做預處理
  5. 用 model.fit() 來訓練
  6. 用 model.predict() 來預測
  7. 用 model.evaluate 來評估模型表現

Share this post on:

Previous
[AI] 2-2. 張量 Tensor
Next
[AI] 1-3. 深度學習的發展