使用 Keras 建立語言模型的循環神經網路(RNN)
David Cecchini
Data Scientist
文字分類的應用:
由二元分類改為多類別時的變動:
y 的形狀輸出變數 y 的形狀:
# Example: num_classes = 3
y[0] = [0, 1, 0]
y.shape = (N, num_classes)
輸出層的單元數:
# Output layer
model.add(Dense(num_classes))

輸出層的啟動函式:
softmax 會回傳每個類別的機率# Output layer
model.add(Dense(num_classes, activation="softmax"))
損失函式:
# Compile the model
model.compile(loss='categorical_crossentropy')
y = ["sports", "economy", "data_science", "sports", "finance"] # 轉為 pandas 的 series 物件 y_series = pd.Series(y, dtype="category")# 列印類別代碼 print(y_series.cat.codes)
0 3
1 1
2 0
3 3
4 2
from tensorflow.keras.utils import to_categoricaly = np.array([0, 1, 2]) # 轉為類別格式 y_prep = to_categorical(y) print(y_prep)
[[1. 0. 0.]
[0. 1. 0.]
[0. 0. 1.]]
使用 Keras 建立語言模型的循環神經網路(RNN)