October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

Implement a Keras Bidirectional LSTM on the IMDB Dataset

Implement Keras’s IMDB sentiment example with a 20,000-word vocabulary cap, 200-token sequences, two Bidirectional LSTMs, and a sigmoid classifier.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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
Sale
Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems
  • 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.

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
inputs = 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.

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:

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.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

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
Sale
The Phonics Machine Learning Pad
  • 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.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.