Keras 中的 RNN 入門

使用 Keras 建立語言模型的循環神經網路(RNN)

David Cecchini

Data Scientist

什麼是 keras?

  • 高階 API

  • 執行於 TensorFlow 2 之上

  • 安裝使用都很簡單

$pip install tensorflow

快速試驗:

from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense
使用 Keras 建立語言模型的循環神經網路(RNN)

keras.models

keras.models.Sequential

顯示 keras 模型中 Sequential 類別的概念圖。每一層依序從輸入連到輸出。

keras.models.Model

顯示 keras 模型中 Model 類別的概念圖。此類別可有多個輸入與多個輸出,能建立更複雜的架構。

使用 Keras 建立語言模型的循環神經網路(RNN)

keras.layers

  1. LSTM
  2. GRU
  3. Dense
  4. Dropout
  5. Embedding
  6. Bidirectional
使用 Keras 建立語言模型的循環神經網路(RNN)

keras.preprocessing

keras.preprocessing.sequence.pad_sequences(texts, maxlen=3)

padding 範例:若文字少於 padding 長度,會在開頭補上「0」權杖;若多於長度,句尾多出的詞會被截去。

使用 Keras 建立語言模型的循環神經網路(RNN)

keras.datasets

內建多種實用資料集

  • IMDB 電影評論
  • Reuters 路透社新聞

還有更多!

完整清單與用法請見 keras 文件

使用 Keras 建立語言模型的循環神經網路(RNN)

建立模型

# Import required modules
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
# Instantiate the model class
model = Sequential()
# Add the layers
model.add(Dense(64, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy'])
使用 Keras 建立語言模型的循環神經網路(RNN)

訓練模型

.fit() 方法會在訓練集上訓練模型

model.fit(X_train, y_train, epochs=10, batch_size=32)
  1. epochs 決定模型權重更新的次數
  2. batch_size 每步處理的資料筆數
使用 Keras 建立語言模型的循環神經網路(RNN)

模型評估與應用

評估模型

model.evaluate(X_test, y_test)
[0.3916562925338745, 0.89324]

對新資料進行預測

model.predict(new_data)
array([[0.91483957],[0.47130653]], dtype=float32)
使用 Keras 建立語言模型的循環神經網路(RNN)

完整範例:IMDB 情感分類

# Build and compile the model
model = Sequential()

model.add(Embedding(10000, 128)) model.add(LSTM(128, dropout=0.2)) model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
# Training
model.fit(x_train, y_train, epochs=5)
# Evaluation
score, acc = model.evaluate(x_test, y_test)
使用 Keras 建立語言模型的循環神經網路(RNN)

一起來練習吧!

使用 Keras 建立語言模型的循環神經網路(RNN)

Preparing Video For Download...