"""
Training and evaluating an LSTM using reversed sequences
"""
from keras import layers
from keras.datasets import imdb
from keras.models import Sequential
from keras.preprocessing import sequence


# Number of words to consider as features
max_features = 10000
# Cuts off texts after this number of words (among the max_features most common words)
maxlen = 500
# Loads data
(x_train, y_train), (x_test, y_test) = imdb.load_data(
    num_words=max_features
)
# Reverses sequences
x_train = [x[::-1] for x in x_train]
x_test = [x[::-1] for x in x_test]
# Pads sequences
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
model = model.Sequential()
model.add(layers.Embedding(max_features, 128))
model.add(layers.LSTM(32))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(
    optimizer='rmsprop',
    loss='binary_crossentropy',
    metrics=['acc']
)
history = model.fit(
    x_train,
    y_train,
    epochs=10,
    batch_size=128,
    validation_split=0.2
)

"""
Training and evaluating an LSTM using reversed sequences
"""
from keras import layers
from keras.datasets import imdb
from keras.models import Sequential
from keras.preprocessing import sequence


# Number of words to consider as features
max_features = 10000
# Cuts off texts after this number of words (among the max_features most common words)
maxlen = 500
# Loads data
(x_train, y_train), (x_test, y_test) = imdb.load_data(
    num_words=max_features
)
# Reverses sequences
x_train = [x[::-1] for x in x_train]
x_test = [x[::-1] for x in x_test]
# Pads sequences
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
model = model.Sequential()
model.add(layers.Embedding(max_features, 128))
model.add(layers.LSTM(32))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(
    optimizer='rmsprop',
    loss='binary_crossentropy',
    metrics=['acc']
)
history = model.fit(
    x_train,
    y_train,
    epochs=10,
    batch_size=128,
    validation_split=0.2
)

Training and evaluating an LSTM using reversed sequences # Number of words to consider as features # Cuts off texts after this number of words (among the max_features most common words) # Loads data # Reverses sequences # Pads sequences