Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 7: Machine Learning Applications for Anomaly Detection

Authors
Affiliations
University of Alberta
University of Alberta

1Introduction

Bridge monitoring systems continuously generate vast quantities of sensor data that capture structural responses to environmental conditions and operational loads. Traditional analysis methods from Chapter 5 (statistical comparisons using z-scores, Mahalanobis distances, or distribution-based metrics) require manually extracted features and expert-defined thresholds. While effective for small-scale monitoring, these approaches face challenges when scaling to networks of hundreds of sensors across multiple structures, particularly when environmental factors introduce complex, nonlinear relationships that mask subtle damage indicators.

Machine learning transforms this challenge by automatically discovering patterns directly from data. Unlike statistical methods that compare predefined features against baseline distributions, machine learning algorithms learn their own feature representations through training on examples. These learned features often capture relationships that manual engineering might overlook, and models continuously adapt as they process new measurements.

This chapter explores two powerful unsupervised machine learning approaches specifically designed for bridge anomaly detection: One-Class Support Vector Machines and Convolutional Autoencoders. Both methods address a fundamental challenge in structural health monitoring: the scarcity of damage examples. By learning exclusively from healthy bridge data, these techniques identify anomalies as deviations from normal patterns, eliminating the need for damage examples during training. This unsupervised paradigm aligns naturally with real-world structural monitoring where structures operate safely for most of their service life.


2Machine Learning Fundamentals

2.1What is Machine Learning?

Machine learning enables computers to learn patterns from data without explicit programming of rules. Rather than coding specific instructions to detect bridge damage, we provide examples of structural behavior and allow algorithms to discover patterns that distinguish normal from anomalous conditions. These systems adapt continuously: as they encounter new data patterns, they refine their understanding of structural condition, improving detection accuracy over time.

The key advantage lies in automatic pattern discovery. Traditional methods require engineers to specify which features matter and how they relate to damage. Machine learning algorithms discover these relationships directly from data, potentially identifying indicators that domain experts might not anticipate.

2.2Core Machine Learning Tasks

Machine learning problems divide into two fundamental categories based on the type of output they predict.

Regression predicts continuous numerical values from input data. In bridge monitoring, regression models might estimate remaining service life from vibration measurements, predict future load capacity from inspection data, or forecast crack propagation rates from environmental conditions. The output is a real number on a continuous scale.

Classification assigns discrete labels to inputs, answering yes-or-no questions or categorizing data into predefined classes. For structural health monitoring, classification dominates because we typically need binary decisions: Is this measurement normal or anomalous? Has damage occurred or not? Classification can also be multi-class, categorizing damage severity into levels (minor, moderate, severe) or identifying damage type (crack, corrosion, fatigue).

Machine-learning task types and learning paradigms. Regression predicts continuous values via y = f(x); classification predicts discrete categories with a learned decision boundary. Supervised learning maps labelled samples through a model f(x;\theta) to predictions \hat y; unsupervised learning discovers structure (e.g., normal vs. anomalous clusters) without labels.

Figure 1:Machine-learning task types and learning paradigms. Regression predicts continuous values via y=f(x)y = f(x); classification predicts discrete categories with a learned decision boundary. Supervised learning maps labelled samples through a model f(x;θ)f(x;\theta) to predictions y^\hat y; unsupervised learning discovers structure (e.g., normal vs. anomalous clusters) without labels.

2.3Supervised vs Unsupervised Learning

Supervised learning requires a training dataset containing input-output pairs where the correct answer is known for each example. To train a crack detector, we need thousands of images labeled “crack” or “no crack.” The algorithm learns to map images to labels by minimizing prediction errors on this labeled training data. Given sufficient examples, supervised methods achieve remarkable accuracy, but they demand extensive labeled datasets.

For bridge monitoring, this requirement creates a critical limitation: damage examples are rare. Deliberately inducing damage for training data is impractical, unethical, and expensive. Waiting for natural damage risks catastrophic failure. Real-world monitoring generates overwhelmingly normal data with infrequent anomalies that may go unnoticed until inspection.

Unsupervised learning solves this problem by discovering structure in data without explicit labels. These algorithms learn patterns of normal behavior from unlabeled measurements. When new data deviates significantly from learned patterns, the algorithm flags an anomaly. This paradigm aligns perfectly with structural health monitoring where structures operate normally for most of their service life, providing abundant examples of healthy behavior.

This chapter focuses exclusively on unsupervised anomaly detection: training models on intact bridge data to identify deviations that may indicate damage. We never provide damage examples during training; the algorithms learn what “normal” looks like and flag anything unusual.

2.4Deep Learning: Hierarchical Feature Discovery

Deep learning extends machine learning through multi-layer neural networks that automatically learn hierarchical feature representations. In image analysis, early network layers detect simple patterns like edges and textures, while deeper layers recognize complex structures like crack patterns or corrosion regions. This automatic feature hierarchy eliminates manual engineering; the network discovers which features matter through training.

Convolutional Neural Networks (CNNs) excel at processing spatial data by preserving structural relationships in images. For bridge monitoring, CNNs can analyze camera images of structural elements or time-frequency spectrograms of vibration signals, automatically extracting features that indicate structural condition without requiring manual specification of what to look for.

2.5The Learning Process: Optimization

Machine learning training solves an optimization problem: find model parameters θ\theta that minimize prediction error on training data. Given input data X∈Rn×d\mathbf{X} \in \mathbb{R}^{n \times d} with nn observations and dd features, we seek:

θ∗=arg⁡min⁡θ[L(fθ(X),Y)+λR(θ)]\theta^* = \arg\min_{\theta} \left[ \mathcal{L}(f_{\theta}(\mathbf{X}), \mathbf{Y}) + \lambda R(\theta) \right]

where:

The optimization proceeds through gradient descent: compute the gradient ∇θL\nabla_{\theta} \mathcal{L} indicating which direction to adjust parameters, then update:

θt+1=θt−η∇θL(θt)\theta_{t+1} = \theta_t - \eta \nabla_{\theta} \mathcal{L}(\theta_t)

where η\eta is the learning rate controlling step size. Training iterates through multiple passes over the data (epochs) until the loss converges to a minimum.

2.6Training Terminology: Batch, Iteration, and Epoch

Before exploring training challenges, we clarify essential terminology that describes how models process data during training.

Batch Size (BB) defines how many training examples the model processes simultaneously before updating parameters. Instead of updating after every single example or waiting for the entire dataset, mini-batch training groups examples together. Common batch sizes range from 16 to 256, balancing computational efficiency with gradient quality.

Iteration represents one complete forward pass (computing predictions), loss calculation, backward pass (computing gradients), and parameter update using a single batch. Each iteration moves the model one step closer to the optimal solution. If we have NN training examples and batch size BB, one epoch contains N/BN/B iterations.

Epoch signifies one complete pass through the entire training dataset, where every training example has been seen exactly once. Training typically requires multiple epochs (often 10-100+) for the model to converge, as a single exposure to the data rarely suffices for learning complex patterns.

The mathematical relationship connecting these concepts:

Iterations per Epoch=⌈NB⌉\text{Iterations per Epoch} = \left\lceil \frac{N}{B} \right\rceil
Total Iterations=⌈NB⌉×E\text{Total Iterations} = \left\lceil \frac{N}{B} \right\rceil \times E

where NN is dataset size, BB is batch size, and EE is the number of epochs.

Training hierarchy: the complete dataset (N = 320) is traversed once per epoch; each epoch is split into 20 batches of B = 16 samples; each batch drives one forward + backward pass and a parameter update \theta \leftarrow \theta - \eta\,\nabla L. For 50 epochs this yields 50 \times 20 = 1{,}000 parameter updates, with each sample seen 50 times.

Figure 2:Training hierarchy: the complete dataset (N=320N = 320) is traversed once per epoch; each epoch is split into 20 batches of B=16B = 16 samples; each batch drives one forward + backward pass and a parameter update θ←θ−η ∇L\theta \leftarrow \theta - \eta\,\nabla L. For 50 epochs this yields 50×20=1,00050 \times 20 = 1{,}000 parameter updates, with each sample seen 50 times.

Practical Example: Training an autoencoder with 320 spectrograms using batch size 16 for 50 epochs:

Batch Size Selection impacts both training dynamics and computational efficiency. Larger batches provide more stable gradient estimates but require more memory and may converge to sharper minima that generalize poorly. Smaller batches introduce noise that can help escape poor local minima but increase training variance. Modern practice favors batch sizes of 32-128 for most deep learning applications, exploiting GPU parallelism while maintaining beneficial gradient noise.

2.7Overfitting and Underfitting

A critical challenge in machine learning is achieving the right model complexity: too simple and the model misses important patterns, too complex and it memorizes noise instead of learning generalizable relationships.

Underfitting occurs when a model is too simple to capture the underlying data structure. A linear model trying to fit nonlinear damage patterns will underfit, achieving poor performance on both training and test data. The model lacks the capacity to represent the true relationship between features and structural condition.

Overfitting occurs when a model is too complex, memorizing training examples including noise and outliers rather than learning general patterns. An overfitted model achieves excellent training performance but fails on new data because it has learned training-specific peculiarities that don’t generalize. In structural monitoring, an overfitted model might memorize measurement noise from specific sensors rather than learning actual damage signatures.

The solution involves several strategies:

Regularization adds penalty terms to the loss function that discourage overly complex models. L2 regularization (weight decay) penalizes large parameter values, encouraging simpler solutions. Dropout randomly disables neurons during training, preventing co-adaptation that leads to overfitting.

Cross-validation splits data into training and validation sets. Models train on training data while validation data monitors generalization performance. If validation error increases while training error decreases, overfitting is occurring.

Early stopping terminates training when validation performance stops improving, preventing the model from memorizing training noise during extended training.

For bridge monitoring, proper generalization is critical: models must detect damage in new structures under different environmental conditions, not just memorize specific training scenarios.

<Figure size 2250x600 with 3 Axes>

Figure 3:Model complexity trade-offs illustrated with polynomial regression of varying degrees on synthetic data

Model complexity and generalization. Underfitting occurs when models are too simple to capture data patterns; overfitting occurs when models memorize training noise. The optimal model balances bias and variance for best generalization.

2.7.1Detecting Overfitting: Training vs Validation Error

<Figure size 2250x600 with 3 Axes>

Figure 4:Training and validation error patterns for underfitting, good fit, and overfitting models

Training and validation error patterns reveal model quality. Underfitting shows both errors remaining high. Good fit exhibits both errors decreasing and converging closely. Overfitting displays a characteristic divergence: training error continues decreasing while validation error increases, indicating the model memorizes training data rather than learning generalizable patterns.


3Classification Foundations

Before exploring sophisticated anomaly detection methods, understanding binary classification provides essential intuition for how algorithms learn decision boundaries from data.

3.1Binary Classification

Binary classification divides data into two classes using a learned decision boundary. Given features x∈Rd\mathbf{x} \in \mathbb{R}^d, we want to predict class y∈{0,1}y \in \{0, 1\}, for example classifying bridge measurements as normal (y=0y=0) or damaged (y=1y=1).

The challenge is learning a decision boundary that separates the two classes in feature space. Simple cases allow linear separation: a straight line (2D) or hyperplane (higher dimensions) divides the classes. Complex real-world problems require nonlinear boundaries that curve through feature space.

3.2Logistic Regression

Logistic regression provides the foundation for probabilistic classification. Despite its name, logistic regression performs classification, not regression; the name reflects its mathematical formulation.

The core idea is mapping any real number to a probability between 0 and 1 using the sigmoid function:

σ(z)=11+e−z\sigma(z) = \frac{1}{1 + e^{-z}}

The sigmoid function has elegant properties: it maps z∈(−∞,+∞)z \in (-\infty, +\infty) to σ(z)∈(0,1)\sigma(z) \in (0, 1), approaching 0 as z→−∞z \to -\infty and 1 as z→+∞z \to +\infty, with σ(0)=0.5\sigma(0) = 0.5.

For classification, we compute a linear combination of features:

z=wTx+bz = \mathbf{w}^T \mathbf{x} + b

where w\mathbf{w} are weights and bb is the bias term. Applying the sigmoid gives the probability of class 1:

P(y=1∣x)=σ(wTx+b)P(y=1 \mid \mathbf{x}) = \sigma(\mathbf{w}^T \mathbf{x} + b)

We classify by thresholding this probability: if P(y=1∣x)>0.5P(y=1 \mid \mathbf{x}) > 0.5, predict class 1; otherwise predict class 0.

Training learns optimal weights w\mathbf{w} by minimizing the binary cross-entropy loss:

L(w,b)=−1n∑i=1n[yilog⁡(y^i)+(1−yi)log⁡(1−y^i)]\mathcal{L}(\mathbf{w}, b) = -\frac{1}{n}\sum_{i=1}^{n} \left[ y_i \log(\hat{y}_i) + (1-y_i) \log(1-\hat{y}_i) \right]

where y^i=σ(wTxi+b)\hat{y}_i = \sigma(\mathbf{w}^T \mathbf{x}_i + b) is the predicted probability.

Logistic regression works well for linearly separable data but struggles when classes require nonlinear boundaries. This limitation motivates more sophisticated methods like Support Vector Machines that can learn complex decision surfaces.

<Figure size 1800x750 with 3 Axes>

Figure 5:Logistic regression sigmoid function and linear decision boundary separating two classes in feature space

Logistic regression maps linear combinations of features to probabilities via the sigmoid function (left), creating a decision boundary in feature space (right). Points are classified based on whether the predicted probability exceeds 0.5.

3.3Simple Binary Classification Example

Let’s implement a practical binary classification task using scikit-learn’s LogisticRegression. This example demonstrates how easily we can train a classifier to distinguish between two classes based on just two features.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

# Generate synthetic dataset
X, y = generate_two_class_data(n_samples=200)

# Split into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.3, random_state=42
)

# Train logistic regression classifier
clf = LogisticRegression()
clf.fit(X_train, y_train)

# Make predictions
y_pred = clf.predict(X_test)

# Evaluate performance
accuracy = accuracy_score(y_test, y_pred)
print(f"Accuracy: {accuracy:.2%}")
print(classification_report(y_test, y_pred))

Now let’s see a complete working example:

Training completed successfully!
Accuracy: 100.0%
<Figure size 2100x1500 with 3 Axes>

Figure 6:Binary classification using logistic regression showing training data with decision boundary, test predictions, and convergence of training/validation loss during optimization

This example demonstrates the simplicity and effectiveness of logistic regression for binary classification. With just a few lines of code, we trained a classifier that achieves high accuracy on a two-feature dataset. The decision boundary (black dashed line) separates the two classes, with the probability contours showing the model’s confidence in its predictions. The training convergence plot shows how both training and validation loss decrease smoothly, confirming proper optimization without overfitting.

Key Observations:

This straightforward approach works well when classes are roughly linearly separable. However, real-world structural health monitoring presents a unique challenge: we typically have abundant normal data but scarce or no damage examples. This asymmetry motivates specialized methods like One-Class SVM, which we explore next.

3.4Evaluation Metrics for Classification

Before implementing One-Class SVM, we need rigorous metrics to evaluate performance. Unlike standard supervised classification where both classes appear in training, anomaly detection presents asymmetric evaluation challenges.

Confusion Matrix organizes predictions into four categories:

[True Negative (TN)False Positive (FP)False Negative (FN)True Positive (TP)]\begin{bmatrix} \text{True Negative (TN)} & \text{False Positive (FP)} \\ \text{False Negative (FN)} & \text{True Positive (TP)} \end{bmatrix}

For anomaly detection:

From the confusion matrix, we derive key performance metrics:

Accuracy measures overall correctness:

Accuracy=TP+TNTP+TN+FP+FN\text{Accuracy} = \frac{TP + TN}{TP + TN + FP + FN}

However, accuracy can be misleading with imbalanced classes (far more normal than anomalous examples).

Precision quantifies the fraction of positive predictions that are correct:

Precision=TPTP+FP\text{Precision} = \frac{TP}{TP + FP}

High precision means few false alarms, which is important for avoiding inspection fatigue.

Recall (or Sensitivity, True Positive Rate) measures the fraction of actual anomalies detected:

Recall=TPTP+FN\text{Recall} = \frac{TP}{TP + FN}

High recall means few missed damage cases, which is critical for safety.

<Figure size 2700x900 with 6 Axes>

Figure 7:Three confusion matrix scenarios demonstrating why single metrics can be misleading. Scenario 1 shows high accuracy (95%) masking complete detection failure with imbalanced data. Scenario 2 demonstrates perfect precision (100%) but dangerous low recall (30%), missing 70% of damage. Scenario 3 illustrates high recall (96%) with excessive false alarms (42%), causing inspection fatigue. These examples emphasize the necessity of balanced metrics like F1-score or ROC-AUC for reliable anomaly detection evaluation.

F1-Score harmonically balances precision and recall:

F1=2⋅Precision⋅RecallPrecision+RecallF_1 = 2 \cdot \frac{\text{Precision} \cdot \text{Recall}}{\text{Precision} + \text{Recall}}

