Thursday, November 12, 2026

Variational Autoencoders (VAE) for Time Series: A PyTorch Example

TL;DR

This guide explains how a variational autoencoder learns what a normal day looks like, so its reconstruction error can flag odd readings in a time series. A small PyTorch example catches all three injected spikes and generates new synthetic days. It is also honest that a plain VAE does not forecast, so please do not ask it about tomorrow.

If you have ten minutes, read these:

Say an operations team watches hourly readings from a pump: a steady daily cycle, some noise, and every so often a short spike nobody can explain. They have months of normal data and almost no labeled faults. A rule like “alert above 15” misses spikes that happen at night, when readings are low, and fires during busy afternoons.

A variational autoencoder (VAE) fits this problem well. A VAE is a neural network that learns to compress data into a few random latent variables and rebuild it, trained so that the latent space follows a simple distribution. Trained on normal days, it rebuilds normal patterns accurately and abnormal ones poorly, so the reconstruction error becomes an anomaly score. The same model can also generate realistic new series. This guide explains how a VAE works on time series and builds one in PyTorch that runs on a CPU in about 10 seconds, with real output. It also says plainly where VAEs are not the right tool, including most forecasting jobs.

Key Takeaways

  • A VAE has an encoder that maps an input window to a mean and variance for each latent variable, and a decoder that rebuilds the window from a sample.
  • Training balances two terms: reconstruction error and a KL divergence penalty that keeps the latent space close to a standard normal distribution.
  • For time series, cut the series into fixed-length windows (here, 24 hours) and treat each window as one example.
  • Main uses: anomaly detection by reconstruction error, generating synthetic series, and filling gaps. In our example, the VAE caught all three injected anomalies with one false alarm in 217 test windows.
  • A plain VAE does not forecast. For forecasting, use a conditional setup or a dedicated probabilistic forecasting model.

What Is a Variational Autoencoder?

Diederik Kingma and Max Welling introduced the VAE in Auto-Encoding Variational Bayes (2013). It looks like a regular autoencoder, an encoder that squeezes the input into a few numbers and a decoder that rebuilds it, with one key difference: the latent code is random.

For each input, the encoder outputs a mean mu and a log variance for every latent variable. The model samples a latent vector z from that distribution and decodes it. Two pieces make this trainable:

  • The reparameterization trick. Sampling is not differentiable, so the model writes z = mu + sigma * epsilon, where epsilon is standard normal noise. Gradients flow through mu and sigma, and the randomness sits in epsilon.
  • The KL term. The loss adds the Kullback-Leibler divergence between each encoded distribution and a standard normal. This keeps the latent space smooth and centered, so random draws from a standard normal decode into realistic outputs.

The total loss is reconstruction error plus a weight (often called beta) times the KL term. A larger beta gives a tidier latent space and blurrier reconstructions. A lower beta does the reverse.

How VAEs Work on Time Series

A VAE needs fixed-size inputs, so the usual first step is windowing: slide a window of length W along the series and treat each window as one example. With hourly data and a daily cycle, W = 24 means each example is one day’s shape, starting at any hour.

The encoder and decoder can be simple fully connected layers, as in the example below, or 1D convolutions and recurrent layers (LSTM or GRU) when windows are long and local patterns matter. Start simple. A fully connected VAE on 24-step windows trains in seconds and is easy to debug.

Scale the series before training, using statistics from the training period only, and keep a clean training period. If the training data contains many anomalies, the model learns to rebuild them too, and the reconstruction error stops separating normal from abnormal.

A Runnable PyTorch Example

The script below builds a synthetic hourly series of 60 days with a daily cycle and noise, and injects three 3-hour spikes into the last 10 days. It trains a VAE on windows from the first 50 days, sets an alert threshold at the 99th percentile of training reconstruction error, and scores every window in the test period. At the end it decodes random latent vectors to generate new synthetic days. It needs only NumPy and PyTorch (pip install torch numpy).

import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

torch.manual_seed(0)
rng = np.random.default_rng(0)

