How to forecast using the Tensorflow model?
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
Forecasting with TensorFlow is straightforward once you separate three concerns: data windowing, model inference, and post-processing. Many “bad forecast” issues come from mismatched shapes or using input scaling differently at training and inference time. Another frequent mistake is confusing one-step prediction with recursive multi-step forecasting. In production, your forecasting pipeline should make these choices explicit so behavior is predictable and reproducible. This guide shows a practical pattern for running forecasts from a trained TensorFlow model, including preparing the latest sequence, generating multiple future steps, and converting predictions back to the original scale for interpretation.
Core Sections
1. Prepare the input window exactly like training
If your model was trained on windows of length lookback, inference must use that same shape. For an LSTM with one feature, shape is (batch, lookback, 1).
If you trained with a persisted scaler, load and reuse it. Refitting a scaler on different data changes the meaning of model outputs.
2. Multi-step forecasting with recursive inference
To predict multiple future points, append each predicted value to the window and predict again.
Recursive inference is simple, but error compounds over horizon. If long-horizon accuracy matters, consider a model trained for direct multi-output forecasting.
3. Handle multivariate features carefully
For multiple features, maintain the feature ordering used during training. If only one target is predicted, you may need a custom inverse transform pipeline. A safe approach is to store metadata: feature names, scaling strategy, lookback, and target index alongside the model artifact.
4. Validate forecast quality before deployment
Use a walk-forward validation split where each prediction uses only past data. Compute metrics aligned with your objective: MAE for absolute error, RMSE for larger-error penalty, MAPE for relative error (when values are not near zero).
Also inspect prediction drift during seasonal transitions. Numeric metrics alone can hide temporal bias.
5. Production checklist
Bundle the model with its preprocessing artifacts, enforce input shape checks, and log forecast inputs and outputs for debugging. Keep versioned model IDs so you can trace anomalies back to specific training runs.
Validation and production readiness
A reliable implementation should include more than a working snippet. Add a small reproducible dataset or input fixture that exercises expected behavior and edge cases, then codify it in automated tests. Include at least one “happy path,” one malformed input case, and one boundary condition so regressions are caught early. Instrument key steps with structured logs or metrics to make failures diagnosable in runtime environments, not just local development. If performance is relevant, keep a lightweight benchmark that can be rerun after refactors to ensure behavior stays within budget.
Operationally, document assumptions near the code: required library versions, environment variables, timezone/locale expectations, and failure handling strategy. For team workflows, add one integration test that mirrors real usage rather than only unit-level checks. This reduces drift between example code and production behavior. Treat these checks as part of feature completion, because most long-term issues are caused by unvalidated assumptions rather than syntax errors.
Common Pitfalls
- Feeding raw values at inference when training used scaled inputs.
- Using the wrong tensor shape, especially missing batch or feature dimensions.
- Mixing feature column order between training and prediction pipelines.
- Expecting stable long-horizon accuracy from a one-step recursive model without evaluation.
- Inverse-transforming predictions with a different scaler than the training scaler.
Summary
TensorFlow forecasting works reliably when inference mirrors training: same lookback, same scaling, same feature order, and clear horizon strategy. Start with a one-step model, implement recursive prediction for short horizons, and validate with walk-forward testing. If forecast drift appears, inspect preprocessing consistency before changing model architecture. A disciplined pipeline with versioned artifacts and shape checks is usually the difference between a demo and a production-grade forecasting system.
Related reading
- How to freeze lf-net tensorflow model to use it with opencv dnn?
- How to freeze weights in certain layer with Keras?
- How to freeze weights in certain layer with Keras?
- How to freeze/lock weights of one TensorFlow variable e.g., one CNN kernel of one layer
- How to generate a train-test-split based on a group id?
- How to generate random number in a given range as a Tensorflow variable
- How to get a tensorflow op by name?
- How to get accuracy of model using keras?
.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.