LSTM Time Series Forecasting in PyTorch: A Step-by-Step Guide with a Baseline Check

How do you do LSTM time series forecasting in PyTorch?
For LSTM time series forecasting in PyTorch, you split the series by time and cut it into windows of the last 24 hours. A small LSTM (a recurrent network that reads a window one hour at a time) learns to predict the next hour, and you check it against two simple guesses on an unseen week.
It helps plan capacity for an hourly series with a repeating pattern, like a web service’s requests. On our synthetic data, the LSTM missed by 42.6 requests per hour on average, against 54.5 for the better guess.
A recurrent neural network reads a sequence, values in a fixed order, one time step (one position) at a time, and carries what it has read to the next step. The LSTM is one kind of recurrent network.
The theory is in how a recurrent network reads a sequence and how an LSTM works inside. This guide is the hands-on side: you train one LSTM and test it.
You run a web service and log requests per hour: busy afternoons, quiet nights, quieter weekends. To plan capacity, you forecast the next hour. Each row is one hour and its request count. Our data is synthetic, made by a script, so you can rerun every step.
What you need
Python, two packages and a laptop: our whole run took 9 to 14 seconds on a MacBook Air CPU, so you need no GPU. Put these lines in requirements.txt:
torch==2.15.0
numpy==2.5.5
Install and run:
python3 -m venv venv
venv/bin/pip install -r requirements.txt # Python 3.13.14, macOS arm64, CPU only
venv/bin/python make_data.py
venv/bin/python forecast.py 0 # argument = seed
The seed fixes the random starting weights (the numbers the network learns) and the shuffle order.
Step 1: Make the request series
Save this as make_data.py and run it. It writes requests.csv and prints the row count and the lowest and highest count.
import numpy as np
rng = np.random.default_rng(42)
hours = np.arange(12 * 7 * 24) # 2,016 hours = 12 weeks
hour_of_day = hours % 24
day_of_week = (hours // 24) % 7 # 5 and 6 = weekend
daily = 300 * np.sin(2 * np.pi * (hour_of_day - 9) / 24) # peak in the afternoon
weekend = np.where(day_of_week >= 5, -250, 0)
noise = rng.normal(0, 40, len(hours))
spikes = np.zeros(len(hours))
spikes[rng.choice(len(hours), 6, replace=False)] = rng.uniform(200, 500, 6)
requests = np.round(np.maximum(1000 + daily + weekend + noise + spikes, 0))
np.savetxt("requests.csv", np.column_stack([hours, requests]), fmt="%d",
delimiter=",", header="hour,requests", comments="")
print(len(hours), "rows, min", requests.min(), "max", requests.max())
For your own logs, write the same two columns.
Step 2: Split by time, scale on training
y = np.loadtxt("requests.csv", delimiter=",", skiprows=1)[:, 1]
n_train, n_val = len(y) - 2 * 168, 168 # last week = test, week before = validation
mean, std = y[:n_train].mean(), y[:n_train].std() # scaler fitted on TRAINING part only
z = ((y - mean) / std).astype(np.float32)
Training comes first, then a validation week for choosing settings, then the test week, seen once at the end. Scaling subtracts the training mean and divides by the training standard deviation, so counts become small numbers around zero. The trap: scale with all the data, and the test week leaks into training.
Step 3: Cut 24-hour windows
def windows(L, start, end): # targets are hours start..end-1
t = np.arange(start, end)
x = np.stack([z[i - L:i] for i in t])[:, :, None] # (n, L, 1)
return torch.tensor(x), torch.tensor(z[t])[:, None] # (n, L, 1), (n, 1)
A window is the last L hours given as input; its target is the next hour. Why 24? The full script also tries a whole week and keeps whichever scores better on validation. The 24-hour window won, narrowly.
Step 4: Build the LSTM
class Net(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(input_size=1, hidden_size=32, batch_first=True)
self.out = nn.Linear(32, 1)
def forward(self, x):
h, _ = self.lstm(x) # h: (batch, L, 32)
return self.out(h[:, -1, :]) # last hidden state -> (batch, 1)
An LSTM has two memories: the hidden state, a list of numbers carried from step to step, and the cell state, a longer memory. Three gates, sets of numbers, decide how much old memory to keep, how much new input to write and how much to pass on.
In PyTorch’s built-in LSTM, nn.LSTM, batch_first=True sets the input layout to (batch, sequence, features), a batch being a group of windows; the default would read the batch axis as time. h[:, -1, :] takes the hidden state after the last hour, and nn.Linear turns it into one forecast.
input_size=1 is one value per hour; hidden_size sets how many numbers the hidden state holds. The run printed:
shapes: input (64, 24, 1) -> output (64, 1)
One forecast per window.
Step 5: Train and keep the best epoch
This part runs inside the loop over window lengths (for L in (24, 168):) in the full script below.
model = Net()
opt = torch.optim.Adam(model.parameters(), lr=0.005)
loss_fn = nn.MSELoss()
best_val, best_state = 1e9, None
for epoch in range(25):
model.train()
for idx in torch.randperm(len(xtr)).split(64):
opt.zero_grad()
loss = loss_fn(model(xtr[idx]), ytr[idx])
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(xva), yva).item()
print(f"L={L} epoch {epoch+1:2d} train_loss {loss.item():.4f} val_loss {val_loss:.4f}")
if val_loss < best_val:
best_val = val_loss
best_state = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
Training adjusts the weights so the forecasts get closer to the true next hours. An epoch is one pass over all training windows. loss.backward() finds which direction lowers the loss (mean squared error) for every weight; opt.step() moves them with Adam, a standard update rule.
After each epoch the script scores the validation week and keeps the best weights. Our best epoch was the last, so more might help; we did not try.
Step 6: Beat two simple guesses
A baseline is a simple guess to beat. “Last value” repeats the previous hour; “same hour last week” repeats the count from a week earlier. The score is MAE, mean absolute error: the average size of the error, in requests per hour.
def mae(pred_scaled, true_scaled): # back to requests per hour
return float(np.abs((pred_scaled - true_scaled) * std).mean())
val_mae, L, model = best
print(f"chosen L={L} (validation MAE {val_mae:.1f})")
t_end = len(y)
xte, yte = windows(L, t_end - 168, t_end)
with torch.no_grad():
lstm_mae = mae(model(xte).numpy(), yte.numpy())
test_true = y[t_end - 168:]
last_value = np.abs(y[t_end - 169:t_end - 1] - test_true).mean()
same_hour = np.abs(y[t_end - 336:t_end - 168] - test_true).mean()
print(f"TEST MAE LSTM {lstm_mae:.1f} | last value {last_value:.1f} | same hour last week {same_hour:.1f}")
| Test-week forecast | MAE |
|---|---|
| LSTM | 42.6 |
| Same hour last week | 54.5 |
| Last value | 73.8 |
These numbers hold for this synthetic data and setup only.
Mistakes that flatter a forecast
- Shuffling before the split puts test hours among training hours. Split by time first.
- Scaling with all the data: see Step 2.
- Without a baseline, you cannot tell whether an error number is good.
- Tuning on the test week means its score no longer measures new data. Tune on validation; we changed nothing after the first run.
If you only wanted a working LSTM forecast with a baseline check, you can stop here.
What published comparisons found
Our LSTM beat both guesses on clean synthetic data. On real series, published comparisons are mixed: simple and statistical methods won in some, tuned recurrent networks in others, each under its own conditions.
The M4 competition (2018) asked teams to forecast 100,000 real series. Its score, OWA, compares a method’s error with a simple benchmark called Naive2, which scores 1.000; lower is better. In the organisers’ results spreadsheet, the winner, a hybrid method by Slawek Smyl of Uber, scored 0.821, clearly better than that benchmark.
The organisers also ran a plain recurrent network with six simple units, in one fixed configuration. It scored 1.482 and ranked 55th of 59 methods, worse than Naive2, so a small RNN lost to a simple guess.
On the hourly M4 series, the M4 case most like our request series, the organisers’ seasonal naive forecast, which repeats the same hour of the previous day, scored 0.627 against 1.006 for Theta, a classic statistical method.
Makridakis, Spiliotis and Assimakopoulos (journal PLOS ONE, 2018) tested a plain RNN and an LSTM on 1,045 monthly series from the earlier M3 competition. On both accuracy measures and at every forecast horizon, the leading statistical methods (Theta, Comb and ARIMA, all classic statistical methods) were more accurate than every machine-learning method, the plain RNN and the LSTM included.
In that study, the LSTM fitted the training data better than simpler networks but forecast worse, which is why you score on a test week.
Their LSTM was small (six units) and ran on Keras 2.0.9, an older version of a deep-learning library, so a tuned LSTM on current software may do better. Each result was averaged over ten runs.
Hewamalage, Bergmeir and Bandara (preprint, 2020) tuned RNNs automatically and trained each on many series at once. Against ETS and ARIMA, two standard statistical methods, the RNNs won on Wikipedia page traffic (997 daily series), monthly M3 and NN5, a set of 111 daily series; on M3 the gap was not statistically significant.
On the M4 monthly series, ARIMA beat every RNN. Their verdict: RNNs are “no silver bullets” but “competitive alternatives in many situations”. Wikipedia page hits are not requests to one service, yet they are the nearest published case to web traffic that we found, so run the baseline check on your own data before you trust any of these results.
If your model must run on a microcontroller, test a small convolutional network as well: on an ESP32, a 1D convolutional network classified signals more accurately than an LSTM and used less memory and time (Saha and Samanta, preprint, 2026; classification, not forecasting).
How repeatable our numbers are
We ran the code on a MacBook Air CPU with Python 3.13.14, PyTorch 2.15.0 (the current stable release, out since 28 October 2026) and NumPy 2.5.5. Two runs with seed 0 printed identical logs, epoch by epoch, so on this machine the same seed gave the same run twice.
Seed 1 moved the LSTM’s test MAE by 0.1, and the simple guesses do not depend on the seed, so the ranking held.
PyTorch’s reproducibility notes say identical seeds do not guarantee identical results across releases, platforms, or CPU and GPU, so expect small differences on your machine. Two seeds are too few for statistics; they show only that the result stayed within that 0.1.
The full script
This is the whole PyTorch LSTM forecast, forecast.py exactly as it ran. Run make_data.py from Step 1 first.
import sys, time
import numpy as np
import torch
from torch import nn
seed = int(sys.argv[1]) if len(sys.argv) > 1 else 0
y = np.loadtxt("requests.csv", delimiter=",", skiprows=1)[:, 1]
n_train, n_val = len(y) - 2 * 168, 168 # last week = test, week before = validation
mean, std = y[:n_train].mean(), y[:n_train].std() # scaler fitted on TRAINING part only
z = ((y - mean) / std).astype(np.float32)
def windows(L, start, end): # targets are hours start..end-1
t = np.arange(start, end)
x = np.stack([z[i - L:i] for i in t])[:, :, None] # (n, L, 1)
return torch.tensor(x), torch.tensor(z[t])[:, None] # (n, L, 1), (n, 1)
class Net(nn.Module):
def __init__(self):
super().__init__()
self.lstm = nn.LSTM(input_size=1, hidden_size=32, batch_first=True)
self.out = nn.Linear(32, 1)
def forward(self, x):
h, _ = self.lstm(x) # h: (batch, L, 32)
return self.out(h[:, -1, :]) # last hidden state -> (batch, 1)
def mae(pred_scaled, true_scaled): # back to requests per hour
return float(np.abs((pred_scaled - true_scaled) * std).mean())
best = None
for L in (24, 168):
torch.manual_seed(seed)
t0 = time.time()
xtr, ytr = windows(L, L, n_train)
xva, yva = windows(L, n_train, n_train + n_val)
model = Net()
opt = torch.optim.Adam(model.parameters(), lr=0.005)
loss_fn = nn.MSELoss()
best_val, best_state = 1e9, None
for epoch in range(25):
model.train()
for idx in torch.randperm(len(xtr)).split(64):
opt.zero_grad()
loss = loss_fn(model(xtr[idx]), ytr[idx])
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
val_loss = loss_fn(model(xva), yva).item()
print(f"L={L} epoch {epoch+1:2d} train_loss {loss.item():.4f} val_loss {val_loss:.4f}")
if val_loss < best_val:
best_val = val_loss
best_state = {k: v.clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
with torch.no_grad():
val_mae = mae(model(xva).numpy(), yva.numpy())
print(f"L={L}: validation MAE {val_mae:.1f}, best val_loss {best_val:.4f}, {time.time()-t0:.0f} s")
if L == 24:
print("shapes: input", tuple(xtr[:64].shape), "-> output", tuple(model(xtr[:64]).shape))
if best is None or val_mae < best[0]:
best = (val_mae, L, model)
val_mae, L, model = best
print(f"chosen L={L} (validation MAE {val_mae:.1f})")
t_end = len(y)
xte, yte = windows(L, t_end - 168, t_end)
with torch.no_grad():
lstm_mae = mae(model(xte).numpy(), yte.numpy())
test_true = y[t_end - 168:]
last_value = np.abs(y[t_end - 169:t_end - 1] - test_true).mean()
same_hour = np.abs(y[t_end - 336:t_end - 168] - test_true).mean()
print(f"TEST MAE LSTM {lstm_mae:.1f} | last value {last_value:.1f} | same hour last week {same_hour:.1f}")
It prints a loss line for every epoch, then these last two lines (seed 0):
chosen L=24 (validation MAE 48.0)
TEST MAE LSTM 42.6 | last value 73.8 | same hour last week 54.5
When it breaks: Our expectation, not measured here: if a launch or an outage changes the traffic level, the windows stop describing the test week, so rerun the baseline check every time you retrain.
Cheat sheet
The article on one page: open it full size, save it or share it.

AI-assisted content, human-reviewed. Images AI-generated. Editorial Standards · Our Editors