Part IV: Deep Learning for Sensor Time Series
Chapter 14: Recurrent and Temporal Convolutional Models

Practical training recipes

"My loss went to zero, my val curve looked gorgeous, and then a colleague pointed out that all my validation windows came from subjects I had already trained on."

A Chastened AI Agent

The architecture is the easy part

By now you can build an LSTM or a temporal convolutional network, size its receptive field, attach the right head, and run it as a stream. None of that matters if the training run itself is broken. Sensor sequence models fail to train for reasons that have almost nothing to do with the layer stack: exploding gradients through time, a loss that rewards the model for ignoring the rare event you actually care about, augmentations borrowed from computer vision that quietly destroy physical meaning, and validation splits that leak a subject's future into its own past. This section is the recipe book: the optimization, regularization, batching, and evaluation choices that turn a correct architecture into a model that generalizes to a sensor it has never seen. These recipes are architecture-agnostic; they apply equally to the RNNs of Section 14.1, the TCNs of Section 14.2, and the transformers of Chapter 15.

This section assumes the encoders and heads of Sections 14.1 through 14.4, the batching and masking of variable-length windows, and the normalization and windowing pipeline of Chapter 13. It leans hard on one non-negotiable discipline: the subject-disjoint, no-peeking-at-the-future evaluation of Chapter 5. Every recipe below is downstream of getting the split right, because a tuning decision measured on a leaky validation set optimizes for a number that will not survive deployment.

The loss is the specification, not a default

The single most consequential training choice for sensor models is the loss, because sensor labels are almost always imbalanced. A fall detector sees minutes of walking for every fraction of a second of falling; a bearing runs healthy for months before it fails; an arrhythmia is a handful of beats in a day-long ECG. Train plain cross-entropy on that and the optimizer discovers the cheapest possible solution: always predict "normal", collect 99.7% accuracy, and never fire. The fix is to make the rare class expensive to miss. Class-weighted cross-entropy multiplies each class's loss by a weight inversely proportional to its frequency. Focal loss goes further, down-weighting easy, confidently-correct samples by a factor \((1-p_t)^\gamma\) so the gradient concentrates on the hard minority, which for detection tasks usually beats static class weights. For heavily skewed segmentation, soft Dice or Tversky losses optimize overlap directly and are far less seduced by the majority background than per-pixel cross-entropy.

Optimize the loss that matches the metric you report

If you will be judged on event-level recall at a fixed false-alarm rate, do not train cross-entropy and hope. Accuracy is not the metric; the confusion matrix under class imbalance is. Pick a loss whose gradient pushes on the errors your deployment actually punishes, and validate on the same metric you will publish. The house rule of construct-matched evaluation, one metric co-computed with the loss it justifies, applies here: a model tuned on accuracy and reported on recall is two different experiments wearing one checkpoint.

Optimization for sequences: clip, warm up, decay

Recurrent networks propagate gradients through as many multiplications as there are timesteps, so a window of \(T=500\) samples is a 500-deep computation graph. That depth makes the gradient norm volatile: one bad batch can produce a gradient a thousand times larger than the running average and blow the weights out in a single step. Gradient clipping is the cheap, load-bearing defense. Clip the global gradient norm to a fixed ceiling (a value of 1.0 to 5.0 is a good starting range) before every optimizer step, and the training that was diverging on batch 40 becomes boring and stable. TCNs are less prone to this than LSTMs because their gradients flow through a fixed convolutional depth rather than an unrolled recurrence, but clipping costs nothing and protects both.

AdamW is the default optimizer for these models: it adapts per-parameter step sizes, which suits the heterogeneous gradient magnitudes of gated recurrent cells, and its decoupled weight decay is a cleaner regularizer than Adam's L2 coupling. Pair it with a schedule that warms up the learning rate over the first few hundred steps, then decays it, typically with a cosine curve. Warmup matters because a large initial learning rate on a freshly initialized recurrent state produces exactly the gradient explosions clipping is fighting; easing in lets the normalization statistics and gate biases settle first. The training loop below wires clipping, warmup-plus-cosine, AdamW, and mixed precision into the few lines that carry most of the stability.

import torch, math
from torch.optim import AdamW

def make_scheduler(opt, warmup, total):
    def lr_lambda(step):
        if step < warmup:                       # linear warmup
            return step / max(1, warmup)
        p = (step - warmup) / max(1, total - warmup)
        return 0.5 * (1 + math.cos(math.pi * p)) # cosine decay to 0
    return torch.optim.lr_scheduler.LambdaLR(opt, lr_lambda)

