Skip to content

Instantly share code, notes, and snippets.

@nervanazoo nervanazoo/
Last active May 7, 2016

What would you like to do?
neon IMDB sentiment classification implementation


This is an implementation of a LSTM model to solve the IMDB sentiment classification task.

Model script

The model run script is included below (

Trained weights

The trained weights file can be downloaded from AWS using the following link: imdb_lstm.p.


This model is acheiving 94.3% and 84.5% accuracy on the training and validation set, respectively.


Neon version: commit SHA e7ab2c2e2. Make sure that your local repo is synced to this commit and run the installation procedure before proceeding.

If neon is installed into a virtualenv, make sure that it is activated before running the commands below. Also, the commands below use the GPU backend by default so add -b cpu if you are running on a system without a compatible GPU.

To train the model from scratch for 2 epochs, use the command:

python -b gpu -e 2 -eval 1 -r 0 -s imdb_lstm.p

Additional options are available to add features like saving checkpoints and displaying logging information, use the --help option for details.


When Are Tree Structures Necessary for Deep Learning of Representations?
Jiwei Li, Dan Jurafsky and Eduard Hovy
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright 2015 Nervana Systems Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# See the License for the specific language governing permissions and
# limitations under the License.
# ----------------------------------------------------------------------------
Example that trains an LSTM or GRU networks for sentiment analysis
See J.Li et al, EMNLP2015 -
$ python examples/ -e 2 -eval 1 --rlayer_type lstm
from neon.backends import gen_backend
from import load_imdb
from import ArrayIterator
from import pad_data
from neon.initializers import Uniform, GlorotUniform
from neon.layers import (GeneralizedCost, LSTM, Affine, Dropout, LookupTable,
RecurrentSum, Recurrent, DeepBiLSTM, DeepBiRNN)
from neon.models import Model
from neon.optimizers import Adagrad
from neon.transforms import Logistic, Tanh, Softmax, CrossEntropyMulti, Accuracy
from neon.callbacks.callbacks import Callbacks
from neon.util.argparser import NeonArgparser, extract_valid_args
# parse the command line arguments
parser = NeonArgparser(__doc__)
parser.add_argument('--rlayer_type', default='lstm',
choices=['bilstm', 'lstm', 'birnn', 'rnn'],
help='type of recurrent layer to use (lstm, bilstm, rnn, birnn)')
args = parser.parse_args(gen_be=False)
# hyperparameters from the reference
args.batch_size = 128
gradient_clip_value = 15
vocab_size = 20000
sentence_length = 128
embedding_dim = 128
hidden_size = 128
reset_cells = True
# setup backend
be = gen_backend(**extract_valid_args(args, gen_backend))
# make dataset
path = load_imdb(path=args.data_dir)
(X_train, y_train), (X_test, y_test), nclass = pad_data(path,
print "Vocab size - ", vocab_size
print "Sentence Length - ", sentence_length
print "# of train sentences", X_train.shape[0]
print "# of test sentence", X_test.shape[0]
train_set = ArrayIterator(X_train, y_train, nclass=2)
valid_set = ArrayIterator(X_test, y_test, nclass=2)
# weight initialization
uni = Uniform(low=-0.1/embedding_dim, high=0.1/embedding_dim)
g_uni = GlorotUniform()
if args.rlayer_type == 'lstm':
rlayer = LSTM(hidden_size, g_uni, activation=Tanh(),
gate_activation=Logistic(), reset_cells=True)
elif args.rlayer_type == 'bilstm':
rlayer = DeepBiLSTM(hidden_size, g_uni, activation=Tanh(), depth=1,
gate_activation=Logistic(), reset_cells=True)
elif args.rlayer_type == 'rnn':
rlayer = Recurrent(hidden_size, g_uni, activation=Tanh(), reset_cells=True)
elif args.rlayer_type == 'birnn':
rlayer = DeepBiRNN(hidden_size, g_uni, activation=Tanh(), depth=1, reset_cells=True)
layers = [
LookupTable(vocab_size=vocab_size, embedding_dim=embedding_dim, init=uni),
Affine(2, g_uni, bias=g_uni, activation=Softmax())
model = Model(layers=layers)
cost = GeneralizedCost(costfunc=CrossEntropyMulti(usebits=True))
optimizer = Adagrad(learning_rate=0.01, gradient_clip_value=gradient_clip_value)
# configure callbacks
callbacks = Callbacks(model, eval_set=valid_set, **args.callback_args)
# train model, optimizer=optimizer, num_epochs=args.epochs, cost=cost, callbacks=callbacks)
# eval model
print "Train Accuracy - ", 100 * model.eval(train_set, metric=Accuracy())
print "Test Accuracy - ", 100 * model.eval(valid_set, metric=Accuracy())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.