Every exercise in 85_debugging_drill.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.
Drill D2.1. A weight read as an answer
The task
Why it matters: a detector flags what is rare in the columns it reads. A household's weight says how it was sampled, not how it fishes. Read as an answer, it sends the supervisor to households for the stratum they were drawn from.
forest_review(table, k) should give the k units an Isolation Forest (200 trees, random_state=0) finds most unusual in what they answered: the k lowest score_samples on the twelve FEATURES, as their unit_ids, sorted. Its author added the weight, reasoning that a household standing for sixteen units matters more than one standing for one.
Input → output: a table of units and k → the unit_ids of the k most unusual, sorted.
| call | should give |
|---|---|
large.set_index("unit_id").loc[forest_review(large, 20), "sel_stratum"].value_counts().to_dict() |
{'F': 14, 'C': 4, 'B': 2}: the area strata hold 37% of the large-scale units, and 6 of the 20 on the list |
forest_review(drill_strata(), 3) |
['T03', 'T06', 'T10']: T06, the one unit with unusual answers, and two others, none from stratum A |
Tools: what to leave out (module 9, section 1 (80_anomalies_ml.py)).
Predict. The large-scale units of stratum F weigh about 1, and those of the area strata about 3, 5 or 16. Given that column, which units will the forest find easiest to isolate?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| The area strata are more than half of the list | The weight is one of the columns the forest reads. | the columns in X |
| KeyError naming a column | A column was dropped by name, and the small table has fewer columns than large. |
name the features instead |
| A few ids differ, the same each run | The columns are in another order: the forest picks a column by its position. | FEATURES in its own order |
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
What was wrong: sel_final_weight is not an answer about the unit. Among the large-scale units it is about 1 in stratum F and about 3, 5 or 16 in the area strata, by design, so the forest's random cuts on it separate the area strata's households from the rest, and they end up isolated sooner than their answers deserve. On the survey, the area strata went from 6 of the 20 on the list to 11.
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 forest_review(table: pd.DataFrame, k: int) -> list: """The unit_ids of the k units an Isolation Forest finds most unusual in their answers, sorted.""" # Drill D2.1: the task is in the text above this cell. Find the mistake and fix it. X = table[FEATURES] scores = IsolationForest(n_estimators=200, random_state=0).fit(X).score_samples(X) return sorted(table["unit_id"].iloc[np.argsort(scores, kind="stable")[:k]])Why each part is there
table[FEATURES]names the twelve answers the detector should read. The weight, the stratum, the area and the ids stay beside the features, where a supervisor can read them, and out of the matrix the forest cuts.- "Weighted" anomaly detection is a different question: an anomaly that moves an estimate more matters more. Answer it after the detector, by sorting the flagged rows by their weight, not by giving the detector the weight to cut on.
- A weight that is itself wrong is real and worth finding, and module 8 finds it: a weight against the median of its own stratum. A detector across strata cannot tell a wrong weight from a stratum.
Drill D2.2. Distances on unscaled features
The task
Why it matters: LOF finds rows whose neighborhood is sparse, and a neighborhood is measured in distances. Unscaled, a column measured in tens of units outweighs one measured in ones, and the detector reads only the wide columns.
lof_review(table, k) should give the k units with the lowest LOF factor (negative_outlier_factor_, 35 neighbors) on the features scaled by their medians and IQRs, which is neighbor_matrix(table): their unit_ids, sorted.
Input → output: a table of units and k → the unit_ids of the k most unusual, sorted.
| call | should give |
|---|---|
lof_review(drill_no_catch(), 3) |
['T08', 'T10', 'T67']: T08 landed no catch at all |
int(furthest(lof_review(small, 117)).isin(["age_of_operator", "hh_interview_minutes"]).sum()) |
23: of the 117 listed, 23 sit furthest out in the operator's age or the interview's length, and the rest in the other ten columns |
Tools: scaling (module 9, section 1 (80_anomalies_ml.py)), LOF (module 9, section 2 (80_anomalies_ml.py)).
Predict. In drill_no_catch(), the operators' ages run from 18 to 79 and the interviews from 15 to 99 minutes; every unit lands 3 to 6 species except T08, which lands none. Which of these differences decides who is far from whom?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
T08 missing from the small table's list |
The features are not scaled: age and minutes decide every distance. | neighbor_matrix(table) |
| Close, but a few ids differ | StandardScaler (mean and standard deviation) in place of median and IQR. |
neighbor_matrix, which uses RobustScaler |
| AttributeError: ... has no attribute 'negative_outlier_factor_' | .fit was replaced by .fit_predict and its result used as the detector. |
keep .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
What was wrong: LOF adds up the differences between two units column by column. Unscaled, a difference of 20 years of age or 20 minutes of interview counts twenty times a difference of one species, so the wide columns decided the distances, and a unit with no catch at all sat among ordinary neighbors. On the survey, 61 of the 117 listed units were there for the operator's age or the interview's length; scaled, 23.
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_review(table: pd.DataFrame, k: int) -> list: """The unit_ids of the k units with the lowest LOF factor (35 neighbors), on the features scaled, sorted.""" # Drill D2.2: the task is in the text above this cell. Find the mistake and fix it. X = neighbor_matrix(table) factors = LocalOutlierFactor(n_neighbors=35).fit(X).negative_outlier_factor_ return sorted(table["unit_id"].iloc[np.argsort(factors, kind="stable")[:k]])Why each part is there
neighbor_matrix(table)subtracts each column's median and divides by its IQR (module 9's Exercise 9.1), so a typical spread is one unit in every column, and a value far out in any column counts.- An Isolation Forest needs no scaling: it cuts one column at a time, between that column's own smallest and largest values. The comment in the broken line was true of the forest and false of LOF.
- On this survey the unscaled list holds as many planted defects as the scaled one, because many of them are short interviews and impossible ages, in the wide columns unscaled LOF reads. That is the planting, not the detector: a defect in a narrow column, such as
T08's empty catch, stays out of its reach. - The R way scales with
scale(), the mean and standard deviation; the median and IQR are the robust version, which a few impossible ages cannot move.
Drill D2.3. Contamination from another table
The task
Why it matters: contamination is the share of rows a detector flags. Set to the share found in another table, it flags as many rows as that table had, and the review either misses most of this table's anomalies or wastes its afternoon.
flags_at_rate(table, truth) should give the unit_ids an Isolation Forest (200 trees, random_state=0) flags on the twelve FEATURES, sorted, with contamination set to this table's anomaly rate: the share of its units whose unit_id is in truth. The course knows that share for the survey from its planted list; a survey team would take it from a reinterview sample or last round's audit of the same kind of table.
Input → output: a table of units and a set of unit_ids known to be wrong → the unit_ids flagged, sorted.
| call | should give |
|---|---|
round(float(small["unit_id"].isin(truth).mean()), 4) |
0.0244: the small-scale units' anomaly rate |
len(flags_at_rate(small, truth)) |
57 of 2,335: 2.44% of them |
Tools: contamination (module 9, section 2 (80_anomalies_ml.py)).
Predict. How many of the 2,335 small-scale units will the function flag?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 11 small-scale units flagged, 1 large-scale | The large table's rate, 0.47%, used for the survey. | where contamination comes from |
| The small-scale count right, the large-scale one wrong | One rate computed on all of features and used for both tables. |
the rate of table, the argument |
| ValueError: The 'contamination' parameter ... must be ... | A percentage, 2.44, where a share, 0.0244, belongs; or a rate of 0 from ids that never match. |
.mean() of isin(truth) |
| About two-fifths of the large-scale units flagged | len(truth) / len(table): truth holds the anomalies of both scales, so its length is not this table's count. |
the share of table's own unit_ids that are in truth |
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
What was wrong: the rate came from the large table, 1,120 planted defects in 240,000 units, 0.47%. The survey was planted differently: 2.4% of its small-scale units and 7.1% of its large-scale ones carry a defect their features show. The forest flagged 0.47% of each table: 11 of the 2,335 small-scale units, so at most 11 of their 57 anomalies, and a supervisor would take the short list for a clean survey.
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 flags_at_rate(table: pd.DataFrame, truth: set) -> list: """The unit_ids an Isolation Forest flags, contamination set to the table's own anomaly rate, sorted.""" # Drill D2.3: the task is in the text above this cell. Find the mistake and fix it. contamination = table["unit_id"].isin(truth).mean() forest = IsolationForest(n_estimators=200, contamination=contamination, random_state=0).fit(table[FEATURES]) return sorted(table["unit_id"][forest.predict(table[FEATURES]) == -1])Why each part is there
table["unit_id"].isin(truth).mean()is the share of this table's units that are known anomalies: True counts as 1 and False as 0, so the mean of the column of booleans is the share.- The function is called on the small-scale and the large-scale units separately, and each gets its own rate, as each gets its own detector. A rate computed once for the whole survey would be wrong for both.
- Contamination moves only the cut, never the scores (module 9, section 2). So the same forest, at the right share, flags every unit it flagged before and more.
- Without a known rate, module 9's honest choice stands: the share the supervisors can review. Either way, the share belongs to the table being scored.
Drill D2.4. Duplicates fitted twice
The task
Why it matters: a unit entered twice is one unit. Fitted twice, its two copies cannot be cut apart, so it looks more ordinary than it is; listed twice, it takes two places on the review list.
Module 4 found units entered twice, and module 9 built its features from each unit once. small_as_entered holds the small-scale units as the unit table does, with the copies. flags_once(table, contamination) should fit an Isolation Forest (200 trees, random_state=0) on the twelve FEATURES of each unit once, and give the unit_ids it flags, sorted, each once.
Input → output: a table of units, perhaps with some entered twice, and a contamination → the unit_ids flagged, sorted, each once.
| call | should give |
|---|---|
len(flags_once(small_as_entered, 0.05)) |
117, each unit once |
flags_once(small_as_entered, 0.05) == flags_once(small, 0.05) |
True: a copy changes nothing |
flags_once(drill_twice(), 0.05) |
['T11', 'T21']: two units with unusual answers |
Tools: duplicates by key (module 4, section 5 (30_edit_rules.py)), each unit once (module 9, section 1 (80_anomalies_ml.py)).
Predict. drill_twice() has 41 rows: forty units and a copy of T11. At a contamination of 0.05, how many rows will the forest flag, and which?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
['T11', 'T11'] |
Both copies of T11 fitted and listed. |
one row per unit before fit |
['T11'] alone, and a few survey ids differ |
Duplicates dropped from the list after fitting: the forest still learned from the copies. | drop them before fit |
| Fewer ids than expected | keep=False dropped both copies, and the unit with them. |
the default, keep="first" |
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
What was wrong: the table was not one row per unit. Each copy of a unit entered twice went into the fit and into the list. In the small table, the two copies of T11 could not be cut apart, which made T11 look more ordinary, and both copies were flagged, taking the two places the contamination allowed, so T21 fell off the list. On the survey the copies are ordinary units, yet 12 of the 117 flags changed: the forest drew the rows for its trees from 2,337 rows instead of 2,335.
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 flags_once(table: pd.DataFrame, contamination: float) -> list: """The unit_ids an Isolation Forest flags, fitted on each unit once, sorted, each once.""" # Drill D2.4: the task is in the text above this cell. Find the mistake and fix it. rows = table.drop_duplicates("unit_id") forest = IsolationForest(n_estimators=200, contamination=contamination, random_state=0).fit(rows[FEATURES]) return sorted(rows["unit_id"][forest.predict(rows[FEATURES]) == -1])Why each part is there
table.drop_duplicates("unit_id")keeps the first row of each unit. Theunit_idis built from the unit's whole key, so it names one unit;drop_duplicates(UNIT_KEY)is the same on a table that has the key columns.- Keeping the first is safe here because the copies are identical. Two rows with the same key and different answers are a question for an editor, which module 4 refers rather than drops.
random_state=0fixes the draws for one table. Two rows more and every tree draws other rows, so even flags far from the copies move: the count of rows and of distinct ids, before fitting, is the check that catches it. The R way isdistinct()on the key, orcount()and a filter onn > 1to see the copies first.
Drill D2.5. An id read as a number
The task
Why it matters: a number that names a row says nothing about it, but a detector cuts on it like any other column. The flags then depend on how the households happened to be numbered, and a new listing changes the review.
Another survey team sends features as CSV files, one row per unit: unit_id, hh_code (the household's 13-digit code), hh_interviewer, then the twelve features. flags_from_file(path) should read such a file and give the unit_ids an Isolation Forest (200 trees, contamination=0.05, random_state=0) flags on the twelve features, sorted. The setup wrote two files into scratch/: SMALL_CSV, the survey's small-scale units, and RENUMBERED_CSV, the same units and answers with the households numbered in the opposite order.
Input → output: the path of a features file → the unit_ids flagged, sorted.
| call | should give |
|---|---|
flags_from_file(SMALL_CSV) == flags_from_file(RENUMBERED_CSV) |
True: the same answers, so the same flags |
flags_from_file(SMALL_CSV) == flags_once(small, 0.05) |
True: the same twelve answers and the same forest as Drill D2.4's |
Tools: codes kept whole (module 2, section 3 (10_flat_table.py)), what to leave out (module 9, section 1 (80_anomalies_ml.py)).
Predict. The function keeps the columns read as numbers, on the reasoning that ids are text. Which columns will read_csv read as numbers?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Different flags for the two survey files | hh_code read as a number, so the forest reads it. |
read_csv's dtype= for hh_code |
| The same flags for both survey files, but not the right ones | The columns are in another order, or one is missing: the forest picks a column by its position. | the twelve features, in the file's order |
ValueError: could not convert string to float, naming an interviewer such as 'INT004' |
hh_interviewer went into the forest: every column, not the numbers. |
select_dtypes("number") |
| KeyError: 'unit_id' | The file was read with index_col=0, which makes unit_id the index. |
read it without index_col |
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
What was wrong: hh_code is written with digits only, so read_csv read it as a whole number. The function keeps every column read as a number, on the reasoning that ids are text, so the household code became a thirteenth feature. The forest cut on it as on any answer, and some units were isolated for where their household's code fell rather than for what they answered: 14 of the 117 flags changed, and numbering the households another way changed them again.
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 flags_from_file(path) -> list: """The unit_ids an Isolation Forest flags on the answers in a features file, sorted.""" # Drill D2.5: the task is in the text above this cell. Find the mistake and fix it. table = pd.read_csv(path, dtype={"hh_code": str}) X = table.select_dtypes("number") # the answers: every column read as a number, since the ids are text forest = IsolationForest(n_estimators=200, contamination=0.05, random_state=0).fit(X) return sorted(table["unit_id"][forest.predict(X) == -1])Why each part is there
dtype={"hh_code": str}keeps the column as the 13 characters the file writes, leading zero and all (Drill D1.1 met the same column). As text,select_dtypes("number")leaves it out withunit_idandhh_interviewer.- Choosing the columns by name,
table[FEATURES], gives the same flags here, since the file holds the twelve features in that order, and it also keeps out the next numeric id a file brings. Reading an id as text is still worth doing: a code that loses its leading zero no longer matches anything. - A check that renumbers the ids and expects the same flags is the general test for this mistake: no answer changed, so no flag should. The R way has the same trap, since readr guesses
col_double()for a column of digits;col_types = cols(hh_code = col_character())is the fix there.
Drill D2.6. ECOD scored chunk by chunk
The task
Why it matters: a review list from a large table has to rest on scores that do not depend on how the table was split to fit in memory. For ECOD they do: module 9, section 5 showed its scores are not exact in chunks.
ecod_review(table, k) should fit ECOD on the table's features scaled (neighbor_matrix(table)[FEATURES]) and give the k units with the highest scores, highest first, as a table of unit_id and ecod_score. Each score must be exact: the score ECOD gives the row as one of the rows it was fitted on. The function scores in chunks of CHUNK_ROWS (50,000) rows, as module 9 scored the large table with its Isolation Forests.
Input → output: a table of units and k → a table of k rows: unit_id and ecod_score, highest score first.
| call | should give |
|---|---|
ecod_review(small, 117) |
the survey's 117 highest scores, the same as the function gives now |
ecod_review(all_regions_small, 600)["ecod_score"].round(2).head(3).tolist() |
[66.67, 60.91, 58.8] |
Tools: ECOD (module 9, section 2 (80_anomalies_ml.py)), scoring in chunks (module 9, section 5 (80_anomalies_ml.py)).
Predict. Run Try it below, on the survey's small-scale units. Is anything wrong with what it gives?
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Right on the survey, wrong on the large table | The rows were scored in chunks: on the survey there is only one. | detector.decision_scores_ |
| AttributeError: 'ECOD' object has no attribute 'decision_scores_' | A new ECOD() that was never fitted. |
detector, the one fitted above |
| The lowest scores, not the highest | np.argsort(scores) sorts up; ECOD scores the unusual high. |
np.argsort(-scores, ...) |
| MemoryError or a long wait | ECOD refitted inside the loop, once per chunk. | fit once, outside any loop |
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
What was wrong: PyOD's ECOD scores rows by joining them to the rows it was fitted on and working out every column's tails again, so a row's score depends on the other rows in the same call. On the survey, one chunk held every row, and the scores were exact. On the large table's small-scale units, five chunks gave each row a score from the fitted rows plus its own chunk: scores moved, and the list changed with them.
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 ecod_review(table: pd.DataFrame, k: int) -> pd.DataFrame: """The k units with the highest exact ECOD scores on the features scaled, highest first: unit_id and ecod_score.""" X = neighbor_matrix(table)[FEATURES].to_numpy() detector = ECOD().fit(X) # Drill D2.6: the task is in the text above this cell. Find the mistake and fix it. scores = detector.decision_scores_ top = np.argsort(-scores, kind="stable")[:k] return pd.DataFrame({"unit_id": table["unit_id"].to_numpy()[top], "ecod_score": scores[top]})Why each part is there
detector.decision_scores_holds the score of every row ECOD was fitted on, computed once on the whole table: the exact scores the task asks for, with no second pass.- The chunks saved no memory either. Each call to
decision_functionjoined a chunk to all the fitted rows, so it held the whole table and more. Chunks help a detector that scores each row on its own, as a fitted Isolation Forest does (module 9, Exercise 9.8). - Where the table does not fit in memory, fit ECOD on a sample and score in chunks of one fixed size, and say so beside the results: the scores are then the sample's and the chunk size's, as module 9 says.
- The bug passed on the survey because the survey is smaller than one chunk. A check on a table larger than
CHUNK_ROWSis what finds it.