Keras:LSTM和GRU示例


Keras:LSTM和GRU示例

长短期记忆网络(LSTM)是一种循环神经网络体系结构,解决了不同网络执行之间的梯度消失问题。LSTM是由Sepp Hochreiter和Jurger Schmidhuber在1997年开发的,本质上是为网络添加了一个优先通道,称为单元状态或存储单元,该通道与网络信号并行传输并存储序列信息。

在本文中,我们将使用LSTM改进神经网络,以在IMDB电影评论数据集上训练情感分析。

<code>from time import timeimport numpy as npimport matplotlib.pyplot as pltfrom keras.utils import to_categoricalfrom keras.models import Sequentialfrom keras.layers import Dense/<code>

机器学习数据集

我们使用Keras加载imdb机器学习数据集,将其限制为10000个最常用的单词。

<code>from keras.datasets import imdb num_words = 10000(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=num_words)print("Number of exemples train set: %d" % len(X_train))print("Number of exemples test set: %d" % len(X_test))/<code>
Keras:LSTM和GRU示例

预处理数据

文本语料库中的评论显然具有不同的长度,我们使用keras的pad_sequences函数将序列限制为500个元素(在我们的情况下为500个单词)。如果一个序列的示例数少于500,则将在末尾添加零

<code>from keras.preprocessing.sequence import pad_sequencesmaxlen = 500X_train = pad_sequences(X_train, maxlen = maxlen)X_test = pad_sequences(X_test, maxlen = maxlen)/<code>

我们创建LSTM模型

我们以这种方式建立机器学习模型:

第一层将为字典中的10,000个单词创建50个嵌入向量。

第二层是循环长短期记忆层。

第三层计算网络输出,为二分类问题,激活函数为sigmoid。

<code>from keras.layers import Embedding, LSTMmodel = Sequential()model.add(Embedding(num_words, 50))model.add(LSTM(32))model.add(Dense(1, activation='sigmoid'))/<code>

我们拟合机器学习模型并训练5个epochs。

<code>model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])model.fit(X_train, y_train, batch_size=512, validation_split=0.2, epochs=5)model.evaluate(X_test, y_test)/<code>
Keras:LSTM和GRU示例

结果比简单的RNN好得多,存在一些过拟合现象,让我们尝试使用dropout对其进行校正。

RNN中的Dropout

要在循环层的输入上使用dropout,而不是使用dropout类,建议使用SimpleRNN和LSTM类的dropout参数。要使用recurrent dropout,可以使用SimpleRNN和LSTM类的recurrent_dropout参数

<code>from keras.layers import Embedding, LSTM, Dropoutmodel = Sequential()model.add(Embedding(num_words, 50))model.add(LSTM(32, dropout=0.4, recurrent_dropout=0.2))model.add(Dropout(0.4))model.add(Dense(1, activation='sigmoid'))/<code>

我们拟合机器学习模型并训练5个epochs

<code>model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])model.fit(X_train, y_train, batch_size=512, validation_split=0.2, epochs=5)model.evaluate(X_test, y_test)/<code>
Keras:LSTM和GRU示例

我们减少了网络中的过度拟合,现在我们尝试通过向网络中添加其他层来改进神经网络模型。

让我们添加更多的LSTM层

我们可以使用Sequential类的add方法将其他循环层添加到网络中。默认情况下,LSTM类flattens序列,将其作为dense层的输入,我们可以通过将return_sequences参数设置为True来更改此行为。

<code>from keras.layers import Embedding, LSTM, Dropoutmodel = Sequential()model.add(Embedding(num_words, 100))model.add(LSTM(32, dropout=0.5, recurrent_dropout=0.2, return_sequences=True))model.add(LSTM(32, dropout=0.5, recurrent_dropout=0.2))model.add(Dropout(0.5))model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])start_at = time()model.fit(X_train, y_train, batch_size=512, validation_split=0.2, epochs=5)model.evaluate(X_test, y_test)/<code>
Keras:LSTM和GRU示例

门控循环单元(GRU)

门控循环单元(GRU)是一种循环神经网络,可从LSTM中获取提示并对其进行简化。与LSTM不同,门控循环单元(GRU)需要较少的张量计算,因此通常可以在更短的时间内得到相似的结果。我们可以通过GRU类在Keras中添加GRU层,让我们使用与深层LSTM网络相同的架构来实现它。

<code>from keras.layers import Embedding, GRU, Dropoutmodel = Sequential()model.add(Embedding(num_words, 100))model.add(GRU(32, dropout=0.5, recurrent_dropout=0.2, return_sequences=True))model.add(GRU(32, dropout=0.5, recurrent_dropout=0.2))model.add(Dropout(0.5))model.add(Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['accuracy'])start_at = time()model.fit(X_train, y_train, batch_size=512, validation_split=0.2, epochs=5)model.evaluate(X_test, y_test)/<code>
Keras:LSTM和GRU示例

结果明显低于LSTM,但训练时间减少了20%。


分享到:


相關文章: