Time Series Basics
Univariate
- Only one variable observed (e.g., outdoor temperature)
Multivariate
- Multiple variables observed — a combination of univariate series (e.g., 3-axis accelerometer)
- The most common situation in AmI
Discretization & sampling rate
The real process is continuous (e.g., acceleration), but the signal must be sampled to be stored digitally. The sampling rate (Hz) sets how many samples per second.
- High rate → more energy + more expensive analysis
- Low rate → information loss
- Find a good utility ↔ efficiency trade-off
Time-domain vs Frequency-domain analysis
Time domain
- Analysis with reference to time — intuitive & common
- Good for linear trends & seasonalities (periodic events)
- Hard to find complex/non-linear patterns or isolate noise
Frequency domain
- Represent the series by its constituent frequencies
- Via Fourier or Wavelet transform
- Adds complexity; needs advanced signal processing
The four tasks we tackle in AmI: classification, clustering, anomaly detection, forecasting.
Pre-processing
Temporal alignment
Multivariate series may have different sampling rates, or be misaligned even at the same rate. Two strategies:
- Time synchronization — devices aligned on the timestamp
- Resampling — align all series to the same sampling frequency
Imputation (missing values)
Conventional imputation doesn't fit time series — the order of values matters. Approaches: backward/forward fill, mean/median imputation, and linear interpolation.
⭐ Denoising by smoothing (Simulation Q22b)
Apply filters to reduce noise. Small overhead, but a risk: changing the original data points may hurt the analysis.
| Method | How it works |
|---|---|
| Simple Moving Avg (SMA) | Replace each value with the average of the last N points: SMAt = (xt+…+xt-N)/N |
| Exponential Moving Avg (EMA) | EMAt = α·xt + (1-α)·EMAt-1 — α weights the current value vs the past |
| Median Filter | Replace xt with the median of its neighbors |
| Fourier denoising | FFT → frequency domain → remove noisy frequencies (low-pass/high-pass) → back to time domain |
Normalization / Scaling
In multivariate series, dimensions may have different ranges → high-value dimensions may dominate. Standardize/normalize each dimension separately (e.g., to [0,1]).
⭐ Outliers (Simulation Q22a)
This is the exact subject of the open-ended Q22a. Nail the outlier-vs-anomaly distinction and the two outlier types.
Two types of outliers
Point outlier
- A single data sample that behaves unusually
- vs the whole series → global outlier
- vs neighboring points → local outlier
Subsequence outlier
- Consecutive samples whose joint behavior is unusual
- Each point alone is not necessarily a point outlier
- Can also be global or local
Both types apply to univariate and multivariate data.
Segmentation & Feature Extraction
Why segment?
Time series are potentially infinite. A single sample isn't representative — spatiotemporal aspects are crucial, so we reason over time intervals (segments).
Segmentation strategies
Fixed-size windows
- Most common, simple
- Time-based: each window = w seconds, overlap factor o
- Event-based: each window = last k sensor events (for discrete smart-home data)
Dynamic segmentation
- Boundaries set by significant changes in distribution (mean shift, std, slope, count)
- Each segment captures an event of interest
- Challenging & computationally demanding
Feature extraction
Handcrafted
- Data scientist designs statistical features per window (time & frequency domain)
- Fed to classic ML (Random Forest, SVM, MLP, K-Means)
- Limit: designing good features is hard
Automatic
- A DNN (CNN/RNN) extracts features from raw segments during training
- The resulting feature vector = embedding (latent-space representation)
- Proved more effective
Feature reduction (PCA, t-SNE) helps when features are many — and aids visualization.
CNNs for Time Series
CNN building blocks
| Layer | Role |
|---|---|
| Convolutional | A filter/kernel (small matrix of learned weights) slides over the input; element-wise multiply + sum → feature map. Many filters per layer capture different aspects. |
| Pooling | Reduce feature-map dimensionality (fewer weights). Max pooling (max per patch) or average pooling. |
| Flattening | Converts CNN output into a vector for the dense layers. |
| Dense (fully-connected) | Transform high-level features into the final output (class probabilities or regression). |
Activations & regularization
- ReLU = max(0, z) — most popular, adds non-linearity, fast convergence. Problem: dying neuron (pre-activation always negative → gradient 0 → weights frozen).
- Leaky ReLU — allows small negative values (e.g., 0.01x), so neurons don't saturate at 0; solves dying neuron, still non-linear.
- Dropout — randomly drop a fraction p of neurons each iteration → regularization, reduces overfitting. Often after pooling.
- Softmax output layer → probability distribution over classes (exp keeps positives, accentuates differences). Binary case: single sigmoid neuron.
- Cross-entropy loss — pushes probability mass onto one class; risk of overconfidence (mitigated with regularization).
Applying CNNs to sequences
- 1D CNN — kernel moves only horizontally (along time). The standard for sequences.
- Multi-head 1D CNN — each dimension processed by its own channel; more flexible.
- 2D CNN — frequency-transformed series (e.g., a scalogram) treated as an image.
⭐ RNNs & LSTM (Simulation Q20)
Recurrent Neural Networks
Designed for sequential data — each input is a sequence, and sequences may have different lengths (unlike FCN/CNN with fixed input). Key difference: feedback loops.
- The output for element xt is used as extra info when processing xt+1; the feedback connection has a learnable weight.
- Unfolding/unrolling: visual way to show a cell processing each element over time — but it's really one cell with a feedback loop. Weights are shared, fixed regardless of sequence length.
The vanishing/exploding gradient problem
The feedback weight w is applied repeatedly. After a long sequence the output behaves like input × wseqLength:
Exploding (w > 1)
- e.g. w=2, length 50 → input × 2⁵⁰ (giant)
- Too-large gradient → optimization oscillates, never settles
Vanishing (w < 1)
- e.g. w=0.5, length 50 → input × 0.5⁵⁰ ≈ 0
- Gradient ≈ 0 → training extremely slow
LSTM — the fix
Evolution of RNNs to mitigate vanishing/exploding gradients. Main idea: two separate paths instead of a single feedback loop — a long-term memory (cell state) and a short-term memory (hidden state). The unit is more complex.
The three gates
| Gate | What it does | Activation |
|---|---|---|
| Forget gate | Multiplies long-term memory by a sigmoid output → decides % of long-term memory to keep (small → forget) | σ (sigmoid) |
| Input gate | tanh = potential new long-term memory; sigmoid = % of new info to add | tanh + σ |
| Output gate | Updates short-term memory: tanh of cell state, sigmoid picks % to keep → this is the output (hidden state) | tanh + σ |
Helpers: sigmoid (σ) maps any input to [0,1]; tanh maps to [-1,1] (a shifted/stretched sigmoid, keeps the cell state from blowing up).
The Four Tasks
① Classification
Classify temporal segments (e.g., Human Activity Recognition, Emotion Recognition). Handcrafted features + classic ML, or automatic features (CNN/LSTM) with a softmax output + cross-entropy loss.
② Clustering
Find patterns in unlabeled data (e.g., discover human behaviors). The challenge is defining "similarity". Either cluster raw series with ad-hoc distances, or extract fixed-size features then use standard similarity.
LCSS
- Longest Common Subsequence of similar points (threshold ε) that are temporally close (threshold σ)
- Compares sequences of different lengths n, m
- Not robust to noise
DTW (Dynamic Time Warping)
- More robust to noise (but more complex)
- Finds the pairing π minimizing distance between points
- Conditions: match endpoints, every index matched, mapping monotonically increasing
Deep clustering: learn embeddings from raw segments (similar series close in space), then cluster the embeddings (PCA/t-SNE help).
⭐ ③ Anomaly Detection (Simulation Q13)
Anomalies are events of interest (not data cleaning). Three settings:
| Approach | Training data | Idea |
|---|---|---|
| Supervised | normal + anomalous | Binary classification — but very unbalanced (anomalies rare & rarely labeled) |
| Semi-supervised | only normal | Model the expected behavior; flag samples that differ significantly |
| Unsupervised | unlabeled | Flag unrepresentative samples (assume normal = majority) |
Method families: clustering-based (sample outside the normal subspace), density-based (low probability under the pdf), and reconstruction-based.
④ Forecasting
Use historical + current data to predict future values (e.g., load forecast in smart energy).
- ARIMA — statistical: AR (previous p values) + MA (previous q errors). Good if the series is stationary (stats don't change over time); may need differencing to remove seasonality.
- Deep forecasting — sensor data is usually not stationary → DL (recurrent nets) most effective; minimize prediction error (regression losses: MAE, MSE, RMSE…).
Linear forecasting
- Input length n → output length m, both fixed
Autoregressive forecasting
- Predict the following values with no fixed bound; feeds predictions back in (recurrent)
Final Quiz — Exam Style
9 MCQs + 3 open-ended. Several are modeled directly on the simulation exam (Q13, Q20, Q22).
a) Outlier detection aims to find unwanted data points so they can be removed — its goal is data cleaning. Anomaly detection aims to find anomalous events of interest that should be analyzed (the difference is subtle and depends on the application). A point outlier is a single sample that behaves unusually — vs the whole series (global) or vs its neighbors (local). A subsequence outlier is a set of consecutive samples whose joint behavior is unusual, even though each individual sample may not be a point outlier; both types apply to univariate and multivariate data.
b) Smoothing applies a filter (e.g., moving average, median filter) to reduce noise by replacing each point with an aggregate of its neighbors, at the risk of altering the original data. The window size controls the trade-off: a too-large window over-smooths the signal and risks losing useful information (utility), while a too-small window barely removes noise. (For EMA, the analogous parameter is α, weighting the current sample vs the past.)
a) An RNN applies the same feedback weight w at every step of the unrolled sequence, so the end-of-sequence output (and the gradient during backprop) scales like input × w^(sequence length). If w > 1 this grows exponentially (exploding gradient → oscillating optimization that never converges); if w < 1 it shrinks toward 0 (vanishing gradient → extremely slow learning, earlier information lost).
b) The LSTM adds a separate cell state (long-term memory) with no weights directly applied as it flows along the sequence — it is only additively updated or cleared — so information and gradient travel largely intact. Three gates control it: the forget gate (sigmoid) decides the % of long-term memory to keep; the input gate (tanh for candidate value + sigmoid for %) adds new information; the output gate (tanh + sigmoid) produces the hidden state / output. The cell state captures long-term dependencies but can still be updated/cleared each step.
a) Supervised: trained on both normal and anomalous samples (binary classification) — but the task is very unbalanced since anomalies are rare and rarely labeled. Semi-supervised: trained only on normal data; it models expected behavior and flags samples that differ significantly. Unsupervised: trained on unlabeled data, assuming normal samples are the majority and anomalies are few/unrepresentative.
b) An autoencoder is trained to reconstruct normal time windows (encoder → latent embedding → decoder). The assumption is it will fail to reconstruct abnormal sequences, so a high reconstruction error (MSE between input and output) indicates an anomaly. The threshold is often set statistically on the reconstruction error of normal data — commonly 2σ or 3σ from the mean.