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.
The idea
Robust scaling centers each column on its median and divides by its interquartile range, two numbers per column that one impossible value cannot move; a column with no spread is left at its own scale.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def robust_scale(table: pd.DataFrame) -> pd.DataFrame: """Each column less its median, divided by its IQR (by 1 where the IQR is 0): RobustScaler, by hand.""" # Exercise 9.1: the task and examples are in the text above this cell. median = table.median() iqr = (table.quantile(0.75) - table.quantile(0.25)).replace(0, 1) return (table - median) / iqrWhy each part is there
table.median()andtable.quantile(...)give one value per column, andtable - mediansubtracts each column's own value, because pandas lines a Series up with the columns by name.- The IQR is the spread of the middle half of the values: three impossible ages do not move it, while they move the standard deviation R's
scale()divides by. .replace(0, 1): in a column such asn_boats, where most units have one boat, the IQR is 0, and dividing by it gives infinity. scikit-learn divides such a column by 1, which leaves it centered and unscaled.
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.
The idea
Fit the forest with its draws fixed, let contamination set the cut, and read scikit-learn's -1 as "flagged": the ids under that mask are the review list.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def isolation_flags(X: pd.DataFrame, ids: pd.Series, contamination: float) -> list: """The ids of the rows an Isolation Forest flags at this contamination (200 trees, random_state=0), sorted.""" # Exercise 9.2: the task and examples are in the text above this cell. forest = IsolationForest(n_estimators=200, contamination=contamination, random_state=0).fit(X) return sorted(ids[(forest.predict(X) == -1)].tolist())Why each part is there
random_state=0fixes the rows each tree draws and the cuts it makes. Without it, every run grows other trees, and the rows near the cut change from run to run.contaminationis a share between 0 and 0.5:0.05, not5. scikit-learn refuses a value outside that range with a ValueError whose last line names the parameter.predictgives -1 for a flagged row and 1 for the rest.== 1would return the other 95%.ids[... .to_numpy()]uses the mask by position, so it works whatever indexidshas;sortedgives the list one order, whatever order the rows came in.
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.
The idea
LOF's factor is lowest for the rows in the sparsest spots compared with their neighbors, so the review list is the k lowest factors, taken by position and turned into ids.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def lof_top(X: pd.DataFrame, ids: pd.Series, n_neighbors: int, k: int) -> list: """The ids of the k rows with the lowest LOF factor (the most unusual), sorted.""" # Exercise 9.3: the task and examples are in the text above this cell. factors = LocalOutlierFactor(n_neighbors=n_neighbors).fit(X).negative_outlier_factor_ return sorted(ids.iloc[np.argsort(factors, kind="stable")[:k]].tolist())Why each part is there
negative_outlier_factor_is the factor with its sign turned, so ordinary rows sit near -1 and the unusual far below it. The k highest values are the k most ordinary rows.np.argsort(..., kind="stable")sorts the positions from the lowest factor up and keeps the order ofXamong equal values, asnsmallest(k)does with its defaultkeep="first".n_neighborsis passed through: the check gives it 3 and then 6 on the same small table, and the group of five points close together is flagged only with 6.
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.
The idea
Precision divides the hits by what was flagged and recall divides them by what was there to find; both start from the set of distinct flagged ids, and each is undefined when its denominator is empty.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def precision_recall(flagged: list, truth: set) -> dict: """flagged (distinct ids), found (in truth), precision (found / flagged) and recall (found / truth).""" # Exercise 9.4: the task and examples are in the text above this cell. flagged_ids = set(flagged) found = len(flagged_ids & set(truth)) return { "flagged": len(flagged_ids), "found": found, "precision": found / len(flagged_ids) if flagged_ids else None, "recall": found / len(truth) if truth else None, }Why each part is there
set(flagged)counts an id flagged twice once. Counted twice, it would lower precision for a row that was right, or raise it for one that was wrong.flagged & set(truth)is the hits: the ids in both. Precision divides them by the flagged, recall by the truth; swapping the denominators is the most common mistake.Nonewhen a denominator is 0: a detector that flags nothing has no precision, which is not the same as a precision of 0, and aZeroDivisionErrorwould stop the review table.
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.
The idea
For each row, sort its contributions from the largest and keep the first k column names: the columns in whose tails the unit sits furthest.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def top_reasons(contributions: pd.DataFrame, k: int) -> pd.Series: """For each row, its k columns with the largest contributions, largest first, joined by ", " (ties: the left one first).""" # Exercise 9.5: the task and examples are in the text above this cell. return contributions.apply(lambda row: ", ".join(row.sort_values(ascending=False, kind="stable").index[:k]), axis=1)Why each part is there
ascending=False: the contributions grow with how unusual a value is, so the reasons are the largest. For shap's values on an Isolation Forest it would be the most negative, which is why the task fixes the direction.kind="stable"keeps the columns' order among equal values, so a tie gives the column further left, as the task asks; the default sort may put either first..index[:k]is the column names of the first k values, since a row of a table is a Series indexed by the column names.
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:
- leave out the units whose
edit_kindis"weight_inflated"; X = tree_matrix(rows),y = rows["was_edited"];train_test_split(X, y, test_size=0.3, stratify=y, random_state=seed);RandomForestClassifier(n_estimators=200, random_state=seed), fitted on the training part;precision_scoreandrecall_scoreof itspredicton 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.
The idea
Keep the rows whose label the features can show, hold 30% of them out with the same share of edits, learn on the rest, and judge only on what the forest never saw.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def held_out_scores(past: pd.DataFrame, seed: int) -> dict: """The forest's precision and recall on the held-out 30% of the 2021 round, the weight edits left out.""" # Exercise 9.6: the task and examples are in the text above this cell. rows = past[past["edit_kind"] != "weight_inflated"] X_train, X_test, y_train, y_test = train_test_split(tree_matrix(rows), rows["was_edited"], test_size=0.3, stratify=rows["was_edited"], random_state=seed) said = RandomForestClassifier(n_estimators=200, random_state=seed).fit(X_train, y_train).predict(X_test) return {"precision": precision_score(y_test, said), "recall": recall_score(y_test, said)}Why each part is there
- The weight edits leave: their answers are ordinary and the weight is not a feature, so as positives they teach the forest nothing it can use, and they lower the figures for a reason no model of answers could fix.
stratify=yputs 30% of the edited units in the held-out part, so its 35 edits are a fair sample; a split that is not stratified can leave a recall resting on far fewer.- The seed goes to both the split and the forest, so one number fixes which rows are held out and which trees grow, and the figures are the same on every run.
- Precision and recall are computed on
y_testagainst the forest's predictions forX_test. On the training rows both would be 1.00, as the cell above showed.
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.
The idea
The forest's probability is the share of its trees voting "edited"; the survey team's threshold on that share decides the list, not the forest's own half-way cut.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def edit_flags(model: RandomForestClassifier, table: pd.DataFrame, threshold: float) -> list: """The unit_ids whose probability of being edited, by this forest, is at least the threshold, sorted.""" # Exercise 9.7: the task and examples are in the text above this cell. share = model.predict_proba(tree_matrix(table))[:, 1] return sorted(table.loc[share >= threshold, "unit_id"].tolist())Why each part is there
predict_probareturns one column per class in the order ofmodel.classes_, which is[0, 1]: column 1 is "edited". Column 0 is its complement and would flag the most ordinary units.>=, as the task says: with 200 trees the probabilities are multiples of 0.005, so a share of exactly 0.5 is common, and>would drop it.predictwould ignore the threshold: it always cuts at one half.
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.
The idea
Read the file a batch at a time, score each batch with the fitted model, and join the scores in the order the batches came: the model never changes, so neither does any row's score.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def score_in_chunks(score, path, chunk_rows: int) -> np.ndarray: """Every row's score, reading the Parquet file chunk_rows rows at a time, in the file's order.""" # Exercise 9.8: the task and examples are in the text above this cell. parts = [score(batch.to_pandas()) for batch in pq.ParquetFile(path).iter_batches(batch_size=chunk_rows)] return np.concatenate(parts)Why each part is there
iter_batches(batch_size=chunk_rows)hands out the rows in the file's order, the last batch shorter when the size does not divide the rows; every row is in exactly one batch.- The model is fitted once, outside the loop. Fitting inside it would give each chunk its own idea of common, and a row's score would depend on its neighbors in the file.
np.concatenatejoins the chunks' arrays end to end. A list of arrays, or only the last chunk's, is the usual slip.