The F1-score reaches maximum (1.0) only when both precision and recall are high.

ROC Curve (Receiver Operating Characteristic) plots True Positive Rate (TPR, also called sensitivity or recall) against False Positive Rate (FPR) across all possible classification thresholds:

TPR=TPTP+FN,FPR=FPFP+TN\text{TPR} = \frac{TP}{TP + FN}, \quad \text{FPR} = \frac{FP}{FP + TN}

Most classifiers output continuous scores (probabilities, distances, or decision values) rather than hard binary predictions. The ROC curve traces classifier performance as we sweep the decision threshold from the most conservative (classifying nearly everything as negative) to the most aggressive (classifying nearly everything as positive). Each point on the curve represents a different threshold’s (TPR, FPR) pair.

The curve reveals fundamental trade-offs: increasing detection rate (TPR) inevitably increases false alarms (FPR). The optimal operating point depends on application requirements: bridge monitoring prioritizes high recall (catching all damage) even at the cost of more false positives, while spam detection might favor high precision (few false positives) and accept some missed detections.

AUC (Area Under the ROC Curve) condenses the entire curve into a single scalar metric. Geometrically, AUC equals the area under the ROC curve in the unit square [0,1]×[0,1]. Probabilistically, AUC represents the probability that the classifier ranks a randomly chosen positive instance higher than a randomly chosen negative instance:

AUC=P(score(x+)>score(x−))\text{AUC} = P(\text{score}(\mathbf{x}_+) > \text{score}(\mathbf{x}_-))

where x+\mathbf{x}_+ is a positive sample and x−\mathbf{x}_- is a negative sample.

AUC Interpretation:

Key Advantages: AUC is threshold-independent and remains valid under class imbalance, unlike accuracy. For anomaly detection where normal cases vastly outnumber anomalies, AUC provides reliable performance assessment without threshold selection bias.

Mathematical Properties: AUC equals the Wilcoxon-Mann-Whitney U statistic normalized to [0,1], and for a binary classifier with scores s1,…,sns_1, \ldots, s_n, can be computed as:

AUC=∑i∈positive∑j∈negative1(si>sj)npositive⋅nnegative\text{AUC} = \frac{\sum_{i \in \text{positive}} \sum_{j \in \text{negative}} \mathbb{1}(s_i > s_j)}{n_{\text{positive}} \cdot n_{\text{negative}}}

where 1(⋅)\mathbb{1}(\cdot) is the indicator function. This formulation enables efficient computation even for large datasets.

<Figure size 2250x900 with 2 Axes>

Figure 8:ROC curves demonstrating classifier performance across different quality levels. Perfect classifier achieves (0,1) corner with AUC=1.0. Excellent classifier (AUC=0.95) shows strong separation. Good classifier (AUC=0.80) provides acceptable discrimination. Random classifier follows the diagonal with AUC=0.5. Optimal operating points marked for each curve balance TPR and FPR based on application requirements.

3.4.1Computing Evaluation Metrics in Python

1
2
3
4
5
6
7
8
9
10
11
12
13
from sklearn.metrics import confusion_matrix, classification_report, roc_auc_score

# Compute confusion matrix
cm = confusion_matrix(y_true, y_pred)

# Compute all metrics at once
from sklearn.metrics import precision_recall_fscore_support
precision, recall, f1, support = precision_recall_fscore_support(
    y_true, y_pred, average='binary', pos_label=1
)

# ROC-AUC score (requires decision scores, not just predictions)
auc_score = roc_auc_score(y_true, decision_scores)

3.5From Probability to Margin: Support Vector Machines

While logistic regression focuses on estimating class probabilities, Support Vector Machines (SVMs) take a geometric approach: find the decision boundary that maximizes the margin between classes. The margin is the distance from the boundary to the nearest data point from each class.

Maximizing margin leads to better generalization: a wider margin means the decision boundary is more robust to small perturbations in training data. SVMs achieve this through constrained optimization, finding the hyperplane with maximum margin while correctly classifying training examples.

The Kernel Trick is the key innovation that makes SVMs powerful for real-world problems. Many datasets are not linearly separable in their original feature space; imagine trying to separate circular clusters with a straight line. The kernel trick solves this by implicitly mapping data to higher-dimensional spaces where linear separation becomes possible.

Rather than explicitly computing these high-dimensional transformations (which would be computationally prohibitive), kernels compute inner products in the transformed space directly. For example, the RBF kernel measures similarity between data points: nearby points in original space remain nearby in transformed space, while distant points become even more separated. This similarity-based transformation creates flexible, curved decision boundaries in the original feature space without ever explicitly visiting the high-dimensional space.

Think of kernels as similarity functions that measure how “alike” two data points are. The SVM uses these similarities to determine which side of the boundary a new point belongs to: if it’s similar to normal training points, classify it as normal; if dissimilar, flag it as anomalous.

For structural health monitoring, we face a unique challenge: we don’t have examples from both classes. Training data contains only normal bridge behavior; damage examples are unavailable or extremely rare. This asymmetry motivates One-Class SVM, a specialized variant that learns boundaries around a single class, well suited for anomaly detection in infrastructure monitoring.


4One-Class SVM for Damage Detection

4.1Conceptual Understanding

Imagine monitoring a bridge by measuring three natural frequencies and three MAC values from vibration tests, giving six features per measurement. When the bridge is healthy, these six values cluster together in a predictable region of six-dimensional feature space. Your task: draw a boundary that encloses most normal measurements while excluding outliers.

This boundary-drawing problem captures the essence of One-Class SVM. The algorithm finds a compact region containing normal data, then labels any new measurement falling outside this boundary as an anomaly. Think of it like drawing a fence around a flock of sheep: any animal appearing outside the fence is unusual and warrants investigation.

