Skip to main content

Detecting anomalies in indicator series and explaining them

Generated from notebooks/data-anomaly/Anomaly_Detection_Suite.ipynb. Do not edit this page directly — edit the notebook and re-run the docs build.

Open in Colab

This notebook walks through the detection suite of ai4data.anomaly: a Python rebuild of the workflow of the World Bank's macroanomaly R package. It finds unusual observations in country-indicator time series and hands them, in the format the explanation pipeline already reads, to a language model and then to a human reviewer.

The two halves fit together without an adapter. Detection writes indicator_id, geography_id, period, value, is_imputed, anomaly_score and outlier_count, which are the canonical columns of ai4data.anomaly.explanation, so the output of one step is the input of the next.

Contents

  1. The data
  2. Prepare: gaps, imputation, trend, z-scores
  3. Detect: five methods on the same z-scores
  4. Agreement and the shortlist
  5. Further methods: robust CAPA and outlier trees
  6. Explain and review: the hand-over to the explanation pipeline
  7. Your own data, the command line and your own detector

The pictures are animated SVG. They loop, and they need no extra packages.

Install the library first if it is not already available: pip install "ai4data[anomaly]". In Colab, run the next cell.

# Colab: install the library and fetch the picture helpers. Skipped when they are already here.
import importlib.util, subprocess, sys, urllib.request
from pathlib import Path

if importlib.util.find_spec("ai4data") is None:
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "ai4data[anomaly] @ git+https://github.com/worldbank/ai4data.git"], check=True)
if not Path("detection_visuals.py").exists():
urllib.request.urlretrieve("https://raw.githubusercontent.com/worldbank/ai4data/main/notebooks/data-anomaly/detection_visuals.py", "detection_visuals.py")
import json
import tempfile
import warnings
from pathlib import Path

import numpy as np
import pandas as pd
from IPython.display import display

import detection_visuals as viz
from ai4data.anomaly.detection import detect, detect_anomalies, normalize

pd.set_option("display.width", 140, "display.max_columns", 20)
warnings.filterwarnings("ignore", category=UserWarning)
viz.pipeline_diagram()

From a table of indicator series to a reviewed explanationDetection is the new first half; explanation and review already existed.Preparefill gaps, impute,remove the trendz-scoresDetectfive methods readthe z-scoresflags per methodShortlistseries flagged bythree methods or moreseries to explainExplaina language model readsthe window of yearsexplanationsReviewa person accepts,rejects or editsa decisionai4data.anomaly.detectionai4data.anomaly.explanation

The diagram shows the steps and where the two packages meet. Prepare turns each series into z-scores. Detect runs several methods on those z-scores. Shortlist keeps the series in which several methods agree. Those series go to the language model (Explain), and a person decides in the reviewer app (Review).

1. The data​

The panel below is fictional: four indicators for eight made-up countries from 2000 to 2024. Each series is a trend with noise, and about a third of them carry a planted anomaly: a single jump, a run of shifted years, or a constant tail. Some have missing years, so that every step of the workflow has something to do. With real data the table has the same shape, one row for each indicator, country and year.

panel = viz.demo_panel()
print(f"{len(panel):,} rows, {panel.indicator_id.nunique()} indicators, {panel.geography_id.nunique()} countries, "
f"{panel.period.min()}-{panel.period.max()}")
panel.head()
780 rows, 4 indicators, 8 countries, 2000-2024
indicator_id indicator_name geography_id geography_name period value
0 SH.MORT.U5 Under-five mortality rate (per 1,000 live births) AAA Aldoria 2000 54.14
1 SH.MORT.U5 Under-five mortality rate (per 1,000 live births) AAA Aldoria 2001 50.10
2 SH.MORT.U5 Under-five mortality rate (per 1,000 live births) AAA Aldoria 2002 50.39
3 SH.MORT.U5 Under-five mortality rate (per 1,000 live births) AAA Aldoria 2003 46.82
4 SH.MORT.U5 Under-five mortality rate (per 1,000 live births) AAA Aldoria 2004 47.88

The column names are already the canonical ones. For a table with other names, pass mapping={"indicator_id": "Indicator.Code", ...}, or mapping="auto" to let the library guess from the headers (section 7).

2. Prepare: gaps, imputation, trend, z-scores​

normalize does four things to every series, in this order:

  1. Fills gaps in the time index, so that a missing year becomes a missing value.
  2. Imputes missing values and records them in is_imputed, so that an invented value is never reported as an anomaly.
  3. Removes the trend. Without it, a series that rises steadily would look unusual at both ends. For yearly data the trend comes from Friedman's super smoother, the smoother that R's feasts::STL uses for series without a season, and it matches R exactly.
  4. Standardises what is left to mean 0 and standard deviation 1, giving zscore. All the detection methods read this column, so one threshold fits every indicator, whatever its unit.

The animation follows one series through the four steps. This one has two missing years.

prepared = normalize(panel, keep_decomposition=True)
print(prepared.attrs["total_gaps"], "gaps filled;", prepared.attrs["total_missing"], "missing values;", len(prepared.attrs["dropped_series"]), "series dropped")
viz.stages(prepared, panel, "SH.MORT.U5", "DDD")
20 gaps filled; 20 missing values; 0 series dropped

Under-five mortality rate (per 1,000 live births) · Dovenia12274156702000200420082012201620202024value1 · The series as observedYears with no value leave gaps in the line.12274156702000200420082012201620202024value2 · Missing years imputedInterpolated values (hollow) are flagged in is_imputed and never reported as anomalies.12274156702000200420082012201620202024value3 · The trend removedThe smooth curve is the trend; what is left over is the remainder.-1.6-0.01.63.24.82000200420082012201620202024z-score4 · Standardised to z-scoresEvery series now has mean 0 and standard deviation 1, so one threshold fits all of them.

Imputation is a choice, and the choice matters most where a series has a long gap. Seven methods are built in: interpolation, locf, mean, ma, random, kalman (a structural time-series model, smoothed) and seadec (seasonal decomposition, for quarterly and monthly data). The na_ names of the R package work as aliases. The animation draws each method over the gaps of one series, one after the other.

s = panel[(panel.indicator_id == "SE.PRM.NENR") & (panel.geography_id == "EEE")].set_index("period")["value"]
years = np.arange(2000, 2025)
observed = s.reindex(years).to_numpy(float)
fills = {}
for method in ["interpolation", "locf", "ma", "kalman"]:
one = normalize(panel[(panel.indicator_id == "SE.PRM.NENR") & (panel.geography_id == "EEE")], impute_method=method)
fills[method] = one.set_index("period")["value"].reindex(years).to_numpy(float)
viz.imputation_compare(years, observed, fills, title="Primary enrolment, Estrella: four ways to fill the gaps")

Primary enrolment, Estrella: four ways to fill the gapsObserved values are blue dots; each method draws its fill over the gaps in turn.64707681872000200420082012201620202024valueinterpolationlocfmakalman

3. Detect: five methods on the same z-scores​

detect_anomalies prepares and detects in one call. By default it runs five methods. Each adds one 0/1 column outlier_<method>:

MethodWhat it flagsRebuilt from
zscore`z
tsoutlierz-scores outside the Tukey fences of the seriesforecast::tsoutliers
hampelz-scores far from the median of their neighbourspracma::hampel
caparuns (collective) and single values (point) with a penalised likelihoodanomaly::capa
isotreeobservations an isolation forest separates from the rest in few splitsisotree

Section 5 adds outliertree and a robust variant of capa. Every column is added to the table next to outlier_count, the number of methods that flag the observation, and anomaly_score, the size of the z-score.

default = detect_anomalies(panel)
print({m: n for m, n in default.summary()["flagged_by_method"].items()})
{'zscore': 7, 'tsoutlier': 13, 'hampel': 10, 'capa': 159, 'isotree': 204}

Two methods flag far more than the others. That is a property of the data and not a fault of the code: the z-scores of a short series are read by CAPA as a baseline of variance 1, and an isolation forest flags 0.5 or more by default. Both have parameters for this. The recipe below raises the penalties of CAPA and the threshold of the forest, and takes the median of each series as CAPA's centre (robust_scale). The thresholds are a decision about how many false alarms the reviewers can bear, and params is where that decision is written down.

PARAMS = {"capa": {"robust_scale": True, "beta": 25, "beta_tilde": 18}, "isotree": {"threshold": 0.65}}
result = detect_anomalies(panel, params=PARAMS)
print({m: n for m, n in result.summary()["flagged_by_method"].items()})
result.summary()["observations_by_methods_in_agreement"]
{'zscore': 7, 'tsoutlier': 13, 'hampel': 10, 'capa': 37, 'isotree': 11}





{0: 758, 1: 28, 2: 6, 3: 1, 5: 7}

Below, a cursor moves along one series. Each method raises a flag when the cursor reaches a year that it flags. The jump in 2007 is flagged by four of the five methods; CAPA also marks a run of years after it.

viz.detector_sweep(result.table, "EG.ELC.ACCS", "FFF")

Access to electricity (% of population) · FenmarkEvery method reads the same z-scores. A flag appears when the cursor reaches the year that a method flags.-1.20.41.93.44.92000200420082012201620202024z-scorezscoretsoutlierhampelcapaisotree

CAPA deserves a closer look because it reports two different things. A point anomaly is one value too far from the baseline. A collective anomaly is a run of at least two values with its own mean and variance, which no threshold on single values can find. The columns capa_type and capa_strength tell them apart.

viz.capa_view(result.table, "EG.ELC.ACCS", "EEE")

Access to electricity (% of population) · EstrellaCAPA looks for runs with their own mean and variance (collective) and for single values that are too far out (point).-4.9-3.3-1.7-0.11.52000200420082012201620202024z-scorecollective 2011–2012point 2016

4. Agreement and the shortlist​

No single method is trusted alone. The table below lists the observations that most methods flag. The explanation pipeline asks a language model about a series only when an observation in it is flagged by at least min_outlier_count methods (3 by default), which is why the first rows are highlighted. Imputed values are left out of the list.

viz.agreement(result.table)

Where the methods agreeThe more methods flag an observation, the more likely it is a real anomaly. Observations flagged by three or more are explained.zscoretsoutlierhampelcapaisotreeFenmark · 2007 · EG.ELC.ACCS4.5σ5 of 5Estrella · 2016 · EG.ELC.ACCS4.5σ5 of 5Garmoor · 2014 · EG.ELC.ACCS4.4σ5 of 5Dovenia · 2013 · SH.MORT.U54.3σ5 of 5Estrella · 2010 · SH.MORT.U54.0σ5 of 5Garmoor · 2010 · SH.MORT.U53.7σ5 of 5Garmoor · 2019 · SI.POV.HEAD3.4σ5 of 5Fenmark · 2017 · EG.ELC.ACCS0.8σ3 of 5Brenvale · 2015 · SH.MORT.U52.9σ2 of 5Aldoria · 2007 · EG.ELC.ACCS2.6σ2 of 5Aldoria · 2008 · EG.ELC.ACCS2.1σ2 of 5Aldoria · 2003 · EG.ELC.ACCS1.9σ2 of 5

shortlist = result.shortlist(min_outlier_count=3)
names = dict(zip(panel.geography_id, panel.geography_name))
viz.shortlist_bars(shortlist, names)
shortlist

Series to explainRanked by the summed size of their flagged observations, imputed values left out.Fenmark · EG.ELC.ACCS5.3Estrella · EG.ELC.ACCS4.5Garmoor · EG.ELC.ACCS4.4Dovenia · SH.MORT.U54.3Estrella · SH.MORT.U54.0Garmoor · SH.MORT.U53.7Garmoor · SI.POV.HEAD3.4

indicator_id geography_id anomaly_score
0 EG.ELC.ACCS FFF 5.265704
1 EG.ELC.ACCS EEE 4.469289
2 EG.ELC.ACCS GGG 4.377430
3 SH.MORT.U5 DDD 4.322920
4 SH.MORT.U5 EEE 3.982803
5 SH.MORT.U5 GGG 3.683969
6 SI.POV.HEAD GGG 3.448895

The shortlist has the three columns that the explanation notebooks build by hand: indicator_id, geography_id and anomaly_score, summed over the flagged observations of each series.

result.flagged(min_count=3)[["geography_name", "indicator_id", "period", "value", "zscore", "outlier_count"]].round(2).head(10)
geography_name indicator_id period value zscore outlier_count
132 Fenmark EG.ELC.ACCS 2007 71.42 4.51 5
116 Estrella EG.ELC.ACCS 2016 57.24 -4.47 5
164 Garmoor EG.ELC.ACCS 2014 78.64 4.38 5
488 Dovenia SH.MORT.U5 2013 51.57 4.32 5
510 Estrella SH.MORT.U5 2010 30.85 -3.98 5
560 Garmoor SH.MORT.U5 2010 49.64 3.68 5
769 Garmoor SI.POV.HEAD 2019 27.56 -3.45 5
142 Fenmark EG.ELC.ACCS 2017 78.01 0.75 3

5. Further methods: robust CAPA and outlier trees​

Two more options extend the suite. They are not in the default list, because they answer different questions.

Robust CAPA. The default capa reads each run as a change in mean and variance. type="robustmean" looks for a change in the mean only, and caps the cost of any single value at beta_tilde, so that one wild value cannot drag the estimate of a run's mean. It suits series with occasional spikes inside a level shift. The picture compares the two types on one series.

robust = detect_anomalies(panel, methods=["capa"], params={"capa": {"type": "robustmean"}}).table
meanvar = detect_anomalies(panel, methods=["capa"], params={"capa": {"type": "meanvar", "robust_scale": True}}).table
print("flagged by capa meanvar:", int(meanvar.outlier_capa.sum()), "| robustmean:", int(robust.outlier_capa.sum()))
viz.capa_view(robust, "EG.ELC.ACCS", "FFF")
flagged by capa meanvar: 122 | robustmean: 19

Access to electricity (% of population) · FenmarkCAPA looks for runs with their own mean and variance (collective) and for single values that are too far out (point).-1.20.41.93.44.92000200420082012201620202024z-scorepoint 2007

Outlier trees. Every method so far asks whether a value is unusual for its own series. The outliertree method asks whether it is unusual given the circumstances: it grows decision trees that split the data by period, country and indicator, and flags a value that is far from the others in its branch. It reports the branch as a sentence, which is the part that helps the person who reads the flag.

The panel below is fictional. Forty countries share a shock in 2009, and two do not. A method that reads each series alone flags the shock in all 38 countries that share it, and it ignores the two countries that stayed on trend. Conditioned on the year, the two that did not move are the unusual ones.

shocks = viz.shock_panel()
TREE = {"outliertree": {"z_outlier": 4, "z_norm": 3, "pct_outliers": 0.05, "targets": ("zscore",)}}
trees = detect_anomalies(shocks, methods=["zscore", "hampel", "outliertree"], params=TREE)
t = trees.table
print("flagged by zscore:", int(t.outlier_zscore.sum()), "| hampel:", int(t.outlier_hampel.sum()), "| outliertree:", int(t.outlier_outliertree.sum()))
in_2009 = t[(t.period == 2009) & (t.outlier_outliertree == 1)]
in_2009[["geography_name", "period", "zscore", "outliertree_reason"]].round(2)
flagged by zscore: 38 | hampel: 38 | outliertree: 6
geography_name period zscore outliertree_reason
284 Shockland 11 2009 -0.25 zscore=-0.245 where period in [2009, 2009] (us...
684 Shockland 27 2009 0.23 zscore=0.227 where period in [2009, 2009] (usu...

The two countries are found, together with a few smaller flags in other years. The reason column states the condition: in 2009 the usual z-score is about -4.4, and this country sits at about 0. The card below shows one of them against the other countries. The reason can be passed to a reviewer as it stands, and the language model sees the same series window.

geo = in_2009.iloc[0].geography_id
window = t[(t.geography_id == geo) & t.period.between(2004, 2014)]
viz.reason_card(window, 2009, in_2009.iloc[0].outliertree_reason, title=f"{in_2009.iloc[0].geography_name}: the country that did not move in 2009",
context=t[(t.geography_id != geo) & t.period.between(2004, 2014)])

Shockland 11: the country that did not move in 2009zscore=-0.245 where period in [2009, 2009] (usual range -4.61..-4.01)434955616720042005200620072008200920102011201220132014valuegrey: the other countries

Outlier trees are strict by default (z_outlier=6, as in the R package), and on standardised data they usually flag nothing at the defaults. The relaxed settings above are a choice, and on a larger panel they need the same care as the thresholds in section 3. The built-in version is written from the published method and agrees with the R package on strong cases but not on borderline ones; the detection reference lists the differences.

6. Explain and review: the hand-over to the explanation pipeline​

The DetectionResult knows how to feed the explanation pipeline. build_explanation_batch writes the file of requests for the language model: one request for each flagged series, with the window of years around the flagged observations, the values and the imputation flags. It uses the same function, build_batch_file, as the explanation notebooks, so the prompts are identical to theirs.

work = Path(tempfile.mkdtemp(prefix="ai4data-anomaly-"))
batch_path, n_requests = result.build_explanation_batch(work / "batch.jsonl", provider="openai", min_outlier_count=3)
print(n_requests, "requests written to", batch_path.name)
first = json.loads(batch_path.read_text().splitlines()[0])
print(first["body"]["input"][1]["content"][0]["text"][-1100:])
8 requests written to batch.jsonl
nd, if appropriate, set "verifiability": "not_applicable".
- For generic data or reporting errors (e.g., implausible magnitudes, placeholders, ingestion artifacts), an empty evidence_source is expected and correct.
9. Keep explanations concise and factual, citing only verifiable events or mechanisms; avoid speculation or uncertain reasoning.
10. Output ONLY valid JSON matching the provided schema—no markdown, comments, or extra text.

# CONTEXT
{
"Indicator": "Access to electricity (% of population)",
"Country": "Fenmark",
"Series": [
{
"YEAR": 2004,
"VALUE": 54.07,
"Imputed": false
},
{
"YEAR": 2005,
"VALUE": 55.59,
"Imputed": false
},
{
"YEAR": 2006,
"VALUE": 57.58,
"Imputed": false
},
{
"YEAR": 2007,
"VALUE": 71.42,
"Imputed": false
},
{
"YEAR": 2008,
"VALUE": 61.49,
"Imputed": false
},
{
"YEAR": 2009,
"VALUE": 62.67,
"Imputed": false
},
{
"YEAR": 2010,
"VALUE": 63.86,
"Imputed": false
}
]
}

With an API key, run_batch sends the file to the provider and returns the answers, as in the explanation notebook. Without one, the cell below writes recorded stand-in answers: a rule, and not a model, that classifies a value whose neighbours are ordinary as a probable data_error and everything else as insufficient_data. The countries here are fictional, so a real model would also have found no documented event. The answers go through the same parser and exporter that real answers do.

sidecar = json.loads((work / "batch_custom_id_map.json").read_text())
flagged = result.flagged(3)
lines, seen = [], {}
for custom_id, series in sidecar.items():
key = (series["indicator_id"], series["geography_id"])
rows = flagged[(flagged.indicator_id == key[0]) & (flagged.geography_id == key[1])].sort_values("period")
k = seen[key] = seen.get(key, -1) + 1 # a series with two windows has two requests
year = int(rows.period.iloc[min(k, len(rows) - 1)])
z = result.table[(result.table.indicator_id == key[0]) & (result.table.geography_id == key[1])].set_index("period")["zscore"]
isolated = abs(z.get(year - 1, 0.0)) < 1.5 and abs(z.get(year + 1, 0.0)) < 1.5 # the neighbours are ordinary
answer = {"anomalies": [{
"window": [year, year],
"is_anomaly": bool(isolated),
"classification": "data_error" if isolated else "insufficient_data",
"confidence": 0.6 if isolated else 0.3,
"explanation": ("A single value that departs from the trend and returns to it the next year, a pattern typical of an entry or ingestion error."
if isolated else "No documented event explains these years."),
"evidence_strength": "no_evidence", "evidence_source": [], "source": "llm_inferred",
}]}
lines.append(json.dumps({"custom_id": custom_id, "response": {"body": {"choices": [{"message": {"content": json.dumps(answer)}}]}}}))
answers_path = work / "batch_output.jsonl"
answers_path.write_text("\n".join(lines) + "\n")

explanations = result.parse_explanations(answers_path, "openai", batch_path=batch_path)
explanations[["country", "indicator_code", "window_str", "classification", "confidence", "explanation"]]
country indicator_code window_str classification confidence explanation
0 Fenmark EG.ELC.ACCS 2007-2007 data_error 0.6 A single value that departs from the trend and...
1 Fenmark EG.ELC.ACCS 2017-2017 data_error 0.6 A single value that departs from the trend and...
2 Estrella EG.ELC.ACCS 2016-2016 data_error 0.6 A single value that departs from the trend and...
3 Garmoor EG.ELC.ACCS 2014-2014 data_error 0.6 A single value that departs from the trend and...
4 Dovenia SH.MORT.U5 2013-2013 data_error 0.6 A single value that departs from the trend and...
5 Estrella SH.MORT.U5 2010-2010 data_error 0.6 A single value that departs from the trend and...
6 Garmoor SH.MORT.U5 2010-2010 data_error 0.6 A single value that departs from the trend and...
7 Garmoor SI.POV.HEAD 2019-2019 data_error 0.6 A single value that departs from the trend and...

export_for_review writes the payload of the reviewer app. Each item carries the explanation and the time series around it, so the reviewer sees the evidence next to the claim.

review_path = work / "review.json"
result.export_for_review(explanations, review_path)
payload = json.loads(review_path.read_text())
item = payload["items"][0]
print(payload["count"], "items for review. First item:", item["geography_name"], "·", item["indicator_name"], "·", item["window_str"])
print("time series points in the item:", len(item["timeseries"]))
8 items for review. First item: Fenmark · Access to electricity (% of population) · 2007-2007
time series points in the item: 11

That is the whole chain: table → z-scores → flags → shortlist → batch file → answers → review payload, with no step in which a column is renamed by hand.

7. Your own data, the command line and your own detector​

Your own table. Any long-format table works. mapping="auto" guesses the canonical columns from the headers with suggest_column_mapping, and a dictionary {canonical name: your column} sets them explicitly. Series with too few observed values are dropped with a warning, and they are listed in attrs["dropped_series"]. Quarterly and monthly series are prepared with frequency="quarterly" or "monthly" and a season, but the explanation pipeline reads yearly periods, so only yearly detections can be explained.

The command line. The same steps run from a shell, which suits a scheduled job:

python -m ai4data.anomaly.detection data.csv --output flagged.csv \
--methods zscore,tsoutlier,hampel,capa,isotree --mapping auto \
--batch batch.jsonl --provider openai --min_outlier_count 3

Your own detector. A detector is a function from the prepared table to a table of new columns. Register it, and it runs beside the others and counts in outlier_count.

from ai4data.anomaly.detection import register_detector


@register_detector("jump")
def jump(table, *, size=3.5):
"""Flag a year-on-year change in the z-score larger than `size`."""
step = table.groupby(["indicator_id", "geography_id"])["zscore"].diff().abs()
return pd.DataFrame({"outlier_jump": (step > size).astype("int8")}, index=table.index)


custom = detect_anomalies(panel, methods=["zscore", "hampel", "jump"])
custom.summary()["flagged_by_method"]
{'zscore': 7, 'hampel': 10, 'jump': 18}

Where this differs from the R package​

Each step was checked against the R packages on seeded data. The z-scores agree to about 1e-10 and the CAPA flags agree on 1,200 random series. The full list of differences is in the detection reference. The ones that change a result are:

  • tsoutlier takes the quartiles of each series. The R package pools all series, which flags almost nothing once every series has unit variance. params={"tsoutlier": {"scope": "pooled"}} reproduces R.
  • isotree uses scikit-learn's isolation forest, so its scores are close to R's, not equal.
  • Seasonal decomposition (season=4 or 12) uses statsmodels STL, which differs slightly from R's, and so do the seadec fill (equal to R on most series) and the kalman fill (close, and further apart with a season). Use interpolation when values must be identical across tools.

Next steps. The cookbook Detecting and explaining anomalies in indicator data turns this walkthrough into recipes for a team, and the explanation notebooks cover running the language model on real data.