Forecast future values with LSTM in Python
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
LSTMs are often used for sequence forecasting because they can learn patterns across time windows instead of treating each row as independent. The practical workflow is straightforward: turn the series into input windows, train on past-to-next-step examples, then roll the model forward to predict future values.
Prepare the Series as Sliding Windows
An LSTM expects a 3D tensor in the shape samples, timesteps, features. For a univariate time series, features is usually 1.
The function below turns one numeric series into training windows.
This creates examples such as "given the last 20 values, predict the next one." That one-step setup is often the easiest place to start.
Train a Simple LSTM Model
A small Keras model is enough to demonstrate the pattern.
This is a one-step forecasting model. It learns to predict the next value after each input window.
Forecast Multiple Future Steps
To forecast beyond the next step, take the most recent window, predict one value, append that prediction, and slide the window forward. This is often called recursive forecasting.
This is simple and useful, but remember the tradeoff: prediction errors can accumulate because each new forecast becomes part of the next input.
Data Preparation Matters More Than Architecture Tweaks
LSTM examples often overemphasize layer choices and underemphasize data preparation. In real forecasting work, the following decisions matter at least as much as the network depth:
- use chronological train-test splits, not random shuffles
- scale the series if the magnitude changes widely
- choose a window size that matches the problem's memory horizon
- compare against simple baselines such as "predict the previous value"
If a naive baseline beats the LSTM, the problem is probably in the framing, features, or training setup rather than the lack of a more complex network.
When LSTM Is and Is Not a Good Fit
LSTMs can work well when the target depends on temporal context and you have enough sequential data to learn stable patterns. They are less compelling when the series is short, mostly linear, or dominated by strong seasonal structure that simpler models already capture.
That is why a good workflow starts with a small baseline and only then moves to recurrent models.
Common Pitfalls
Randomly shuffling time-series examples is a frequent mistake because it leaks future structure into training.
Using too short a window can hide important history. Using too long a window can make the model harder to train without adding useful information.
Forecasting many steps recursively without understanding error accumulation is another common problem. Multi-step prediction looks impressive, but the uncertainty grows quickly.
Finally, do not skip a baseline. If a simple persistence forecast performs almost as well as the LSTM, the extra model complexity may not be justified.
Summary
- convert the series into sliding windows with shape
samples, timesteps, features - train the LSTM to predict the next value from each window
- for multi-step forecasting, roll the model forward recursively one prediction at a time
- preserve chronological order in train-test splits
- always compare LSTM results against simple forecasting baselines before trusting the added complexity
Related reading
- from keras.backend.tensorflow_backend import set_session
- from_logitsTrue and from_logitsFalse get different training result for tf.losses.CategoricalCrossentropy for UNet
- Full gradient descent in keras
- Fully-connected layer weight dimensions in TensorFlow ConvNet
- freeze some variables/scopes in tensorflow stop_gradient vs passing variables to minimize
- Freezing graph to pb in Tensorflow2
- Format / Suppress Scientific Notation from Pandas Aggregation Results
- Format numbers in django templates
.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.