深度學習中有許多的RNN(循環神經網路)結構,其中LSTM(長短時記憶網路)與GRU(門限遞歸單元)是應用比較廣泛的兩種結構。本文將重點介紹這兩種結構的原理和應用,並提供完整的代碼示例。
一、LSTM介紹
LSTM最早是由Hochreiter等人在1997年提出的,它可以避免RNN中的梯度消失問題(當反向傳播過程中,梯度值變得很小,導致很難訓練)。
LSTM的核心是使用三個門結構(輸入門、輸出門和遺忘門)來控制信息的流動,保證信息在訓練過程中可以根據需要選擇保留或遺忘。其中,輸入門可以控制當前信息的「重要性」,輸出門可以控制信息的輸出程度,遺忘門可以控制需要遺忘的信息。
import tensorflow as tf # 定義LSTM結構 class LSTM(tf.keras.Model): def __init__(self, units): super(LSTM, self).__init__() self.units = units self.forget_gate = tf.keras.layers.Dense(units, activation='sigmoid') self.input_gate = tf.keras.layers.Dense(units, activation='sigmoid') self.output_gate = tf.keras.layers.Dense(units, activation='sigmoid') self.memory_gate = tf.keras.layers.Dense(units, activation='tanh') def call(self, inputs, memory, state): concat_inputs = tf.concat([inputs, memory], axis=-1) forget = self.forget_gate(concat_inputs) input = self.input_gate(concat_inputs) output = self.output_gate(concat_inputs) memory_ = forget * state + input * self.memory_gate(concat_inputs) state_ = output * tf.tanh(memory_) return state_, memory_
二、GRU介紹
GRU是於2014年由Cho等人提出的,它對LSTM進行了簡化,將輸入門和遺忘門合併為「重置門」,將輸出門合併為「更新門」。
GRU的優點在於計算速度比LSTM快,同時也相對容易訓練,因此在一些較為簡單的任務中,GRU的表現可以與LSTM相當甚至更好。
# 定義GRU結構 class GRU(tf.keras.Model): def __init__(self, units): super(GRU, self).__init__() self.units = units self.reset_gate = tf.keras.layers.Dense(units, activation='sigmoid') self.update_gate = tf.keras.layers.Dense(units, activation='sigmoid') self.memory_gate = tf.keras.layers.Dense(units, activation='tanh') def call(self, inputs, state): concat_inputs = tf.concat([inputs, state], axis=-1) reset = self.reset_gate(concat_inputs) update = self.update_gate(concat_inputs) memory = self.memory_gate(tf.concat([inputs, reset * state], axis=-1)) state_ = update * state + (1 - update) * memory return state_
三、應用案例
在很多自然語言處理(NLP)的任務中,LSTM和GRU都得到了廣泛的應用,例如語言模型、機器翻譯、情感分析等。下面以情感分析為例,展示如何使用LSTM和GRU對文本進行情感分類。
情感分析的數據集通常包括一系列帶有標記的文本數據,如0表示負面情緒,1表示正面情緒。我們可以使用LSTM或GRU對文本進行處理,並利用全連接層進行分類。以下是使用Keras框架實現的完整代碼示例。
import tensorflow as tf from tensorflow.keras.datasets import imdb from tensorflow.keras.preprocessing.sequence import pad_sequences # 模型參數 max_features = 10000 max_len = 200 embedding_dim = 128 lstm_units = 64 batch_size = 32 epochs = 10 # 載入數據集 (x_train, y_train), (x_val, y_val) = imdb.load_data(num_words=max_features) # 填充序列 x_train = pad_sequences(x_train, maxlen=max_len) x_val = pad_sequences(x_val, maxlen=max_len) # 定義模型 model = tf.keras.Sequential([ tf.keras.layers.Embedding(max_features, embedding_dim, input_length=max_len), tf.keras.layers.LSTM(lstm_units, dropout=0.2, recurrent_dropout=0.2), tf.keras.layers.Dense(1, activation='sigmoid') ]) # 編譯模型 model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # 訓練模型 model.fit(x_train, y_train, batch_size=batch_size, epochs=epochs, validation_data=(x_val, y_val)) # 測試 test_loss, test_acc = model.evaluate(x_val, y_val) print('Test Accuracy:', test_acc)
以上代碼中,我們使用了Keras自帶的IMDB數據集,利用LSTM和全連接層進行情感分析任務的訓練,並在測試集上進行測試,最終輸出測試的準確率。
原創文章,作者:PRXOK,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/368623.html