【深度學習 走進tensorflow2.0】建立一個遞歸神經網絡(LSTM)對MNIST數字集進行分類

無意中發現了一個巨牛的人工智能教程,忍不住分享一下給大家。教程不僅是零基礎,通俗易懂,而且非常風趣幽默,像看小說一樣!覺得太牛了,所以分享給大家。點這裏可以跳轉到教程。人工智能教程

使用CNN進行圖像分類是很稀疏平常的,其實使用RNN也是可以的.
大家都知道卷積神經網絡可以用來做圖片分類,那麼循環神經網絡可不可以同樣用來做圖片分類呢,答案是可以滴,下面我們使用TensorFlow 2.0構建循環神經網絡LSTM,一起從minist 學習下吧。

數據集特點:
該數據集包含60,000個用於訓練的示例和10,000個用於測試的示例。這些數字已經過尺寸標準化並位於圖像中心,圖像是固定大小(28x28像素),值爲0到255。爲簡單起見,每個圖像都被展平並轉換爲包含784個特徵(28*28)的一維numpy數組。

主要注意點:
MNIST的圖像形狀爲28 * 28px,因此我們將爲每個樣本處理28個時間步長的28個序列。

實戰項目–遞歸神經網絡(LSTM)對MNIST數字集進行分類:

from __future__ import absolute_import, division, print_function

# 導入TensorFlow v2.
import tensorflow as tf
from tensorflow.keras import Model, layers
import numpy as np
# MNIST 數據集參數
num_classes = 10   #所有類別(數字 0-9)
num_features = 784 # 數據特徵 (圖像形狀: 28*28)

# 訓練參數
learning_rate = 0.001
training_steps = 2000
batch_size = 32
display_step = 100

# 網絡參數
# MNIST的圖像形狀爲28 * 28px,因此我們將爲每個樣本處理28個時間步長的28個序列。
num_input = 28 # 序列數
timesteps = 28 # 時間步長
num_units = 64  # LSTM層神經元數目


# 準備MNIST數據
from tensorflow.keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# 轉化爲float32
x_train, x_test = np.array(x_train, np.float32), np.array(x_test, np.float32)
# 將圖像展平爲784個特徵的一維向量(28*28)。
x_train, x_test = x_train.reshape([-1, 28, 28]), x_test.reshape([-1, num_features])
# 將圖像值從[0,255]歸一化到[0,1]
x_train, x_test = x_train / 255., x_test / 255.
# 使用tf.data API對數據進行隨機排序和批處理
train_data = tf.data.Dataset.from_tensor_slices((x_train, y_train))
train_data = train_data.repeat().shuffle(5000).batch(batch_size).prefetch(1)


# 創建LSTM模型
class LSTM(Model):
    # 創建TF模型
    def __init__(self):
        super(LSTM, self).__init__()
        # RNN (LSTM) 隱含層
        self.lstm_layer = layers.LSTM(units=num_units)
        self.out = layers.Dense(num_classes)

    # 前向傳播
    def call(self, x, is_training=False):
        # LSTM層
        x = self.lstm_layer(x)
        # 輸出層 (num_classes).
        x = self.out(x)
        if not is_training:
            # tf 交叉熵接收沒有經過softmax的概率輸出,所以只有不是訓練時才應用softmax
            x = tf.nn.softmax(x)
        return x

# 創建LSTM模型
lstm_net = LSTM()
# 交叉熵損失
# 注意,這將對概率輸出應用'softmax'
def cross_entropy_loss(x, y):
    # 將標籤轉換爲int 64 作爲tf交叉熵函數的輸入
    y = tf.cast(y, tf.int64)
    # 對概率輸出應用softmax並計算交叉熵
    loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=y, logits=x)
     # 批中的平均損失
    return tf.reduce_mean(loss)

# 準確率評估
def accuracy(y_pred, y_true):
    # 預測類是預測向量(即argmax)分數最高的分量下標
    correct_prediction = tf.equal(tf.argmax(y_pred, 1), tf.cast(y_true, tf.int64))
    return tf.reduce_mean(tf.cast(correct_prediction, tf.float32), axis=-1)

# Adam 優化器
optimizer = tf.optimizers.Adam(learning_rate)
# 優化過程
def run_optimization(x, y):
     # 將計算封裝在GradientTape中以實現自動微分
    with tf.GradientTape() as g:
        # 前向傳播
        pred = lstm_net(x, is_training=True)
        # 計算損失
        loss = cross_entropy_loss(pred, y)

    # 要更新的變量,即可訓練變量
    trainable_variables = lstm_net.trainable_variables

    # 計算梯度
    gradients = g.gradient(loss, trainable_variables)

    # 按gradients更新 W 和 b
    optimizer.apply_gradients(zip(gradients, trainable_variables))


# 針對給定步驟數進行訓練
for step, (batch_x, batch_y) in enumerate(train_data.take(training_steps), 1):
     # 運行優化過程以更新W和b值
    run_optimization(batch_x, batch_y)

    if step % display_step == 0:
        pred = lstm_net(batch_x, is_training=True)
        loss = cross_entropy_loss(pred, batch_y)
        acc = accuracy(pred, batch_y)
        print("step: %i, loss: %f, accuracy: %f" % (step, loss, acc))

訓練結果:

step: 100, loss: 1.346812, accuracy: 0.500000
step: 200, loss: 0.803729, accuracy: 0.718750
step: 300, loss: 0.522755, accuracy: 0.843750
step: 400, loss: 0.394801, accuracy: 0.875000
step: 500, loss: 0.465856, accuracy: 0.875000
step: 600, loss: 0.205619, accuracy: 0.937500
step: 700, loss: 0.323130, accuracy: 0.937500
step: 800, loss: 0.406646, accuracy: 0.906250
step: 900, loss: 0.097341, accuracy: 0.968750
step: 1000, loss: 0.141899, accuracy: 0.937500
step: 1100, loss: 0.140804, accuracy: 0.937500
step: 1200, loss: 0.196056, accuracy: 0.906250
step: 1300, loss: 0.072516, accuracy: 1.000000
step: 1400, loss: 0.228695, accuracy: 0.968750
step: 1500, loss: 0.071493, accuracy: 1.000000
step: 1600, loss: 0.268323, accuracy: 0.937500
step: 1700, loss: 0.042088, accuracy: 1.000000
step: 1800, loss: 0.075105, accuracy: 1.000000
step: 1900, loss: 0.195024, accuracy: 0.968750
step: 2000, loss: 0.021159, accuracy: 1.000000

最後模型訓練準確率 達到100% ,真厲害啊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章