Chapter 5 — Sub-chapter 5.1

Sequence Models & RNNs

From the rhythmic pulse of a strain gauge on a suspension cable to the scrolling lines of a structural specification document — data that arrives in order demands models that remember what came before.

35 min read 2 interactive demos 4 quiz questions

When Order Is Everything

Imagine a network of strain gauges installed along the main cables of a suspension bridge. Every second, each sensor records a numerical reading — the tension in that cable at that instant. A single reading tells you very little. But weeks of readings, taken in sequence, reveal the bridge breathing under traffic, flexing through temperature cycles, and — crucially — any slow, creeping anomaly that precedes structural distress.

The order of those readings is just as important as their values. Shuffle the time series randomly and you destroy the story entirely. This is the fundamental insight behind sequence models: some data only makes sense when its ordering is preserved.

In previous chapters, we explored models that treat each input independently — a single image, a single row of tabular data. But much of the data civil engineers work with is inherently sequential: sensor time series, construction schedules, loading histories, text in project specifications, and even the step-by-step progression of a finite element analysis converging to a solution.

This sub-chapter introduces Recurrent Neural Networks (RNNs) — the foundational architecture for processing sequential data. We will build up from the intuition of why order matters, through the mechanics of how RNNs maintain memory via hidden states, to the critical problem of vanishing gradients and the elegant solutions provided by LSTM and GRU cells.

Prerequisites

This sub-chapter assumes familiarity with basic neural network concepts from Chapters 2 and 3 — neurons, layers, weights, activation functions, and backpropagation. No prior knowledge of sequence models is required. We build everything from first principles.

Sequential Data: Why Order Matters

Before diving into the architecture of RNNs, let us first understand what makes sequential data fundamentally different from the data we have worked with so far. In tabular data (e.g., concrete mix design parameters), each row is independent — row 5 does not depend on row 4. In images, pixels are spatially arranged but there is no inherent ordering from first pixel to last. Sequential data, however, has a strict temporal or positional ordering where context flows from earlier elements to later ones.

Types of Sequential Data in Civil Engineering

Time Series Data

Time series data is the most common form of sequential data in structural and geotechnical engineering. Examples include:

  • Strain gauge readings — continuous tension/compression measurements on structural members
  • Accelerometer data — vibration recordings from bridges, buildings, or equipment during seismic events
  • Settlement monitoring — ground surface elevation changes over weeks or months
  • Traffic load patterns — vehicle counts and weights crossing a bridge over time
  • Temperature profiles — thermal expansion/contraction cycles in long-span structures
  • Groundwater level fluctuations — piezometric data recorded at regular intervals

Text & Document Data

Text is sequential by nature — words in a sentence derive meaning from their position and from the words that precede them. Civil engineering generates enormous volumes of text:

  • Project specifications — clauses that reference earlier definitions
  • Inspection reports — narrative descriptions of defects and observations
  • Building codes & standards — hierarchically structured regulatory text
  • Construction logs — daily entries recording activities and incidents

The Shuffling Thought Experiment

Here is a powerful test for whether data is truly sequential: would shuffling it destroy information?

Take a table of concrete cylinder test results (compressive strength, age, mix proportions). Shuffle the rows randomly. You lose nothing — each row stands alone. Now take a week of accelerometer readings from a bridge pier during an earthquake. Shuffle the time steps randomly. The earthquake signal is destroyed. The gradual build-up, the peak ground acceleration, the decay — all gone. That destruction proves the data is sequential.

Civil Engineering Analogy

Sequential data is like a construction schedule. A Gantt chart shows tasks in a specific order — you cannot pour concrete before formwork is erected, and you cannot strip formwork before concrete cures. Each task depends on what came before. Shuffling the task order produces a nonsensical schedule.

Similarly, a model processing sequential data must respect the order of inputs. A strain reading at time step 100 can only be properly interpreted in the context of the 99 readings that preceded it.

Why Standard Neural Networks Fail at Sequences

A standard feedforward neural network receives a fixed-size input vector and produces a fixed-size output. It has no mechanism for "remembering" previous inputs. If you fed it time step 1, then time step 2, then time step 3 of a sensor signal, it would process each step independently — as if the previous steps never existed. There is no internal state that carries information forward through the sequence.

You might think of a workaround: concatenate all time steps into one giant input vector. But this approach has severe limitations. First, it requires a fixed sequence length — you cannot handle a 100-step sequence and a 5,000-step sequence with the same network. Second, the parameter count explodes with sequence length. Third, the network has no structural bias toward recognising temporal patterns — it must learn from scratch that adjacent time steps are related.

