Every exercise in 81_stretch_detection.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.
Stretch S3.1. A detector by stratum
The task
The problem. Module 9 fitted an Isolation Forest per scale (unit_scale), so that small boats were compared with small boats. The scale is an answer, and an error can change it. A boat measured in feet and recorded as meters becomes a boat of many tons, and the unit's scale says large-scale (feet_recorded_as_meters in the planted list). Among the large-scale units it looks like any other large boat, so a detector fitted on that scale has little to find.
The stratum is a fact of the design (sel_stratum: F for the registered large units, taken whole; A, B and C for the sampled areas). A household was listed and sampled in it before anyone measured a boat, and no answer moves it. A large boat in an area stratum is unusual there, whether it is an error or a real large unit that turned up in a sampled area (module 6 met these households: an area stratum's household that runs a large-scale unit). The design columns stay out of the features, as module 9 said; here the stratum decides who is compared with whom, not what is compared.
Input → output: a matrix of features X (a table), the group of each row groups (a Series with X's index), the ids of its rows ids (a Series with X's index) and a contamination → the sorted list of the ids flagged when one IsolationForest(n_estimators=200, contamination=contamination, random_state=0) is fitted on each group's rows and flags that group's rows.
flags_by_group(features[FEATURES], features["sel_stratum"], features["unit_id"], 0.05) # ['01-5022-1-1', '01-5027-5-1', ...]
The rows of X need not be sorted by group, and its index need not run 0, 1, 2: a flag must land on the row it belongs to.
Tools: X.groupby(groups) (each group's rows, with their own index labels), IsolationForest, .fit(...) and .predict(...) (-1 is flagged), ids.loc[...] by those labels, sorted.
If the check is red
Fit one IsolationForest(n_estimators=200, contamination=..., random_state=0) per group of X.groupby(groups); read the flagged rows' ids by their index labels; sort.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
One detector per group learns what is common in that group; each row's flag is read back through its own index label, so the flags land on the right rows whatever order the table is in.
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_by_group(X: pd.DataFrame, groups: pd.Series, ids: pd.Series, contamination: float) -> list: """The sorted ids flagged by one Isolation Forest (200 trees, random_state=0) per group, each fitted on its group's rows.""" # Exercise S3.1: the task and examples are in the text above this cell. flagged = [] for _, rows in X.groupby(groups): forest = IsolationForest(n_estimators=200, contamination=contamination, random_state=0).fit(rows) flagged += ids.loc[rows.index[forest.predict(rows) == -1]].tolist() return sorted(flagged)Why each part is there
X.groupby(groups)hands out each group's rows with their own index labels. Fitting and predicting on the same rows keeps each flag beside its row's label.ids.loc[rows.index[...]]reads the ids by label. Collecting the predictions group by group and pasting them onto the table in its own order would put group A's flags on whatever rows come first, which are not A's when the table is not sorted by group.contaminationapplies within each group: 5% of every stratum is flagged, a small stratum's few and a large one's many. The review budget follows the strata's sizes, not where the errors are.random_state=0in each forest fixes its trees, so the same table gives the same list on every run and every computer.
Stretch S3.2. Near-duplicate interviews: the maximum percent match
The task
The problem. Module 8 flagged a copy when an interview had another's members and catch exactly. A copy typed again with one age wrong, or a household copied and edited a little to fill a quota, matches no other interview as a whole, though it matches its original on almost every answer.
The idea. Kuriakose and Robbins proposed the maximum percent match: for each interview, the share of questions on which it gives the same answer as the most similar other interview in the survey. An interview copied from another agrees with it on nearly every question; two honest interviews agree on fewer. They flagged an interview whose maximum percent match is above 85%, and took more than 5% of a survey's interviews above it as a sign of fabrication.
The caveat. Pew Research Center tested the proposal (Simmons, Mercer, Schwarzer and Kennedy, Evaluating a new proposal for detecting data falsification in surveys, 23 February 2016) and found that how many honest interviews pass 85% depends on the questionnaire and the sample: the number of questions, the number of answers each allows, the sample's size and how alike its respondents are. A fixed threshold flags honest interviews in a short questionnaire, or in a population that answers alike. Pew recommends several indicators, paradata (data on how each interview was done, such as its length) and follow-up in the field over one threshold for every survey. This section measures that on the survey.
The next cells lay each household's questionnaire out as one row of answers, and measure it.
If the check is red
Count agreements per pair one column at a time (equal, or both missing); fill the diagonal with -1; max / number of columns, and the label at argmax.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Count, for every pair of rows, the questions they answer alike, one column at a time into one n × n table; then each row's best count, out of every question, is its maximum percent match.
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 max_percent_match(answers: pd.DataFrame) -> pd.DataFrame: """For each row, the share of columns on which it agrees with its most similar other row (both missing counts as agreeing), and that row's label (the first of a tie).""" # Exercise S3.2: the task and examples are in the text above this cell. a = answers.to_numpy(dtype=float) n, k = a.shape counts = np.zeros((n, n), dtype=np.int32) for j in range(k): column = a[:, j] missing = np.isnan(column) counts += (column[:, None] == column[None, :]) | (missing[:, None] & missing[None, :]) np.fill_diagonal(counts, -1) best = counts.argmax(axis=1) return pd.DataFrame({"max_match": counts.max(axis=1) / k, "closest": answers.index[best]}, index=answers.index)Why each part is there
a[:, None] == a[None, :]compares one column's n answers with themselves in an n × n table, by broadcasting. Adding the columns' tables one by one keeps memory at one n × n count; comparing every column at once needs all of them.np.nan == np.nanis False, so two missing answers would count as different.np.isnan(a)[:, None] & np.isnan(a)[None, :]adds them back as agreeing, the decision the task made.- Every row agrees with itself on every question.
np.fill_diagonal(counts, -1)takes the diagonal out of the maximum; with it left in, every row's match would be 1.0 and its closest itself. argmaxreturns the first position of the largest value, which is the first of a tie in the table's order. The position becomes a label throughanswers.index[...].- Dividing by the number of columns, not by the questions both rows answered, keeps every row on the same scale: two rows that skipped most of the questionnaire do not reach 100% on three answers.
Stretch S3.3. Judging the pairs against the planted copies
The task
Why it matters: a list of pairs is judged as module 9 judged a list of units, by how many of the known cases it finds and what else it brings. Two things differ. A pair is unordered: splink lists a pair once, with whichever id it puts on the left, and the list of planted defects names the copy, with its original only in the detail text. And a household is its region and its id together, so 01-5421 and 07-5421 are different households. copy_pairs() above reads the list into pairs of text ids; made_up_households() gives the planted made-up interviews' ids.
Input → output: splink's pairs (unique_id_l, unique_id_r, match_probability), the planted copies as copy_pairs() gives them, and the made-up households as a set → one row per pair, with:
| column | what it is |
|---|---|
household_a, household_b |
the pair's two ids, the smaller first (as text) |
match_probability |
splink's |
what |
"planted copy" when the pair is a copy and its original, in either order; "both made up" when both households are made-up interviews; "other" otherwise |
sorted by match_probability, largest first, then by household_a and household_b; the index runs 0, 1, 2…
Tools: np.minimum and np.maximum on two text columns (or min, max in a list comprehension), frozenset for an unordered pair, isin, np.select, sort_values with two directions.
If the check is red
Smaller id first (np.minimum, np.maximum); a planted pair matches as a frozenset of copy and original; then 'both made up'; sort by probability (largest first), then the ids.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Put each pair in one order and each truth pair in a form where order does not matter, then a pair is a hit when its two ids are a truth pair's two ids, whichever side each came on.
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 label_pairs(pairs: pd.DataFrame, copies: pd.DataFrame, made_up: set) -> pd.DataFrame: """Each pair with its ids ordered (household_a < household_b), its match probability and what it is: planted copy, both made up, or other; the most likely first.""" # Exercise S3.3: the task and examples are in the text above this cell. household_a = np.minimum(pairs["unique_id_l"].astype(str), pairs["unique_id_r"].astype(str)) household_b = np.maximum(pairs["unique_id_l"].astype(str), pairs["unique_id_r"].astype(str)) planted_pairs = {frozenset(pair) for pair in zip(copies["copy"], copies["original"])} is_copy = [frozenset((a, b)) in planted_pairs for a, b in zip(household_a, household_b)] both_made_up = household_a.isin(made_up) & household_b.isin(made_up) what = np.select([np.array(is_copy, dtype=bool), both_made_up.to_numpy()], ["planted copy", "both made up"], default="other") out = pd.DataFrame({"household_a": household_a, "household_b": household_b, "match_probability": pairs["match_probability"].to_numpy(), "what": what}) return out.sort_values(["match_probability", "household_a", "household_b"], ascending=[False, True, True]).reset_index(drop=True)Why each part is there
np.minimumandnp.maximumof the two id columns put the smaller id first in every row, so a pair reads the same whichever side splink put each id on.frozenset({copy, original})is a pair with no order, and a set of them answers "is this a planted pair?" in one lookup. Comparingunique_id_lwith the copy andunique_id_rwith the original finds only the pairs listed that way round.- The ids carry the region:
01-5421and07-5421are different households. Comparing the household numbers alone would call a pair across regions a copy. np.selecttakes the first condition that holds: a planted pair is labeled as such even if a made-up household were in it.- Sorting by probability, then the ids, gives one order every run, ties included, so two runs' lists compare line by line.
Stretch S3.4. The large table, end to end
The task
Why it matters: module 9 found the useful pipeline for the large table: the rules, which find every scale error, made-up interview and inflated weight, and the 2021 round's random forest, which finds the wrong units of measure the rules miss. It ran them across several cells. For the next round, the pipeline is one function, from the file to the review list, that gives the same list whatever the chunk size, so that the list does not depend on how much memory the computer had.
Input → output: the Parquet file's path, the 2021 round's table past, a budget (how many units the supervisors can review) and chunk_rows → the review list, a table of at most budget rows with the unit's key (region_code, hh_id, operator_line, unit_no), rules (how many of the three rules the unit fails) and edit_share (the forest's probability of "edited"), the index 0, 1, 2…, by these steps:
- the forest:
fit_forest(past), module 9's (200 trees,random_state=0, the weight edits left out); - the median weight of the whole file, once, before any chunk:
SELECT median(sel_final_weight) FROM read_parquet(...)in DuckDB; - for each chunk of
chunk_rowsrows (pq.ParquetFile(path).iter_batches(batch_size=chunk_rows)): the three rules (the scale against the largest boat, an interview under 20 minutes, a weight over 5 times the median of step 2), the number each unit fails, andfit_forest's probabilitypredict_proba(tree_matrix(chunk))[:, 1]; keep the units that fail a rule or whose probability is at least 0.5; - all chunks' units together, sorted by
rules, thenedit_share, both largest first, then by the unit's key; the firstbudgetrows.
| the rule | fails when |
|---|---|
| scale (U3) | unit_scale is 1 and largest_tonnage is 5 or more, or unit_scale is 2 and largest_tonnage is under 5 |
| short interview | hh_interview_minutes under 20 |
| weight | sel_final_weight above 5 times the median weight of the whole file (module 9 set this cut for this table) |
Tools: duckdb.connect() and .execute(...).fetchone() (DuckDB 2.0 has no fetchone on a relation), iter_batches, .to_pandas(), boolean columns added up as numbers, pd.concat, sort_values with six keys, head.
If the check is red
The forest and the file's median weight once, before the loop; rules and the forest's probability per chunk; keep rules > 0 or probability >= 0.5; sort the whole list, then take the budget.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the check's hint above covers the usual slip. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Everything that depends on the whole table (the forest, the median weight) is computed once before the loop; everything that depends on one row (the rules, the forest's probability) is computed chunk by chunk; the ranking waits until every chunk is in.
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 review_list(path, past: pd.DataFrame, budget: int, chunk_rows: int) -> pd.DataFrame: """The review list of a large table: the units that fail a rule or that the 2021 round's forest calls edited, the rules and the forest's probability, most suspect first, at most budget of them; the same for any chunk size.""" # Exercise S3.4: the task and examples are in the text above this cell. forest = fit_forest(past) with duckdb.connect() as con: median = con.execute(f"SELECT median(sel_final_weight) FROM read_parquet('{path.as_posix()}')").fetchone()[0] kept = [] for batch in pq.ParquetFile(path).iter_batches(batch_size=chunk_rows): chunk = batch.to_pandas() scale = ((chunk["unit_scale"] == 1) & (chunk["largest_tonnage"] >= 5)) | ((chunk["unit_scale"] == 2) & (chunk["largest_tonnage"] < 5)) rules = scale.astype(int) + (chunk["hh_interview_minutes"] < 20).astype(int) + (chunk["sel_final_weight"] > 5 * median).astype(int) chunk = chunk.assign(rules=rules, edit_share=forest.predict_proba(tree_matrix(chunk))[:, 1]) kept.append(chunk.loc[(chunk["rules"] > 0) | (chunk["edit_share"] >= 0.5), [*UNIT_KEY, "rules", "edit_share"]]) ranked = pd.concat(kept, ignore_index=True).sort_values(["rules", "edit_share", *UNIT_KEY], ascending=[False, False, True, True, True, True]) return ranked.head(budget).reset_index(drop=True)Why each part is there
- The median weight is a statistic of the whole file. A chunk's own median is another number in every chunk, so the weight rule would flag different units for different chunk sizes. DuckDB reads the one column it needs from the file, without the rest.
fit_forestruns once, outside the loop: a forest fitted per chunk would learn from different rows in each, and a row's probability would depend on its neighbors in the file.- Each rule is a True or False column; added together as numbers they count the rules a unit fails, which ranks a unit that fails two above one that fails one.
- The budget is applied after the chunks are joined and sorted. Taking the first rows of each chunk would keep the most suspect of each chunk, not of the table, and change with the chunk size.
- The sort ends with the unit's key, so ties at the same rules and probability come in one order every run.