Lecture 4: Time Series Forecasting and Anomaly Detection

Predict expected behavior, recognize meaningful deviations

Special Topics in Artificial Intelligence (STAI 2026)

Week 4: Overview What Changes When Data Has a Time Order?

Machine vibration, electricity demand, traffic, sales, and heart rate all change over time.

  • Forecasting: can we predict what happens next?
  • Anomaly detection: is what happened consistent with what we expected?

Historical sensor data form an expectation. One branch forecasts future values; the other compares an actual observation with that expectation.

Figure 1. One history, two questions.

Week 4: Overview Today’s Roadmap

Today’s story: first we learn to predict what comes next. Then we learn to notice when what happens is not what we expected.

Part I: Forecasting, including exercises

I.A Time-series data · I.B Forecast definition · I.C Forecasting methods · I.D Forecast evaluation · I.E Distribution shift and adaptation.

BREAK

Part II: Anomaly detection, including discussion

II.A Understanding anomalies · II.B Normal behavior · II.C Detection methods · II.D Detection evaluation · II.E Monitoring · II.F Decisions.

We will mainly use machine temperature and RPM, with other sensors where useful. Week 6 applies these ideas in a practical session. Full explanations, worked answers, and a glossary are in the lecture notes on the Week 4 page.

I.A) Understanding Time-Series Data Reading a Time-Series Graph

A time series is a sequence of observations recorded over time.

Here, each point is an hourly machine-temperature reading. Time is on the horizontal axis; temperature is on the vertical axis.

Hourly machine temperatures over five days rise overall and show a repeating daily pattern with smaller irregular fluctuations. Time runs from left to right.

Figure 2. Hourly temperature readings from one machine, using illustrative data.

What can you see? An overall rise, repeating peaks, and smaller irregular changes. We will separate these patterns next.

I.A) Understanding Time-Series Data Decomposition: Why Separate the Patterns?

Time-series decomposition separates an observed series into estimated components. For an observed value y_t at time t, an additive decomposition is:

y_t=T_t+S_t+R_t

  • Trend (T_t): the underlying level and longer-term direction.
  • Seasonality (S_t): variation that repeats at a regular interval, such as each day.
  • Remainder (R_t): what remains after removing the estimated trend and seasonality.

Why use it? Separate long-term change from repeated variation, then examine what remains.

I.A) Understanding Time-Series Data Decomposition: Reading the Components

This is the same temperature series, now split into its three parts. All panels share the same time axis.

Four vertically aligned panels show the observed temperature series, its estimated upward trend, a repeating 24-hour seasonal component centered on zero, and the smaller remainder centered on zero. Trend plus seasonality plus remainder equals the observed temperature at every hour; the vertical scales differ.

Figure 3. Additive decomposition of the temperature series from the earlier graph.

The remainder is not just noise: it can also hide unusual events, or patterns the split missed.

I.A) Understanding Time-Series Data Lags: How Past Readings Help Forecasting

Machine temperature often changes gradually, so a recent reading can help predict the next one. A relationship between readings at different times is called temporal dependence.

A lag tells us how far back a reading is from the value we want to predict.

Predict the next reading from 10, 12, 14: lag 1 is 14; lag 2 is 12; lag 3 is 10.

Known readings 10, 12, and 14 are lag 3, lag 2, and lag 1 relative to the unknown next reading.

Figure 4. Count lags back from the value being predicted.

Quick question: once 17 arrives, what are lags 1 and 2 when predicting the next reading?

I.B) Defining the Forecast Choosing the Lookback Window and Forecast Horizon

Forecasting uses information available now to estimate future observations. The forecast origin is the moment the forecast is made.

  • Lookback window: the history supplied to the model.
  • Forecast horizon: how far ahead we predict.

Example: use the previous 12 hours to predict the next 6 hours of machine temperature.

The forecast is made at hour 24. Hours 12 to 24 form the lookback, and hours 24 to 30 form a six-hour forecast horizon; the observed line ends at the origin.

Figure 5. History ends at the forecast origin.

I.B) Defining the Forecast Choosing the Variables and Prediction Steps

  • Univariate: forecast a variable from its own history.
  • With covariates: add related inputs, such as past RPM or a known future load schedule.
  • Joint multivariate forecasting: forecast several related variables together.

One-step / multi-step means one future reading / several. Reusing predictions as future inputs can accumulate error.

Historical inputs can contain temperature alone or temperature together with RPM and load. Outputs can be one future reading or a sequence of future readings.

Figure 6. Input choice and forecast horizon are separate decisions.

I.C) Forecasting Methods How a Model Learns to Forecast

A model is a rule or learned relationship that turns inputs into a prediction.

  • Inputs, or features: information we provide, such as three past readings.
  • Target: the next reading we want to predict.
  • Training: use past examples with known targets to adjust the model.
  • Prediction: apply the trained model when the next target is still unknown.

During training, inputs 10, 12, 14 are paired with known target 17. At prediction time, inputs 14, 17, 18 are available but the next target is unknown.

Figure 7. Training uses known outcomes; forecasting estimates an unknown outcome.

I.C) Forecasting Methods Comparing Forecasting Approaches

We can forecast the same target in several ways. The difference is how each approach uses history.

A baseline is a simple method used for comparison. Start there, then test whether a more complex method improves the forecast.

Five separate cards describe simple rules, statistical models, lag-feature models, sequence models, and pretrained models. They are alternatives rather than a chain.

Figure 8. Alternative forecasting approaches, not steps in a required pipeline.

For each approach, ask: what history does it use, and does it beat the baseline?

I.C) Forecasting Methods Naive Forecasts: Setting a Baseline

Naive: the next value equals the latest observation. Seasonal naive: repeat the value from the corresponding point in the last cycle. In decomposition terms, it reuses the seasonal pattern.

Fast and transparent, but unable to anticipate a new trend or operating regime.

If a complex model does not beat these baselines, reconsider its value.

A naive forecast repeats the latest observed value. A seasonal-naive forecast repeats the hourly pattern from the previous daily cycle into the next day.

Figure 9. Repeat the latest reading or the last known cycle.

I.C) Forecasting Methods Smoothing: Estimate the Recent Level

We want an estimate of the current level that smooths short-term fluctuations.

  • Moving average: average the latest few readings.
  • Exponential smoothing: combine the previous level and the latest reading using weighted averaging.

Example: previous level 70°C, new reading 80°C. Give the new reading 20% weight: 0.8\times70+0.2\times80=\mathbf{72}°C. Use 72°C as the next forecast.

A trailing average and an exponentially smoothed level follow a temperature trace and respond after its level jumps.

Figure 10. Smoothing reduces short-term variation but responds after a change.

A larger weight reacts faster, but also follows more of the short-term variation.

I.C) Forecasting Methods Before ARIMA: Does the Pattern Stay Stable?

The next method, ARIMA, needs reasonably stable relationships in the series it models.

Stationarity means the average, spread, and relationships at a fixed time gap stay stable over time.

The left series fluctuates around 60 degrees with a steady spread. The right series has a rising average and growing fluctuations.

Figure 11. A stable level and spread on the left; a changing level and spread on the right.

Differencing stops looking at the value itself and looks at how much it changed: \Delta y_t=y_t-y_{t-1}.

Example: 10, 12, 14, 16, 18 keeps rising. Its changes are 2, 2, 2, 2: a stable pattern. The trend is gone.

Differencing can reduce a trend. It does not fix every type of change.

I.C) Forecasting Methods ARIMA: Combine History and Past Errors

ARIMA combines past values, changes between readings, and past forecast errors.

Three boxes show past values, changes between readings, and earlier forecast errors as ingredients in an ARIMA model.

Figure 12. ARIMA combines past values, differencing, and past forecast errors.

ARIMA(p,d,q): three numbers, one per ingredient.

  • p: how many past values to use. This is the AR part.
  • d: how many differencing steps. This is the I part.
  • q: how many past prediction mistakes to use. This is the MA part.

A past prediction mistake, or residual: forecast 70, actual 72, a miss of +2.

ARIMA(2,1,1) differences the series once, then models the differenced series using two past lagged values and one past residual.

I.C) Forecasting Methods Lag Features: Turning History into Training Examples

A training example pairs available history with the value that came next. Lags are counted back from that target, just as in the earlier timeline.

Try it: for 10, 12, 14, 17, 18, use three past readings to predict the next one.

Table 1. Each row is one past forecasting example.
Lag 3 Lag 2 Lag 1 Target
10 12 14 17
12 14 17 18

Once 18 arrives, the next input row is 14, 17, 18. Its target is still unknown.

A model learns a relationship between the input columns and the target column.

I.C) Forecasting Methods Sequence Models: Learning from Ordered History

Keep the same task: use 10, 12, 14 to predict the next reading.

A sequence model learns from readings in time order. It can learn patterns across a longer history instead of relying only on summaries we chose.

  • Recurrent neural network (RNN): update a learned memory as each reading is processed.
  • Temporal convolution: move a learned filter across nearby readings to detect short patterns.

A recurrent model passes memory between time steps. A temporal filter moves across neighboring readings.

Figure 13. Sequence models can retain information over time or detect patterns in short windows.

Both approaches learn patterns in history to forecast the next reading.

I.C) Forecasting Methods Attention: Connecting Distant Times

What if a useful pattern occurred one day ago, rather than in the latest few readings?

Attention learns how much information to use from different parts of the available history. A Transformer is a model that uses this mechanism.

Example: the model weights the earlier cycle 0.5, the recent cycle 0.2, the latest readings 0.3. The most relevant part contributes most.

An earlier cycle from yesterday at the same operating condition, the current operating period, and the most recent temperatures feed a representation with example attention weights 0.5, 0.2, and 0.3. The earlier cycle is most relevant, so its connection is strongest.

Figure 14. Attention combines information from relevant parts of the observed history.

Attention can connect distant readings, but longer histories require more computation.

I.C) Forecasting Methods Pretrained Models: Reusing Learned Patterns

We can also start from a model that already learned from many time series.

A pretrained model has learned settings, called weights, that we can reuse. A broadly reusable model is often called a foundation model.

Zero-shot forecasting: provide our machine’s history and request a forecast, with no weight update on our data.

A model trained on many series receives the new machine history as context and produces a forecast without updating its weights.

Figure 15. Reuse a trained model, while still supplying the new series history.

The task stays the same. Compare its forecasts with our simple baseline on later readings.

I.D) Evaluating Forecasts Temporal Splits: Training on the Past, Testing on the Future

Before comparing methods, decide which data each method is allowed to use.

  • Training: learn from the earlier readings.
  • Validation: use later readings to choose the model and its settings.
  • Test: assess the final choice on a period kept out of those decisions.

A random split mixes time periods. A chronological split separates earlier training data, later validation data, and the newest test period.

Figure 16. Learn first, choose settings next, and assess the final choice last.

Keep time order. Mixing past and future can give an overly optimistic result.

I.D) Evaluating Forecasts Leakage: Information Arrives Too Early

Data leakage: a forecast uses information unavailable at its forecast origin.

  • A centered rolling mean averages readings before and after a time, including future values.
  • A scaler adjusts feature ranges. Fitting it on all data uses future statistics.

Quick question (1 minute): can today’s prediction use tomorrow’s actual weather, or a weather forecast already issued today?

Past training data precede a forecast origin and future measurements. A backward red arrow illustrates future measurements or future-derived statistics leaking into training.

Figure 17. Future information must not enter past predictions.

I.D) Evaluating Forecasts Forecast Errors: Comparing MAE, RMSE, and MAPE

How far were our forecasts from the actual readings?

Actual energy: 10, 20, 30 kWh. Forecasts: 12, 18, 36. Error sizes: 2, 2, 6 kWh.

Table 2. Three ways to summarize the same forecast errors.
Measure What it tells us Formula Calculation
MAE: mean absolute error Average error size \frac{1}{n}\sum_{t=1}^{n}\lvert y_t-\hat{y}_t\rvert (2+2+6)/3=\mathbf{3.33} kWh
RMSE: root mean squared error Gives large errors more influence \sqrt{\frac{1}{n}\sum_{t=1}^{n}(y_t-\hat{y}_t)^2} \sqrt{(2^2+2^2+6^2)/3}=\mathbf{3.83} kWh
MAPE: mean absolute percentage error Average error relative to actual values \frac{100}{n}\sum_{t=1}^{n}\left\lvert\frac{y_t-\hat{y}_t}{y_t}\right\rvert (20+10+20)/3=\mathbf{16.7}\%

y_t: the actual value at time t; \hat{y}_t: its forecast; n: the number of forecasts, here 3.

Start with MAE. MAPE breaks near zero, so never use it on Celsius temperature.

I.D) Evaluating Forecasts Walk-Forward Validation: Testing Several Forecast Origins

Walk-forward validation repeats forecasting at successive points in time.

At each origin: fit using earlier data, predict the required horizon, and record the errors.

This tests performance across several periods, not only one convenient split.

Three successive origins expand the earlier blue training history and evaluate two subsequent orange observations at each origin.

Figure 18. Expanding training history with a two-step forecast horizon.

I.D) Evaluating Forecasts Exercise: Walk Forward with a Naive Forecast

Series: 10, 12, 14, 17, 18. At each origin, predict that the next value equals the latest observed value.

Try it (3 minutes): fill in the three missing errors, then compute their MAE.

Table 3. Each forecast uses only the history available at that origin.
Origin Forecast Next actual value Absolute error
After 12 12 14 …
After 14 14 17 …
After 17 17 18 …

We will solve it together. Notice what each forecast is allowed to see at its origin.

I.D) Evaluating Forecasts Prediction Intervals: Forecasting a Range

A prediction interval describes uncertainty about a future observation, not a safe operating range.

Example: 75°C, with an illustrative 90% interval of 68 to 82°C.

Observed coverage = test observations inside their intervals / test observations checked. If 90 of 100 are inside, coverage is 90%.

Check coverage and interval width together. Very wide intervals can cover almost everything yet offer little decision value.

A temperature history ends at the forecast origin. The forecast line reaches 75 degrees Celsius and its illustrative 90 percent interval spans 68 to 82 degrees at the last horizon.

Figure 19. Forecast uncertainty can grow with the horizon.

I.E) Distribution Shift and Adaptation Model Degradation: Monitoring Forecast Errors

A model performed well when we tested it. Will it stay accurate during daily use?

Model degradation means its predictions become less accurate over time. Compare forecasts with actual readings as those readings arrive.

Daily temperature forecast MAE rises after an indicated change. The error plot does not identify the cause.

Figure 20. An increase in forecast error is a reason to investigate.

Next question: did the operating conditions change, or did the machine behave differently under the same conditions?

I.E) Distribution Shift and Adaptation Covariate Shift and Concept Drift: What Changes?

Rising errors can have different causes. Compare these two possibilities:

  • Input change (covariate shift): more high-RPM operation; unchanged fuel use at the same RPM and load.
  • Relationship change (concept drift): more fuel use at the same RPM and load.

One panel shows more operation at high RPM. The other shows increased fuel use at the same RPM with load held fixed.

Figure 21. Different inputs versus a changed relationship between inputs and output.

Check conditions and forecast errors before updating the model.

I.E) Distribution Shift and Adaptation Drift Patterns: Sudden, Gradual, Incremental, and Recurring

Sudden: abrupt replacement. Gradual: old and new behavior coexist during a transition. Incremental: the relationship keeps moving. Recurring: an earlier regime returns.

Quick question (1 minute): which panel fits a sensor replaced in one step? Which fits a machine that wears a little more each month?

Four schematic plots show abrupt replacement of a regime, alternating old and new regimes during a gradual transition, continuous movement, and recurring regimes.

Figure 22. Four schematic patterns of system change.

I.E) Distribution Shift and Adaptation Adaptation: Four Ways to Update a Model

  • Periodic retraining: refit on a schedule.
  • Sliding window: use only recent history.
  • Drift-triggered retraining: investigate a detected change, then refit.
  • Online learning: update incrementally as training data arrive.

Test each update on later data before relying on it. First investigate why performance changed.

Four boxes define periodic scheduled retraining, a recent sliding training window, retraining triggered after investigating drift, and incremental online updates.

Figure 23. Update strategies can be combined.

I) Forecasting From Prediction to Monitoring

A useful forecast needs an appropriate baseline, honest evaluation, and monitoring.

Discuss: if errors rise after a sensor replacement, what would you check before retraining?

Forecasting asks what we expect next. Now we ask whether the observed behavior is unusual.

Observe past data, learn patterns, forecast and evaluate, monitor change, and adapt if needed; feedback returns to the observation and modeling process.

Figure 24. Forecasting is an ongoing process.

BREAK

After the break: how can a model recognize unusual behavior?

II.A) Understanding Anomalies Anomalies: A Reason to Investigate

Part I taught us what to expect. Part II asks: what if the actual behavior does not match?

An anomaly is an observation or pattern that differs meaningfully from expected behavior. A temperature spike might reflect a fault, a sensor problem, or a valid operating event.

Anomaly detection tells us where to investigate. It does not establish the cause.

A mostly stable temperature trace contains one high reading highlighted in red. The deviation identifies something to investigate rather than a confirmed fault.

Figure 25. A deviation is evidence to examine, not a diagnosis.

II.A) Understanding Anomalies Normal References: Defining Expected Behavior

A normal reference is evidence we trust to describe expected behavior under the relevant operating conditions.

  • Example: a period an engineer confirms was healthy, covering both low and high loads.
  • Possible forms: limits, typical values, similar examples, or a forecast.
  • Main risk: a reference with hidden faults or missing conditions can be misleading.

Without confirmed healthy data, a method still needs assumptions. For example, it may treat rare, isolated readings as unusual.

Ask first: what evidence tells us what normal behavior should look like?

II.A) Understanding Anomalies Detection Challenges: Rare Events and Changing Conditions

  • Rare events: 990 normal examples may accompany only 10 anomalies.
  • Few labels: engineers may not know which past readings were abnormal.
  • Unknown events: future faults may differ from known examples.
  • Noise: random variation can resemble a problem.
  • Changing normality: a valid new operating regime may look unusual.

Why does this list matter? Every detection method in the next section is an answer to these difficulties. Each method builds its own picture of normal behavior in a different way, and then flags the readings that do not fit that picture.

II.A) Understanding Anomalies Anomaly Types: Points, Context, and Sequences

Before building any detector, know what shapes an anomaly can take.

A point is unusual alone. A contextual anomaly is unusual for its time or condition. A collective anomaly is an unusual pattern across several readings.

Choose a representation that preserves the context needed to detect the problem.

Three traces illustrate an isolated temperature spike, an in-range value that is wrong for its temporal context, and a flat segment replacing an expected oscillation.

Figure 26. Different anomalies require different evidence.

II.A) Understanding Anomalies Multivariate Anomalies: Unusual Combinations

A temperature of 72°C can be normal at high RPM but unusual at 1,000 RPM.

Univariate detection examines one variable. Multivariate detection examines several variables and their relationships.

Separate sensor limits can miss an inconsistent combination.

The red 72-degree reading lies within the overall range of unordered temperature examples, but paired with 1000 RPM it is far above the normal RPM-temperature relationship.

Figure 27. The operating condition changes how a value is interpreted.

II.B) Defining Normal Behavior Learning Settings: What Labels Are Available?

A label records what an example represents, such as normal operation or a confirmed failure.

The labels available for training determine what we can teach a detector.

Table 4. Different training evidence leads to different learning tasks.
Setting Available examples What we teach the model
Supervised 900 normal, 100 failure labels Distinguish the known classes
Normal-only / one-class 900 examples confirmed normal Learn normal, flag departures
Unsupervised 1,000 examples, no labels Search for unusual patterns

A method’s name does not determine its setting. What matters is the data used to train it.

II.B) Defining Normal Behavior From an Unusualness Score to an Alert

An anomaly score measures how unusual a reading or pattern looks to a detector. In this example, higher means more unusual.

A threshold is the cutoff for raising an alert: score > 0.70 → alert.

Scores 0.10, 0.17, 0.25, 0.73, and 0.94 are compared with a threshold of 0.70. Only the last two exceed it.

Figure 28. The two scores above the cutoff produce alerts.

A score of 0.94 is not automatically a 94% chance of failure. Some methods use different scales; a fixed rule may directly return yes or no.

II.B) Defining Normal Behavior What Does Each Detection Method Check?

Each method checks a different kind of departure from expected behavior. These questions follow the order of the next method slides.

Seven questions cover known limits, statistical ranges, forecast error, distance to reference points, local density, random isolation, and reconstruction error.

Figure 29. Questions used to check whether behavior is unusual.

II.C) Anomaly Detection Methods Rules: Alert Outside a Known Limit

From the map: unusual means outside a limit. Example rule: temperature > 90°C → alert.

  • Strength: clear, fast, and easy to explain.
  • Limitation: a single limit may miss context or generate unnecessary alerts.

Use expert limits when they match the decision; do not treat them as a complete diagnosis.

Temperature readings above an illustrative 90-degree limit are marked as alerts; lower readings do not cross this particular rule.

Figure 30. An illustrative rule flags readings above a fixed limit.

II.C) Anomaly Detection Methods Statistics: Far from the Expected Range

From the map: unusual means far from the expected range. Standard deviation measures spread around the mean of a suitable normal reference.

z=\frac{x-\mu}{\sigma}=\frac{86-70}{4}=4

x: reading; \mu: reference mean; \sigma: reference standard deviation. 86°C is 16°C above the mean, or four standard deviations.

Estimate the reference for comparable operating conditions. Lopsided (skewed) data and mixed regimes can make a single mean and spread misleading.

An illustrative bell-shaped reference has mean 70 degrees and standard deviation 4 degrees. Limits at 58 and 82 are three deviations away; 86 is four deviations above the mean.

Figure 31. Mean ± 3 standard deviations is an illustrative rule.

II.C) Anomaly Detection Methods Prediction: Compare Expected and Actual

This connects detection to Part I: make a forecast, then compare it with the reading that arrives.

Forecast 70°C, actual 75°C: the absolute forecast error is 5°C. We can use that error as an anomaly score.

An earlier one-step forecast follows the expected temperature pattern. A later spike creates a large difference between the forecast and observation.

Figure 32. A forecast made earlier becomes the reference for checking a new reading.

Judge the error against usual forecast errors. A 5°C error is more unusual when typical errors are around 1°C than when they are around 5°C.

A poor forecast can cause a false alert. A large error alone does not prove a fault.

II.C) Anomaly Detection Methods Neighbors: Is There Similar Data Nearby?

Idea: a reading looks unusual if similar examples are far away.

Each dot represents two measurements: blue = reference observations; red = a new observation.

k-nearest neighbors (kNN): choose a number of neighbors, k. Use the distance to the kth nearest reference point as the score. Here, k=3.

Two panels show the same reference group. A query within the group reaches three neighbors at a short distance; a distant query needs a much larger distance.

Figure 33. Compare the distance needed to reach three reference neighbors.

Make feature scales comparable first, so a large numerical unit does not dominate distance.

II.C) Anomaly Detection Methods Local Density: Unusual Compared with Which Neighbors?

Distance alone can be misleading when one valid group is tightly packed and another is spread out.

Local Outlier Factor (LOF) asks: is this point in a less crowded area than its own neighbors?

A dense group and a spread-out valid group are shown. A highlighted point near the dense group is less crowded than its immediate neighbors; the spread-out group is not automatically anomalous.

Figure 34. A spread-out group can be normal; compare a point with its own neighborhood.

The comparison is local. A sparse group is not automatically a faulty group.

II.C) Anomaly Detection Methods Isolation Forest: Easy to Separate?

