Skip to content
Learn Python with BNHR

Stretch: detection

On this page
  1. Overview
  2. S3.1 · A detector by stratum
  3. S3.2 · Near-duplicate interviews: the maximum percent match
  4. S3.3 · Judging the pairs against the planted copies
  5. S3.4 · The large table, end to end

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.

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.

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.

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:

  1. the forest: fit_forest(past), module 9's (200 trees, random_state=0, the weight edits left out);
  2. the median weight of the whole file, once, before any chunk: SELECT median(sel_final_weight) FROM read_parquet(...) in DuckDB;
  3. for each chunk of chunk_rows rows (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, and fit_forest's probability predict_proba(tree_matrix(chunk))[:, 1]; keep the units that fail a rule or whose probability is at least 0.5;
  4. all chunks' units together, sorted by rules, then edit_share, both largest first, then by the unit's key; the first budget rows.
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.

Something new

Identify results
LayerExplore a module
Modulepolars
AboutModule 6 of Arrays & DataFrames: the same analysis as expressions in polars, lazy queries, and moving data between pandas and polars. Its sections, its notebooks to read on the web, and the companion's solutions and explanations.
CourseArrays & DataFrames, free