Skip to main content

2. Detecting anomalies with several methods

Question: Which observations are unusual, and how sure is the pipeline?

Rationale​

No single method finds every kind of anomaly. A rule on the standardised score finds an isolated jump. A rule that compares each value with its neighbours finds a value that departs from the local level. A method that looks for runs of shifted values finds a collective anomaly, in which no single value is extreme although the run as a whole is. Each method also has its own errors, and a rule that works on one series can flag a dozen ordinary values on another.

The suite therefore runs several methods and counts, for every observation, how many of them flag it. The count is the measure of how sure the pipeline is. An observation that all five methods flag has been found by rules that look at the data in different ways, and it deserves a reviewer's time first. An observation that only one method flags is a weaker signal, and with short series many such flags are noise. The count does not give a probability. It orders the observations, and the team decides where to cut.

The cut depends on the capacity for review, because every flagged series that goes to the explanation step costs a request to a language model and the time of a reviewer. This chapter shows how to run the methods, how to set the thresholds so that the number of flags is manageable, and how to check the result on data in which the anomalies are known. Chapter 3 explains the series that the count selects.

Target state​

  • Several methods have run on the same prepared series, and every observation has a count of the methods that flag it.
  • The thresholds of the methods are set on purpose, and the share of observations flagged is known and matches what the team can review.
  • The result is checked at least once on data with known anomalies, and the team knows which kinds of anomaly the methods miss.

Maturity levels​

LevelSteps
FoundationalRun the default methods, read the count of agreeing methods, and list the observations that most methods flag.
AI-readySet the thresholds, write the flags and the options to files, and fix the minimum count that sends a series to explanation.
AI-nativeScore every change of method or threshold against anomalies that are known, and keep the score with the run record.
Running example

This chapter runs the five default methods on the fictional panel of Chapter 1. The panel has 32 series and 800 observations after gaps are filled, 20 of them imputed. The planted anomalies in planted_anomalies.csv are used in Recipe 2.3 to check what the methods find.

Recipes​

Recipe

2.1 Run the methods and count the agreement

Level
Foundational
Skills
Data analyst
Indicative time
30 minutes

Result: A flagged file lists the observations that at least one method flags, with the number of methods that agree, and the most flagged observations are read and understood.

The suite offers five methods by default. Each reads the standardised score of Chapter 1, adds a column outlier_<method> with the value 0 or 1, and the suite adds the sum of the columns as outlier_count. The column anomaly_score holds the absolute standardised score and ranks the observations with the same count.

MethodWhat it flagsMain option
zscoreObservations whose absolute standardised score is above a threshold.threshold, 3 by default
tsoutlierObservations outside the fences of Tukey, which lie at a multiple of the interquartile range beyond the quartiles of the series.threshold, 3 by default
hampelObservations far from the median of their neighbours, in the manner of the Hampel filter (Hampel 1974). The first and last observations of a series are not tested.k neighbours on each side, 5 by default
capaCollective anomalies, which are runs of two or more values, and point anomalies, found by penalised likelihood with the CAPA method of Fisch, Eckley, and Fearnhead (2022).The penalties beta and beta_tilde, and robust_scale
isotreeObservations that an isolation forest separates from the rest in few splits (Liu, Ting, and Zhou 2008).threshold of the anomaly score, 0.5 by default

Further methods and the options of each are listed in the detection reference, where a team can also register a method of its own.

The script detect_and_shortlist.py runs the methods and writes the files that the rest of the guide reads. It is also the script of the next recipes.

