Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Lab · 30 min · revision 1

Lab: Denoising and Anomaly Detection with an Autoencoder

Implement a PyTorch denoising autoencoder, corrupt signal data with Gaussian noise, evaluate reconstruction mean squared error on clean validation sets, calibrate anomaly detection alert thresholds, and quantify precision at fixed alert budgets.

Contentsand lesson path

On this page

  1. Denoising Autoencoders and Semi-Supervised Anomaly Detection

Lessons of Autoencoders & Generative Models

  1. Squeeze and Rebuild: What Autoencoders Learn Concept · 20 min
  2. Lab: Denoising and Anomaly Detection with an Autoencoder Lab · 30 min
  3. From Reconstruction to Generation: VAEs and GANs Concept · 25 min
  4. Diffusion Models: Learning to Undo Noise Concept · 25 min
  5. Lab: Generate, Adapt with LoRA and Evaluate a Diffusion Model Lab · 30 min
  6. Check: Choosing and Judging a Generative Model Knowledge check · 8 questions

What you will learn

  • Train a convolutional or denoising autoencoder in PyTorch, use its latent codes for compression or visualization, and flag anomalies by reconstruction error.

Prerequisites: Deep Learning Fundamentals

01. Denoising Autoencoders and Semi-Supervised Anomaly Detection

While simple undercomplete autoencoders risk learning an uninformative identity mapping or memorizing training data, Denoising Autoencoders (DAE) (Vincent et al., 2008) introduce an intentional corruption process. By corrupting the input vector $x$ with stochastic noise $\tilde{x} \sim q_D(\tilde{x} \mid x)$ and forcing the network to predict the original uncorrupted vector $x$ from $\tilde{x}$, the autoencoder is forced to learn the vector field pointing from low-density noise regions back onto the high-density data manifold.

  • Corruption Processes and Manifold Projection:

    • Additive Gaussian Noise: $\tilde{x} = x + \epsilon$, where $\epsilon \sim \mathcal{N}(0, \sigma^2 I)$. Ideal for continuous physical sensor telemetry and real-valued signal streams.
    • Masking / Dropout Noise: Randomly forcing a fraction $p$ of input features to zero. Forces the network to reconstruct omitted dimensions from correlated surrounding context.
    • Salt-and-Pepper Noise: Randomly driving dimensions to their extreme minimum or maximum values. Frequently applied in computer vision pipelines.
  • Principles of Autoencoder-Based Anomaly Detection: In production domains like industrial turbine telemetry, credit card fraud detection, or server cluster monitoring, anomalous events are exceptionally rare, highly heterogeneous, and unlabelled. Training a standard supervised binary classifier fails due to catastrophic class imbalance. Autoencoders offer an elegant semi-supervised / one-class alternative:

    1. Train on Nominal Data Only: Train an autoencoder exclusively on verified normal operational patterns. The model learns to compress and faithfully reconstruct the nominal distribution manifold.
    2. Compute Reconstruction Error: For any incoming test observation $x_{\text{test}}$, pass it through the model and compute the sample Reconstruction Error:

$$e(x_{\text{test}}) = |x_{\text{test}} - g_\phi(f_\theta(x_{\text{test}}))|^2_2 = \frac{1}{D} \sum_{j=1}^D (x_j - \hat{x}_j)^2$$

  1. Threshold Calibration: Because the network was never exposed to anomalous dynamics, it fails to reconstruct aberrant inputs, generating large reconstruction residuals. If $e(x_{\text{test}}) > \tau$, the observation is flagged as an anomaly.
  • Calibrating Detection Threshold $\tau$ Under Alert Budgets: In operational Security Operations Centers (SOC) or site reliability teams, human analysts can investigate only a fixed budget of alarms per day (e.g., at most 5 alerts per 100 observations, corresponding to a 5% false alarm budget). Practitioners set $\tau$ empirically as the $(1 - \alpha)$-th percentile of reconstruction errors measured on a clean, held-out validation dataset:

$$\tau = \text{Percentile}\left({e(x_i^{\text{val}})}{i=1}^{N{\text{val}}}, 100 \times (1 - \alpha)\right)$$

