Chapter 2 — Sub-chapter 2.4

Classification Basics

Not every engineering question asks "how much?" Sometimes the question is "which category?" — does this concrete specimen pass or fail? Is this soil sample sand, clay, or silt? Is this structure safe or non-compliant? Classification is the branch of supervised learning that answers categorical questions, and it is everywhere in civil engineering practice.

35 min read 2 interactive demos 4 quiz questions

From "How Much?" to "Which One?"

In Sub-chapters 2.2 and 2.3 you built regression models that predicted a continuous number — concrete strength in MPa, settlement in millimetres, stress in kPa. The output lived on a smooth number line with infinite possible values.

But many engineering decisions are categorical. A building inspector does not say "the structure is 73.4% safe." They say pass or fail. A geotechnical report does not say "the soil is 0.62 along the clay-sand continuum." It says clay, sand, or silt. These are classification problems, and they require a different family of algorithms that output discrete class labels instead of continuous numbers.

Classification is arguably the most common machine learning task in civil engineering practice. Every quality control check, every safety inspection, every material categorisation, and every damage detection pipeline is, at its core, a classification problem. By the end of this sub-chapter you will understand how classifiers work, when to use them, and how to evaluate whether they are performing well.

We will cover:

  • The difference between classification and regression
  • Binary vs. multi-class classification
  • Decision boundaries — how classifiers carve up feature space
  • The k-Nearest Neighbours (k-NN) algorithm — your first classifier
  • The confusion matrix — the essential evaluation tool
  • Real-world civil engineering applications

Classification vs. Regression

Both classification and regression are supervised learning tasks. They both learn from labelled training data. The difference is in the nature of the label:

Regression

The label is a continuous number. The model outputs a value on a number line. Examples: predicting concrete strength (32.7 MPa), settlement (14.2 mm), or traffic volume (8,350 vehicles/day). The loss function measures how far the prediction is from the true value (e.g., mean squared error).

Classification

The label is a discrete category (also called a class). The model outputs one of a finite set of labels. Examples: pass/fail, sand/clay/silt, damaged/undamaged, low-risk/medium-risk/high-risk. The loss function measures how often the prediction matches the true label (e.g., accuracy, or more nuanced metrics like precision and recall).

The Key Distinction

If the label is a number on a continuum, it is regression. If the label is a category (even if categories happen to be numbered, like soil group 1, 2, 3), it is classification. The numbers in classification are just identifiers — "class 3" is not "more" than "class 1" in any arithmetic sense.

Interestingly, some problems can be framed either way. Consider concrete strength: you could predict the exact value in MPa (regression) or predict whether the specimen exceeds a threshold of 25 MPa (classification). The framing depends on the engineering question you need to answer.

Regression vs. Classification Framing
Regression:   f(cement, w/c, age) = 32.7 MPa   (continuous)
Classification: f(cement, w/c, age) = "Pass"    (category: Pass if > 25 MPa)

Same features, same data — different question, different output type.

Binary vs. Multi-class Classification

Classification problems fall into two categories based on the number of possible labels:

2

Binary Classification

Exactly two classes. The model answers a yes/no question. Civil engineering examples:

  • Pass / Fail — does a concrete cube meet the specified characteristic strength?
  • Safe / Unsafe — does a structure comply with safety regulations after an earthquake?
  • Cracked / Uncracked — does an image of a bridge deck show visible cracking?
  • Liquefaction / No Liquefaction — will this soil layer liquefy under the design earthquake?

Conventionally, one class is called positive (the event of interest, e.g., "fail") and the other negative (e.g., "pass"). This convention is important for understanding metrics like precision and recall.

3+

Multi-class Classification

Three or more classes. The model picks one label from a larger set. Civil engineering examples:

  • Soil type — classify a sample as sand, clay, silt, gravel, or peat based on particle size distribution, Atterberg limits, and moisture content.
  • Damage grade — label a post-earthquake building as grade 0 (none), 1 (slight), 2 (moderate), 3 (severe), or 4 (collapse) following the EMS-98 scale.
  • Traffic level-of-service — classify an intersection as LOS A, B, C, D, E, or F based on delay.
  • Rock quality designation — very poor, poor, fair, good, or excellent based on core recovery.
Ordinal vs. Nominal Classes

Some multi-class problems have a natural order (damage grade 0 < 1 < 2 < 3 < 4). These are ordinal. Others have no inherent order (sand, clay, silt). These are nominal. Standard classifiers treat all classes as unordered — they do not know that misclassifying grade 3 as grade 4 is "closer" than misclassifying grade 3 as grade 0. For ordinal problems, specialised techniques (ordinal regression) can exploit the ordering, but basic classifiers still work well in many cases.

Decision Boundaries

Every classifier, regardless of how sophisticated it is, does one fundamental thing: it divides the feature space into regions, one region per class. The borders between these regions are called decision boundaries.

Imagine plotting every soil sample on a 2D chart with "plasticity index" on the x-axis and "liquid limit" on the y-axis. Sand samples cluster in the lower-left, clay samples in the upper-right, and silt samples somewhere between. A classifier draws invisible lines (or curves) through this space, separating the sand zone from the clay zone from the silt zone. When a new sample arrives, the classifier checks which zone it falls into and assigns the corresponding label.

Shape of Decision Boundaries

Different algorithms produce different boundary shapes:

  • Linear classifiers (logistic regression, linear SVM) draw straight lines (or hyperplanes in higher dimensions). Simple and interpretable, but struggle when classes are not linearly separable.
  • k-Nearest Neighbours produces jagged, locally adaptive boundaries that conform to the shape of the data clusters. Flexible but sensitive to noise.
  • Decision trees create axis-aligned rectangular regions. Easy to interpret, but the staircase boundaries can be a poor fit for smooth class transitions.
  • Neural networks can learn arbitrary curved boundaries. Powerful but require large datasets and are harder to interpret.

The concept of decision boundaries is central to understanding classification. When you visualise a classifier's boundaries overlaid on the training data, you can immediately see whether the model has learned a reasonable separation or is drawing bizarre, overly complex boundaries that chase individual noisy points (overfitting).

Analogy: Zoning Maps

Think of decision boundaries like a zoning map in urban planning. The map divides a city into residential, commercial, and industrial zones. Each parcel of land falls into exactly one zone. The boundary lines are the "decision boundaries." A classifier does exactly the same thing, but in feature space instead of geographic space.

The Nearest-Neighbour Idea

Before diving into the formal k-NN algorithm, let us build the intuition. Suppose you are a junior geotechnical engineer on site. You pull a soil sample from a borehole and want to classify it. You do not have time for a full sieve analysis, but you have a notebook of past samples with their lab-confirmed classifications and a few quick field measurements (moisture content, colour, feel).

What would you do? You would flip through your notebook, find the past sample that is most similar to the one in your hand, and assume the new sample belongs to the same class. That is 1-nearest neighbour classification.

But relying on a single past sample is risky — what if that one sample was mislabelled or unusual? A more robust approach: find the k closest past samples and take a majority vote. If 4 out of 5 nearest samples are clay, classify the new sample as clay, even if the single closest sample happens to be silt. That is k-nearest neighbours.

Why k-NN Is Special

k-NN is one of the simplest machine learning algorithms. It has no training phase — it simply memorises the entire training dataset. All the computation happens at prediction time, when the algorithm searches for the k nearest neighbours. This makes it a lazy learner (as opposed to eager learners like regression, which do their heavy lifting during training).

Despite its simplicity, k-NN is surprisingly effective for many problems, especially when classes form clear clusters in feature space. It is also fully non-parametric — it makes no assumptions about the shape of the decision boundary.

How k-NN Works: Step by Step

1

Store the training data

k-NN has no traditional "training." It simply stores all training examples — their features and their labels. Think of it as building a reference library of past test results.

2

Receive a new, unlabelled sample

A new soil sample arrives with measured features (e.g., moisture content = 28%, liquid limit = 42) but no class label. The goal is to predict its class.

3

Compute distances to all training points

Measure the distance from the new sample to every stored training sample in feature space. The most common distance metric is Euclidean distance:

Euclidean Distance
d(a, b) = sqrt( (a1 - b1)^2 + (a2 - b2)^2 + ... + (an - bn)^2 )

Where a and b are two samples and ai, bi are their feature values. This is the straight-line distance in n-dimensional feature space.

4

Find the k nearest neighbours

Sort all training samples by distance and pick the k closest ones. The value of k is a hyperparameter that you choose before running the algorithm (more on choosing k shortly).

5

Take a majority vote

Count how many of the k neighbours belong to each class. The class with the most votes wins. If k = 5 and the neighbours are {clay, clay, sand, clay, silt}, the prediction is clay (3 out of 5).

Feature Scaling Is Critical

If moisture content ranges from 5 to 50 (%) and liquid limit ranges from 20 to 80, the Euclidean distance will be dominated by the larger-scale feature. A difference of 10 in liquid limit will outweigh a difference of 10 in moisture content, even if the latter is more informative. Always normalise or standardise your features before using k-NN. This is the same lesson you learned in regression, but it is even more critical here because k-NN relies entirely on distances.

Choosing k: The Bias-Variance Trade-off

The value of k controls the trade-off between a flexible model (small k) and a stable model (large k):

Small k (e.g., k = 1 or 3)

  • The decision boundary is highly irregular and conforms tightly to the training data.
  • Sensitive to noise — a single mislabelled point can create an "island" of the wrong class.
  • Low bias, high variance — the model captures fine details but may overfit.

Large k (e.g., k = 15 or 25)

  • The decision boundary is smoother and more generalised.
  • Robust to noise — individual mislabelled points are outvoted by the majority.
  • High bias, low variance — the model may miss genuine local patterns.
  • At the extreme, if k equals the total number of training samples, the model always predicts the most common class — useless.

In practice, k is chosen by cross-validation: try several values of k, evaluate each on a held-out validation set, and pick the one that gives the best accuracy (or F1-score, depending on the problem). Common starting points are k = 3, 5, or 7. For binary classification, use an odd k to avoid ties.

Rule of Thumb

A classic heuristic is k = sqrt(n), where n is the number of training samples. If you have 100 soil samples, start with k = 10. But always validate — the optimal k depends on the data, not on a formula.

CE Application: Pass/Fail Structural Tests

Every concrete cube test, every steel rebar tensile test, and every pile load test ends with a binary verdict: pass or fail. Traditionally, the verdict comes from comparing a measured value to a code-specified threshold. But what if you want to predict the verdict before the test is complete?

Consider a scenario: a concrete plant produces cubes and needs early warning of potential failures. By measuring quick-turnaround properties (7-day strength, ultrasonic pulse velocity, rebound hammer reading) as features, you can train a binary classifier to predict whether the 28-day strength will exceed the characteristic strength.

Features for a Pass/Fail Classifier

  • 7-day compressive strength (MPa)
  • Ultrasonic pulse velocity (km/s)
  • Rebound hammer reading (Schmidt number)
  • Water-cement ratio (from batch record)
  • Cement content (kg/m3)

Label: Pass (28-day strength ≥ fck) or Fail (28-day strength < fck).

A k-NN classifier trained on historical test data can flag suspicious batches within 7 days, giving the plant time to investigate before the concrete is placed in the structure. This is proactive quality control, enabled by classification.

CE Application: Soil Type Classification

Soil classification is one of the most natural applications of classification algorithms in civil engineering. The Unified Soil Classification System (USCS) and the AASHTO system both assign soil to discrete categories based on measured properties.

Traditional Approach

A geotechnical engineer performs a sieve analysis (particle size distribution) and Atterberg limits tests (liquid limit, plastic limit). They then consult the USCS flowchart to assign the soil to a category: well-graded gravel (GW), poorly-graded sand (SP), lean clay (CL), elastic silt (MH), and so on.

ML Approach

Collect a database of past soil samples with their measured properties and confirmed classifications. Train a classifier (k-NN, decision tree, or more advanced methods) to predict the class from the measurements. The classifier can:

  • Automate the classification, reducing human error in reading the flowchart
  • Handle borderline cases more consistently
  • Incorporate additional features (colour, moisture content, field descriptions) that the flowchart ignores
  • Provide confidence levels ("85% likely clay, 15% likely silt")

For our interactive demo below, we simplify to three soil types — sand, clay, and silt — plotted in a 2D feature space. In practice, you would have more features and more categories, but the k-NN algorithm works exactly the same way.

CE Application: Safety Compliance

Structural safety compliance is inherently a classification problem. After an earthquake, hurricane, or flood, engineers must inspect structures and classify them as safe for occupancy, restricted use, or unsafe. This triage must be done quickly, often for thousands of buildings.

Machine learning classifiers can assist by processing sensor data (accelerometers, strain gauges, tilt sensors) and structural properties (building age, material type, number of stories) to produce rapid safety classifications. This does not replace expert inspection, but it can prioritise which buildings need urgent attention.

The Cost of Misclassification

In safety applications, not all errors are equal. Classifying an unsafe building as safe (a false negative) is far more dangerous than classifying a safe building as unsafe (a false positive). The false positive wastes resources; the false negative risks lives. This asymmetry means you cannot rely on simple accuracy — you need the confusion matrix to understand what kinds of errors the model makes.

Interactive Demo: k-NN Classifier

Click on the canvas below to place data points. Use the class selector to switch between Class A (e.g., pass) and Class B (e.g., fail). As you add points, the decision boundary updates in real time. Adjust k with the slider and watch how the boundary changes from jagged (small k) to smooth (large k).

Click to Place Points — Watch the Decision Boundary

Left-click to add a point of the selected class. The coloured background shows the predicted class for every location.

3
Class A: 0 Class B: 0 Total: 0

The Confusion Matrix

Accuracy alone is not enough to evaluate a classifier. If 95% of concrete cubes pass and only 5% fail, a model that blindly predicts "pass" for every sample achieves 95% accuracy — but it misses every single failure. In safety-critical engineering, that is catastrophic.

The confusion matrix (also called an error matrix) is the most important evaluation tool for classifiers. It shows exactly how the model's predictions compare to the true labels, broken down by class.

Structure of a Binary Confusion Matrix

Predicted Positive Predicted Negative
Actual Positive TP
True Positive
FN
False Negative
Actual Negative FP
False Positive
TN
True Negative
TP

True Positive

The model predicted "positive" and the true label is also positive. Example: the model predicted "fail" and the cube actually failed. Correct prediction of the event of interest.

TN

True Negative

The model predicted "negative" and the true label is also negative. Example: the model predicted "pass" and the cube actually passed. Correct prediction of the non-event.

FP

False Positive (Type I Error)

The model predicted "positive" but the true label is negative. Example: the model predicted "fail" but the cube actually passed. This is a false alarm. It wastes resources (you investigate a batch that was fine) but does not endanger safety.

FN

False Negative (Type II Error)

The model predicted "negative" but the true label is positive. Example: the model predicted "pass" but the cube actually failed. This is a missed detection. In safety-critical applications, this is the most dangerous error type.

Metrics Derived from the Confusion Matrix

The four cells of the confusion matrix give rise to several important metrics. Each captures a different aspect of classifier performance:

Key Metrics
Accuracy    = (TP + TN) / (TP + TN + FP + FN)
             "How often is the model correct overall?"

Precision   = TP / (TP + FP)
             "Of all samples predicted positive, how many actually are?"

Recall      = TP / (TP + FN)
  (Sensitivity) "Of all actual positives, how many did the model catch?"

F1-Score    = 2 * (Precision * Recall) / (Precision + Recall)
             "Harmonic mean of precision and recall — balances both."

Which Metric Matters Most?

It depends on the engineering context:

  • Safety-critical (structural inspection): Maximise recall. Missing a genuinely unsafe building (false negative) is unacceptable. You would rather have false alarms than missed detections.
  • Cost-sensitive (extra testing): Balance precision and recall. Every false positive triggers an expensive re-test. You want to avoid unnecessary costs while still catching failures.
  • Balanced classes: Accuracy is reasonable when the classes are roughly equal in size. When classes are imbalanced (95% pass, 5% fail), accuracy is misleading.
The Precision-Recall Trade-off

Increasing recall (catching more true positives) usually decreases precision (more false positives). Imagine lowering the pass/fail threshold: you catch every failure, but you also flag many passing samples. There is no free lunch — the F1-score helps you find the sweet spot, and domain expertise determines where to set the bar.

Interactive Demo: Confusion Matrix Builder

Imagine you have a set of concrete cube test results. For each cube, you know the actual outcome (pass or fail) and the predicted outcome from your classifier. Click the buttons below to add predictions and watch the confusion matrix and derived metrics update in real time.

Build a Confusion Matrix

Click a button to record a prediction outcome. The matrix and metrics update instantly.