# Synthetic hourly series: a daily cycle plus noise, 60 days long.
hours = np.arange(24 * 60)
series = 10 + 3 * np.sin(2 * np.pi * hours / 24) + rng.normal(0, 0.3, hours.size)

# Inject three anomalies into the last 10 days (the test period).
anomaly_hours = [24 * 52 + 5, 24 * 55 + 14, 24 * 58 + 20]
for h in anomaly_hours:
    series[h:h + 3] += 4

WINDOW = 24
mean, std = series[: 24 * 50].mean(), series[: 24 * 50].std()
scaled = (series - mean) / std
windows = np.lib.stride_tricks.sliding_window_view(scaled, WINDOW)
x_train = torch.tensor(windows[: 24 * 50 - WINDOW], dtype=torch.float32)
x_test = torch.tensor(windows[24 * 50:], dtype=torch.float32)


class VAE(nn.Module):
    def __init__(self, n_in=WINDOW, hidden=64, latent=4):
        super().__init__()
        self.encoder = nn.Sequential(nn.Linear(n_in, hidden), nn.ReLU())
        self.to_mu = nn.Linear(hidden, latent)
        self.to_logvar = nn.Linear(hidden, latent)
        self.decoder = nn.Sequential(nn.Linear(latent, hidden), nn.ReLU(),
                                     nn.Linear(hidden, n_in))

    def forward(self, x):
        h = self.encoder(x)
        mu, logvar = self.to_mu(h), self.to_logvar(h)
        # Reparameterization trick: sample z in a way gradients can flow through.
        z = mu + torch.randn_like(mu) * torch.exp(0.5 * logvar)
        return self.decoder(z), mu, logvar


def vae_loss(x_hat, x, mu, logvar, beta=0.1):
    recon = F.mse_loss(x_hat, x, reduction="sum") / x.shape[0]
    kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) / x.shape[0]
    return recon + beta * kl


model = VAE()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
loader = torch.utils.data.DataLoader(x_train, batch_size=64, shuffle=True)

for epoch in range(1, 61):
    for batch in loader:
        x_hat, mu, logvar = model(batch)
        loss = vae_loss(x_hat, batch, mu, logvar)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    if epoch % 20 == 0:
        print(f"epoch {epoch}: loss {loss.item():.2f}")

# Score each test window by reconstruction error, using the mean of z.
model.eval()
with torch.no_grad():
    def errors(x):
        mu = model.to_mu(model.encoder(x))
        return ((model.decoder(mu) - x) ** 2).mean(dim=1).numpy()

    threshold = np.quantile(errors(x_train), 0.99)
    test_err = errors(x_test)

flagged = np.where(test_err > threshold)[0] + 24 * 50  # first hour of each window
print(f"threshold (99th percentile of training error): {threshold:.3f}")
print(f"windows flagged: {len(flagged)} of {len(test_err)}")
touches = lambda start: any(start <= h + 2 and start + WINDOW > h for h in anomaly_hours)
print(f"flagged windows with no anomaly in them: {sum(not touches(s) for s in flagged)}")
for h in anomaly_hours:
    caught = np.any((flagged <= h) & (flagged + WINDOW > h))
    print(f"anomaly at hour {h}: {'detected' if caught else 'missed'}")

# Generate new, synthetic days by decoding random draws from the prior.
with torch.no_grad():
    fake = model.decoder(torch.randn(3, 4)).numpy() * std + mean
print("generated day, first 6 hours:", np.round(fake[0, :6], 1))

Output (PyTorch 2.14 on a CPU):

epoch 20: loss 1.26
epoch 40: loss 1.21
epoch 60: loss 0.99
threshold (99th percentile of training error): 0.032
windows flagged: 79 of 217
flagged windows with no anomaly in them: 1
anomaly at hour 1253: detected
anomaly at hour 1334: detected
anomaly at hour 1412: detected
generated day, first 6 hours: [12.7 12.5 12.  11.4 10.8 10. ]

Reading the Results