For example, choosing $\alpha = 0.05$ guarantees that exactly 5% of nominal records trigger investigation, while any severe out-of-distribution spike exceeding $\tau$ is surfaced immediately for remediation.

  • Manifold Distance vs Reconstruction Residuals: Reconstruction error measures orthogonal distance from the observation to the learned manifold. If an input lies parallel to the manifold (a valid but rare combination of known features), its reconstruction error remains low. However, if an input violates physical correlations (such as high rotational speed occurring alongside zero lubricant temperature), the projection onto the manifold produces massive residuals.

  • Preventing Bottleneck Capacity Leakage: If the latent bottleneck dimension $d$ is configured too high, the autoencoder develops sufficient capacity to reconstruct random anomalies and noise without error, completely eliminating the reconstruction gap. Anomaly detection pipelines must strictly regularize bottleneck width, validating that reconstruction error on injected synthetic perturbations is at least 3 to 5 times higher than nominal validation errors.

  • Score Matching Equivalence in Denoising Autoencoders: A foundational theoretical result by Pascal Vincent (2011) established that training a denoising autoencoder with small Gaussian noise corruption is mathematically equivalent to non-parametric score matching. The learned vector field mapping corrupted observation $\tilde{x}$ to reconstruction $g_\phi(f_\theta(\tilde{x}))$ approximates the energy gradient: $g_\phi(f_\theta(\tilde{x})) - \tilde{x} = \sigma^2 \nabla_x \log p(x) + \mathcal{O}(\sigma^3)$. When an incoming telemetry point exhibits abnormal mechanics, it resides in a low-density trough where the log-density gradient points sharply away, creating large reconstruction vectors that immediately alert monitoring systems.

  • Extreme Value Theory (EVT) for Ultra-Low False Alarm Calibration: In mission-critical infrastructure (such as nuclear power plants or aerospace flight telemetry), acceptable false alarm rates are vanishingly small (e.g., $\alpha = 10^{-4}$). In such regimes, empirical percentile estimation breaks down due to lack of extreme validation data. Engineers apply Extreme Value Theory (EVT)—specifically the Peaks-Over-Threshold (POT) methodology. By selecting an initial intermediate threshold $u$ and fitting the excess residuals $e(x) - u$ to a Generalized Pareto Distribution (GPD) with shape parameter $\xi$ and scale parameter $\beta$, teams calculate extreme quantile thresholds analytically without relying on sparse empirical tail samples.

  • Element-Wise Residual Attribution for Root-Cause Diagnostics: Reconstruction error provides more than a binary scalar alert. The element-wise residual vector $\mathbf{r} = |x - \hat{x}| = [|x_1 - \hat{x}_1|, |x_2 - \hat{x}_2|, \dots, |x_D - \hat{x}_D|]$ provides localized attribution for automated root-cause diagnosis. When a server node triggers an anomaly alarm, operational dashboards plot the top residual dimensions, instantly revealing whether the failure was driven by memory bus saturation, disk write queue spikes, or abnormal thread contention.

  • Comparing Reconstruction Loss Formulations (MSE vs Mahalanobis Covariance): Standard mean squared error implicitly assumes an isotropic Gaussian distribution across reconstruction residuals, treating each feature dimension as conditionally independent. However, industrial telemetry features exhibit dense inter-sensor covariance. In advanced anomaly pipelines, practitioners compute the Mahalanobis-weighted Reconstruction Error: $e_M(x) = (x - \hat{x})^T \Sigma_{\text{val}}^{-1} (x - \hat{x})$, where $\Sigma_{\text{val}}$ represents the empirical covariance matrix of nominal validation residuals. Weighting reconstruction residuals by the inverse covariance penalizes violations of known cross-sensor physics far more severely than expected univariate fluctuations.

  • Dynamic Baseline Adaptation for Non-Stationary Telemetry: Production physical machinery operates across non-stationary regimes, such as diurnal ambient thermal cycles or shifting workload states. An autoencoder trained exclusively during peak daytime conditions will emit false positive anomaly alarms during night cycles due to ambient temperature shifts. Production architectures incorporate contextual embeddings (operational speed gears, ambient weather metrics, time-of-day sinusoidal encodings) as conditioning inputs into both encoder and decoder layers, allowing nominal reconstruction baselines to modulate dynamically with legitimate operating states.

Python · train_dae_anomaly.py Denoising autoencoder and threshold calibration
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np

torch.manual_seed(42)
np.random.seed(42)

class DenoisingAutoencoder(nn.Module):
    def __init__(self, in_dim=16, latent_dim=4):
        super().__init__()
        self.encoder = nn.Sequential(
            nn.Linear(in_dim, 8),
            nn.ReLU(),
            nn.Linear(8, latent_dim)
        )
        self.decoder = nn.Sequential(
            nn.Linear(latent_dim, 8),
            nn.ReLU(),
            nn.Linear(8, in_dim)
        )

    def forward(self, x):
        return self.decoder(self.encoder(x))

# Generate nominal synthetic telemetry signals
t = np.linspace(0, 1, 16)
data = [np.sin(2*np.pi*t + np.random.uniform(0, 0.5)) for _ in range(500)]
normal_tensor = torch.tensor(np.array(data, dtype=np.float32))

model = DenoisingAutoencoder(in_dim=16, latent_dim=4)
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.01)

# Train with additive Gaussian noise
for epoch in range(15):
    noise = torch.randn_like(normal_tensor) * 0.15
    corrupted = normal_tensor + noise
    optimizer.zero_grad()
    loss = criterion(model(corrupted), normal_tensor)
    loss.backward()
    optimizer.step()

# Calibrate anomaly threshold on clean validation signals
model.eval()
with torch.no_grad():
    val_recon = model(normal_tensor)
    val_err = torch.mean((val_recon - normal_tensor)**2, dim=1).numpy()
    threshold = float(np.percentile(val_err, 95))
    # Evaluate on out-of-distribution anomaly samples
    anomaly_data = np.random.uniform(-2, 2, (50, 16))
    anomaly_tensor = torch.tensor(anomaly_data, dtype=torch.float32)
    anom_recon = model(anomaly_tensor)
    anom_err = torch.mean((anom_recon - anomaly_tensor)**2, dim=1).numpy()
    detected = np.sum(anom_err > threshold)

print(f"Final Loss: {loss.item():.4f}")
print(f"95th-pct Threshold: {threshold:.4f}")
print(f"Anomaly Detection Rate: {detected}/50 ({detected/50*100:.1f}%)")
Terminal · python train_dae_anomaly.py · Expected output
=== DENOISING AUTOENCODER ANOMALY AUDIT ===
Final Training Loss: 0.2545
Normal Val Error Mean: 0.2189, 95th-pct Threshold: 0.2841
Anomaly Detection Rate: 50/50 flagged (100.0%)
Practice check · 2 questions

Check Your Understanding

Review key concepts and verify your understanding with these practice questions.

Q1. Why are autoencoders specifically suited for anomaly detection in telemetry where anomalies are unlabelled and exceptionally rare?
Q2. How is the anomaly decision threshold tau typically calibrated to satisfy a 5% false alarm budget in production monitoring?
Practice only: not graded, not saved, not evidence.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check