Trains an LSTM model on the IMDB sentiment classification task.

The dataset is actually too small for LSTM to be of any advantagecompared 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 differentfrom what you see with CNNs/MLPs/etc.

  1. from __future__ import print_function
  2. from keras.preprocessing import sequence
  3. from keras.models import Sequential
  4. from keras.layers import Dense, Embedding
  5. from keras.layers import LSTM
  6. from keras.datasets import imdb
  7. max_features = 20000
  8. # cut texts after this number of words (among top max_features most common words)
  9. maxlen = 80
  10. batch_size = 32
  11. print('Loading data...')
  12. (x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
  13. print(len(x_train), 'train sequences')
  14. print(len(x_test), 'test sequences')
  15. print('Pad sequences (samples x time)')
  16. x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
  17. x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
  18. print('x_train shape:', x_train.shape)
  19. print('x_test shape:', x_test.shape)
  20. print('Build model...')
  21. model = Sequential()
  22. model.add(Embedding(max_features, 128))
  23. model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2))
  24. model.add(Dense(1, activation='sigmoid'))
  25. # try using different optimizers and different optimizer configs
  26. model.compile(loss='binary_crossentropy',
  27. optimizer='adam',
  28. metrics=['accuracy'])
  29. print('Train...')
  30. model.fit(x_train, y_train,
  31. batch_size=batch_size,
  32. epochs=15,
  33. validation_data=(x_test, y_test))
  34. score, acc = model.evaluate(x_test, y_test,
  35. batch_size=batch_size)
  36. print('Test score:', score)
  37. print('Test accuracy:', acc)