Keras LSTM model for binary classification with sequences
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.
Introduction
An LSTM is a reasonable baseline for binary classification when each example is a sequence, such as a sentence, a clickstream, or a sensor window. The model reads the sequence order, compresses useful temporal information, and outputs a probability for one of two classes.
The structure is simple, but most failures come from input preparation rather than the LSTM layer itself. Sequence padding, masking, label shape, and the final activation all need to line up.
What the Model Should Look Like
For binary classification, the usual Keras pattern is:
- sequence input
- one or more recurrent layers
- a final dense layer with one unit
- sigmoid activation
- '
binary_crossentropyloss'
If the inputs are token IDs, an Embedding layer usually comes first. If the inputs are already numeric feature vectors per timestep, you can feed them directly into the LSTM.
A Runnable Example with Padded Integer Sequences
This example uses mask_zero=True, which tells Keras to ignore the padded zeros when the LSTM reads the sequence.
Input Shape Rules
LSTM layers expect a three-dimensional tensor:
- batch size
- timesteps
- features
When you use an Embedding layer, Keras converts integer token IDs shaped like (batch, timesteps) into embedded vectors shaped like (batch, timesteps, embedding_dim). If you skip embeddings and provide numeric features directly, your input should already be three-dimensional.
For binary labels, the target can usually be shaped as either (batch,) or (batch, 1) as long as the final layer has one sigmoid unit.
When To Use return_sequences
If there is only one LSTM layer and you want one final classification per sequence, leave return_sequences=False, which is the default. That returns only the last output state.
If you stack LSTM layers, all but the last recurrent layer usually need:
Without that setting, the next recurrent layer will not receive a full sequence.
Practical Improvements
A basic LSTM often benefits from:
- dropout on the recurrent stack
- validation splitting and early stopping
- class weighting if labels are imbalanced
- proper tokenization and vocabulary control
Example of adding regularization:
Use this only after the base pipeline is correct. Regularization will not fix broken shapes or mislabeled targets.
Common Pitfalls
- Using two output units with
sigmoidfor a binary problem when one output unit is enough. - Forgetting to pad sequences to a consistent length for batch training.
- Padding with zeros but not enabling masking when zeros are only placeholders.
- Feeding labels with the wrong shape or datatype for
binary_crossentropy. - Stacking LSTM layers without
return_sequences=Trueon intermediate layers.
Summary
- A binary sequence classifier in Keras usually ends with one sigmoid output and
binary_crossentropy. - '
EmbeddingplusLSTMis a standard pattern for tokenized sequences.' - Padding and masking are critical for variable-length inputs.
- Shape mismatches are a more common bug than the recurrent layer itself.
- Start with a small working model, then add regularization or deeper sequence stacks.
Related reading
- Keras LSTM Multiple Input Multiple Output
- Keras LSTM neural net TypeError LSTM missing 1 required positional argument 'Y
- Keras LSTM not training
- Keras LSTM predicted timeseries squashed and shifted
- Keras LSTM Time Series
- Keras Making a neural network to find a number's modulus
- Keras Making a neural network to find a number's modulus
- Keras Masking and Flattening
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
ML System Design practice on Codemia
Design recommenders, ranking systems and training pipelines the way ML interviews actually ask for them, with worked solutions.