Last active
August 19, 2018 06:22
-
-
Save arjun-kava/4e08c8c1056785d9b0d7581d724dc08f to your computer and use it in GitHub Desktop.
Simple LSTM example using keras
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(num_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(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, | |
epochs=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) | |
model.save("polarity_model.h5") | |
word2index = imdb.get_word_index() | |
model= load_model("polarity_model.h5") | |
#predict sentiment from reviews | |
bad = "you know even better than them that you have potential! Stop portraying in parody movies!" | |
good = "Great movie I had ever watched." | |
for review in [good,bad]: | |
test=[] | |
for word in text_to_word_sequence(review): | |
test.append(word2index[word]) | |
test=sequence.pad_sequences([test],maxlen=max_review_length) | |
model.predict(test) | |
print("%s. Sentiment: %s" % (review, model.predict(test))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment