数据预处理

使用 Keras 构建语言建模的循环神经网络(RNN)

David Cecchini

Data Scientist

文本分类

文本分类的应用:

  • 新闻自动分类
  • 企业文档分类
  • 客服队列分流
  • 还有更多!
使用 Keras 构建语言建模的循环神经网络(RNN)

与二分类的变化

从二分类到多分类的变化:

  • 输出变量 y 的形状
  • 输出层单元数
  • 输出层激活函数
  • 损失函数
使用 Keras 构建语言建模的循环神经网络(RNN)

与二分类的变化

输出变量 y 的形状:

  • 类别的独热编码
# Example: num_classes = 3
y[0] = [0, 1, 0]
y.shape = (N, num_classes)

输出层单元数:

# Output layer
model.add(Dense(num_classes))
使用 Keras 构建语言建模的循环神经网络(RNN)

与二分类的变化

数字在一条线上与在空间中的差异,展示独热编码的作用

使用 Keras 构建语言建模的循环神经网络(RNN)

与二分类的变化

输出层的激活函数:

  • softmax 给出每个类别的概率
# Output layer
model.add(Dense(num_classes, activation="softmax"))

损失函数:

  • 不是二元交叉熵,而是多类交叉熵
# Compile the model
model.compile(loss='categorical_crossentropy')
使用 Keras 构建语言建模的循环神经网络(RNN)

为 keras 准备文本类别

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
使用 Keras 构建语言建模的循环神经网络(RNN)

预处理 y

from tensorflow.keras.utils import to_categorical

y = np.array([0, 1, 2]) # 转为独热编码 y_prep = to_categorical(y) print(y_prep)
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]
使用 Keras 构建语言建模的循环神经网络(RNN)

Passons à la pratique !

使用 Keras 构建语言建模的循环神经网络(RNN)

Preparing Video For Download...