Real-world data rarely forms simple spherical clusters. Features exhibit complex, nonlinear relationships: damage might manifest as subtle shifts in the correlation between frequency changes and mode shape variations. The kernel trick makes this complexity tractable by transforming data into higher dimensions where even intricate clusters become easier to enclose with simple boundaries. Linear separation impossible in original space becomes achievable in the transformed space.

<Figure size 2400x750 with 3 Axes>

Figure 9:One-Class SVM training and anomaly detection workflow with linear kernel for conceptual clarity

One-Class SVM learns a compact decision boundary around normal training data in feature space. The kernel trick implicitly maps data to higher dimensions where boundary definition becomes simpler. Support vectors (highlighted points) define the boundary; test points outside indicate anomalies.

This approach offers key advantages for bridge monitoring:

4.2Theoretical Foundation

One-Class Support Vector Machines provide a principled mathematical framework for the boundary-drawing intuition. The algorithm solves an optimization problem: find a decision boundary that encompasses normal data while maximizing the margin from the origin in a high-dimensional feature space.

Given training data {x1,x2,…,xn}\{\mathbf{x}_1, \mathbf{x}_2, \ldots, \mathbf{x}_n\} representing normal structural behavior, OC-SVM solves:

min⁡w,ξ,ρ12∥w∥2+1νn∑i=1nξi−ρ\min_{\mathbf{w}, \xi, \rho} \frac{1}{2}\|\mathbf{w}\|^2 + \frac{1}{\nu n} \sum_{i=1}^{n} \xi_i - \rho

subject to:

wTϕ(xi)≥ρ−ξi,ξi≥0,i=1,…,n\mathbf{w}^T \phi(\mathbf{x}_i) \geq \rho - \xi_i, \quad \xi_i \geq 0, \quad i = 1, \ldots, n

where:

The parameter ν\nu has intuitive interpretation: setting ν=0.05\nu=0.05 means roughly 5% of training data may lie outside the boundary, accommodating measurement noise or environmental variations.

The dual formulation introduces Lagrange multipliers αi\alpha_i and enables the kernel trick:

min⁡α12∑i,j=1nαiαjk(xi,xj)\min_{\alpha} \frac{1}{2} \sum_{i,j=1}^{n} \alpha_i \alpha_j k(\mathbf{x}_i, \mathbf{x}_j)

subject to 0≤αi≤1νn0 \leq \alpha_i \leq \frac{1}{\nu n} and ∑i=1nαi=1\sum_{i=1}^{n} \alpha_i = 1.

The kernel function k(xi,xj)=ϕ(xi)Tϕ(xj)k(\mathbf{x}_i, \mathbf{x}_j) = \phi(\mathbf{x}_i)^T \phi(\mathbf{x}_j) computes inner products in the transformed space without explicit transformation. For bridge monitoring, the Radial Basis Function (RBF) kernel works well:

k(xi,xj)=exp⁡(−γ∥xi−xj∥2)k(\mathbf{x}_i, \mathbf{x}_j) = \exp\left(-\gamma \|\mathbf{x}_i - \mathbf{x}_j\|^2\right)

where γ\gamma controls the influence radius: larger γ\gamma creates tighter, more complex boundaries.

The decision function for a new observation x\mathbf{x} becomes:

f(x)=sgn(∑i=1nαik(xi,x)−ρ)f(\mathbf{x}) = \text{sgn}\left(\sum_{i=1}^{n} \alpha_i k(\mathbf{x}_i, \mathbf{x}) - \rho\right)

Positive values (f(x)>0f(\mathbf{x}) > 0) indicate normal behavior; negative values (f(x)<0f(\mathbf{x}) < 0) suggest anomalies. The magnitude ∣f(x)∣|f(\mathbf{x})| quantifies confidence: larger negative values indicate stronger anomalies.

4.3Implementation: Modal Feature-Based Detection

We now apply One-Class SVM to bridge damage detection using modal features: three natural frequencies and three MAC values. This six-dimensional feature vector captures both global stiffness (frequencies) and local shape changes (MAC values) from vibration testing.

4.3.1Key Steps

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from sklearn.svm import OneClassSVM
from sklearn.preprocessing import StandardScaler

# Load intact bridge features for training
X_intact, X_damage, feature_names = load_modal_data()

# Standardize features (fit on training data only)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_intact)

# Train One-Class SVM on normal data only
model = OneClassSVM(kernel='rbf', nu=0.05, gamma='scale')
model.fit(X_train_scaled)

# Test on damage data (should be flagged as anomalies)
X_damage_scaled = scaler.transform(X_damage)
anomaly_scores = model.decision_function(X_damage_scaled)
predictions = model.predict(X_damage_scaled)  # -1 = anomaly, +1 = normal

4.3.2Complete Implementation

Source
One-Class SVM trained on 150 intact samples
Testing on 50 intact + 200 damaged samples
Source
✓ OC-SVM results stored in memory for visualization

4.3.3Results Summary

Loading...

4.4Visualization and Analysis

Source
<Figure size 2250x1500 with 7 Axes>

Figure 10:One-Class SVM performance analysis including decision boundary, anomaly scores, ROC curve, and feature sensitivity

The One-Class SVM successfully learns a compact decision boundary around normal bridge behavior using only intact training data. Testing reveals strong separation between intact and damaged conditions in the normalized anomaly index space. The ROC curve demonstrates excellent discrimination capability (AUC > 0.95), while the confusion matrix confirms high detection rates with minimal false alarms. Feature sensitivity analysis shows that natural frequencies exhibit the strongest damage signatures, with Frequency 1 changing by more than 10% under severe damage conditions.


5Autoencoders for Reconstruction-Based Anomaly Detection

5.1Conceptual Understanding

