In [1]:
import numpy as np
from keras.datasets import imdb
from keras.models import Sequential
from keras.layers import Dense, Flatten
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence


Using TensorFlow backend.

In [2]:
np.random.seed(7)

In [3]:
top_words = 5000
(X_train, y_train), (X_test, y_test) = imdb.load_data(num_words=top_words, seed=7)

In [4]:
X_train = sequence.pad_sequences(X_train, maxlen=500)
X_test = sequence.pad_sequences(X_test, maxlen=500)

In [5]:
def build_model():
    model = Sequential()
    model.add(Embedding(top_words, 32, input_length=500))
    model.add(Flatten())
    model.add(Dense(250, activation='relu'))
    model.add(Dense(1, activation='sigmoid'))
    model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

In [6]:
model = build_model()

In [7]:
model.fit(X_train, y_train, validation_data=(X_test, y_test),
          epochs=2, batch_size=64,  verbose=1)
scores = model.evaluate(X_test, y_test, verbose=0)
print(scores[1] * 100)


Train on 25000 samples, validate on 25000 samples
Epoch 1/2
25000/25000 [==============================] - 56s - loss: 0.4446 - acc: 0.7656 - val_loss: 0.2848 - val_acc: 0.8797
Epoch 2/2
25000/25000 [==============================] - 84s - loss: 0.1560 - acc: 0.9445 - val_loss: 0.3332 - val_acc: 0.8694
86.936

In [12]:
from keras.layers.convolutional import Convolution1D
from keras.layers.convolutional import MaxPooling1D
from keras.layers import Dropout

In [15]:
def create_cnn():
    model = Sequential()
    model.add(Dropout(0.2, input_shape=(top_words,)))
    model.add(Embedding(top_words, 32, input_length=max_words))
    model.add(Convolution1D(nb_filter=32, filter_length=3, border_mode= 'same', activation= 'relu' ))
    model.add(MaxPooling1D(pool_length=2))
    model.add(Flatten())
    model.add(Dropout(0.3))
    model.add(Dense(250, activation= 'relu' ))
    model.add(Dense(1, activation= 'sigmoid' ))
    model.compile(loss= 'binary_crossentropy' , optimizer= 'adam' , metrics=['accuracy'])
    return model
    
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=2, batch_size=128, verbose=1)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Accuracy:", scores[1]*100)


Train on 25000 samples, validate on 25000 samples
Epoch 1/2
25000/25000 [==============================] - 68s - loss: 1.0830e-04 - acc: 1.0000 - val_loss: 0.7315 - val_acc: 0.8640
Epoch 2/2
25000/25000 [==============================] - 92s - loss: 8.9186e-05 - acc: 1.0000 - val_loss: 0.7421 - val_acc: 0.8642
Accuracy: 86.416