Why Site Response Matters
The 1985 Mexico City earthquake originated more than 350 km away, yet it devastated a city built on soft lake-bed sediments. The soil deposit acted like a bowl of jelly on a shaking table: ground motion that was modest at the bedrock level was amplified two to five times by the time it reached the surface. Thousands of structures collapsed, most of them founded on the softest soils.
Site response analysis quantifies this amplification. Traditional methods rely on 1-D wave-propagation theory (e.g. SHAKE, DEEPSOIL), which requires detailed shear-wave velocity profiles, dynamic soil properties, and significant computational effort for every new site. Can supervised learning offer a faster, data-driven alternative — trained on thousands of existing analyses — that predicts the amplification factor directly from routinely available soil parameters?
This sub-chapter is the capstone of Chapter 2. We will apply every concept covered so far — feature engineering, model selection, training-testing splits, cross-validation, evaluation metrics, overfitting countermeasures — to a single, realistic geotechnical problem. By the end, you will have seen the complete ML pipeline in action and be ready to tackle similar problems on your own projects.
The pipeline we will follow:
- Problem definition — what are we predicting and why?
- Data collection — gathering borehole logs, shear-wave velocity profiles, and earthquake records
- Feature engineering — deriving predictive features like Vs30 from raw data
- Model selection — comparing Linear Regression, Random Forest, and SVM
- Training & evaluation — cross-validation and performance metrics
- Results interpretation — feature importance and residual analysis
- Deployment considerations — moving from notebook to field tool
This capstone draws on material from every preceding sub-chapter in Chapter 2. In particular, make sure you are comfortable with: Sub-chapter 2.1 (Core ML Concepts), 2.3 (Linear Regression), 2.5 (Random Forest), 2.7 (Support Vector Machines), 2.8 (Model Evaluation), and 2.9 (Overfitting & Regularization).
Step 1: Problem Definition
Before writing a single line of code, we need a crisp problem statement. In site response analysis, the quantity we care about most is the site amplification factor (AF): the ratio of spectral acceleration at the ground surface to that at the bedrock for a given period. A higher AF means the soil deposit amplifies ground motion more.
Amplification Factor (AF) = Sa(surface) / Sa(bedrock)
Where:
Sa(surface) = Spectral acceleration at ground surface
Sa(bedrock) = Spectral acceleration at bedrock (input motion)
Typical range: 0.5 (de-amplification) to 5.0+ (strong amplification)
Depends on: soil type, layer thickness, shear-wave velocity, input motion intensity
We frame this as a regression problem: given a set of measurable soil and earthquake properties, predict the continuous-valued amplification factor. This is squarely in the domain of supervised learning — we have labelled examples (existing site response analyses) where both the input features and the output AF are known.
Why Not Classification?
We could bin the amplification factor into categories (e.g. "Low", "Medium", "High") and treat it as classification. However, civil engineers need a number to plug into structural design equations. Regression preserves the continuous nature of AF and is far more useful in practice.
Scope and Assumptions
- We focus on 1-D site response: vertically propagating shear waves through horizontal soil layers. This covers the vast majority of practical applications.
- We predict AF at a single spectral period (e.g. T = 0.5 s). Extending to multiple periods is straightforward by training separate models or using multi-output regression.
- We assume access to standard geotechnical investigation data: borehole logs, SPT blow counts, shear-wave velocity measurements, and earthquake recording metadata.
Step 2: Data Collection
Real site response datasets are compiled by running hundreds or thousands of 1-D ground response analyses (e.g. using SHAKE or DEEPSOIL) across a variety of soil profiles and input motions. For this case study, we describe a realistic synthetic dataset with 2 000 records. Each record represents one site-motion pair and contains the following raw fields:
| Field | Description | Typical Range | Source |
|---|---|---|---|
depth_to_bedrock |
Total thickness of soil above bedrock (m) | 5 – 100 m | Borehole log |
avg_vs |
Depth-weighted average shear-wave velocity (m/s) | 100 – 760 m/s | MASW / downhole test |
vs_surface |
Shear-wave velocity of the topmost layer (m/s) | 80 – 400 m/s | MASW / downhole test |
num_layers |
Number of distinct soil layers | 2 – 15 | Borehole log |
avg_spt_n |
Average SPT-N value over the profile | 3 – 60 | SPT test |
plasticity_index |
Average plasticity index (PI) of cohesive layers | 0 – 50 | Atterberg limits |
water_table_depth |
Depth to groundwater table (m) | 0 – 20 m | Borehole log |
pga_bedrock |
Peak ground acceleration of input motion (g) | 0.01 – 0.60 g | Earthquake record |
magnitude |
Earthquake moment magnitude (Mw) | 4.5 – 8.0 | Seismological catalogue |
distance |
Closest distance to rupture surface (km) | 5 – 200 km | Seismological catalogue |
AF |
Amplification factor at T = 0.5 s (target) | 0.5 – 5.0 | SHAKE / DEEPSOIL output |
Before modelling, we would inspect the dataset for: (1) missing values — some boreholes lack Vs measurements, so we might impute from SPT correlations; (2) outliers — unrealistic AF values may indicate numerical instability in the SHAKE run; (3) class imbalance — most sites have moderate AF, very few have extreme amplification; (4) unit consistency — ensure all velocities are in m/s, all depths in metres, etc.
Data Splitting Strategy
We reserve 80 % of the data (1 600 records) for training and 20 % (400 records) for final testing. Within the training set, we use 5-fold cross-validation for hyperparameter tuning, as covered in Sub-chapter 2.8.
from sklearn.model_selection import train_test_split, cross_val_score
X = df[feature_columns]
y = df['AF']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42
)
# 5-fold CV used within X_train for model tuning
Step 3: Feature Engineering
Raw measurements rarely enter a model directly. Feature engineering is the process of transforming and combining raw variables into features that encode domain knowledge and make the model's job easier.
Derived Feature: Vs30
The single most important derived feature in earthquake engineering is Vs30 — the time-averaged shear-wave velocity in the upper 30 metres of the soil profile. It is used worldwide for site classification (NEHRP Site Classes A through E) and is a required parameter in modern ground motion prediction equations.
Vs30 = 30 / sum( h_i / Vs_i )
Where:
h_i = thickness of layer i within the top 30 m
Vs_i = shear-wave velocity of layer i
Site Classification (NEHRP / Eurocode 8):
Class A (Hard rock): Vs30 > 1500 m/s
Class B (Rock): 760 < Vs30 <= 1500
Class C (Dense soil): 360 < Vs30 <= 760
Class D (Stiff soil): 180 < Vs30 <= 360
Class E (Soft soil): Vs30 < 180
Additional Derived Features
- Impedance contrast — ratio of bedrock Vs to average soil Vs. Higher contrast leads to stronger amplification due to trapped energy at the soil-bedrock interface.
- Fundamental period (T0) — estimated as 4H/Vs (quarter-wavelength approximation), where H is the total soil column depth and Vs is the average shear-wave velocity. When the earthquake's dominant period is close to T0, resonance occurs.
- log(PGAbedrock) — the logarithm of the bedrock PGA. Ground motion parameters in earthquake engineering are typically log-normally distributed, so working in log space linearises the relationship.
- Vs30 / depth_to_bedrock — a proxy for the overall "stiffness gradient" of the deposit. High values indicate a thin, stiff deposit; low values indicate a thick, soft deposit.
- SPT-N / depth — normalised blow count that accounts for increasing confining pressure. Similar concept to the (N1)60 correction used in liquefaction analysis.
Feature Engineering Is Domain Knowledge
Notice that every derived feature above comes from decades of earthquake engineering research. Vs30, impedance contrast, and the fundamental period are not arbitrary combinations — they have clear physical meaning. This is where civil engineering expertise becomes a superpower in machine learning. A data scientist without domain knowledge might never think to compute the impedance contrast or the quarter-wavelength period, yet these features dramatically improve model accuracy.
Final Feature Set
| # | Feature | Type | Notes |
|---|---|---|---|
| 1 | Vs30 | Derived | Primary site parameter |
| 2 | depth_to_bedrock | Raw | Soil column thickness |
| 3 | impedance_contrast | Derived | Vs_bedrock / avg_vs |
| 4 | fundamental_period | Derived | 4H / avg_vs |
| 5 | log_pga_bedrock | Derived | log10(pga_bedrock) |
| 6 | magnitude | Raw | Earthquake Mw |
| 7 | distance | Raw | Closest distance to rupture |
| 8 | avg_spt_n | Raw | Average blow count |
| 9 | plasticity_index | Raw | Cohesive soil indicator |
| 10 | water_table_depth | Raw | Saturation indicator |
| 11 | vs_gradient | Derived | Vs30 / depth_to_bedrock |
| 12 | norm_spt | Derived | avg_spt_n / depth_to_bedrock |
All features are standardised (zero mean, unit variance) before feeding them to Linear Regression and SVM. Random Forest does not require standardisation but is not harmed by it either.
Step 4: Model Selection
We compare three supervised learning algorithms, each representing a different modelling philosophy. This mirrors a common workflow in practice: start simple, add complexity only if the data warrants it.
Candidate 1: Ridge Regression (Linear)
A regularised linear model (L2 penalty) — our baseline. It assumes a linear relationship between features and AF. Fast to train, easy to interpret, and provides a floor for comparison. If a linear model performs well, there may be no need for more complex approaches.
AF = w0 + w1*Vs30 + w2*depth + w3*impedance + ... + w12*norm_spt
Loss = MSE + alpha * sum(w_i^2) # L2 regularization
alpha (regularization strength) tuned via cross-validation
Typical best alpha: 1.0 to 10.0
Candidate 2: Random Forest
An ensemble of decision trees, each trained on a bootstrap sample. Random Forest captures non-linear relationships and feature interactions automatically. It is robust to outliers and does not require feature scaling. The main hyperparameters are the number of trees, maximum depth, and minimum samples per leaf.
n_estimators = [100, 200, 500] # number of trees
max_depth = [10, 20, None] # tree depth limit
min_samples_leaf = [2, 5, 10] # minimum leaf size
max_features = ['sqrt', 0.5] # features per split
Grid search with 5-fold CV over the training set
Candidate 3: Support Vector Regression (SVR)
SVR with an RBF kernel maps the input features into a high-dimensional space where a linear fit captures non-linear relationships. It is particularly effective when the number of features is moderate relative to the number of samples. Key hyperparameters are C (regularisation), epsilon (insensitivity tube), and gamma (RBF kernel width).
kernel = 'rbf'
C = [0.1, 1, 10, 100] # regularization
epsilon = [0.01, 0.05, 0.1] # tube width
gamma = ['scale', 'auto'] # kernel coefficient
Grid search with 5-fold CV over the training set
Why These Three?
Ridge Regression is the simplest interpretable baseline. Random Forest is the go-to non-linear model for tabular data and provides built-in feature importance. SVR with RBF is a strong kernel-based learner that often excels when data is not too large. Together, they span the complexity spectrum from linear to highly non-linear.
Step 5: Training & Evaluation
Each model is trained on the 1 600-record training set using 5-fold cross-validation for hyperparameter tuning. The best configuration of each model is then evaluated on the held-out 400-record test set. The metrics we report are:
- R2 — coefficient of determination (closer to 1 is better)
- RMSE — root mean squared error (lower is better)
- MAE — mean absolute error (lower is better)
- CV RMSE — average RMSE across 5 cross-validation folds (indicates generalisation)
Cross-Validation Results (Training Set)
| Model | CV R2 (mean) | CV RMSE (mean) | CV MAE (mean) | Training Time |
|---|---|---|---|---|
| Ridge Regression | 0.72 | 0.41 | 0.32 | < 1 s |
| Random Forest | 0.93 | 0.21 | 0.15 | ~12 s |
| SVR (RBF) | 0.88 | 0.27 | 0.20 | ~45 s |
Test Set Results (Final Evaluation)
| Model | Test R2 | Test RMSE | Test MAE | Overfit? |
|---|---|---|---|---|
| Ridge Regression | 0.71 | 0.42 | 0.33 | No (high bias) |
| Random Forest | 0.92 | 0.22 | 0.16 | Minimal |
| SVR (RBF) | 0.87 | 0.28 | 0.21 | Minimal |
Interpreting the Results
Ridge Regression achieves R2 = 0.71, meaning it explains 71 % of the variance in AF. This is respectable but leaves significant prediction error. The relationship between soil properties and amplification is inherently non-linear — a linear model cannot fully capture resonance effects, impedance trapping, and nonlinear soil behaviour.
Random Forest is the clear winner with R2 = 0.92 and test RMSE of 0.22. The gap between CV and test metrics is small, indicating excellent generalisation. The ensemble approach effectively captures the non-linear interactions between Vs30, depth, and input motion intensity.
SVR performs well (R2 = 0.87) but falls short of Random Forest. Its computational cost is also significantly higher, scaling roughly as O(n2) to O(n3) with sample size.
Step 6: Results Interpretation
A model that scores well on metrics is necessary but not sufficient. We also need to understand why it makes the predictions it does and where it fails. This is especially critical in civil engineering, where a misguided prediction could lead to structural damage or loss of life.
Feature Importance (Random Forest)
Random Forest provides built-in feature importance scores based on the average reduction in impurity (Gini importance) or the decrease in out-of-bag accuracy when a feature is permuted. Our model yields the following ranking:
Rank Feature Importance
---- -------------------- ----------
1 impedance_contrast 0.243
2 Vs30 0.198
3 fundamental_period 0.157
4 log_pga_bedrock 0.112
5 depth_to_bedrock 0.089
6 magnitude 0.064
7 distance 0.042
8 plasticity_index 0.035
9 avg_spt_n 0.027
10 water_table_depth 0.018
11 vs_gradient 0.010
12 norm_spt 0.005
The top three features — impedance contrast, Vs30, and fundamental period — together account for nearly 60 % of the model's predictive power. These are precisely the features that earthquake engineers know to be physically controlling: a sharp velocity contrast traps seismic energy, low Vs30 indicates soft soil prone to amplification, and the fundamental period governs resonance.
Physics-Consistent Feature Importance
The fact that the ML model independently identifies impedance contrast and Vs30 as the most important features is a strong validation signal. If the model had instead ranked, say, water_table_depth as the most important feature, we would suspect data leakage, a proxy variable, or a bug in the pipeline. ML results should always be sanity-checked against domain knowledge.
Residual Analysis
Residuals (predicted AF minus observed AF) reveal systematic patterns that summary metrics might miss. We examine:
- Residuals vs. predicted value — ideally randomly scattered around zero. A funnel shape indicates heteroscedasticity (prediction uncertainty grows with AF).
- Residuals vs. Vs30 — if the model systematically over-predicts AF for very soft soils (Vs30 < 150) or under-predicts for stiff soils, we may need to add interaction terms or train separate models for different site classes.
- Histogram of residuals — should be approximately normal and centred at zero. A skewed distribution suggests the model has a systematic bias in one direction.
For our Random Forest model, the residuals are approximately normally distributed with mean near zero and standard deviation of 0.22 (matching the RMSE). There is a slight tendency to under-predict extreme amplification (AF > 4.0), which is expected given that extreme events are rare in the training data. This is a known challenge and can be addressed with oversampling or a specialised high-AF model.
Residuals = Predicted AF - Observed AF
Mean residual: 0.003 (near zero = unbiased)
Std of residuals: 0.218 (matches RMSE)
Min residual: -0.89 (worst under-prediction)
Max residual: 0.72 (worst over-prediction)
95% of predictions fall within +/- 0.44 of the true AF
Step 7: Deployment Considerations
A trained model sitting in a Jupyter notebook is not useful to the field engineer standing at a borehole. Deployment bridges the gap between research and practice.
Deployment Options
- REST API — Wrap the model in a lightweight web service (e.g. Flask or FastAPI). The engineer enters soil properties through a web form or sends a JSON request, and receives the predicted AF instantly. Ideal for office-based design work.
- Spreadsheet plug-in — Export the Random Forest as an ONNX model and call it from an Excel add-in. Many geotechnical engineers live in spreadsheets, so meeting them where they are reduces adoption friction.
- Mobile app — A field-ready app that accepts borehole log data (even manually entered) and returns predicted AF on-site. Useful during preliminary site investigations when full site response analysis is not yet justified.
- Embedded in BIM — Integrate the model into Building Information Modelling workflows so structural engineers can automatically fetch site-specific amplification factors during seismic design.
Monitoring and Retraining
Once deployed, the model needs ongoing care:
- Input validation — Reject requests with features outside the training range (e.g. Vs30 > 800 m/s when the model was trained on Vs30 up to 760). Extrapolation is dangerous.
- Drift detection — If new site investigation data consistently falls outside the model's training distribution, the model may become stale. Periodic retraining with new data is essential.
- Uncertainty quantification — Report prediction intervals, not just point estimates. A prediction of AF = 2.5 +/- 0.4 is far more useful than AF = 2.5 alone.
- Audit trail — Log every prediction with its input features, model version, and timestamp. This is critical for regulatory compliance and forensic engineering.
An ML-based site response predictor should be viewed as a screening tool, not a replacement for rigorous site-specific analysis. For critical structures (hospitals, nuclear facilities, major bridges), full 1-D or 2-D site response analysis remains the standard of care. The ML model excels for rapid preliminary assessment, parametric studies, and situations where detailed Vs profiles are not yet available.
Pipeline Summary
Let us consolidate the entire pipeline into a single view. Every step below maps directly to a concept covered in Chapter 2:
Define the Problem
Predict site amplification factor (AF) from soil and earthquake properties. Regression problem. Target: continuous AF at T = 0.5 s. (Sub-chapter 2.1)
Collect & Clean Data
2 000 records from SHAKE/DEEPSOIL runs. Handle missing Vs with SPT correlations. Remove outliers. 80/20 train-test split. (Sub-chapter 2.2)
Engineer Features
Derive Vs30, impedance contrast, fundamental period, log(PGA). 12 total features. Standardise for linear models and SVM. (Sub-chapter 2.2)
Select & Train Models
Ridge Regression, Random Forest, SVR. Grid search with 5-fold CV. Random Forest selected as best performer (R2 = 0.92). (Sub-chapters 2.3, 2.5, 2.7)
Evaluate & Interpret
Test RMSE = 0.22, MAE = 0.16. Feature importance confirms physics (impedance contrast, Vs30 dominant). Residuals ~normal. (Sub-chapters 2.8, 2.9)
Deploy & Monitor
REST API or spreadsheet plug-in. Input validation, drift detection, uncertainty reporting, audit logging. (Beyond Chapter 2)
Demo 1: Interactive Soil Profile Builder
Build a soil profile by stacking layers with adjustable properties. The model computes Vs30, impedance contrast, and the estimated fundamental period in real time, then predicts the site amplification factor using a simplified regression model. Experiment with soft versus stiff soils, shallow versus deep profiles, and see how the predicted AF responds.
Demo 2: Model Comparison Dashboard
Toggle between the three models and watch the accuracy metrics update in real time. Adjust the training data size to see how each model responds to limited data. Notice how Random Forest maintains strong performance across data sizes while Ridge Regression plateaus quickly.
Key Takeaways
What We Learned
- Domain knowledge is the secret weapon. Features like Vs30, impedance contrast, and fundamental period — all rooted in earthquake engineering theory — dramatically outperform raw measurements.
- Start simple, add complexity only if needed. Ridge Regression provides a fast, interpretable baseline. Random Forest delivered significantly better accuracy because the underlying relationship is non-linear.
- Cross-validation prevents self-deception. All three models showed similar CV and test performance, confirming that none was severely overfitting.
- Feature importance should match physics. If ML identifies physically meaningful features as most important, the model is likely learning the right patterns. If it does not, investigate data leakage or engineering errors.
- Residual analysis catches what metrics miss. Our model slightly under-predicts extreme amplification — a finding that would be invisible from R2 alone.
- Deployment is part of the project. A model is only useful if it reaches the practitioner. Plan for input validation, uncertainty quantification, and retraining from day one.
Check Your Understanding
Chapter 2 Complete
Congratulations — you have completed Chapter 2: Supervised Learning. From the foundations of regression and classification through to this capstone site response analysis, you now have a solid grasp of the most widely used branch of machine learning. You understand how to frame a problem, engineer features, select and train models, evaluate performance, interpret results, and think about deployment.
In Chapter 3: Unsupervised Learning, we will explore algorithms that work without labelled data — clustering, dimensionality reduction, and anomaly detection. These techniques are invaluable for discovering hidden patterns in structural health monitoring data, grouping similar soil profiles, and detecting anomalies in construction quality control.
What Comes Next
Chapter 3 opens with unsupervised learning fundamentals and quickly moves to K-means clustering (imagine automatically grouping hundreds of soil samples into distinct categories), principal component analysis (reducing a 50-sensor structural monitoring dataset to its key dimensions), and anomaly detection (flagging the one bridge accelerometer reading that does not fit the pattern). The transition from supervised to unsupervised learning is one of the most exciting leaps in applied ML.