"""Detect anomalies in a long-format indicator file and prepare their explanation.

Purpose: run the detection suite (`ai4data.anomaly.detection`) on a CSV file with
one row per indicator, geography, and year, and write the files that the next
steps read: the full detections table, the flagged observations, the shortlist
of series to explain, the batch file of explanation requests, and a run record.

Usage:
python detect_and_shortlist.py indicator_panel.csv --outdir run1
python detect_and_shortlist.py data.csv --methods zscore,hampel,capa --min-count 2

Requires ai4data[anomaly] (pandas, scikit-learn, scipy, statsmodels).

Exit status: 0 when the run completed, including a run that flagged nothing;
1 when the input cannot be read or lacks the required columns. A shortlist
that is empty is reported on the standard error stream, writes no batch file, and
removes the batch file and its sidecar left in the folder by an earlier run.

What this does not check: whether a flag is an error. The script finds
observations that are unusual within their own series; it does not check the
source of the data, the unit of the indicator, or whether a flagged value is
true. It does not call a language model; the batch file is the input of a
separate step, and only yearly data can be explained.
"""

import argparse
import hashlib
import json
import sys
from importlib import metadata
from pathlib import Path

import pandas as pd

from ai4data.anomaly.detection import DEFAULT_METHODS, detect_anomalies

# The defaults of capa and isotree flag a large share of short, standardised
# series, so the example uses these settings, which flag about 5% of observations.
DEMO_PARAMS = {
"capa": {"robust_scale": True, "beta": 25, "beta_tilde": 18},
"isotree": {"threshold": 0.65},
}
REQUIRED = ["indicator_id", "geography_id", "period", "value"]
FLAG_COLUMNS = [
"indicator_id",
"geography_id",
"period",
"value",
"zscore",
"outlier_count",
"anomaly_score",
]


def sha256(path: Path) -> str:
"""Return the SHA-256 checksum of a file.

Parameters
----------
path : Path
File to read.

Returns
-------
str
Hexadecimal digest.
"""
return hashlib.sha256(path.read_bytes()).hexdigest()