Idea: an unusual point is easy to separate from the rest.

Imagine cutting the data with random lines. Left: the red point is far from the others, so one cut is enough to leave it alone. Right: a blue point inside the group needs many cuts before it stands alone.

Isolation Forest repeats this with many random trees and averages: the fewer cuts a point needs, the more unusual it is.

It needs no labels and runs fast. Two limits: it does not see time order, and useless input features weaken it.

A random vertical split isolates one distant red observation, while additional horizontal and vertical splits are needed to separate a blue point inside a cluster.

Figure 35. One illustrative tree; a forest repeats the random process.

II.C) Anomaly Detection Methods Reconstruction: Can We Rebuild the Input?

Reconstruction rebuilds a supplied input. Forecasting estimates a future reading.

An autoencoder learns to compress an input and rebuild it.

Train it on trusted normal examples. Then compare a new input with its reconstruction.

An autoencoder reconstructs a supplied normal window with small discrepancies and an unusual window with a larger discrepancy near a spike.

Figure 36. Compare the observed window with the model’s reconstruction of that same window.

Use reconstruction error as a score. Large errors suggest unusual patterns, but some anomalies can also be rebuilt well.

II.D) Evaluating Anomaly Detection Evaluation Roadmap: Three Questions

We have turned unusual behavior into alerts. Do those alerts help us find real problems?

We will answer three questions:

Three branches ask whether alerts find known anomalies, how thresholds trade false alerts against missed events, and what evidence is possible without reliable labels.

Figure 37. Evaluate whether alerts find problems, then choose settings that suit the task.

Use a labeled test period when available. Without labels, the evidence is more limited.

II.D) Evaluating Anomaly Detection Class Imbalance: Why 99% Accuracy Can Be Misleading

A detector predicts normal for every observation.

Its accuracy is 990 / 1,000 = 99%, but it finds none of the 10 anomalies.

Evaluate detected events and false alerts, not accuracy alone.

Among 1000 observations, 990 are normal and 10 anomalous. Predicting every observation as normal produces 99 percent accuracy while detecting no anomalies.

Figure 38. A high score can hide complete failure to detect anomalies.

II.D) Evaluating Anomaly Detection Precision and Recall: Counting Detection Outcomes

In a test period there were 10 anomalous readings. The detector raised 12 alerts: 8 correct and 4 false. It missed 2 anomalies.

  • Precision: of all alerts, how many were correct? 8 out of 12 = 66.7%.
  • Recall: of all anomalies, how many did we find? 8 out of 10 = 80%.

The matrix contains 8 correct alerts, 4 false alerts, 2 missed anomalies, and 986 correct normal decisions.

Figure 39. Correct alerts, false alerts, and missed anomalies answer different questions.

Precision describes alert reliability. Recall describes how many anomalies were found.

II.D) Evaluating Anomaly Detection Threshold Selection: Balancing Misses and False Alerts

With a lower threshold, more readings raise alerts. This may catch more anomalies, but also creates more false alerts.

With a higher threshold, fewer readings raise alerts. Some anomalies may be missed.

The same labeled scores are compared at thresholds 0.45 and 0.80. The lower threshold catches more anomalies and more normal points.

Figure 40. Changing the threshold changes both correct detections and false alerts.

Choose on validation data: balance missed problems against false alerts and review capacity.

With only trusted normal data: a cutoff above 99% of those scores is one starting point. Check it later; it does not tell us how many anomalies will be missed.

II.D) Evaluating Anomaly Detection Evaluation in Each Situation: What If Labels Are Missing?

Training labels and evaluation labels answer different questions. A detector trained without labels can still be checked against labeled test data.

Table 5. Match the strength of the conclusion to the available evidence.
Available test evidence What we can check
Known anomalies and normal periods Correct alerts, false alerts, missed anomalies, and detection delay
No reliable anomaly labels Try artificial anomalies, ask experts to review alerts, and check behavior during trusted normal periods

Without known events, we cannot measure recall. Artificial anomalies test only the patterns we create; reviewed alerts do not reveal every missed event.