Key Insight

We need an architecture that can process inputs one at a time, in order, while maintaining an internal memory (hidden state) that accumulates information from all previous steps. This is exactly what a Recurrent Neural Network provides.

RNN Architecture: The Hidden State

A Recurrent Neural Network introduces a deceptively simple idea: give the network a hidden state — a vector of numbers that persists between time steps and gets updated at each step. This hidden state serves as the network's memory, carrying forward a compressed summary of everything it has seen so far.

The Core Equations

At each time step t, the RNN receives two inputs: the current data point xt (e.g., the current sensor reading) and the previous hidden state ht−1 (the memory from all prior steps). It produces a new hidden state ht and optionally an output yt:

RNN Update Rule

ht = tanh( Whh · ht−1 + Wxh · xt + bh )
yt = Why · ht + by

Whh = hidden-to-hidden weight matrix (how past memory influences current memory)
Wxh = input-to-hidden weight matrix (how current input contributes to memory)
Why = hidden-to-output weight matrix (how memory translates to predictions)
tanh = activation function squashing values to [−1, +1]

The crucial detail is that the same weight matrices are shared across all time steps. The network applies the same transformation at step 1, step 50, and step 1,000. This weight sharing is what allows RNNs to handle sequences of arbitrary length with a fixed number of parameters.

Unrolling Through Time

To visualise how an RNN processes a sequence, we "unroll" it through time. Instead of thinking of a single recurrent cell with a loop, we draw the same cell repeated once for each time step, with connections showing how the hidden state flows from one step to the next.

Civil Engineering Analogy

The hidden state is like a running engineering logbook. Imagine a site engineer who walks through a construction site every morning. They carry a notebook (the hidden state) that contains a summary of everything they have observed on previous days. At each new station (time step), they look at the current conditions (the input), update their notebook with new observations, and write a brief report (the output). The notebook is never reset — it accumulates context continuously.

The engineer uses the same skills (shared weights) at every station. They do not need a different brain for station 1 versus station 50 — just the accumulated context in their notebook changes.

Hidden State Dimensions

The size of the hidden state vector is a hyperparameter you choose. A hidden state of size 64 means the network compresses all past information into a vector of 64 numbers. Larger hidden states can store more information but require more computation and data to train effectively. For civil engineering sensor data with relatively simple temporal patterns, hidden sizes of 32 to 128 are often sufficient. For complex text processing, larger states (256+) may be needed.

Practical Note

In structural health monitoring, a typical sensor produces readings at 100–1000 Hz. An RNN processing this data would update its hidden state at each time step, building up a representation of the structural response over time. After processing the full sequence, the final hidden state contains a compressed summary of the entire event — which can be fed to a classifier to detect anomalies or categorise events.

Interactive Demo: RNN Unrolling Visualiser

The demo below shows how a recurrent neural network processes a sequence step by step. Watch the hidden state vector evolve as each new input arrives. The connections between time steps illustrate the flow of memory through the network. Click Step to advance one time step, or Play to animate the full sequence automatically.

RNN Unrolling Visualiser — Hidden State Flow Through Time

Press Step or Play to begin. The hidden state vector ht carries memory forward through each time step.

Notice how the hidden state gradually changes colour and magnitude as it absorbs each new input. Early in the sequence, the hidden state is mostly determined by the first few inputs. As more inputs arrive, the hidden state becomes a blend of all past information — though, as we will see shortly, earlier inputs tend to fade from memory in a basic RNN.

The Vanishing Gradient Problem

The basic RNN has a fatal flaw. During training, the network learns by backpropagation through time (BPTT) — tracing the error signal backwards through each time step. At each step, the gradient is multiplied by the weight matrix Whh and passed through the derivative of the tanh activation. When these multiplied factors are consistently less than 1.0 (which they usually are), the gradient shrinks exponentially as it travels back through time.

Exponential Decay of Gradients

If the gradient shrinks by a factor of 0.9 at each time step, after 10 steps it is 0.910 = 0.35 of its original value. After 50 steps: 0.950 = 0.005. After 100 steps: 0.9100 ≈ 0.00003. The gradient has essentially vanished — the network can no longer learn from events that happened 100 steps ago.

Conversely, if the factor is greater than 1.0, gradients explode exponentially, causing numerical instability. Gradient clipping can mitigate exploding gradients, but vanishing gradients require a fundamentally different architecture.

Civil Engineering Analogy

Vanishing gradients are like signal attenuation in a long pipeline. Imagine pumping water through a very long pipeline with minor leaks at every joint. At the start, pressure is strong. But after passing through hundreds of joints, the accumulated losses reduce the pressure to almost nothing — the signal at the end is too weak to be useful.

Similarly, the error signal in a basic RNN leaks away at every time step. After 50–100 steps, the gradient is too faint to update the weights meaningfully, so the network cannot learn long-range dependencies — like the relationship between a foundation load event and a settlement measurement recorded weeks later.

Practical Impact

The vanishing gradient problem means that basic RNNs can only learn short-range dependencies — patterns spanning roughly 5–20 time steps. For many civil engineering applications, this is insufficient. Structural health monitoring data may require correlating events separated by hundreds or thousands of time steps. A specification document may have a defined term in paragraph 1 that is referenced in paragraph 50. We need architectures that can maintain memory over much longer spans.

LSTM: Long Short-Term Memory

The Long Short-Term Memory (LSTM) cell, introduced by Hochreiter and Schmidhuber in 1997, elegantly solves the vanishing gradient problem by introducing a separate cell state — a highway of information that runs through the entire sequence with minimal interference. Information is added to or removed from this cell state through carefully regulated structures called gates.

The Three Gates

An LSTM cell contains three gates, each implemented as a sigmoid layer (outputting values between 0 and 1) that controls how much information flows through:

1. Forget Gate (ft)

Decides what information to discard from the cell state. It looks at the previous hidden state ht−1 and the current input xt, and outputs a value between 0 (completely forget) and 1 (completely keep) for each element of the cell state.

ft = σ( Wf · [ht−1, xt] + bf )

2. Input Gate (it)

Decides what new information to store in the cell state. This involves two parts: a sigmoid layer decides which values to update, and a tanh layer creates a vector of candidate values that could be added.

it = σ( Wi · [ht−1, xt] + bi )
C̃t = tanh( WC · [ht−1, xt] + bC )

3. Output Gate (ot)

Decides what parts of the cell state to output as the hidden state. The cell state is passed through tanh (squashing to [−1, +1]) and multiplied by the output gate's sigmoid to select which information to expose.

ot = σ( Wo · [ht−1, xt] + bo )
ht = ot ⊙ tanh( Ct )

Cell State Update

The cell state update is the heart of the LSTM. The old cell state is multiplied element-wise by the forget gate (removing information the gate decided to discard), then the new candidate values (scaled by the input gate) are added:

Cell State Update Equation

Ct = ft ⊙ Ct−1 + it ⊙ C̃t

The ⊙ symbol denotes element-wise multiplication. This additive update is the key to preventing vanishing gradients — gradients can flow backwards through the cell state without being repeatedly multiplied by weight matrices.

Civil Engineering Analogy

An LSTM is like a well-managed project filing system. The cell state is the filing cabinet — a permanent record of important project information. The forget gate is the archivist who periodically removes outdated documents. The input gate is the project manager who decides which new reports deserve to be filed. The output gate is the secretary who pulls out only the relevant documents when someone needs a briefing.

Without this structured system (i.e., with a basic RNN), everything goes into a single notebook that gets overwritten each day — critical early-project decisions are lost by the time they are needed.

Why LSTMs Solve Vanishing Gradients

The additive cell state update (Ct = ft ⊙ Ct−1 + ...) creates a gradient highway. During backpropagation, the gradient flowing through the cell state is multiplied only by the forget gate values, not by weight matrices. If the forget gate is close to 1.0 (keeping most information), gradients flow nearly unchanged across hundreds of time steps. This allows LSTMs to learn dependencies spanning 100+ steps — a dramatic improvement over basic RNNs.

Engineering Application

In structural health monitoring, an LSTM can learn that a spike in temperature 200 time steps ago is correlated with a current change in strain readings — capturing thermal expansion effects that a basic RNN would miss entirely. This makes LSTMs the go-to architecture for bridge monitoring, dam safety, and long-term settlement prediction.

GRU: Gated Recurrent Unit

The Gated Recurrent Unit (GRU), proposed by Cho et al. in 2014, is a streamlined alternative to the LSTM. It achieves comparable performance on many tasks while using fewer parameters and being faster to train. The GRU merges the cell state and hidden state into a single state vector and uses only two gates instead of three.

GRU Gates

Reset Gate (rt): Controls how much of the previous hidden state to forget when computing the candidate hidden state. When rt is close to 0, the network can "reset" its memory and act as if the sequence is starting fresh.

rt = σ( Wr · [ht−1, xt] + br )