Imagine an artist who spent years practicing to draw only perfect circles. Given a new circle to reproduce, the artist copies it flawlessly, and the reproduction matches the original almost exactly. Now present a square to this circle-trained artist. The reproduction attempt fails; the artist, having never learned squares, produces a poor copy with significant errors. This reconstruction error signals that the square is unusual relative to the artist’s training.

Autoencoders work analogously. An encoder network compresses input data (such as a STFT spectrogram of bridge vibrations) into a compact representation called the latent code, capturing only essential features. A decoder network reconstructs the original input from this compressed code. When trained exclusively on spectrograms from a healthy bridge, the autoencoder learns to reproduce normal vibration patterns accurately.

Present the trained autoencoder with a spectrogram from a damaged bridge, and reconstruction quality degrades because the network never learned damaged patterns during training. High reconstruction error flags the anomaly. This approach scales beautifully: rather than manually engineering features like peak frequencies or spectral centroids, the network automatically discovers which patterns define normal behavior through exposure to hundreds of normal spectrogram images.

Autoencoder architecture. The encoder compresses input x into a low-dimensional latent code z; the decoder reconstructs \hat x. Training minimises L = \|x - \hat x\|^2 on normal data only. At inference, normal samples reconstruct well (\varepsilon < \tau → continue monitoring), while anomalous samples produce poor reconstructions (\varepsilon > \tau → flag for inspection).

Figure 11:Autoencoder architecture. The encoder compresses input xx into a low-dimensional latent code zz; the decoder reconstructs x^\hat x. Training minimises L=∥x−x^∥2L = \|x - \hat x\|^2 on normal data only. At inference, normal samples reconstruct well (ε<τ\varepsilon < \tau → continue monitoring), while anomalous samples produce poor reconstructions (ε>τ\varepsilon > \tau → flag for inspection).

5.2Automatic Feature Extraction

A fundamental advantage of autoencoders over traditional methods is automatic feature learning. Chapter 5 required manual extraction of features: computing FFTs for frequencies, calculating MAC values from mode shapes, computing statistical moments. Each feature required domain expertise to design and implement.

Autoencoders eliminate this manual engineering. The encoder network learns to extract features automatically during training. Early convolutional layers detect simple patterns like edges and intensity gradients in spectrograms. Deeper layers combine these primitive features into increasingly abstract representations: frequency band structures, temporal patterns, harmonic relationships. The latent code at the bottleneck represents the most compressed, information-rich description of the input.

This hierarchical feature learning mirrors how human visual perception works: early visual cortex detects edges, intermediate areas recognize textures and shapes, higher areas identify objects. Deep learning replicates this hierarchy in artificial networks.

The learned features often capture relationships that manual engineering would miss. An autoencoder might discover that certain combinations of frequency bands and temporal evolution patterns characterize normal bridge response, without an engineer explicitly programming this relationship. The network finds whatever features minimize reconstruction error on training data.

5.3From Vibration Signals to Images: STFT Spectrograms

Bridge sensors record acceleration time series, one-dimensional signals capturing vibrations over seconds or minutes. Convolutional neural networks (CNNs) excel at processing images, not raw time series. We bridge this gap through the Short-Time Fourier Transform (STFT), converting 1D signals into 2D time-frequency spectrograms.

STFT applies Fourier transforms to overlapping time windows, creating a matrix where rows represent frequencies, columns represent time, and pixel intensity indicates energy at each time-frequency location. Damage alters bridge dynamics: frequencies shift, modes change, and damping increases, all visible as pattern changes in spectrograms.

Converting bridge acceleration signals x(t) to STFT spectrograms |X(t, f)|^2 for CNN training. The time signal is split into overlapping windows (w_1, w_2, w_3, \ldots with 50% overlap), each transformed via FFT and stacked into a 2-D time-frequency image. With n sensors and m time windows the dataset has N = n \times m training samples feeding the pipeline raw signal → windowed FFT → spectrogram → CNN → classification.

Figure 12:Converting bridge acceleration signals x(t)x(t) to STFT spectrograms ∣X(t,f)∣2|X(t, f)|^2 for CNN training. The time signal is split into overlapping windows (w1,w2,w3,…w_1, w_2, w_3, \ldots with 50% overlap), each transformed via FFT and stacked into a 2-D time-frequency image. With nn sensors and mm time windows the dataset has N=n×mN = n \times m training samples feeding the pipeline raw signal → windowed FFT → spectrogram → CNN → classification.

5.3.1Example: Real Bridge STFT Spectrogram

<Figure size 2250x1200 with 8 Axes>

Figure 13:STFT spectrograms from bridge vibration measurements across multiple sensors showing time-frequency patterns

The STFT of a signal x(t)x(t) is defined as:

X(t,f)=∫−∞∞x(τ)w(τ−t)e−j2πfτdτX(t, f) = \int_{-\infty}^{\infty} x(\tau) w(\tau - t) e^{-j2\pi f \tau} d\tau

where w(τ)w(\tau) is a window function (typically Hann or Hamming) centered at time tt. In discrete form for digital signals:

X[m,k]=∑n=0N−1x[n]w[n−m]e−j2πkn/NX[m, k] = \sum_{n=0}^{N-1} x[n] w[n - m] e^{-j2\pi kn/N}

The spectrogram is the squared magnitude:

S[m,k]=∣X[m,k]∣2S[m, k] = |X[m, k]|^2

A bridge monitored with multiple sensors over multiple time periods generates a large dataset. For example, 8 sensors measured over 20 time periods, with each time window producing 2 spectrogram parts, yields 320 spectrograms, each a grayscale image. Training the autoencoder on these intact bridge images teaches it normal spectral patterns.

Alternative Approach: Continuous Wavelet Transform (CWT) also produces time-frequency representations with better temporal localization for transient events. Both STFT and wavelets work; this chapter uses STFT for computational simplicity and widespread adoption in signal processing.

5.4Convolutional Autoencoder Architecture