II.E) Monitoring in Practice Anomaly or Drift: Investigating Persistent Change

Evaluation used recorded data. Now the detector runs every day, and daily operation brings new questions.

A brief spike may be an isolated anomaly. A persistent deviation may indicate a new regime, drift, a sensor issue, or an ongoing fault.

Duration is a clue, not a diagnosis. A persistent fault remains important even if it becomes common.

Before accepting a change as the new normal, check the operating conditions and whether the input-target relationship really changed.

One temperature trace briefly departs and returns; another shifts persistently. Either trace requires context to distinguish valid change, drift, sensor trouble, or a fault.

Figure 41. A change in the trace does not reveal its cause.

II.E) Monitoring in Practice Online Detection: Score Data as They Arrive

So far we scored recorded data. In operation, readings arrive one by one.

Offline: analyze a collected dataset later. Online: evaluate each new reading or short window as it arrives.

Meet the required response time while controlling false alerts. Online detection does not necessarily mean online model training.

For each incoming sensor reading, use past context, compute a score now, raise or record an alert, and later review feedback.

Figure 42. Streaming evaluation can use a fixed or periodically updated model.

II.E) Monitoring in Practice Alert Explanations: Showing Evidence for Investigation

An alert has fired. What does the engineer see next?

For an alert score of 0.94, ask: what changed, when, and under which conditions?

Show expected versus observed behavior and the sensors contributing most to the discrepancy.

An explanation supports investigation; it does not prove a root cause.

An alert score of 0.94 is accompanied by observations: temperature is high for the RPM, vibration increased, and pressure stayed near its expected range.

Figure 43. Translate an alert into evidence an engineer can examine.

II.E) Monitoring in Practice Human Review: Recording Findings and Improving Detection

The last step of daily monitoring is human judgment. An engineer reviews the alert, checks context, and records what was found.

Useful feedback distinguishes a fault, a sensor problem, a valid event, and an unresolved case.

Use reviewed feedback to improve thresholds and training data. An unreviewed alert is not a confirmed anomaly label.

A model alert goes to an engineer for review, classification of the event or false alarm, and recorded feedback for controlled improvements.

Figure 44. Detection and human review have different responsibilities.

II.F) From Detection to Decisions Method Selection: Choosing a Suitable Starting Point

Which method should you start with? Ask what evidence you have. Find your row, start there, then test on later data.

Table 6. Match the evidence you have with a starting method.
What you have Start with Be careful
Safe limits from engineering knowledge A fixed rule It cannot see context
Examples labeled normal and fault A supervised classifier New faults it has never seen
A stable, confirmed healthy period Statistics: mean and spread Conditions that change over time
Many trusted normal examples Neighbors: kNN or LOF Scale features, choose k carefully
Mostly normal rows, no labels Isolation Forest It cannot see time order
Trusted windows of normal readings An autoencoder It may rebuild anomalies well too
A forecast you can trust Forecast error as the score A poor forecast creates false alerts

These are starting points, not final answers. Whatever you pick, compare it with a simple baseline on the same later events.

II.F) From Detection to Decisions Detection, Diagnosis, and Prognostics: Different Questions

Detection found something. What happens after an alert?

  • Detection: something differs from expectation.
  • Diagnosis / root-cause analysis: what fault occurred, and why?
  • Prognostics: how might the condition develop, or when might failure occur?

An action needs evidence, operating constraints, and human responsibility.

Detection asks whether behavior is unusual, diagnosis asks what fault and why, prognosis asks what happens next, and decision asks what action to take.

Figure 45. Later stages need evidence beyond an anomaly score.

Week 4: Summary Expected Behavior Connects Both Tasks

Forecasting: what should happen next? Anomaly detection: is what happened consistent with what we expected?

Use honest temporal evaluation, meaningful thresholds, and monitoring for change.

A prediction or alert is useful when it supports a better decision.

One path uses historical measurements and a forecasting model to estimate future behavior. A second compares actual and expected behavior, turns the difference into an anomaly score and alert, and supports investigation.

Figure 46. Two questions built on an appropriate expectation.