利用 Keras 辨識 MNIST手寫數字資料集
Date: 2019/12/28 | Lecturer: Chia
安裝深度學習套件
MNIST手寫數字資料集
五個步驟
載入資料
建構神經網路架構
資料預處理
模型訓練
評估測試正確率
$ pip install keras
$ pip install tensorflow
$ pip install matplotlib
# A_Neural_Network_keras.py
from keras.datasets import mnist
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
plt.imshow(train_images[0], cmap=plt.cm.binary)
plt.show()
print(train_labels[0])
# mnist_subplot.py
from keras.datasets import mnist
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
plt.subplot(1, 4, 1)
plt.imshow(train_images[0], cmap=plt.cm.binary)
plt.subplot(1, 4, 2)
plt.imshow(train_images[1], cmap=plt.cm.binary)
plt.subplot(1, 4, 3)
plt.imshow(train_images[2], cmap=plt.cm.binary)
plt.subplot(1, 4, 4)
plt.imshow(train_images[3], cmap=plt.cm.binary)
plt.show()
1. 載入資料
用來訓練模型
對模型進行測試
2. 建構神經網路架構
3. 資料預處理
訓練集 & 測試集
轉換為神經網路能夠處理的形式
4. 模型訓練
學習把圖片加以歸類
訓練集圖片
5. 評估測試正確率
測試集圖片
預測出來的數字
測試集標籤
# A_Neural_Network_keras.py
from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical
匯入所需套件
# A_Neural_Network_keras.py
# ...
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(train_labels[0], test_labels[0])
# 5 7
載入MNIST
relu
softmax
Activation Function
激勵函數
# A_Neural_Network_keras.py
# ...
network = models.Sequential()
#激勵函數:relu, softmax
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
# 編譯
network.compile(optimizer='rmsprop', #優化器
loss='categorical_crossentropy', #損失函數
metrics=['accuracy']) #評量準則
建構神經網路架構
# A_Neural_Network_keras.py
# ...
# 訓練集 & 測試集 轉換為神經網路能夠處理的形式
# 並縮放到所有值都在 [0, 1] 區間 (除以255)
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
資料預處理
# A_Neural_Network_keras.py
# ...
# 對標籤進行分類編碼(One-hot encoding) => 目標:預測數字
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
print(train_labels[0], test_labels[0])
# [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.] [0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
One-hot encoding
# A_Neural_Network_keras.py
# ...
# epochs:表示訓練遍數
# batch_size:表示每次餵給網路的資料數目
network.fit(train_images, train_labels, epochs=5, batch_size=128)
模型訓練
# A_Neural_Network_keras.py
# ...
# 檢測在測試集上的正確率
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('測試正確率:', test_acc)
評估測試正確率