Standard fully-connected autoencoders treat images as flat vectors, destroying spatial structure. Convolutional autoencoders preserve 2D relationships through convolutional layers that process local image regions, respecting the spatial topology of spectrograms.

The Encoder downsamples through strided convolutions: each layer reduces spatial dimensions while increasing feature channels. For a 128×128 input:

  1. Conv2D(32, kernel=3, stride=2): 128×128×1 → 64×64×32

  2. Conv2D(64, kernel=3, stride=2): 64×64×32 → 32×32×64

  3. Conv2D(128, kernel=3, stride=2): 32×32×64 → 16×16×128

  4. Flatten + Dense: 16×16×128 → latent vector (e.g., 32 dimensions)

Each layer detects increasingly abstract patterns. Batch normalization after each convolution stabilizes training by normalizing layer activations.

The Decoder mirrors this process with transposed convolutions (also called deconvolutions), upsampling back to original dimensions:

  1. Dense + Reshape: latent vector → 16×16×128

  2. ConvTranspose2D(64): 16×16×128 → 32×32×64

  3. ConvTranspose2D(32): 32×32×64 → 64×64×32

  4. ConvTranspose2D(1): 64×64×32 → 128×128×1 (reconstructed spectrogram)

During training, the network minimizes reconstruction error through backpropagation. The loss function measures dissimilarity between input x\mathbf{x} and reconstruction x^\hat{\mathbf{x}}:

L(ϕ,ψ)=1N∑i=1N∥xi−gψ(fϕ(xi))∥2+λΩ(ϕ,ψ)\mathcal{L}(\phi, \psi) = \frac{1}{N}\sum_{i=1}^{N} \|\mathbf{x}_i - g_{\psi}(f_{\phi}(\mathbf{x}_i))\|^2 + \lambda \Omega(\phi, \psi)

where:

The network learns to compress normal patterns efficiently, minimizing reconstruction error on intact bridge spectrograms. Testing on damaged bridge spectrograms produces high errors, the anomaly signal.

5.5Preventing Overfitting in Autoencoder Training

Autoencoders risk overfitting: memorizing individual training spectrograms rather than learning general patterns of normal bridge behavior. Several techniques prevent this:

Early Stopping: Monitor reconstruction error on a held-out validation set. Training continues while validation error decreases. When validation error plateaus or increases while training error still decreases, stop training, since the model is beginning to overfit.

L2 Regularization (weight decay) penalizes large weights:

Ltotal=LMSE+λ∑iwi2\mathcal{L}_{\text{total}} = \mathcal{L}_{\text{MSE}} + \lambda \sum_{i} w_i^2

This encourages simpler models that generalize better.

Dropout randomly disables neurons during training, preventing co-adaptation where neurons learn to correct each other’s errors in training-specific ways.

Data Augmentation (for images) artificially expands training data through transformations like rotation, scaling, or noise addition. For spectrograms, careful augmentation preserves physical validity, since we can’t arbitrarily rotate a time-frequency representation.

Validation Monitoring splits training data: 80% for training, 20% for validation. Validation data never updates weights but provides an independent performance estimate.

5.6Anomaly Detection Through Reconstruction Error

Once trained on normal bridge spectrograms, the autoencoder detects anomalies by measuring reconstruction quality. For each test spectrogram xtest\mathbf{x}_{\text{test}}:

  1. Encode: z=fϕ(xtest)\mathbf{z} = f_{\phi}(\mathbf{x}_{\text{test}})

  2. Decode: x^=gψ(z)\hat{\mathbf{x}} = g_{\psi}(\mathbf{z})

  3. Compute Error: E=∥xtest−x^∥2E = \|\mathbf{x}_{\text{test}} - \hat{\mathbf{x}}\|^2

High reconstruction error EE indicates an anomaly: the network cannot reproduce the pattern because it differs from training data.

To set detection thresholds, we normalize errors relative to validation set performance:

Anomaly Score=∥Etest−μval∥σval\text{Anomaly Score} = \frac{\|E_{\text{test}} - \mu_{\text{val}}\|}{\sigma_{\text{val}}}

where μval\mu_{\text{val}} and σval\sigma_{\text{val}} are mean and standard deviation of validation errors. Scores exceeding a threshold (e.g., 3 standard deviations) flag anomalies.

Alternatively, use the 99th percentile of validation errors as the threshold; classifying the top 1% of reconstruction errors as anomalies provides a statistically rigorous criterion.

5.7Implementation: STFT Spectrogram-Based Detection

We now implement a convolutional autoencoder for bridge damage detection using STFT spectrograms. The dataset contains 320 training images (normal bridge) and 80 test images (damaged bridge) from the ch07_data/STFT_Images/ directory.

5.7.1Teaching Code: Architecture Overview

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import torch
import torch.nn as nn

# Define encoder: downsample through convolutions
encoder = nn.Sequential(
    nn.Conv2d(1, 32, kernel_size=3, stride=2, padding=1),  # 300x400 -> 150x200
    nn.BatchNorm2d(32), nn.ReLU(),
    nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),  # -> 75x100
    # ... continue downsampling ...
)

# Define decoder: upsample through transposed convolutions  
decoder = nn.Sequential(
    nn.ConvTranspose2d(128, 64, kernel_size=3, stride=2, padding=1, output_padding=1),
    nn.BatchNorm2d(64), nn.ReLU(),
    nn.ConvTranspose2d(64, 1, kernel_size=3, stride=2, padding=1, output_padding=1),
    nn.Sigmoid()  # Output in [0, 1]
)

# Training loop
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
loss = nn.functional.mse_loss(reconstructed, original)

5.7.2Complete Implementation

