Why Anomaly Detection Matters
A modern instrumented bridge may stream data from 200+ sensors — accelerometers, strain gauges, displacement transducers, thermocouples, tilt sensors, GPS receivers. Every second, thousands of numbers flow into a database. Buried in that torrent of normal readings are the rare signals that matter most: a sudden strain spike indicating a cracked girder, a gradual drift in a displacement sensor revealing foundation settlement, or a flat-line from a failed accelerometer feeding false confidence into a monitoring dashboard.
Manual inspection of every reading is impossible at scale. Simple threshold-based alarms (e.g., “flag if strain exceeds 500 micro-strain”) miss subtle, multivariate anomalies and drown operators in false positives from normal environmental variation. What you need are algorithms that learn what normal looks like and automatically flag deviations — that is anomaly detection.
Types of Anomalies in Civil Engineering
Understanding the taxonomy helps choose the right algorithm:
- Point anomalies — A single reading deviates drastically. Example: a strain gauge suddenly reporting 10,000 micro-strain while all neighbours report 200. Often caused by sensor malfunction or a sudden structural event.
- Contextual anomalies — A reading is normal in one context but anomalous in another. Example: a bridge deck temperature of 45 °C is normal in August but alarming in January. The value itself is not extreme; the context makes it anomalous.
- Collective anomalies — A sequence of individually normal readings that together form an abnormal pattern. Example: accelerometer readings that individually stay within limits but whose frequency spectrum shifts over weeks, indicating progressive stiffness degradation.
Think of anomaly detection like a site safety inspector who has watched thousands of concrete pours. She instantly notices when the slump is off, the colour is wrong, or the vibration pattern during compaction sounds different — not because she memorised every possible failure mode, but because she has an internal model of “normal” and flags anything that deviates from it. Anomaly detection algorithms build the same internal model, but from data instead of experience.
This sub-chapter builds on Sub-chapter 3.5 (PCA) and 3.6 (t-SNE & UMAP). Familiarity with basic statistics (mean, standard deviation, quartiles) is assumed. Knowledge of neural networks (Chapter 2) helps for the autoencoder section but is not strictly required — we develop the intuition from first principles.
Statistical Methods: Z-Score
The simplest anomaly detector asks: “How many standard deviations is this point from the mean?” That number is the z-score.
Definition and Formula
Given a dataset with mean μ and standard deviation σ, the z-score of a value x is:
A common rule flags any observation with |z| > 3 as an anomaly. For normally distributed data, only 0.27 % of points fall beyond 3σ, so a reading at |z| = 4 or 5 is extremely unlikely under the normal model.
Civil engineering example: A strain gauge on a steel girder reports readings with μ = 180 με and σ = 25 με under routine traffic. A reading of 310 με gives z = (310 − 180) / 25 = 5.2 — far beyond the 3σ threshold, triggering an immediate alert for potential overload or sensor fault.
Strengths and Limitations
- Simple and fast — requires only μ and σ, computable in O(n).
- Interpretable — engineers understand “5 standard deviations from the mean.”
- Assumes normality — sensor data is often skewed or multimodal (e.g., different traffic regimes).
- Sensitive to outliers in training data — a few extreme values inflate σ, masking future anomalies.
- Univariate only — checks one feature at a time; cannot detect multivariate anomalies where each individual feature is normal but the combination is unusual.
Statistical Methods: IQR (Interquartile Range)
The IQR Approach
The Interquartile Range is a robust alternative that does not assume normality. It uses the 25th percentile (Q1) and 75th percentile (Q3) to define a “normal box”:
Lower fence = Q1 − 1.5 × IQR
Upper fence = Q3 + 1.5 × IQR
Any point below the lower fence or above the upper fence is flagged as an outlier. The factor 1.5 is Tukey's classic choice; using 3.0 yields “extreme outliers.”
Civil engineering example: Foundation settlement measurements over 50 monitoring points show Q1 = 2.1 mm, Q3 = 4.8 mm, so IQR = 2.7 mm. The fences are [2.1 − 4.05, 4.8 + 4.05] = [−1.95, 8.85] mm. A point settling 12 mm exceeds the upper fence and is flagged for investigation — possible void formation or differential settlement.
Why IQR is Robust
Unlike the z-score, the IQR method is based on order statistics (percentiles), which are not pulled by extreme values. Even if 5 % of your strain gauge readings are corrupted by electrical spikes, Q1 and Q3 remain stable because they depend on the central 50 % of the data. This makes IQR ideal as a first-pass filter for noisy field sensor data.
The IQR method is like a structural engineer who judges concrete cube test results by looking at the middle 50 % of all tests, rather than computing the average. If one cube was accidentally tested wet and gave a wildly low strength, the median-based assessment barely notices, whereas a mean-based z-score would be dragged down, potentially masking a genuinely weak batch that follows.
Z-Score vs. IQR: When to Use Each
Comparison Table
| Criterion | Z-Score | IQR |
|---|---|---|
| Distribution assumption | Normal (Gaussian) | None |
| Robustness to existing outliers | Low — mean and σ are pulled | High — percentiles resist contamination |
| Best suited for | Clean, Gaussian data | Skewed, heavy-tailed, or noisy data |
| Multivariate extension | Mahalanobis distance | Not straightforward |
| Typical CE use case | Lab test results (well-controlled) | Field sensor data (noisy, variable) |
Isolation Forest
Statistical methods work on individual features. But real engineering anomalies are often multivariate — each sensor reading looks normal alone, but their combination is unusual. Isolation Forest is a tree-based algorithm designed specifically for multivariate anomaly detection.
Core Intuition
The key insight is elegant: anomalies are easy to isolate. If you randomly select a feature and a random split value, an anomalous point (sitting far from the crowd) will be isolated in fewer splits than a normal point (embedded deep in a dense cluster).
The algorithm builds many random binary trees (an “isolation forest”). For each tree:
- Randomly select a feature from the dataset.
- Randomly select a split value between the feature's minimum and maximum.
- Split the data into left (below split) and right (above split).
- Recurse on each side until every point is isolated or a maximum depth is reached.
The anomaly score of a point is the average path length across all trees, normalised by the expected path length for the dataset size. Points with short average paths are anomalies; points with long average paths are normal.
Civil Engineering Application: SHM Sensor Validation
Consider a bridge SHM system recording 10 features per time step: 3 accelerations, 2 strains, temperature, humidity, wind speed, traffic load, and cable tension. An Isolation Forest trained on 6 months of normal operation data will learn the multivariate relationships — for example, that high wind speed correlates with increased cable tension and specific vibration patterns.
When a cable tension sensor begins drifting due to a loose connection, its readings might still be within the univariate normal range, but the combination of low wind speed with unusually high cable tension becomes easy to isolate. The Isolation Forest catches what z-scores and IQR miss.
Key Hyperparameters
- n_estimators — Number of trees in the forest. Typically 100–300. More trees give stabler scores but increase computation.
- max_samples — Number of samples drawn to build each tree. Smaller subsets speed up training and can improve anomaly detection by reducing swamping (normal points masking anomalies).
- contamination — Expected fraction of anomalies. Sets the decision threshold automatically. In SHM, typical values are 0.01–0.05 (1–5 % anomaly rate).
Imagine sorting a pile of mixed aggregate by randomly splitting it with dividers. A large, oddly shaped boulder (anomaly) sitting on top of the pile gets separated in just one or two splits. But a typical-sized pebble (normal point) buried in the middle of a dense pile needs many splits before it is isolated. The Isolation Forest counts these splits.
Local Outlier Factor (LOF)
Isolation Forest treats the entire dataset uniformly. But real sensor data often has regions of different density — daytime traffic creates a dense cluster of high-acceleration readings, while nighttime readings form a sparser cluster of low-acceleration values. A point at the edge of the daytime cluster might be perfectly normal, but the same point appearing at the edge of the nighttime cluster could be anomalous. LOF captures this by considering local density.
How LOF Works
For each point p, LOF computes a score comparing the local density around p with the local densities of its neighbours:
- k-distance: Find the distance to the k-th nearest neighbour of p.
- Reachability distance: For each neighbour o, compute reach-distk(p, o) = max(k-dist(o), dist(p, o)). This smooths out small fluctuations in very dense regions.
- Local reachability density (LRD): The inverse of the average reachability distance from p to its k nearest neighbours.
- LOF score: The average ratio of the LRDs of p's neighbours to the LRD of p.
A LOF score near 1.0 means the point has similar density to its neighbours (normal). Scores significantly greater than 1.0 indicate that the point lives in a much sparser region than its neighbours — it is a local outlier.
CE Application: Detecting Unusual Settlement Patterns
In a highway embankment monitoring project, settlement readings cluster into two natural groups: fast-consolidating clay sections and slow-consolidating sand sections. A reading that is moderate in absolute terms but falls between these two clusters — too fast for sand, too slow for clay — is a local outlier. LOF detects it because its local density is much lower than either cluster. This could indicate an unexpected soil transition or drainage problem.
Choosing k (Number of Neighbours)
The parameter k controls the scale of “local”:
- Small k (5–10): Very local view. Sensitive to micro-clusters but prone to noise.
- Large k (50–100): Broader view. More stable but may miss anomalies in small, dense sub-clusters.
- Rule of thumb: Start with k = 20 and check the LOF score distribution. If scores cluster tightly near 1.0 with clear outliers above 1.5, the choice is working.
Autoencoders for Anomaly Detection
When the number of features grows into the hundreds and the relationships between them are highly non-linear, statistical methods and tree-based approaches can struggle. Autoencoders — a type of neural network — offer a powerful alternative by learning a compressed representation of normal data and flagging anything that cannot be reconstructed well.
Architecture Overview
An autoencoder has two halves:
- Encoder: Compresses the input (e.g., 200 sensor features) through progressively smaller hidden layers into a low-dimensional bottleneck (e.g., 10 dimensions).
- Decoder: Reconstructs the original 200-dimensional input from the 10-dimensional bottleneck.
The network is trained on normal data only, minimising the reconstruction error (typically mean squared error between input and output). After training, the autoencoder can faithfully reconstruct any input that resembles normal operation. When an anomalous input arrives — say, a pattern of sensor readings never seen during normal operation — the bottleneck cannot encode it properly, and the reconstruction error spikes. A threshold on this error flags anomalies.
Example Architecture for SHM
→ Dense(128, ReLU)
→ Dense(64, ReLU)
→ Dense(16, ReLU) [bottleneck]
→ Dense(64, ReLU)
→ Dense(128, ReLU)
→ Dense(200, linear) [reconstruction]
The bottleneck of 16 dimensions forces the network to learn the most important correlations among the 200 sensors. If sensor 47 always tracks sensor 112 (because they are on the same girder), the bottleneck learns this dependency. When sensor 47 suddenly stops tracking sensor 112, the reconstruction error for both channels increases.
Setting the Reconstruction Error Threshold
After training, compute the reconstruction error for all samples in the validation set (normal data). The threshold is typically set at the 95th or 99th percentile of these errors:
- 95th percentile: More sensitive, catches subtle anomalies but generates more false alarms. Good for safety-critical structures.
- 99th percentile: Less sensitive, fewer false alarms but may miss subtle early-stage damage. Suitable for routine monitoring.
CE Application: Structural Response Anomalies
A high-rise building instrumented with floor-level accelerometers during an earthquake generates a complex multivariate time series. An autoencoder trained on wind-induced vibration data (normal operation) will produce low reconstruction error for typical wind events. During a seismic event, the completely different vibration pattern yields high reconstruction error across all channels — correctly flagging the event as anomalous.
More importantly, after the earthquake, if the building's response to subsequent wind events changes (due to structural damage altering stiffness), the autoencoder will detect the shift because the new normal no longer matches the learned patterns. This enables automated post-event structural assessment.
An autoencoder is like a skilled draughtsman who has drawn the same bridge elevation a thousand times. Give him a photo of the bridge, and he can reproduce it almost perfectly from memory, filling in small gaps. But show him a photo of a different bridge, or the same bridge with a buckled member, and his reproduction will have obvious errors — the reconstruction error reveals that something does not match his learned template.
Choosing the Right Method
Decision Flowchart
Selecting an anomaly detection method depends on the data characteristics and engineering requirements:
- Single sensor, clean data, quick check → Z-score. Fastest to implement, easy to explain in a report.
- Single sensor, noisy or skewed data → IQR. Robust to outlier contamination in training data.
- Multiple sensors, tabular data, moderate dimensionality (5–50 features) → Isolation Forest. Handles multivariate relationships, fast, scalable.
- Multiple sensors, varying density clusters → LOF. Captures local density variations that Isolation Forest may miss.
- High-dimensional (100+ sensors), complex non-linear correlations, large training set available → Autoencoder. Most powerful but requires more data and tuning.
Ensemble Approach in Practice
In production SHM systems, engineers often stack multiple methods. A common pipeline:
- Layer 1 (Pre-filter): IQR on each sensor individually — catches obvious sensor faults (stuck readings, spikes, out-of-range values) cheaply.
- Layer 2 (Multivariate): Isolation Forest on the cleaned multi-sensor feature vector — catches unusual combinations of readings.
- Layer 3 (Deep patterns): Autoencoder on windowed time-series features — catches subtle changes in dynamic behaviour over time.
Each layer catches different types of anomalies, and the combined false-positive rate is lower than any single method alone because obvious faults are removed before they reach the more sensitive methods.
Demo 1: Anomaly Detection Sandbox
Click on the canvas to place data points. Use the controls to switch between adding normal or anomalous points. Then select an algorithm and hit Detect to see which points are flagged and the decision boundary the algorithm draws.
Demo 2: Time-Series Anomaly Detector
This demo simulates a strain gauge sensor on a bridge girder. The signal contains normal cyclic traffic loading with injected anomalies — sensor spikes, drift, and flat-line events. Adjust the sensitivity threshold and watch the detector flag anomalous segments in real time.
Practical Considerations for Civil Engineers
Data Quality and Pre-processing
Anomaly detection is only as good as your definition of “normal.” Before training:
- Remove known events — earthquake records, planned load tests, and maintenance periods should be excluded from the training set, or the model learns to treat damage-like signals as normal.
- Account for seasonality — bridge sensor data varies with temperature, traffic patterns (weekday vs. weekend), and humidity. Train on a full annual cycle or normalise by environmental variables.
- Handle missing data — sensor dropouts are common. Impute short gaps with interpolation; flag long gaps as missing rather than zero-filling.
- Feature engineering — raw readings often benefit from derived features: rolling means, rolling standard deviations, frequency-domain features (FFT peaks), and cross-sensor correlation coefficients.
The False Positive Problem
In SHM, false positives are expensive. Each alarm triggers an investigation: an engineer reviews data, possibly sends an inspection team to a remote bridge site. If the system generates 50 false alarms per week, operators quickly learn to ignore alerts — the “alarm fatigue” problem — and real anomalies get missed.
Strategies to reduce false positives:
- Use a confirmation window — flag an anomaly only if it persists for N consecutive readings.
- Require multiple methods to agree — ensemble approach (IQR + Isolation Forest).
- Implement tiered alerts — Advisory (low confidence), Warning (moderate), Critical (high confidence, multiple sensors confirm).
Model Retraining and Concept Drift
Structures change over time. Concrete creeps, foundations settle, repairs alter stiffness, and new traffic patterns emerge. An anomaly detection model trained in 2020 may generate increasing false positives by 2025 because “normal” has shifted.
Best practices:
- Periodic retraining on verified-normal recent data (e.g., quarterly updates).
- Monitoring the anomaly score distribution — if the baseline distribution drifts upward, the model may need updating.
- Human-in-the-loop: All flagged anomalies should be reviewed by an engineer and labelled as true or false positive, building a feedback loop for continuous improvement.
CE Application: Anomaly Detection in Infrastructure
Catching the abnormal before it becomes a failure — the most safety-critical unsupervised learning application in civil engineering.
Dam Piezometer Spikes
Sudden pore pressure spikes in embankment dams can indicate piping failure. Isolation Forest on time-series data catches anomalies within minutes, enabling emergency drawdown.
Settlement Monitoring
Expected consolidation follows a predictable curve. Anomaly detection flags deviations — unexpected heave, sudden settlement acceleration, or instrument drift.
Structural Health Monitoring
Bridge accelerometers: normal vibration patterns form a baseline. When new data deviates beyond the learned boundary, it triggers a structural inspection alert.
Test Your Understanding
Quick Check 1
A strain gauge on a steel bridge reports μ = 200 με and σ = 30 με under normal traffic. A reading of 320 με arrives. What is the z-score and should it be flagged (using |z| > 3 threshold)?
Quick Check 2
Why is Isolation Forest effective at detecting multivariate anomalies that z-score and IQR methods miss?
Quick Check 3
An autoencoder-based anomaly detector for a bridge SHM system has a reconstruction error threshold set at the 95th percentile of normal data. After a minor earthquake, the reconstruction error for wind-induced vibration data rises above this threshold even though no visible damage is found. What is the most likely explanation?
Quick Check 4
In an LOF analysis of foundation settlement data, a monitoring point has an LOF score of 3.8. What does this mean in practical terms?
Key Takeaways
Summary
- Z-score flags points beyond a σ-threshold. Simple, fast, interpretable, but assumes normality and is univariate only.
- IQR uses percentile-based fences and is robust to outlier contamination and non-normal distributions. Ideal for noisy field sensor data.
- Isolation Forest uses random partitioning to isolate anomalies in fewer splits. Handles multivariate data, scales well, and requires no density estimation.
- LOF compares local density to neighbours' densities. Excels when data has clusters of varying density — e.g., different soil types or traffic regimes.
- Autoencoders learn to reconstruct normal data; high reconstruction error flags anomalies. Best for high-dimensional data with complex non-linear correlations.
- In production SHM, ensemble approaches (layering IQR → Isolation Forest → Autoencoder) reduce false positives and catch different anomaly types.
- Data quality, seasonality, and concept drift require careful handling. Periodic retraining and human-in-the-loop review are essential.
What Comes Next
In Sub-chapter 3.8 (Association Rules), you will learn how to discover co-occurrence patterns in categorical engineering data — for example, which combinations of material properties, construction methods, and environmental conditions tend to appear together in defect reports. Association rules mine “if X and Y, then Z” patterns from large inspection databases.