def main(argv: list[str] | None = None) -> int:
"""Run detection and write the output files.

Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.

Returns
-------
int
Zero when the run completed.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("input", type=Path, help="CSV file in long format")
parser.add_argument("--outdir", type=Path, default=Path("run"))
parser.add_argument(
"--methods",
default=",".join(DEFAULT_METHODS),
help="comma-separated detection methods",
)
parser.add_argument(
"--params",
default=json.dumps(DEMO_PARAMS),
help="JSON with the options of each method",
)
parser.add_argument(
"--min-count",
type=int,
default=3,
help="methods that must flag an observation for its series to be explained",
)
parser.add_argument("--provider", default="openai")
parser.add_argument(
"--top",
type=int,
default=0,
help="print this many of the most flagged observations with their methods",
)
args = parser.parse_args(argv)

try:
df = pd.read_csv(args.input)
params = json.loads(args.params)
except (OSError, ValueError) as error:
print(f"Cannot read the input: {error}", file=sys.stderr)
return 1
missing = [c for c in REQUIRED if c not in df.columns]
if missing:
print(f"Missing columns: {', '.join(missing)}", file=sys.stderr)
return 1

methods = args.methods.split(",")
params = {m: p for m, p in params.items() if m in methods}
result = detect_anomalies(df, mapping="auto", methods=methods, params=params)
args.outdir.mkdir(parents=True, exist_ok=True)
result.to_csv(args.outdir / "detections.csv")
flagged = result.flagged(1)
flagged[FLAG_COLUMNS].to_csv(args.outdir / "flagged.csv", index=False)
shortlist = result.shortlist(args.min_count)
shortlist.to_csv(args.outdir / "shortlist.csv", index=False)

requests = 0
if shortlist.empty:
# A batch file and its sidecar from an earlier run in this folder would be read as requests for these detections.
for stale in (
args.outdir / "batch.jsonl",
args.outdir / "batch_custom_id_map.json",
):
stale.unlink(missing_ok=True)
print("The shortlist is empty; no batch file written.", file=sys.stderr)
else:
_, requests = result.build_explanation_batch(
args.outdir / "batch.jsonl",
provider=args.provider,
min_outlier_count=args.min_count,
)

summary = result.summary()
record = {
"input": args.input.name,
"input_sha256": sha256(args.input),
"library_version": metadata.version("ai4data"),
"methods": methods,
"params": params,
"min_count": args.min_count,
"summary": summary,
"shortlisted_series": len(shortlist),
"batch_requests": requests,
}
(args.outdir / "run_record.json").write_text(
json.dumps(record, indent=2) + "\n", encoding="utf-8"
)

rate = 100 * summary["flagged_observations"] / summary["observations"]
print(
f"{summary['series']} series, {summary['observations']} observations "
f"({summary['imputed_observations']} imputed)"
)
print(
f"flagged by at least one method: {summary['flagged_observations']} ({rate:.1f}%)"
)
print(
"flags by method: "
+ ", ".join(f"{m} {n}" for m, n in summary["flagged_by_method"].items())
)
print(f"shortlist at {args.min_count} methods: {len(shortlist)} series")
print(f"batch requests: {requests}")
if args.top:
print("\nmost flagged observations:")
for _, row in flagged.head(args.top).iterrows():
names = [m for m in methods if row[f"outlier_{m}"]]
print(
f" {row['indicator_id']} {row['geography_id']} {int(row['period'])} "
f"value {row['value']:.2f} z {row['zscore']:+.2f} "
f"methods {row['outlier_count']}: {', '.join(names)}"
)
return 0


if __name__ == "__main__":
raise SystemExit(main())
  1. Run the script on the prepared table. The option --top prints the most flagged observations with the methods that flag them.
  2. Read the first lines of the output. They state the number of series and observations, the share flagged by at least one method, and the flags of each method.
  3. Read the list of the most flagged observations and open the series of the first few. A value flagged by all five methods is the first candidate for review.
  4. Note the observations with a count of two or three. They are the border of the shortlist that Recipe 3.1 sets.

Worked example. The command runs the five methods with the settings that Recipe 2.2 explains.

python detect_and_shortlist.py indicator_panel.csv --outdir run1 --top 9
32 series, 800 observations (20 imputed)
flagged by at least one method: 40 (5.0%)
flags by method: zscore 7, tsoutlier 13, hampel 10, capa 37, isotree 11
shortlist at 3 methods: 7 series
batch requests: 8

most flagged observations:
EG.ELC.ACCS FFF 2007 value 71.42 z +4.51 methods 5: zscore, tsoutlier, hampel, capa, isotree
EG.ELC.ACCS EEE 2016 value 57.24 z -4.47 methods 5: zscore, tsoutlier, hampel, capa, isotree
EG.ELC.ACCS GGG 2014 value 78.64 z +4.38 methods 5: zscore, tsoutlier, hampel, capa, isotree
SH.MORT.U5 DDD 2013 value 51.57 z +4.32 methods 5: zscore, tsoutlier, hampel, capa, isotree
SH.MORT.U5 EEE 2010 value 30.85 z -3.98 methods 5: zscore, tsoutlier, hampel, capa, isotree
SH.MORT.U5 GGG 2010 value 49.64 z +3.68 methods 5: zscore, tsoutlier, hampel, capa, isotree
SI.POV.HEAD GGG 2019 value 27.56 z -3.45 methods 5: zscore, tsoutlier, hampel, capa, isotree
EG.ELC.ACCS FFF 2017 value 78.01 z +0.75 methods 3: tsoutlier, hampel, capa
SH.MORT.U5 BBB 2015 value 29.30 z -2.88 methods 2: capa, isotree

Forty of 800 observations, or 5.0 percent, are flagged by at least one method. Seven observations are flagged by all five methods, and they are the first seven rows. The eighth row, the electricity series of Fenmark in 2017, is flagged by three methods although its own standardised score is only 0.75. Most of that series lies close to its trend after the jump of 2007 is set aside, so the fences of tsoutlier, which run from about -0.35 to 0.53 for this series, are narrow and a score of 0.75 lies outside them. A flag with a small score is a reason to look at the series, and the reason is usually that the other values of the series are unusually regular.

What this does not do. The methods work on one series at a time, apart from the isolation forest, which looks at all series together. They do not know the subject, so a real change such as a conflict or a reform is flagged like an error. A series needs about ten observations for the flags to mean much, and the flags on shorter series serve only to set priorities for review.

Recipe

2.2 Set the thresholds to the capacity for review

Level
AI-ready
Skills
Data analyst or statistician
Indicative time
1 hour

Result: The options of the methods are fixed in the run, the share of flagged observations is known and matches the number that the team can review, and the options are stored with the results.

The default options of two methods flag a large share of short, standardised series. The method capa assumes that the baseline of a series has mean 0 and variance 1, and a series with a long departure from its trend has a narrower baseline, so that runs of ordinary values come out as collective anomalies. The method isotree scores every observation, and its default threshold of 0.5 flags many observations of these series. The methods zscore, tsoutlier, and hampel have fixed rules of thumb that behave well on standardised series.

Two options of capa set how much evidence a flag needs. The option beta is the penalty for a collective anomaly and beta_tilde is the penalty for a point anomaly, and a higher penalty flags less. The option robust_scale centres and scales each series by its median and its median absolute deviation before CAPA reads it, which keeps one large value from setting the baseline. For isotree, a higher threshold flags less. The script of Recipe 2.1 uses the following settings by default.

MethodOptionValue in the guideEffect
caparobust_scaleTrueThe baseline comes from the median and the median absolute deviation.
capabeta25A collective anomaly needs more evidence.
capabeta_tilde18A point anomaly needs more evidence.
isotreethreshold0.65Only the most isolated observations are flagged.

The values are a choice for this panel and have no general standing. They were set so that about one observation in twenty is flagged, which is the number of flags that a reviewer can read for 32 series. Another team with a larger or a smaller review capacity sets other values, and the target is the share of flags and not the values themselves.

  1. Decide how many observations the team can review in one cycle. Express the number as a share of the observations.
  2. Run the script with the default options of the methods by passing an empty JSON object to --params, and read the share of flagged observations.
  3. Raise the penalties of capa and the threshold of isotree until the share is near the target, and pass the values as a JSON object to --params.
  4. Keep the object with the run. The script writes it to the run record that Chapter 4 describes.

Worked example. The first command uses the default options and the second the settings of the guide.

python detect_and_shortlist.py indicator_panel.csv --outdir run_default --params '{}'
32 series, 800 observations (20 imputed)
flagged by at least one method: 328 (41.0%)
flags by method: zscore 7, tsoutlier 13, hampel 10, capa 159, isotree 204
shortlist at 3 methods: 8 series
batch requests: 8

With the default options, 328 of 800 observations (41.0 percent) are flagged, and capa and isotree account for 159 and 204 of the flags. With the settings of the guide, the flags of these two methods fall to 37 and 11 (Recipe 2.1), and the total falls to 40 (5.0 percent). The three other methods flag the same observations in both runs. The shortlist of Recipe 3.1 changes from 8 series to 7, and the series that drops out is electricity access in Aldoria (code AAA), which holds a planted run of shifted values. The settings therefore cost one find, and in exchange the reviewer reads 40 flagged observations and not 328.

What this does not do. The settings are tuned on one panel to reach a target share, and they do not make the methods more accurate. A change of data, of series length, or of the share of anomalies can move the flag rate, so the share is read again at every run. Recipe 2.3 shows how to check what the settings find.

Recipe

2.3 Check the flags against known anomalies

Level
AI-native
Skills
Statistician
Indicative time
1 hour

Result: A report states, for each anomaly that is known, whether the methods found it, found it weakly, or missed it, and the team knows which kinds of anomaly the pipeline does not find.

On real data the true anomalies are unknown, so that a count of flags says nothing about accuracy. A fictional panel offers a check that real data cannot. The file planted_anomalies.csv lists the 16 anomalies that were put into the panel: seven jumps, five runs of three shifted values, and four constant tails in which the last years repeat one value. The following script reads the flagged file and the list and reports the result for each.

"""Compare the flags of a run with the anomalies planted in the example panel.