GPU available: False, used: False
TPU available: False, using: 0 TPU cores
💡 Tip: For seamless cloud logging and experiment tracking, try installing [litlogger](https://pypi.org/project/litlogger/) to enable LitLogger, which logs metrics and artifacts automatically to the Lightning Experiments platform.
💡 Tip: For seamless cloud uploads and versioning, try installing [litmodels](https://pypi.org/project/litmodels/) to enable LitModelCheckpoint, which syncs automatically with the Lightning model registry.
Data loaded: 256 training, 64 validation, 80 test samples

Training autoencoder...
`Trainer.fit` stopped: `max_epochs=30` reached.
Training completed in 30 epochs

5.7.3Training Progress

Warning: No training loss column found in metrics.csv
<Figure size 1500x900 with 1 Axes>

Figure 14:Autoencoder training and validation loss curves showing convergence and model performance

5.7.4Testing and Anomaly Detection

Source

5.7.5Results Summary

Loading...

5.8Visualization and Analysis

Source
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[21], line 81
     77 
     78 # 4. Normalized Damage Score - Box Plot
     79 ax = fig.add_subplot(gs[2, 1])
     80 data_to_plot = [val_scores_norm, test_scores_norm]
---> 81 bp = ax.boxplot(data_to_plot, labels=['Normal\n(Validation)', 'Damaged\n(Test)'],
     82                 patch_artist=True, widths=0.6,
     83                 medianprops=dict(color=COLORS['warning'], linewidth=2.5))
     84 box_colors = [COLORS['success'], COLORS['warning']]

    [... skipping hidden 1 frame]

File /opt/hostedtoolcache/Python/3.11.16/x64/lib/python3.11/site-packages/matplotlib/__init__.py:1531, in _preprocess_data.<locals>.inner(ax, data, *args, **kwargs)
   1528 __tracebackhide__ = True
   1530 if data is None:
-> 1531     return func(
   1532         ax,
   1533         *map(cbook.sanitize_sequence, args),
   1534         **{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
   1536 bound = new_sig.bind(ax, *args, **kwargs)
   1537 auto_label = (bound.arguments.get(label_namer)
   1538               or bound.kwargs.get(label_namer))

TypeError: Axes.boxplot() got an unexpected keyword argument 'labels'
<Figure size 2400x1800 with 10 Axes>

Figure 15:Convolutional autoencoder reconstruction quality on normal and damaged bridge spectrograms with error analysis

5.8.1Performance Evaluation

Source

Figure 16:Confusion matrix for autoencoder-based anomaly detection showing classification performance on normal and damaged bridge spectrograms

Source

The convolutional autoencoder demonstrates excellent reconstruction of normal bridge spectrograms (validation SSIM > 0.98) while producing significantly higher errors on damaged bridge spectrograms. The error distributions show clear separation between normal and damaged conditions, with damaged spectrograms exhibiting MSE values 2-3× higher than normal. Error maps reveal that reconstruction failures concentrate in specific frequency-time regions where structural dynamics changed due to damage, providing interpretable damage signatures without manual feature engineering.


6Advanced Methods and Future Directions

While this chapter focused on One-Class SVM and Autoencoders as foundational approaches, the field of machine learning for structural health monitoring continues evolving with increasingly sophisticated methods.

Generative Adversarial Networks (GANs) extend generative modeling through adversarial training between a generator creating synthetic data and a discriminator distinguishing real from synthetic samples. For SHM, GANs can generate realistic damage scenarios for training classifiers when actual damage data remains scarce. The discriminator itself becomes a powerful anomaly detector, identifying inputs deviating from the learned distribution of normal structural responses.

Graph Neural Networks (GNNs) explicitly model spatial relationships between sensors as graph structures, with sensors as nodes and structural connections as edges. This architecture naturally captures how vibrations propagate through bridge structures, enabling more accurate damage localization. Message passing between nodes allows the network to learn how local damage affects global structural behavior.

Long Short-Term Memory (LSTM) networks and other recurrent architectures excel at modeling temporal dependencies in continuous monitoring data. These networks maintain hidden states evolving through time, capturing how structural responses change under varying operational conditions. Bidirectional LSTMs process sequences in both forward and backward directions, improving detection of subtle anomalies manifesting as deviations from expected temporal patterns.

Transformer architectures with self-attention mechanisms represent the current frontier, processing entire time series simultaneously while learning which temporal segments deserve focus. Attention weights provide interpretable insights into which signal aspects indicate potential damage.

These advanced methods build on the foundations established in this chapter: unsupervised learning from normal data, automatic feature extraction, and reconstruction-based anomaly detection remain central to modern approaches.


7Summary

This chapter introduced machine learning approaches for anomaly detection in bridge structural health monitoring, addressing fundamental challenges of environmental variability, operational complexity, and damage data scarcity. Through detailed implementations of One-Class Support Vector Machines and Convolutional Autoencoders, we demonstrated how unsupervised learning methods effectively identify structural anomalies without requiring extensive damage examples.

The One-Class SVM approach showed how stable decision boundaries in feature space can separate normal operational states from potential damage conditions, achieving high detection rates while maintaining acceptable false positive levels. Training exclusively on modal features (natural frequencies and MAC values) from intact bridge measurements, the algorithm learned compact boundaries that generalized well to detecting damage in test data.

The convolutional autoencoder implementation illustrated how reconstruction-based anomaly detection naturally handles high-dimensional sensor data through automatic feature learning. By training on STFT spectrograms from normal bridge vibrations, the network learned compressed latent representations capturing essential patterns of healthy structural behavior. Reconstruction errors on damaged bridge spectrograms provided clear anomaly signals without manual feature engineering.

Both methods provide practical solutions for real-world bridge monitoring systems where continuous assessment under varying conditions remains essential for infrastructure safety. The combination of automated feature learning, unsupervised training paradigms, and reliable anomaly detection creates a powerful framework for identifying structural degradation before catastrophic failure occurs.


8Exercises