使用 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)