Purpose: the example panel is fictional, and the file `planted_anomalies.csv`
lists the jumps, runs, and constant tails that were put into it. This script
reports, for each planted anomaly, the largest number of methods that flag one
of its observed years, so that the team sees what the methods find and what
they miss on data where the answer is known.

Usage:
python score_against_planted.py run1/flagged.csv planted_anomalies.csv indicator_panel.csv

Requires pandas. Exit status: 0 after the report; 1 when a file cannot be read
or lacks the expected columns.

What this does not check: how the methods perform on real series. Planted
anomalies are simpler than real ones, the panel is small, and the report counts
a flag anywhere in the planted years as a find.
"""

import argparse
import sys
from pathlib import Path

import pandas as pd

KEY = ["indicator_id", "geography_id"]


def main(argv: list[str] | None = None) -> int:
"""Print one line per planted anomaly and a count by outcome.

Parameters
----------
argv : list[str] | None, optional
Command arguments, or the process arguments when omitted.

Returns
-------
int
Zero after the report.
"""
parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
parser.add_argument("flagged", type=Path)
parser.add_argument("planted", type=Path)
parser.add_argument("panel", type=Path)
parser.add_argument("--min-count", type=int, default=3)
args = parser.parse_args(argv)
try:
flagged = pd.read_csv(args.flagged)
planted = pd.read_csv(args.planted)
panel = pd.read_csv(args.panel)
planted[["first_period", "last_period"]]
flagged[["period", "outlier_count"]]
except (OSError, KeyError, ValueError) as error:
print(f"Cannot read the inputs: {error}", file=sys.stderr)
return 1

outcomes: dict[str, int] = {}
for row in planted.itertuples():
years = range(row.first_period, row.last_period + 1)
observed = panel[
(panel["indicator_id"] == row.indicator_id)
& (panel["geography_id"] == row.geography_id)
& panel["period"].isin(years)
]
hits = flagged[
(flagged["indicator_id"] == row.indicator_id)
& (flagged["geography_id"] == row.geography_id)
& flagged["period"].isin(years)
]
best = int(hits["outlier_count"].max()) if len(hits) else 0
if observed.empty:
outcome = "not in the data"
elif best >= args.min_count:
outcome = "found"
elif best > 0:
outcome = "weak"
else:
outcome = "missed"
outcomes[outcome] = outcomes.get(outcome, 0) + 1
print(
f"{row.indicator_id} {row.geography_id} {row.kind} "
f"{row.first_period}-{row.last_period}: {outcome} (most methods: {best})"
)
print(", ".join(f"{k} {v}" for k, v in sorted(outcomes.items())))
return 0


if __name__ == "__main__":
raise SystemExit(main())

The columns of the planted file are the indicator, the geography, the kind of anomaly, and the first and last year that it covers.

  1. Run the script on the flagged file of Recipe 2.1.
  2. Read the outcome of each anomaly. The outcome is "found" when at least the minimum count of methods flags a year inside its years, "weak" when fewer methods flag it, "missed" when none does, and "not in the data" when every year of the anomaly is a missing year.
  3. Group the outcomes by kind, and write down the kinds that the pipeline does not find.
  4. Repeat the check after every change of methods, options, or preparation, and keep the result with the run record.

Worked example. The command compares the run of Recipe 2.1 with the planted anomalies.

python score_against_planted.py run1/flagged.csv planted_anomalies.csv indicator_panel.csv
SH.MORT.U5 BBB run 2014-2016: weak (most methods: 2)
SH.MORT.U5 CCC run 2010-2012: missed (most methods: 0)
SH.MORT.U5 DDD jump 2013-2013: found (most methods: 5)
SH.MORT.U5 EEE jump 2010-2010: found (most methods: 5)
SH.MORT.U5 FFF constant tail 2021-2024: missed (most methods: 0)
SH.MORT.U5 GGG jump 2010-2010: found (most methods: 5)
SE.PRM.NENR FFF run 2015-2017: missed (most methods: 0)
SE.PRM.NENR GGG constant tail 2021-2024: missed (most methods: 0)
EG.ELC.ACCS AAA run 2005-2007: weak (most methods: 2)
EG.ELC.ACCS BBB constant tail 2021-2024: missed (most methods: 0)
EG.ELC.ACCS EEE jump 2016-2016: found (most methods: 5)
EG.ELC.ACCS FFF jump 2007-2007: found (most methods: 5)
EG.ELC.ACCS GGG jump 2014-2014: found (most methods: 5)
EG.ELC.ACCS HHH run 2007-2009: weak (most methods: 1)
SI.POV.HEAD EEE jump 2008-2008: not in the data (most methods: 0)
SI.POV.HEAD GGG constant tail 2021-2024: missed (most methods: 0)
found 6, missed 6, not in the data 1, weak 3

All six jumps that remain in the data are found by all five methods. The seventh jump falls in a year that is missing from the panel, so that the value was never observed and interpolation filled the year with a value that follows its neighbours. None of the four constant tails is flagged. Two of the five runs are missed, and the other three are flagged weakly. On this panel, the pipeline therefore finds isolated jumps and is weak on runs and on repeated values. A repeated value is not far from the level of the series, so no method that measures the size of a departure reacts to it. A separate rule, such as a count of identical consecutive values, would find it. The seven observations that all five methods flag also include one that is not on the planted list, in the poverty series of Garmoor (code GGG) in 2019, next to the constant tail of that series. The output does not show whether it is an ordinary random movement of the generator or an effect of the planted tail on the estimated trend.

What this does not do. Planted anomalies are simpler and more regular than real ones, the panel has 32 short series, and a method that finds a planted jump may still miss an irregular break in real data. The check shows the kinds of anomaly that a method cannot see by construction. It does not estimate the rate at which the pipeline finds real errors.

Implementation options​

  • The five default methods run on the suite's own implementations. A team can register a method of its own, which receives the prepared table and returns a column outlier_<name>, as the detection reference shows.
  • A team with a detector of its own can pass its scores to the explanation pipeline through the adapters, in the canonical columns anomaly_score and outlier_count, and keep the suite for preparation only.
  • The methods are rebuilt in Python from the macroanomaly package of the World Bank and from the R packages anomaly, feasts, pracma, isotree, and outliertree. The reference describes where the flags agree with the R packages and where they differ. A team that redistributes the code checks the licence terms of those packages.

World Bank examples​

  • The macroanomaly R package of the World Bank is the source of the workflow and the reference for the agreement tests of the suite.
  • The detection reference records the agreement of the Python methods with the R implementations on seeded test data.

Resources​

  • Fisch, A., Eckley, I., and Fearnhead, P. (2022), A linear time method for the detection of collective and point anomalies, Statistical Analysis and Data Mining 15(4), describes the CAPA method of Recipe 2.1.
  • Liu, F., Ting, K., and Zhou, Z. (2008), Isolation forest, IEEE International Conference on Data Mining, describes the isolation forest of Recipe 2.1.
  • Hampel, F. (1974), The influence curve and its role in robust estimation, Journal of the American Statistical Association 69, describes the filter behind the hampel method.
  • The detection reference lists every method, option, and known difference from the R packages, and is used throughout this chapter.

Common mistakes​

  • Accepting the default options of capa and isotree on short series produces hundreds of flags, which no reviewer reads, and the useful ones are lost among them.
  • Reading the count of agreeing methods as a probability gives it a meaning that it does not have. The count orders the observations.
  • Tuning the options until the planted anomalies are all found fits the example and says little about other data.
  • Ignoring the kinds of anomaly that the methods miss leaves the team without a rule for them, and a repeated value passes every method.

Verification​

  • Read the flag rate. The share of flagged observations is stated at every run and lies near the target that the team set.
  • Open the top observations. The first observations by count are plotted or listed with their neighbours and look unusual to a person who knows the indicator.
  • Run the planted check. The report of Recipe 2.3 is produced at every change of options, and the number found does not fall.

Checklist​

0 of 4 done

Ticks are saved in this browser only.