Forecasting energy demand with LSTMs, starting with the data
How we built 30-day energy demand forecasts for twenty customer segments: profiling the data first, calendar and lag features, a CNN-LSTM, leak-aware validation and honest per-day error.
In 2020 we were asked a question that sounds simple: how much energy will each kind of customer draw from the network over the next thirty days? Residential, commercial, industrial, time-of-use, controlled load, street lighting, solar export. Each one behaves differently, and the people planning the network wanted a number for each, every day, a month ahead.
We built it for Essential Energy as a set of deep-learning models, one per customer segment, trained on more than four years of daily metering data and served as an API. This post covers how, and starts where every one of these projects should start: before the model.
Step zero: profile the data
The year before, we had spent time on a less glamorous job: profiling Essential Energy's asset management database to find out which attributes were actually filled in. We dumped every table to Parquet, picked the transformer categories, and produced a missing-value matrix: for each type of transformer, the percentage of each column that was empty. Profiling reports flagged columns so strongly correlated with others that they added nothing. An audit workbook covering the same attributes gave us something to check the automated profile against.
None of that is machine learning. All of it decides whether machine learning will work. A model trained on a column that is mostly empty for one asset type learns the gaps, not the asset. The habits we built there carried straight into forecasting:
- Know the holes. Metering data has missing days. We made the series strictly daily and forward-filled gaps, and dropped any day with no target value rather than invent one.
- Know the outliers. Values beyond set thresholds were blanked and interpolated from their neighbours, not deleted.
- Know what you'll have at prediction time. More on that below, because it is the most common way forecasts lie.
Architecture
BigQuery: daily MWh by segment + calendar flags (stored procedure)
-> repository (BigQuery or CSV, chosen by config)
-> preprocessor: daily frequency, holidays, seasons, lags, rolling means
-> scalers fitted on training data only (features and target separately)
-> sliding windows: 30 days in -> 30 days out
-> Conv1D -> stacked LSTM -> Dense(30)
-> build artefacts per segment: model, best checkpoint, scalers, validation error
-> predict: forecast + error band -> JSON + BigQuery forecast table -> Power BI
-> Flask API in Docker behind nginx: GET /predict/<segment>/<date> - Twenty JSON configs, one per segment, each naming the tariff codes it aggregates and its model settings. One codebase, twenty forecasts.
- Swappable parts. Model, trainer, predictor, preprocessor and data repository are chosen by name through a small factory. We started from an open-source Keras project template and built this structure on top.
Features: the calendar and the past
Energy demand is mostly a story about the calendar and about recent history. The production feature set reflected that:
- Calendar flags: public holiday, school holiday (NSW school terms) and weekend.
- Season, one-hot encoded, with all four columns always present so the feature count never changes when a training slice happens to miss a season.
- Week, month and year.
- Lags of the target: yesterday, the same day last week and the same day last year.
- Rolling means: weekly and monthly.
Here is the part of the preprocessor that handles the leak and the lags:
# remove import or export data as won't have this data when predicting
if target_col == 'importmwh':
processed_df.drop(columns=['exportmwh'], inplace=True)
elif target_col == 'exportmwh':
processed_df.drop(columns=['importmwh'], inplace=True)
# configure dataframe as Daily frequency, and impute missing values by forward filling.
processed_df = processed_df.asfreq('D', method='ffill')
# add historical days
for hd in self.config.data_preprocessor.append_historical_days:
# D minus i = current day minus i
processed_df[f'{target_col}_d_minus_{hd}'] = processed_df[target_col].shift(hd, freq='D') The first block is the lesson in four lines. Import and export are measured together, so on a training spreadsheet each looks like a wonderful predictor of the other. On the morning you need a forecast, you have neither. Leave one in and the validation score looks superb, and the forecast is useless.
The 365-day lag earns its place too. Christmas, school holidays and summer peaks recur at the same time each year, and "the same day last year" hands the model that pattern directly, instead of hoping it rediscovers it from a short window.
The model: convolution, then memory
self.model.add(Conv1D(filters=self.config.model.conv_filters, kernel_size=self.config.model.conv_kernel_size,
input_shape=[self.config.model.num_input_steps, self.num_features]))
for idx, layer_inputs in enumerate(self.config.model.lstm_layers):
self.model.add(LSTM(layer_inputs, dropout=self.config.model.dropout,
recurrent_dropout=self.config.model.recurrent_dropout,
return_sequences=(idx != len(self.config.model.lstm_layers) - 1)))
self.model.add(Dense(self.config.model.num_output_steps)) In the production configs that is a 1D convolution with 64 filters over a 7-day kernel, then LSTM layers of 1,200, 900, 600, 300 and 60 units with recurrent dropout, then a dense layer with 30 outputs. Trained with the Adam optimiser on mean absolute error.
Three choices are worth explaining:
- The convolution comes first. A 7-day kernel learns weekly shapes, such as the weekday-weekend cycle, and hands the LSTMs a cleaner signal than raw daily values.
- The output is direct, not recursive. The final layer predicts all thirty days at once. A recursive model predicts tomorrow, feeds that back in and predicts the next day, so its errors compound. A direct model has no such feedback loop.
- Mean absolute error as the loss. It is in the same units as the forecast, MWh per day, which makes it easy to explain to the people using it, and it is less dominated by a few extreme days than squared error.
In notebooks we also tried a single LSTM, a pure CNN and a weighted blend of the two before settling on this shape. Weather features (temperatures, humidity, rainfall, wind gusts) were explored there too, but the production configs stayed with calendar and history.
Validation that doesn't flatter
Time series punish careless validation. The rules we built into the code:
- Hold out the most recent 90 days. Never a random split: the model must be tested on a future it hasn't seen.
- Fit scalers on training data only, so the validation period leaks nothing about its own range.
- Refuse impossible setups. The preprocessor raises an error if the validation period is shorter than the input window plus twice the forecast horizon, because otherwise you aren't really validating thirty days ahead.
- Score every horizon separately. Error for day 1 is not error for day 30. We reported R² and MAE for each of the thirty steps, and charted each with an error band.
Training ran with checkpoints on the best validation loss, a learning rate that backed off on plateaus, and early stopping, so long training budgets didn't turn into overfitting. Every build saved its model, scalers and validation error together, so a forecast could always be traced to the exact artefacts that made it.
Where AI fits
This was the AI: deep learning on real operational data, served as an API, with forecasts written back to the warehouse for reporting. The engineering lesson is that the network was the smaller part of the work. Data profiling, feature design, leak prevention and honest validation took most of the effort and made most of the difference.
If we built it today we'd add one thing first: a simple baseline, such as "the same day last year, adjusted by recent growth", scored the same way. A deep model has to beat the obvious answer by enough to justify itself. Our code computed the model's error carefully; it didn't compare it with the obvious answer, and it should have.
What it taught us
Alongside the models we wrote the data-science strategy prerequisites and machine-learning guidelines for the program: the lifecycle, versioning, model monitoring and CI/CD for ML. The view behind them was that agile delivery alone fits data science poorly, because an experiment can succeed or fail on the data before anyone writes a feature.
In the code, that showed up as separate train, test and predict entry points, fixed random seeds, one config per experiment and versioned build artefacts. None of it is clever. All of it is what lets a second person rerun your result.
Why it still matters
Forecasting demand, stock, staffing or failures is still one of the most useful things machine learning does for an organisation, and still one of the easiest to get subtly wrong. Start with the data, design features from what you'll know on the day, and validate like a sceptic. See our predictive AI work, or the forecasting case study.