Accuracy: — Precision: — Recall: — F1-Score: —

The Classification Workflow

Building a classification model follows a similar workflow to regression, with a few key differences in evaluation:

1

Define the problem

What are the classes? Is this binary or multi-class? Which class is "positive"? What are the consequences of each error type? These decisions drive everything that follows.

2

Collect and label data

Gather training data with confirmed class labels. Labels must be reliable — if your soil classifications are inconsistent between lab technicians, the classifier will learn that noise.

3

Feature engineering and scaling

Select relevant features, handle missing values, and normalise. For distance-based algorithms like k-NN, scaling is essential.

4

Split into train and test sets

Ensure both sets contain representative proportions of each class. Use stratified splitting to maintain class ratios.

5

Train, tune, and evaluate

Train the classifier, tune hyperparameters (e.g., k in k-NN) using cross-validation, and evaluate on the test set using the confusion matrix and appropriate metrics.

6

Interpret and deploy

Examine the confusion matrix to understand error types. If false negatives are unacceptable, adjust the decision threshold or choose an algorithm that allows cost-sensitive learning. Deploy only when the error profile is acceptable for the engineering context.

Practical Tips for Civil Engineers

Tip 1: Always Look at the Confusion Matrix

Never evaluate a classifier by accuracy alone, especially when classes are imbalanced. A model with 97% accuracy that misses every single failure is worse than useless in quality control. The confusion matrix shows you where the model is failing and lets you make informed decisions about whether those failures are acceptable.

Tip 2: Understand the Cost of Errors

In structural safety, a false negative (declaring a damaged building safe) can cost lives. In material testing, a false positive (flagging a good batch as defective) costs money. Before choosing a metric, understand the real-world consequences of each error type. Optimise for the metric that reflects the engineering risk.

Tip 3: Start Simple

k-NN is an excellent starting point. It requires no assumptions about the data distribution, is easy to implement, and its predictions are interpretable ("the 5 closest past samples were all clay"). Use it as a baseline. If its performance is sufficient, you may not need anything more complex. If it is not, its errors will guide you toward better algorithms.

Tip 4: Watch for Class Imbalance

If 95% of your specimens pass and only 5% fail, the classifier will be biased toward predicting "pass." Techniques to handle imbalance include oversampling the minority class, undersampling the majority class, or using class weights to penalise errors on the minority class more heavily. We will explore these techniques in later sub-chapters.

CE Applications: Classification in Water Resources

Classification isn't just for soils and structures. Water resources engineering has critical classification problems where k-NN and other classifiers save lives and protect infrastructure.

Water Resources Classification Problems

  • Water quality index (WQI) classification — Label: Excellent / Good / Poor / Unfit. Features: pH, turbidity, dissolved oxygen, BOD, coliform count. k-NN works well because similar water chemistry → similar quality class.
  • Flood risk zoning — Label: Low / Medium / High risk zone. Features: elevation, distance to river, soil permeability, land use, historical flood frequency. Classification maps directly to zoning decisions.
  • Pipe condition assessment — Label: Good / Fair / Poor / Critical. Features: pipe age, material, diameter, soil corrosivity, break history. Automates asset management for municipal water systems.
  • Drought classification — Label: Normal / Watch / Warning / Emergency. Features: SPI index, reservoir level, groundwater depth, precipitation deficit.
Classification in Design Codes

Many engineering standards are essentially classification rules: IS 1893 classifies sites into Zone II–V, BIS classifies water quality into grades A–E. ML classifiers learn these boundaries from data and handle edge cases more consistently.

Try it interactively

Inspect a classification dataset before you model it

Drop a CSV and use the colour-by-class scatter plot to see how separable your features actually are — the cheapest sanity check you can run before picking any classifier.

Open Explorer

Test Your Understanding

Answer the following questions to check your grasp of classification fundamentals. Each question relates to civil engineering applications covered in this sub-chapter.

Quick Check 1

A geotechnical lab classifies soil samples into four categories (sand, clay, silt, gravel) based on particle size distribution and Atterberg limits. What type of ML problem is this?

Quick Check 2

In a k-NN classifier with k = 7, you classify a new soil sample. The 7 nearest neighbours have the following labels: clay, sand, clay, clay, silt, clay, sand. What is the predicted class?

Quick Check 3

