Skip to content
Learn Python with BNHR

Anomalies with machine learning

On this page
  1. Overview
  2. 9.1 · Robust scaling, by hand
  3. 9.2 · The rows an Isolation Forest flags
  4. 9.3 · The k most unusual rows by LOF
  5. 9.4 · Precision and recall from two lists of ids
  6. 9.5 · The reasons for each flag, in words
  7. 9.6 · Held-out precision and recall
  8. 9.7 · The units a forest flags at a threshold
  9. 9.8 · Scores, chunk by chunk

Every exercise in 80_anomalies_ml.py, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.

Exercise 9.1. Robust scaling, by hand

The task

Why it matters: a scaler is two numbers per column and one line of arithmetic. Written by hand once, it stops being a black box, and R's scale() habit (mean and standard deviation) shows itself as the different choice it is.

Input → output: a table of numeric columns → a table of the same shape and column names, each column with its median subtracted and then divided by its IQR (the 75th percentile less the 25th, pandas' quantile, default interpolation). A column whose IQR is 0 (most of its values the same) is divided by 1, not by 0: scikit-learn's RobustScaler does the same, and the result must equal its.

n_boats age_of_operator → n_boats age_of_operator
1 40 0.0 -0.5
1 50 0.0 0.0
2 60 1.0 0.5

Here n_boats has a median of 1 and an IQR of 0, so it is divided by 1; age_of_operator has a median of 50 and an IQR of 20.

Tools: table.median(), table.quantile(0.75) and table.quantile(0.25) (one value per column), and arithmetic between a table and a Series, which lines up by column name.

If the check is red: common causes

what you see the usual cause look at
inf or nan in the n_boats column Divided by an IQR of 0. .replace(0, 1) on the IQRs
Every value smaller than it should be, the age of 199 near 2 The mean and standard deviation, R's scale(). table.median() and the IQR
Values centered but not scaled, or scaled but not centered One of the two steps left out. (table - median) / iqr
Close, but not equal quantile given another interpolation=. the default, linear

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.2. The rows an Isolation Forest flags

The task

Why it matters: the list a supervisor gets is ids, not scores. This is the function that turns a table of features into that list, and it must give the same list every time it runs, or nobody can check last week's review against this week's.

Input → output: a matrix of features X (a table), the ids of its rows ids (a Series in the same order), and a contamination (a share, such as 0.05) → the ids of the rows flagged, sorted, as a list:

isolation_flags(X, ids, 0.05)   # ['01-5023-1-2', '01-5051-1-1', ...]

Use exactly IsolationForest(n_estimators=200, contamination=contamination, random_state=0): the check compares your flags with the ones those settings give.

Tools: IsolationForest, .fit(X), .predict(X) (-1 is flagged), a boolean mask on ids (module 3), sorted.

If the check is red: common causes

what you see the usual cause look at
Almost every id == 1 keeps the rows the forest calls normal. predict(X) == -1
Right on the small table, wrong on the survey, and different each time you run it random_state not set: each run grows other trees. random_state=0
A few ids differ, the same each run Another number of trees (the default is 100). n_estimators=200
ValueError: The 'contamination' parameter ... must be ... A percentage, 5, given where a share, 0.05, belongs. the third argument
Positions such as [3, 17, ...], not ids np.flatnonzero or np.where returns positions. ids[mask]

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.3. The k most unusual rows by LOF

The task

Why it matters: a review team works through a fixed number of rows. Taking the k lowest factors gives exactly that many, which a contamination share only approximates. Getting the direction right is the exercise: LOF, like the Isolation Forest, scores the unusual low.

Input → output: a scaled matrix X, its row ids ids, n_neighbors and k → the ids of the k rows with the lowest negative_outlier_factor_, sorted, as a list. When two factors tie at the cut, the row that comes first in X goes in.

id negative_outlier_factor_ k = 2
r1 -1.02
r2 -6.81 in
r3 -1.98 in
r4 -1.10

Tools: LocalOutlierFactor(n_neighbors=...), .fit(X), .negative_outlier_factor_, and np.argsort(..., kind="stable") or Series.nsmallest(k).

If the check is red: common causes

what you see the usual cause look at
Ordinary points such as r03 and r07, not r26 The k highest factors: the most ordinary rows. the k lowest negative_outlier_factor_
One id too many or too few [:k+1] or [1:k]. [:k]
Right on the small table, a few ids off on the survey fit_predict with a contamination: that flags a share, not k rows. the k lowest factors
AttributeError: ... has no attribute 'negative_outlier_factor_' The detector was not fitted first. .fit(X)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.4. Precision and recall from two lists of ids

The task

Why it matters: every detector, rule and model in this module is judged with these two numbers, and so is any list a supervisor is handed. Computed from ids rather than from a library's arrays, they work on any two lists: this week's flags against last week's confirmed errors, a rule's failures against a reinterview.

Input → output: flagged (a list of ids; a detector run twice may list an id twice) and truth (a set of ids) → a dictionary:

key value
"flagged" how many different ids are flagged
"found" how many of them are in truth
"precision" found / flagged; None when nothing is flagged
"recall" found / the size of truth; None when truth is empty

Flagged ["a", "b", "b", "c"] against truth {"b", "c", "d", "e"}: 3 flagged, 2 found, precision 2/3, recall 2/4. Don't round: the check compares to six decimals.

Tools: set(...), & (the ids in both sets), len, a conditional expression x if ... else None (Python Essentials).

If the check is red: common causes

what you see the usual cause look at
'flagged': 4 for the first case The list's length, so the id listed twice counts twice. set(flagged)
precision and recall swapped The two denominators exchanged. precision over flagged, recall over truth
ZeroDivisionError: division by zero Nothing flagged, and precision divided by 0. None when nothing is flagged
'precision': 0.6667 Rounded: the check compares to six decimals. return the fraction as it is
'found': 1 for the third case The ids were cut to hh_id and the key parts, which repeat across regions. compare the whole ids

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.5. The reasons for each flag, in words

The task

Why it matters: a review table with a column "look at: largest_tonnage, sum_tonnage" saves the supervisor from reading every answer of every flagged unit. One line per flag, from any table of per-feature contributions.

Input → output: a table of contributions (one row per unit, one column per feature, higher meaning more unusual, as ECOD's O) and k → a Series with, for each row, the names of its k columns with the largest contributions, largest first, joined by ", ". When two contributions are equal, the column further left comes first.

n_boats largest_tonnage n_species k = 2
row 0 0.1 4.2 1.3 "largest_tonnage, n_species"
row 1 2.0 0.5 2.0 "n_boats, n_species"

Tools: table.apply(..., axis=1) (one call per row), Series.sort_values(ascending=False, kind="stable"), .index[:k], ", ".join(...).

If the check is red: common causes

what you see the usual cause look at
"age_of_operator, n_boats" for row 0 The smallest contributions: sort_values() sorts up by default. ascending=False
"n_species, n_boats" for row 1 A sort that is not stable put the tied columns the other way round. kind="stable"
The numbers, not the column names .values[:k] instead of .index[:k]. .index[:k]
One long text for the whole table axis=1 missing, so apply ran on columns. apply(..., axis=1)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.6. Held-out precision and recall

The task

Why it matters: these two figures are what a supervisor hears before trusting a model with next round's review. Computed on the training rows, they would promise everything.

Input → output: the 2021 round's table and a seed → a dictionary {"precision": ..., "recall": ...} for the held-out units, unrounded. Exactly:

  1. leave out the units whose edit_kind is "weight_inflated";
  2. X = tree_matrix(rows), y = rows["was_edited"];
  3. train_test_split(X, y, test_size=0.3, stratify=y, random_state=seed);
  4. RandomForestClassifier(n_estimators=200, random_state=seed), fitted on the training part;
  5. precision_score and recall_score of its predict on the held-out part.

Tools: a boolean filter (module 3), and the scikit-learn functions above, all imported in the setup cell.

If the check is red: common causes

what you see the usual cause look at
1.0 and 1.0 Judged on the training rows. predict(X_test) against y_test
A lower recall than expected The weight edits are still in the training rows. edit_kind != "weight_inflated"
Figures that change each run A random_state missing from the split or the forest. random_state=seed in both
Close, but not equal stratify= missing, or another test_size or number of trees. test_size=0.3, stratify=y, n_estimators=200
ValueError: Classification metrics can't handle a mix of ... The arguments to precision_score reversed, or the probabilities passed. precision_score(y_test, said)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.7. The units a forest flags at a threshold

The task

Why it matters: the threshold is the survey team's decision, not the model's. This function turns a fitted forest, a table and that decision into the review list.

Input → output: a fitted forest model, a table of units table (with unit_id, the features and unit_scale) and a threshold → the sorted list of unit_ids whose probability of "edited", model.predict_proba(tree_matrix(table))[:, 1], is at least the threshold.

Tools: tree_matrix (section 1), predict_proba, column 1 of its result ([:, 1]), >=, a boolean mask, sorted.

If the check is red: common causes

what you see the usual cause look at
Almost every unit_id Column 0, the probability of "not edited". [:, 1]
Right at 0.5, wrong at 0.2 predict used: it always cuts at one half. predict_proba and the threshold
One or two ids missing > where the task says at least. >=
KeyError or ValueError naming feature names The table passed as it is, with its ids and codes. tree_matrix(table)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Exercise 9.8. Scores, chunk by chunk

The task

Why it matters: this is the loop that lets a model fitted on a sample score a table of every region on a laptop. It must give every row its score, in the file's order, whatever the chunk size, or the review list depends on a setting nobody thinks about.

Input → output: score (a function that takes a pandas table, one chunk, and returns one number per row), the Parquet file's path and chunk_rows → one NumPy array with every row's score, in the file's order:

score_in_chunks(score_by_scale, PATHS.all_regions, 50_000)   # array([-0.43, -0.41, ...]), 240,000 values

Tools: any of the three readers above, .to_pandas(), a list of the chunks' scores, and np.concatenate.

If the check is red: common causes

what you see the usual cause look at
An array of 60,000 or 30,000 values Only the last chunk's scores returned. collect every chunk's scores in a list
Right for chunks of 60,000, wrong for 70,000 The last, shorter chunk left out (a range that stops early). let the reader hand out every batch
AttributeError: 'RecordBatch' object has no attribute 'loc' The batch given to score as it is, not as pandas. batch.to_pandas()
ValueError: need at least one array to concatenate The loop never ran: the file's path or the batch size is wrong. iter_batches(batch_size=chunk_rows)

Still stuck after ten minutes? Ask your table, then raise your hand.

The solution, and why it works

Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.

Something new

Identify results
LayerExplore a module
ModulePublish the tables
AboutModule 7 of Python for Survey Statistics: estimates written to a formatted workbook, and the tabulation as one script that writes every table at every level, with the sample's own counts beside each estimate, to one workbook. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython for Survey Statistics, free