All three anomalies were detected. The 79 flagged windows look like a lot until you count: each 3-hour spike appears in 26 overlapping 24-hour windows, so the three spikes account for 78 of them. Only one flagged window had no anomaly in it. In practice you would merge overlapping flagged windows into one alert per event and point to the hours with the largest reconstruction error.

The threshold is a choice, not a fact of the model. The 99th percentile of training error means about 1% of normal windows will cross it by chance. Raise it for fewer false alarms, lower it to catch subtler faults, and check the trade-off on whatever labeled incidents you have.

The generated day starts at 12.7 and falls steadily over the first 6 hours, a slice of the daily sine wave between its peak of 13 and its average of 10. That is the generative side of the VAE: random draws from the latent space decode into plausible days, which is useful for testing pipelines or adding training data, with the usual caveat that synthetic data only reflects patterns the model has learned.

Can a VAE Forecast Time Series?

Not on its own. A plain VAE rebuilds a window it has already seen. It does not predict what comes next. Forecasting needs a model that maps the past to a distribution over the future. Three common routes:

  1. Conditional VAE. Encode the past window as a condition, and train the decoder to produce the next window given that condition and a latent sample. Sampling many z values gives a range of possible futures.
  2. VAE features plus a forecaster. Use the latent means as compact features for a separate forecasting model.
  3. A dedicated probabilistic forecaster. Models such as DeepAR, or gradient boosting trained with quantile loss, predict ranges directly and are usually the simpler choice. Our explainer on quantile (pinball) loss shows how to train and score that kind of forecast.

VAEs are one of three main families of generative models, alongside GANs and diffusion models. Our comparison of diffusion, GAN and VAE techniques covers when each one fits. For long sequences, newer architectures such as Mamba state space models are another option.

Practical Tips for Time Series VAEs

  • Match the window to the pattern. The window should cover at least one full cycle (a day for hourly data with a daily cycle, a week for weekly patterns).
  • Use the latent mean for scoring. At inference, decode mu instead of a random sample, as the example does, so scores do not change from run to run.
  • Watch for posterior collapse. If the KL term drops to near zero and the decoder ignores z, lower beta or start beta at 0 and increase it during training.
  • Retrain as normal behavior drifts. If the pump’s normal cycle changes with the seasons, a model trained on summer data will flag all of winter.

Back to the Pump

The operations team from the opening now has an alert that knows what a normal day looks like. A night-time spike stands out because it does not fit the learned shape, even though its value is lower than a normal afternoon peak. The threshold is set from training data, the model takes seconds to retrain, and when they later need forecasts, they know to add a conditional model or a quantile forecaster rather than expect the VAE to do it.

Frequently Asked Questions

What Is the Difference Between an Autoencoder and a VAE?

A plain autoencoder maps each input to one fixed code. A VAE maps it to a distribution and is trained to keep those distributions close to a standard normal. That makes the latent space smooth enough to sample from, which is why a VAE can generate new data and a plain autoencoder usually cannot.

How Long Should the Window Be?

Long enough to contain the pattern you care about, usually at least one full cycle. Longer windows give more context but need more data and capacity. For hourly data with a daily cycle, 24 to 48 steps is a reasonable start.

Do I Need Labeled Anomalies to Train a VAE?

No. The VAE trains on normal data only, which is its main advantage when faults are rare. Labeled incidents are still valuable for choosing the alert threshold and checking how many real problems the model catches.

Can a VAE Handle Multivariate Time Series?

Yes. Stack the variables so each window is a matrix of time steps by features, then flatten it for fully connected layers or keep the shape for 1D convolutions. Scale each variable separately so no single sensor dominates the reconstruction error.

Disclaimer: The content on this website reflects the views of contributing authors and not necessarily those of Generative AI Lab. This site may contain sponsored content, affiliate links, and material created with generative AI. Thank you for your support.

Generative AI Lab mascot
Generative AI Lab Editorial Team
Articles researched, written and edited by the Generative AI Lab team. About Generative AI Lab

Must read

- Advertisement -spot_img

More articles

- Advertisement -spot_img

Latest articles

Available for Amazon Prime