opt   = AdamW(model.parameters(), lr=3e-3, weight_decay=1e-2)
sched = make_scheduler(opt, warmup=300, total=10_000)
scaler = torch.cuda.amp.GradScaler()            # mixed precision

for x, y, mask in train_loader:
    opt.zero_grad()
    with torch.cuda.amp.autocast():
        loss = masked_loss(model(x), y, mask)   # ignore padded steps
    scaler.scale(loss).backward()
    scaler.unscale_(opt)
    torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
    scaler.step(opt); scaler.update(); sched.step()
A stability-first training step for sequence models. The three lines that matter most are clip_grad_norm_ (tames the through-time gradient), the cosine schedule with warmup=300 (prevents the early-step blowup), and masked_loss (never trains on padding). Everything else is standard AdamW with mixed precision.

Schedules, clipping, and early stopping for free

A hand-rolled trainer with warmup, cosine decay, gradient clipping, mixed precision, checkpointing, and early stopping is a few hundred lines you will maintain forever. PyTorch Lightning collapses it: pass gradient_clip_val=1.0 to the Trainer, return the scheduler from configure_optimizers, and add EarlyStopping(monitor="val_recall", mode="max", patience=10) as a callback. That is roughly 200 lines of boilerplate and its associated off-by-one bugs replaced by three arguments, and the AMP and multi-GPU plumbing comes along for free.

Regularization and augmentation that respect physics

Sensor models overfit fast because labeled sensor data is scarce, so regularization earns its keep. Weight decay and dropout are the baseline, but recurrent dropout must be applied with the same mask across timesteps (variational dropout) rather than resampled each step, or it corrupts the recurrence itself. The higher-leverage lever is data augmentation, and here sensor work diverges sharply from vision. An augmentation is only legal if the label survives it. Adding Gaussian noise, small time warps, magnitude scaling, and random cropping of windows all preserve "this is walking". But flipping the sign of an accelerometer axis inverts gravity and turns walking into physical nonsense; time-reversing an ECG destroys the causal P-QRS-T ordering; rotating a three-axis IMU is valid only if you rotate all three channels by the same rotation matrix, because the axes are physically coupled. The measurement models of Chapter 2 tell you which transforms are label-preserving; borrow a vision augmentation blindly and you train the model on data that cannot occur.

Industrial vibration: the recipe that saved the run

A team building a bearing fault classifier for a fleet of factory pumps had a TCN that trained to 96% on their held-out windows and detected almost nothing on a new pump. Three recipe changes fixed it, none of them architectural. First, they switched from random-window to machine-disjoint validation, which immediately dropped the honest score to 71% and revealed the real problem. Second, they replaced cross-entropy with focal loss, because incipient faults were 2% of the data and the model had been predicting "healthy" everywhere. Third, they replaced their vision-style augmentation (which included time-reversal) with jitter, magnitude scaling, and small time-warps drawn from the actual RPM variation across pumps. The reworked recipe reached 88% machine-disjoint recall on unseen pumps, and the diagnostics that had once looked worse were the ones telling the truth.

Windowing, batching, and honest validation

Two mechanical choices decide whether your batches are even coherent. Window length must exceed the receptive field of Section 14.3 and must contain the temporal pattern the label describes; a two-second window cannot learn a gait cycle that takes three. Batching variable-length sequences requires padding to the longest member and a mask so the loss ignores the pad, exactly the masked loss the code above assumes; bucket sequences of similar length together to keep padding waste low. For very long sequences that will not fit in memory, truncated backpropagation through time splits the sequence into chunks, carries the recurrent state forward across chunk boundaries (detached from the graph), and backpropagates only within each chunk. Set the truncation length to comfortably exceed the longest dependency you need the model to learn, because gradients never flow past the truncation boundary.

The recipe that overwhelmingly determines the deployed number is the split. Random-window splits leak because consecutive windows from one subject or one machine are nearly identical, so a window in validation has a near-twin in training. Split by subject, by device, or by time period, never by window, and normalize using statistics computed on the training split alone, then applied unchanged to validation, so no test-set statistic ever touches training. Early-stop on the leakage-safe validation metric, and treat the resulting curve as the truth. The formal protocols for this live in Chapter 65, and when labels are scarce enough that no split leaves you enough to train on, the self-supervised pretraining of Chapter 17 is the recipe that buys back label efficiency.

