本例子是“IMDB sentiment classification task”,用单层LSTM实现。
1. 输入数据预处理
输入文本数据统一规整到长度maxlen=80个单词,为什么呢?
是不是长度太长时训练容易发散掉,这样就限制了记忆的长度了。
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
有没有动态的呢?因为输入的句子长度本身是动态长度的。
2. Embedding layer
代码中,max_features=20000对应的是词汇量大小。
关于Embedding Vector,如果是中文的,怎么处理呢?
在RNN训练过程中Embedding Vector是否也参与了训练呢?如何选择?
3. 关于RNN的模型架构的理解
Embedding Vector是128维的,隐层是128个节点(也可以是其他数值)。
Embedding Vector与隐层的节点是全连接的,隐层每个节点自带存储单元的。
在这个128节点的隐层之上,有一个Dense节点。这个Dense节点是和128节点的隐层全连接的。
Foward过程就是每次输入80个单词中的一个,直到最后一个单词输入结束,Dense节点最终的输出就是估计的Y值了
完整代码如下:
'''Trains a LSTM on the IMDB sentiment classification task.
The dataset is actually too small for LSTM to be of any advantage
compared to simpler, much faster methods such as TF-IDF + LogReg.
Notes:
- RNNs are tricky. Choice of batch size is important,
choice of loss and optimizer is critical, etc.
Some configurations won't converge.
- LSTM loss decrease patterns during training can be quite different
from what you see with CNNs/MLPs/etc.
'''
from __future__ import print_function
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding
from keras.layers import LSTM
from keras.datasets import imdb
max_features = 20000
maxlen = 80 # cut texts after this number of words (among top max_features most common words)
batch_size = 32
print('Loading data...')
(x_train, y_train), (x_test, y_test) = imdb.load_data(nb_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')
print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)
print('Build model...')
model = Sequential()
model.add(Embedding(max_features, 128))
#model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
model.add(LSTM(128))
model.add(Dense(1, activation='sigmoid'))
# try using different optimizers and different optimizer configs
model.compile(loss='binary_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print('Train...')
model.fit(x_train, y_train,
batch_size=batch_size,
nb_epoch=15,
validation_data=(x_test, y_test))
score, acc = model.evaluate(x_test, y_test,
batch_size=batch_size)
print('Test score:', score)
print('Test accuracy:', acc)
通过summary()得到的函数统计如下:
____________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
embedding_3 (Embedding) (None, None, 128) 2560000 embedding_input_1[0][0]
____________________________________________________________________________________________________
lstm_1 (LSTM) (None, 128) 131584 embedding_3[0][0]
____________________________________________________________________________________________________
dense_9 (Dense) (None, 1) 129 lstm_1[0][0]
====================================================================================================
Total params: 2,691,713
Trainable params: 2,691,713
Non-trainable params: 0