情感分类再探

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

David Cecchini

Data Scientist

先前结果

初始模型表现不佳。

model = Sequential()
model.add(SimpleRNN(units=16, input_shape=(None, 1)))
model.add(Dense(1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy'])

model.evaluate(x_test, y_test)
$[0.6991182165145874, 0.495]
使用 Keras 构建语言建模的循环神经网络(RNN)

改进模型

为提升性能,可:

  • 添加嵌入层
  • 增加层数
  • 调参与优化
  • 扩大词表
  • 接受更长句子并增加记忆单元
使用 Keras 构建语言建模的循环神经网络(RNN)

避免过拟合

RNN 容易过拟合

  • 测试不同的 batch size。
  • 添加 Dropout 层。
  • 在 RNN 层上设置 dropoutrecurrent_dropout
# removes 20% of input to add noise
model.add(Dropout(rate=0.2))

# Removes 10% of input and memory cells respectively model.add(LSTM(128, dropout=0.1, recurrent_dropout=0.1))
使用 Keras 构建语言建模的循环神经网络(RNN)

扩展:卷积层

超出本节范围:

model.add(Embedding(vocabulary_size, wordvec_dim, ...))
model.add(Conv1D(num_filters=32, kernel_size=3, padding='same'))
model.add(MaxPooling1D(pool_size=2))
  • 卷积层在嵌入向量上做特征选择
  • 在多种 NLP 任务上达到了 SOTA 水平
使用 Keras 构建语言建模的循环神经网络(RNN)

示例模型

model = Sequential()
model.add(Embedding(  vocabulary_size, wordvec_dim, trainable=True,
                      embeddings_initializer=Constant(glove_matrix), 
                      input_length=max_text_len, name="Embedding"))

model.add(Dense(wordvec_dim, activation='relu', name="Dense1"))
model.add(Dropout(rate=0.25)) model.add(LSTM(64, return_sequences=True, dropout=0.15, name="LSTM"))
model.add(GRU(64, return_sequences=False, dropout=0.15, name="GRU"))
model.add(Dense(64, name="Dense2")) model.add(Dropout(rate=0.25)) model.add(Dense(32, name="Dense3"))
model.add(Dense(1, activation='sigmoid', name="Output"))
使用 Keras 构建语言建模的循环神经网络(RNN)

开始练习吧!

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

Preparing Video For Download...