This Keras example trains a binary sentiment classifier on pre-indexed IMDB movie reviews. It caps the vocabulary at 20,000 words, truncates or pads every review to 200 tokens, and passes the resulting sequences through an embedding layer and two bidirectional LSTMs. The values and performance below describe the published example, not a guaranteed result for a different run.
What the example builds
The Keras Bidirectional LSTM on IMDB example uses a Functional model. Its input is a sequence of integer word indexes. An embedding layer maps each index to a 128-dimensional vector, then two bidirectional LSTM layers process the sequence. A one-unit Dense layer with sigmoid activation returns a score for the positive class.
As an Amazon Associate I earn from qualifying purchases.
The first recurrent layer sets return_sequences=True, so it returns an output at every time step for the next LSTM. The second layer produces a final representation for the classifier. The example’s model summary reports 2,757,761 total parameters.
Load and prepare the IMDB data
The Keras IMDB dataset contains positive and negative reviews represented as integer word indexes, with a binary label for each review. It is not raw review text. The IMDB dataset API documents options for limiting the vocabulary, truncating reviews, setting a shuffle seed, and configuring the start, out-of-vocabulary, and index-offset values. Zero is reserved for padding by convention; decoding indexes into words requires the corresponding mapping and special-token settings.
#1 Best Overall
- Use scikit-learn to track an example ML project end to end
- Explore several models, including support vector machines, decision trees, random forests, and ensemble methods
- Exploit unsupervised learning techniques such as dimensionality reduction, clustering, and anomaly detection
- Dive into neural net architectures, including convolutional nets, recurrent nets, generative adversarial networks, autoencoders, diffusion models, and transformers
- Use TensorFlow and Keras to build and train neural nets for computer vision, natural language processing, generative models, and deep reinforcement learning
The example uses max_features = 20000 and maxlen = 200. It loads the pre-indexed data and pads both splits to the same length:
import keras
from keras import layers
max_features = 20000
maxlen = 200
(x_train, y_train), (x_val, y_val) = keras.datasets.imdb.load_data(
num_words=max_features
)
x_train = keras.utils.pad_sequences(x_train, maxlen=maxlen)
x_val = keras.utils.pad_sequences(x_val, maxlen=maxlen)
In the example, each split contains 25,000 sequences. With a maximum length of 200, sequences longer than that are truncated and shorter ones are padded. This is a modeling choice: the discarded tokens cannot contribute to the prediction, while padding lets the model process fixed-length batches.
Rank #2
Build, compile, and train the model
In this architecture, the first bidirectional layer must return sequences so that the second recurrent layer receives a time series rather than only one final vector. The Keras Bidirectional API wraps a compatible sequence-processing RNN such as LSTM.
Windows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallOutdated Drivers Are Slowing You Down
One free scan finds every outdated or missing driver and matches the right update for your exact hardware.Free scan · exact hardware matchinputs = keras.Input(shape=(None,), dtype="int32")
x = layers.Embedding(max_features, 128)(inputs)
x = layers.Bidirectional(layers.LSTM(64, return_sequences=True))(x)
x = layers.Bidirectional(layers.LSTM(64))(x)
outputs = layers.Dense(1, activation="sigmoid")(x)
model = keras.Model(inputs, outputs)
model.compile(
optimizer="adam",
loss="binary_crossentropy",
metrics=["accuracy"],
)
model.fit(x_train, y_train, batch_size=32, epochs=2, validation_data=(x_val, y_val))
The displayed example run trains for two epochs with batch size 32, using Adam, binary cross-entropy, and accuracy. The `Input` shape has a variable sequence dimension; the loaded arrays are nevertheless padded to 200 tokens by the preceding data-preparation step.
Rank #3
One detail matters when reusing layers: passing an existing RNN instance into `Bidirectional` does not reuse that instance’s weights. The wrapper initializes fresh forward and backward weights, as noted in the Bidirectional API documentation.
Understand the reported results
The Keras example page, created and last modified May 3, 2020, displays these validation metrics for its run:
Rank #4
| Epoch | Validation accuracy | Validation loss |
|---|---|---|
| 1 | 0.8269 | 0.4202 |
| 2 | 0.8428 | 0.3650 |
These are the figures shown for that example run, not a stable benchmark or a promise for other versions, hardware, random seeds, or reruns.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
Adapt the workflow carefully
When starting from raw text
This recipe starts with Keras’s pre-indexed dataset. If instead you build a pipeline from raw text, tokenization and vocabulary creation become part of preprocessing and must match the model’s input representation. For validation-based hyperparameter tuning, Keras’s text classification from scratch example advises controlling the split with a seed or shuffle=False when using validation_split and subset, so training and validation do not overlap.
Best Value
- THE FASTEST WAY TO PHONICS MASTERY - Teach and Learn Phonics with Audio Sounds, learners get to see the spelling pattern and hear the related phonetic sounds. The audio reinforcement demonstrates the content and solidifies the learning quicker than flash cards and workbooks.
- PHONICS SYSTEM QUIZZES THEM IN 13 STEPS - The electronic phonics workbook starts with single letter sounds like a, b and c. This progresses through short and long vowel sounds, consonant digraphs, trigraphs, diphthongs, bossy R, silent letters and irregular phonics.
- TEST AND BUILD PHONEMIC AWARENESS - Our Educational Learn to Read Machine challenges them to find words which contain a particular phonetic sound or pick out phonetic sounds from the given vocabulary. All created with American English Audio.
- LEARNING THAT CHILDREN ENJOY - The Screenless Educational Tablet With Talking Flash Cards tests and quizzes children on their reading and phonics knowledge while correcting errors and compounding knowledge, all the while putting a smile on their face.
- UNLOCK YOUR CHILD'S POTENTIAL WITH BAMBINO TREE! - From numbers and pictures bingo to letter flashcards and phonics games, we offer a variety of learning materials and games for children with effective tested teaching strategies.
When changing sequence or vocabulary limits
Increasing the vocabulary cap or sequence length changes the inputs the model can see and can affect memory use and training behavior. The example’s 20,000-word cap and 200-token length are specific choices, not universal settings. When comparing alternatives, use the same data split and evaluation setup; the example does not establish a head-to-head advantage over another model.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