Update Gate (zt): Controls the balance between keeping the old hidden state and adopting the new candidate. It effectively combines the forget and input gates of an LSTM into a single mechanism.

zt = σ( Wz · [ht−1, xt] + bz )

Hidden State Update:

h̃t = tanh( W · [rt ⊙ ht−1, xt] + b )
ht = (1 − zt) ⊙ ht−1 + zt ⊙ h̃t

LSTM vs GRU: When to Use Which?

Comparison

  • Parameters: GRU has ~25% fewer parameters than LSTM (2 gates vs 3 gates + separate cell state)
  • Training speed: GRU trains faster due to fewer computations per step
  • Long-range memory: LSTM generally performs better on very long sequences (500+ steps)
  • Small datasets: GRU often generalises better with limited training data due to fewer parameters
  • Rule of thumb: Try GRU first; switch to LSTM if performance on long sequences is insufficient
Practical Guidance

For many civil engineering sensor datasets — where sequences are moderate in length (50–500 steps) and training data may be limited — GRUs are often the pragmatic choice. They provide gate-based memory control with lower computational cost and fewer hyperparameters to tune.

Bidirectional RNNs

A standard RNN processes a sequence from left to right — from the first time step to the last. But in many tasks, the context that follows a given position is just as important as the context that precedes it. A Bidirectional RNN runs two independent RNNs (or LSTM/GRU cells) in parallel: one processing the sequence forward and one processing it backward. At each time step, the outputs of both directions are concatenated, giving the network access to both past and future context.

How It Works

The forward RNN computes hidden states h1→, h2→, ..., hT→ from left to right. The backward RNN computes hidden states hT←, hT−1←, ..., h1← from right to left. At each step t, the combined hidden state is the concatenation:

ht = [ ht→ ; ht← ]

This doubles the hidden state dimension but provides strictly more information at each time step.

When to Use Bidirectional Models

Bidirectional RNNs are ideal when the entire sequence is available before processing begins. This is the case for:

  • Text classification — classifying a full inspection report into categories
  • Named entity recognition — extracting material names, standards references, and measurements from specification text
  • Post-hoc sensor analysis — analysing a complete earthquake recording after the event

They are not suitable for real-time prediction tasks where you must make a decision at each time step before future data arrives — such as real-time structural alarm systems.

Civil Engineering Analogy

A bidirectional RNN is like reading a specification document twice. First you read it front-to-back to understand the narrative flow. Then you read it back-to-front, starting from the conclusions and working back to see how the requirements were derived. Combining both readings gives you a much richer understanding of each clause than either reading alone.

Civil Engineering Applications

Sequence models have found numerous applications across civil engineering disciplines. Let us examine the most impactful use cases in detail.

Structural Health Monitoring (SHM)

Sensor Time Series Analysis

Modern structures are instrumented with networks of sensors: strain gauges, accelerometers, displacement transducers, temperature probes, and tiltmeters. Each sensor produces a continuous time series. LSTM and GRU networks can be trained to:

  • Anomaly detection — identify unusual patterns that may indicate damage or degradation
  • Event classification — distinguish between traffic loading, wind events, seismic excitation, and thermal effects
  • Remaining useful life prediction — forecast when a component will need maintenance based on degradation trends
  • Missing data imputation — fill gaps in sensor recordings using learned temporal patterns

Text Processing for Specifications

NLP in Construction Documents

Construction projects generate vast volumes of text — specifications, contracts, RFIs, submittals, daily logs. Sequence models can automate tedious text analysis tasks:

  • Clause classification — automatically categorise specification clauses by topic (safety, materials, workmanship)
  • Conflict detection — identify contradictory requirements across documents
  • Information extraction — pull structured data (material strengths, tolerances, standards references) from unstructured text
  • Sentiment analysis of daily logs — detect early warning signs of disputes or safety concerns

Construction Activity Sequence Prediction

The temporal sequence of construction activities can be modelled with RNNs to predict delays, optimise schedules, and identify productivity patterns. Given a sequence of completed activities with their durations, an LSTM can predict the expected duration of upcoming activities and flag sequences that are trending toward delay.

Interactive Demo: LSTM Gate Animator

This demo visualises the inner workings of an LSTM cell at a single time step. Watch how the forget gate selectively erases information from the cell state, the input gate writes new information, and the output gate controls what the cell exposes as its hidden state. Use the sliders to adjust the input values and observe how the gates respond.

LSTM Gate Animator — Cell State & Gate Operations

Adjust sliders and click Animate to see the gate operations. Bars show gate activations; the pipeline shows cell state flow.