A concrete quality classifier has the following confusion matrix: TP = 12, FP = 3, FN = 8, TN = 77. The "positive" class is "fail." What is the recall, and why is it concerning?

Quick Check 4

You train a k-NN classifier with k = 1 on a soil classification dataset. On the training data, you achieve 100% accuracy. On the test data, accuracy drops to 72%. What is happening?

Key Takeaways

What You Should Remember

  • Classification predicts discrete categories (pass/fail, sand/clay/silt), unlike regression which predicts continuous values.
  • Binary classification has two classes; multi-class has three or more. The same algorithms apply to both, with minor adaptations.
  • Decision boundaries divide feature space into regions, one per class. Different algorithms produce different boundary shapes.
  • k-Nearest Neighbours (k-NN) classifies a new sample by majority vote among the k closest training samples. Small k gives flexible but noisy boundaries; large k gives smooth but potentially biased boundaries.
  • Feature scaling is critical for distance-based algorithms. Always normalise before using k-NN.
  • The confusion matrix is the essential evaluation tool for classifiers. It reveals TP, TN, FP, and FN separately.
  • Accuracy is misleading for imbalanced classes. Use precision, recall, and F1-score for a nuanced evaluation.
  • In safety-critical civil engineering applications, minimising false negatives (maximising recall) is often more important than maximising overall accuracy.
Coming Up Next

In Sub-chapter 2.5, we introduce Logistic Regression — a classifier that not only assigns a class label but also outputs a probability. Instead of just "pass" or "fail," it tells you "82% likely to pass." This probabilistic output is invaluable for risk-based decision-making in civil engineering practice.

Real-world case study · Probabilistic classification in geotechnical engineering

Boulanger–Idriss liquefaction triggering — the logistic classifier inside every modern liquefaction analysis

Given a CPT or SPT sounding and a design earthquake, will the soil liquefy? Boulanger & Idriss fit a binary classifier (logistic regression) to 250+ case histories of liquefied vs non-liquefied sites — and that probability curve now drives NASEM 2016, AASHTO LRFD and every commercial geotech software.

0Case histories in DB
0Classes (liquefy / not)
0Default design PL
0of US DOTs use it

Soil liquefaction destroyed neighbourhoods of Niigata (1964), San Francisco's Marina District (1989) and Christchurch (2011). The engineering question is binary: at this site, under this earthquake, will the sand liquefy — yes or no? But the underlying physics is too messy to solve from first principles in design office time.

  • Features available from a routine CPT: cone tip resistance qc, sleeve friction, depth, effective stress, fines content.
  • Hazard from a USGS deaggregation: PGA, magnitude M.
  • Answer must be a probability, not a yes/no, so the engineer can apply a load & resistance factor.

Boulanger & Idriss formalised this as logistic regression on case-history data — one of the cleanest examples of supervised classification in geotechnical practice.

  • Feature engineering: normalise qc to qc1Ncs; compute Cyclic Stress Ratio CSR from PGA, depth, magnitude scaling factor.
  • Model: P(liquefaction) = 1 / (1 + exp(−(β0 + β1·qc1Ncs + β2·ln(CSR)))).
  • Training: maximum-likelihood fit to 250+ sites where liquefaction was/wasn't observed after past earthquakes.
  • Decision rule: design typically targets PL ≤ 15% for important structures.

Same sigmoid you learn in week 2 of any ML course — it just happens to underlie billions of dollars of bridge and port design.

The Boulanger–Idriss (2014) procedure is the reference method in:

  • NASEM Special Report 327 (2016) — consensus US national guidance on liquefaction triggering.
  • AASHTO LRFD Bridge Design Specifications — Section 10 (geotech).
  • Commercial software (Settle3D, CLiq, NovoLiq) and essentially every US DOT.

The same logistic framework was used to design ground improvement for the SR 520 floating bridge approaches (Seattle), the Port of Long Beach Pier G, and post-Christchurch reconstruction of CBD foundations.

  • Classification doesn't need deep learning. A well-engineered logistic regression on the right 2–3 features has driven a generation of geotechnical practice.
  • Imbalanced data is the rule. Liquefaction case histories are dominated by "did liquefy" sites — sampling bias has been the central methodological debate for 30 years.
  • The output is a probability, not a label. Codes pick the threshold; engineers pick the consequence class.