Where the recipe is moving

The 2023 to 2026 shift is away from training a bespoke model per task and toward fine-tuning a pretrained time-series backbone. Models such as MOMENT and TimesFM, and wearable-specific efforts like Google's Large Sensor Model (LSM), are trained on enormous unlabeled sensor corpora and then adapted with a small labeled set, which changes the recipe: lower learning rates, layer-wise decay, and often a frozen backbone with a trained head. When you have a few hundred labeled windows rather than a few hundred thousand, the modern recipe is increasingly "fine-tune a foundation model" rather than "train from scratch", a tradeoff the book returns to across Part V.

Exercise: ablate the recipe, not the architecture

Take one fixed TCN and one imbalanced sensor task (for example fall detection from wrist IMU). Hold the architecture constant and ablate the recipe: (a) cross-entropy versus focal loss, (b) with and without gradient clipping, (c) random-window versus subject-disjoint split, (d) physics-respecting augmentation versus a vision-style set that includes axis flips and time-reversal. Report event-level recall at a fixed false-alarm rate for every combination. Rank the four recipe choices by their effect size and confirm the claim of this section: the split and the loss move the honest number more than most architecture changes would.

Self-check

  1. Under 100:1 class imbalance, plain cross-entropy reaches 99% accuracy and fires on nothing. Name two loss changes that fix this and say which errors each one's gradient emphasizes.
  2. Why is gradient clipping more critical for a 500-step LSTM than for a shallow TCN, and what failure does it prevent in the first few training steps if you skip warmup?
  3. You augment IMU walking data by flipping the sign of the vertical accelerometer axis and your model gets worse. Why is this augmentation illegal, and what is a label-preserving alternative?

Lab 14

compare LSTM and TCN on a multivariate sensor task, including a streaming variant.

What's Next

In Chapter 15, we replace the recurrence and the fixed convolution with attention over time and channels, which lets a model relate any two timesteps directly, at a compute cost that forces its own set of training recipes: patchification, positional encoding for sensor identity, and the efficient-attention tricks that keep long sensor sequences affordable.

Bibliography

Optimization and regularization

Loshchilov, I., & Hutter, F. (2019). Decoupled Weight Decay Regularization (AdamW). ICLR.

Introduces AdamW, the default optimizer for sequence models here; decoupling weight decay from the adaptive step is the fix that makes regularization behave predictably.

Pascanu, R., Mikolov, T., & Bengio, Y. (2013). On the difficulty of training recurrent neural networks. ICML.

The paper that diagnoses exploding and vanishing gradients through time and motivates gradient clipping, the single most load-bearing stability trick for RNN training.

Loshchilov, I., & Hutter, F. (2017). SGDR: Stochastic Gradient Descent with Warm Restarts. ICLR.

Origin of the cosine learning-rate schedule used in the training loop; warmup plus cosine decay is the standard recipe for stable convergence.

Losses for imbalance

Lin, T.-Y., Goyal, P., Girshick, R., He, K., & Dollar, P. (2017). Focal Loss for Dense Object Detection. ICCV.

Introduces focal loss; its down-weighting of easy examples is directly why it beats class-weighted cross-entropy on the heavy imbalance typical of sensor detection.

Augmentation and pretraining for sensor time series

Iwana, B. K., & Uchida, S. (2021). An empirical survey of data augmentation for time series classification with neural networks. PLOS ONE.

Systematic catalogue of time-series augmentations (jitter, scaling, warping) and their effect on accuracy; the reference for choosing label-preserving transforms.

Goswami, M., Szafer, K., Choudhry, A., et al. (2024). MOMENT: A Family of Open Time-series Foundation Models. ICML.

A pretrained time-series backbone that changes the recipe from train-from-scratch to fine-tune; illustrative of the frontier shift noted in this section.

Das, A., Kong, W., Sen, R., & Zhou, Y. (2024). A decoder-only foundation model for time-series forecasting (TimesFM). ICML.

Google's TimesFM; a concrete example of the pretrained backbone plus light fine-tuning recipe now competitive with bespoke models.

Narayanswamy, G., Liu, X., Ayush, K., et al. (2024). Scaling Wearable Foundation Models (Large Sensor Model, LSM). arXiv.

Google's wearable foundation model trained on large-scale unlabeled sensor data; grounds the claim that fine-tuning is displacing from-scratch training for scarce-label sensor tasks.