Skip to content
Learn Python with BNHR

Debugging drill: a detector that flags the wrong rows

On this page
  1. Overview
  2. D2.1 · A weight read as an answer
  3. D2.2 · Distances on unscaled features
  4. D2.3 · Contamination from another table
  5. D2.4 · Duplicates fitted twice
  6. D2.5 · An id read as a number
  7. D2.6 · ECOD scored chunk by chunk

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.

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.

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.

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.

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.

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.

Something new

Identify results
LayerExplore a module
ModuleCheck: Round 2 and the contract
AboutModule 3 of Python for Data Management: write the round's rules once, check every round against them, and clean what can be cleaned as code. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CoursePython for Data Management, free