Observe how increasing the input xt tends to raise the input gate activation (more new information enters the cell state), while the forget gate independently decides how much of the old cell state to retain. The output gate then filters what portion of the updated cell state becomes the new hidden state ht.

Summary & Key Takeaways

What We Covered

  • Sequential data — data where order matters: time series, text, activity sequences. Shuffling destroys information.
  • RNN architecture — a neural network with a hidden state that carries memory forward through time steps, using shared weights.
  • Vanishing gradients — basic RNNs lose the ability to learn long-range dependencies because gradients decay exponentially during backpropagation through time.
  • LSTM — solves vanishing gradients with a cell state highway and three gates (forget, input, output) that control information flow.
  • GRU — a simpler alternative with two gates (reset, update) that achieves comparable performance with fewer parameters.
  • Bidirectional RNNs — process sequences in both directions for richer context when the full sequence is available.
  • CE applications — structural health monitoring, sensor anomaly detection, text processing for specifications, and construction schedule prediction.

CE Applications: RNNs in Structural Health Monitoring

Recurrent Neural Networks process sequential data — exactly what civil engineers get from sensors mounted on bridges, dams, and buildings.

Flood Level Prediction

RNNs predict river water levels hours ahead by learning patterns from historical gauge data. LSTM variants handle the long-term seasonal patterns critical for early warning systems.

Bridge Vibration Monitoring

Accelerometer time-series from bridges are fed into RNNs to detect anomalous vibration patterns that may indicate structural damage or fatigue cracking.

Settlement Prediction

Sequential settlement readings from monitoring points are modeled with GRU/LSTM networks to predict future consolidation settlement, helping engineers verify design assumptions.

Test Your Understanding

Answer the following questions to check your grasp of the key concepts from this sub-chapter.

Question 1 of 4

What is the primary function of the hidden state in a basic RNN?

Question 2 of 4

The vanishing gradient problem in basic RNNs means that:

Question 3 of 4

Which LSTM gate decides what old information to discard from the cell state?

Question 4 of 4

A bidirectional RNN is most appropriate when:

Mini case study

LSTM streamflow at scale: Google’s flood-forecasting platform across India & Bangladesh

Hydrology was the original sequence problem — rainfall in, discharge out, with memory measured in hours-to-weeks of catchment storage. The Google Research Flood Forecasting team trained a single LSTM ensemble on tens of thousands of gauges worldwide and used it to issue operational riverine-flood warnings across 460 million people in India and Bangladesh, with lead times of up to 7 days.

0People covered
0Lead time
0Mean NSE (5-day)
0Countries covered (2024)

Conceptual rainfall–runoff models (SAC-SMA, HBV, HEC-HMS) need careful per-basin calibration that doesn’t generalise across ungauged catchments. Most of the world’s flood-vulnerable basins have either no gauge at all, or a single short record full of gaps — making per-basin physics-based calibration impossible at population scale.

“If you can’t calibrate everywhere, then one model has to learn from everywhere at once.”

  • One global LSTM — static catchment attributes (area, slope, soil, land-cover from ERA5/MERIT/MODIS) embedded, then concatenated to dynamic forcings (IMERG rainfall, ERA5 temperature) and fed to a 256-unit LSTM, predicting discharge over 7 days.
  • Ensemble across seeds & folds — 10-fold k-fold across basins, 8 random seeds → 80 LSTMs averaged, giving calibrated probabilistic intervals.
  • Public alerts — the predictions feed flood inundation maps on Google Search, Maps and Android emergency alerts in 80+ countries.
Representative event: observed vs LSTM-forecast hydrograph (5-day lead)

Single representative monsoon event on a Brahmaputra tributary — LSTM captures the peak timing and magnitude that the physics-based GloFAS baseline under-predicts.

  • Mean Nash–Sutcliffe efficiency 0.83 at 5-day lead, beating the European GloFAS baseline by a wide margin and matching local conceptual models in calibrated basins.
  • 460 M+ people covered by operational alerts in the India/Bangladesh program; expanded to 80+ countries by 2024.
  • Open dataset (Caravan) — the team open-sourced the harmonised global forcings + discharge corpus used to train the model.
  • One model from many basins. The LSTM regularises across thousands of catchments, learning latent hydrological similarity that per-basin calibration cannot.
  • Static attributes are essential. Without basin descriptors, the LSTM can’t generalise to ungauged basins — the static-input embedding is the “basin ID” the network needs.
  • Sequence memory matters most at the peak. A feed-forward network on the same inputs missed peak timing by ~12 h; only the LSTM’s cell state captured antecedent moisture.