Every exercise in 50_design_estimates.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 6.1. The rows the design can use, and its lonely PSUs
The task
Why it matters: this is the step before a design is declared, in any language. Keep the rows that have a final weight, a stratum and a cluster id (sel_final_weight, sel_stratum and psu_id), then set the lonely-PSU rule. A row without a weight stands for no household, and a row without a stratum or a PSU has no place in the variance formula. The lonely PSUs are found after those rows are dropped: dropping a household can leave its stratum with one area.
Input → output: a frame of households with sel_stratum, stratum_id, psu_id and sel_final_weight → the rows the design can use, in the frame's order, every column kept, with one new column, lonely_psu:
- a row is kept when
sel_final_weight,sel_stratumandpsu_idall have a value; lonely_psuis True on every kept row of a stratum that has one PSU among the kept rows, and False on the others.
| region_code | hh_id | stratum_id | psu_id | sel_final_weight | → kept | → lonely_psu |
|---|---|---|---|---|---|---|
| 01 | 1 | X-A | 1 | 2.5 | yes | False: X-A keeps PSUs 1 and 2 |
| 01 | 4 | Y-A | 1 | 2.5 | yes | True: Y-A's other PSU had one household, with no weight |
| 01 | 5 | Y-A | 2 | missing | no | |
| 04 | 1 | missing | missing | 1.0 | no: no stratum | |
| 04 | 2 | Z-C | missing | 15.0 | no: no PSU | |
| 04 | 3 | Z-C | 7 | 15.0 | yes | True |
The rows of a lonely stratum stay: they are part of every estimate. singleton="skip", like ReGenesees' "remove", leaves out only their stratum's share of the variance, and lonely_psu names the rows that share comes from, for the notes of a table.
Tools: .notna() and & for the rows to keep; groupby("stratum_id")["psu_id"].transform("nunique") (module 5's transform) gives each row its stratum's count of PSUs; assign.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Y-A and Z-C not lonely | The PSUs were counted before the rows were dropped. | drop first, then transform("nunique") on the kept rows |
| The row with no weight, or no PSU, is still there | One of the three tests is missing. | sel_final_weight, sel_stratum and psu_id, each .notna() |
| The lonely strata's rows are gone | Their rows were dropped, as if "remove" dropped households. |
keep them, with lonely_psu True |
lonely_psu True on one row per stratum |
The count was taken with groupby(...).nunique() and joined back wrongly, or only the first row marked. |
transform: one value per row |
TypeError or ValueError on & |
The tests were joined with and, which wants single values. |
&, with each test a column of True and False |
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
Drop the rows the design has no place for first, then count each stratum's PSUs among the rows that are left, because a dropped row can take a stratum's last other area with it.
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 design_rows(frame: pd.DataFrame) -> pd.DataFrame: """The rows the design can use (sel_final_weight, sel_stratum and psu_id all present), in the frame's order, with lonely_psu: True on every row of a stratum left with one PSU.""" # Exercise 6.1: the task and examples are in the text above this cell. kept = frame[frame["sel_final_weight"].notna() & frame["sel_stratum"].notna() & frame["psu_id"].notna()] psus = kept.groupby("stratum_id")["psu_id"].transform("nunique") return kept.assign(lonely_psu=psus == 1)Why each part is there
- The three tests together are what any design needs of a row:
sel_final_weightfor the weight,sel_stratumfor the stratum, andpsu_idfor the cluster id. A row missing any one of them can't be placed in the design, in svy or in R. - The PSUs are counted on the kept rows. Counted on the frame as it came, stratum Y-A of the example still has two PSUs, and its lonely PSU goes unseen until svy meets it.
transform("nunique")gives every row its own stratum's count, in the frame's order, so the comparison== 1marks every row of a lonely stratum, not one row per stratum.- The lonely stratum's rows stay in the result. ReGenesees'
"remove"and svy's"skip"drop the stratum's share of the variance, not its households: dropping them would lower every total.
Exercise 6.2. Population counts from sampling fractions
The task
Why it matters: this is the first line of any translation of an R design to svy. Get n wrong (households instead of PSUs) and the fpc is wrong in every stratum, silently: svy takes any count of at least n.
Input → output: a frame with stratum_id, psu_id and a column of sampling fractions (its name is the argument fraction) → a column of whole numbers, one per row, each row's stratum's population count N = n / f:
| stratum_id | psu_id | fraction | → N |
|---|---|---|---|
| S-A | 1, 2, 3, 4 (several households each) | 0.4 | 10 |
| S-F | one per household, 4 households | 1 | 4 |
| S-C | 10 PSUs | 0.0667 (10 of 150, written to four decimals) | 150 |
The last row is why the result is rounded to a whole number: 10 / 0.0667 is 149.93. It is this survey's own stratum C.
Tools: groupby(...)["psu_id"].transform("nunique") (module 5's transform), division, .round() and .astype("int64").
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| 28 for the four-area stratum, thousands for the survey's stratum C | Households divided by the fraction, not PSUs. | transform("nunique") on psu_id |
| 149 for the stratum of 0.0667 | The decimals were cut, not rounded. | .round() before .astype("int64") |
| One number for the whole table | nunique() without transform: one count, not one per row. |
groupby("stratum_id")["psu_id"].transform("nunique") |
| KeyError: 'fraction' on the last check | The column name was written in, not taken from the argument. | frame[fraction] |
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
A sampling fraction is n / N, so N is n / f; n is the stratum's PSUs in the sample, put on every row with transform, and the result is rounded because fractions are often written rounded.
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 population_counts(frame: pd.DataFrame, fraction: str = "fraction") -> pd.Series: """Each row's stratum's population count of PSUs: the PSUs in the sample divided by the sampling fraction, rounded.""" # Exercise 6.2: the task and examples are in the text above this cell. n = frame.groupby("stratum_id")["psu_id"].transform("nunique") return (n / frame[fraction]).round().astype("int64")Why each part is there
transform("nunique")counts the distinct PSUs of each row's stratum and hands the count back on every row, so the division lines up row by row.- PSUs, not households: a province's stratum C has 10 areas and well over a hundred households, and households divided by 0.0667 would claim thousands of areas where there are 150.
.round()before.astype("int64"): 10 / 0.0667 is 149.93 and becomes 150.astypealone cuts the decimals, which turns 149.93 into 149.
Exercise 6.3. A stratified total and its SE, from the formula
The task
Why it matters: this formula is under every SE this course prints. Written once from the formula, it shows what the library does, it is what you check a library against, and section 4 builds every other estimator on it.
Input → output: a frame with stratum_id, psu_id, psus_in_stratum and sel_final_weight, and the name of a column y → a Series with three values, labeled est, se and cv:
| est | se | cv | |
|---|---|---|---|
the small design below, y |
40 | 7.4833 | 0.1871 |
The small design has a take-all stratum T (3 households, each its own PSU, N = 3, weight 1, y = 2, 5, 1) and a stratum S of 3 PSUs out of N = 6, every weight 4: PSU s1 holds y = 1 and 0, s2 holds 3, s3 holds 1, 1 and 2. Work it by hand once: T adds 8 to the total and nothing to V; S's PSU totals are 4, 12 and 16.
Tools: a column of w·y (assign), groupby(["stratum_id", "psu_id"]).agg(...) for the PSU totals, groupby("stratum_id")[...].transform("size") and transform("mean") for n_h and t̄_h, then the formula.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
se far too small on the survey |
The spread of households, not of PSU totals. | group by ["stratum_id", "psu_id"] before the spread |
se of 10.58 on the small design |
The fpc left out. | (1 - n / N) |
se of 6.11 on the small design |
Divided by n, not n − 1: the n / (n − 1) factor is missing. | n / (n - 1) |
se of 0 or nan |
Every stratum skipped, or n counted as households so that the fpc turned negative. | transform("size") on the PSU table |
est too small by the weights |
The values summed, not w·y. | frame["sel_final_weight"] * frame[y] |
| KeyError: 'est' | The result is not labeled est, se, cv. |
pd.Series({"est": ..., "se": ..., "cv": ...}) |
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 total is the sum of w·y; its variance is the spread of the PSUs' weighted totals within each stratum, scaled by n/(n−1) and by the fpc, added over strata.
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 stratified_total(frame: pd.DataFrame, y: str) -> pd.Series: """The design-based total of column y, its standard error and its coefficient of variation (est, se, cv).""" # Exercise 6.3: the task and examples are in the text above this cell. rows = frame.assign(wy=frame["sel_final_weight"] * frame[y]) psu = rows.groupby(["stratum_id", "psu_id"]).agg(t=("wy", "sum"), N=("psus_in_stratum", "first")).reset_index() stratum = psu.groupby("stratum_id")["t"] n = stratum.transform("size") terms = (1 - n / psu["N"]) * n / (n - 1) * (psu["t"] - stratum.transform("mean")) ** 2 est = rows["wy"].sum() se = terms[n > 1].sum() ** 0.5 return pd.Series({"est": est, "se": se, "cv": se / est})Why each part is there
- The PSU totals come first: the formula's unit is the PSU, so households are added up to their PSU before any spread is measured. Measuring the spread of households would treat an area's fifteen households as fifteen draws.
transform("size")andtransform("mean")put each stratum's n_h and t̄_h on its PSUs' rows, so every PSU's term is one line of arithmetic.(1 - n_h / N_h)is the fpc: 0 in a take-all stratum with every household present, 0.6 in stratum A, 0.8 in stratum B and 0.933 in stratum C. Leaving it out treats the areas as drawn with replacement and overstates the SE.terms[n_h > 1]leaves out a stratum with one PSU, whose n_h / (n_h − 1) divides by zero: theskiprule.- The CV divides the SE by the estimate, so it is a fraction: 0.15 is 15%.
Exercise 6.4. A table by province, with svy
The task
Why it matters: this is the table a report prints: one row per province, the estimate, its SE, its CV as a percentage, and its 95% confidence interval. Module 7 writes tables like it to a workbook.
Input → output: a svy Sample whose data has a province column, and the name of a column y → a pandas DataFrame, one row per province in order of name, with the columns:
| province | est | se | cv_pct | lci | uci |
|---|---|---|---|---|---|
| Batangas | … | … | 29.9 | … | … |
cv_pct is the CV in percent: svy's cv is a fraction, so 0.299 is 29.9.
Tools: sample.estimation.total(y=..., by=...), .to_polars(), .to_pandas(), a new column, and the column list.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
cv_pct below 1 |
svy's fraction kept as it is. | result["cv"] * 100 |
| One row, no province | by= left out: the total of all provinces. |
by="province" |
| UnknownNameError: Estimate.to_pandas does not exist [UNKNOWN_NAME] | A result is not a table; convert it first. | .to_polars().to_pandas() |
Extra columns (df, n) |
The column list was not applied. | [["province", "est", "se", "cv_pct", "lci", "uci"]] |
| Rows in another order | Not sorted. | .sort_values("province") |
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
One svy call with by="province" gives every province its estimate on the full design; the rest is turning the result into the table a report prints.
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 province_totals(sample, y: str) -> pd.DataFrame: """One row per province: the design-based total of y, its SE, its CV in percent and its 95% confidence interval.""" # Exercise 6.4: the task and examples are in the text above this cell. result = sample.estimation.total(y=y, by="province").to_polars().to_pandas() result["cv_pct"] = result["cv"] * 100 return result[["province", "est", "se", "cv_pct", "lci", "uci"]].sort_values("province").reset_index(drop=True)Why each part is there
by="province"estimates every province on the whole design, each with the degrees of freedom of its own PSUs. A loop that filters each province's rows first would drop the other provinces' PSUs, which for a province domain changes nothing here only because the provinces are made of whole strata; for any other domain it understates the SE..to_polars()gives full precision; the printed result is rounded for reading, so never copy numbers from it.cv * 100: svy'scvis SE / estimate, a fraction. A report and a CV threshold in percent need the percentage.
Exercise 6.5. Every cell of a cross table
The task
Why it matters: ask svy for the operators by province and sex, and it returns one row per combination that holds a sampled operator. A province whose sample has no operator with an invalid sex code gets no row for it; if a region's database lost its women operators, their rows would vanish the same way. A cell nobody fell into is still a cell: its estimate is 0 and it has no sampling error to report.
Input → output: a svy sample, the name of a column y to total, and levels, a dictionary from each domain variable to its categories in order (one variable, two, or three) → one row per combination of the categories, in the order itertools.product would list them, with the columns: the domain variables, est, se, cv and n:
- a combination svy returned: its
est,se,cvandn; - a combination svy did not return:
est0,se0,cvmissing,n0.
The checks' small table has nine operators in provinces P and Q, and none in R or with an invalid sex code; the accordion under this exercise shows it. Its first rows:
domain_cells(operator_sample(small_operators()), "operators", {"province": ["P", "Q", "R"], "sex": ["Male", "Female", INVALID]})
| province | sex | est | se | cv | n |
|---|---|---|---|---|---|
| P | Male | 9.0 | 2.83 | 0.314 | 3 |
| P | Female | 4.0 | 2.83 | 0.707 | 1 |
| P | Invalid value | 0.0 | 0.0 | missing | 0 |
| Q | Male | 13.0 | 4.90 | 0.377 | 4 |
| Q | Female | 1.0 | 0.0 | 0.000 | 1 |
| … | |||||
| R | Invalid value | 0.0 | 0.0 | missing | 0 |
Q's woman is in the take-all stratum T: an estimate with no sampling error, a CV of 0.
Tools: sample.estimation.total(y=..., by=[...]) and .to_polars().to_pandas() (Exercise 6.4), itertools.product(*lists) for every combination, pd.DataFrame(..., columns=...), merge(..., how="left", validate=...) (module 3), and fillna.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| Fewer rows than combinations | svy's result returned as it is: it has no row for an empty cell. | the grid, merged how="left" |
| The right rows in another order | svy sorts its result by text (Female before Male): the grid was merged onto svy's rows instead of the other way round, or built from the data's categories. |
grid.merge(found, ...), the grid from levels |
est missing in empty cells, or n a decimal |
The grid's empty rows left as NaN, or n filled but not turned back into whole numbers. |
fillna(0.0); fillna(0).astype("int64") |
| The SEs are smaller than svy's | The rows were filtered to each domain before estimating. | by= on the full sample |
| KeyError naming a domain variable | by was given the dictionary's values, or one name as text where a list is needed. |
by=list(levels) |
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 shape of a published table comes from its categories, not from its data: estimate what the sample has, then lay it on the grid of every combination and say what an empty cell is.
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 domain_cells(sample: svy.Sample, y: str, levels: dict) -> pd.DataFrame: """One row per combination of the levels, in order: the total of y, its SE, CV and n, with 0, 0, missing and 0 where no sampled row falls in the combination.""" # Exercise 6.5: the task and examples are in the text above this cell. by = list(levels) found = sample.estimation.total(y=y, by=by).to_polars().to_pandas() grid = pd.DataFrame(itertools.product(*levels.values()), columns=by) table = grid.merge(found[[*by, "est", "se", "cv", "n"]], on=by, how="left", validate="one_to_one") table[["est", "se"]] = table[["est", "se"]].fillna(0.0) table["n"] = table["n"].fillna(0).astype("int64") return tableWhy each part is there
by=list(levels)estimates every combination on the full design, as section 2 taught: a filter first would drop the PSUs with no member of the domain and shrink the SE.itertools.product(*levels.values())lists every combination in the levels' order, for one variable or three. The grid is the table's definition; the estimates are laid on it.- A left merge keeps the grid's rows in the grid's order and brings svy's figures to the combinations svy returned. A combination svy did not return keeps its row with missing figures, so the result has the same shape whatever the sample holds.
validate="one_to_one"writes down that svy returns each combination once. - An empty cell's total is 0 with an SE of 0: no sampled operator, so nothing to add and nothing to vary. Its CV is 0 divided by 0, which is why it stays missing.
- A category the data holds and
levelslacks is dropped by the left merge: the levels are the table's definition, so list every category in them, the catch-alls included.
Exercise 6.6. A domain mean, from the formula
The task
Why it matters: "how many members does a household that runs a large-scale unit have, on average?" is a mean over a domain, and the domain is the trap: the right answer keeps every row and lets the households outside the domain count as zeros in the linearized variable. Written once, it is how svy's mean(..., where=...) works.
Input → output: a frame, the name of a column y, and a boolean Series domain (one value per row, True in the domain) → a Series labeled est and se:
1[d] 1 for a row in the domain, 0 outside
N̂_d = Σ w · 1[d] the households the domain stands for
m_d = Σ w · 1[d] · y / N̂_d the domain mean
z = w · 1[d] · (y − m_d) / N̂_d 0 for every row outside the domain
SE = √ taylor_variance(frame, z)
Tools: the formula above, with taylor_variance (shown above).
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
est right, se too small |
The frame filtered to the domain before the variance: the PSUs with no member are gone. | z on every row, taylor_variance(frame, z) |
est too small |
Divided by all households' weights, not the domain's. | N_d = (w * d).sum() |
se many times too large |
z left as w·d·y, the domain total's variable, not the mean's. | (y − m) / N_d |
| TypeError on the domain | The True/False Series used in arithmetic as it is. | np.asarray(domain, dtype=float) |
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
A domain mean is a ratio of two domain totals; its linearized variable is zero outside the domain, and its variance is taken over every PSU of the design.
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 domain_mean(frame: pd.DataFrame, y: str, domain: pd.Series) -> pd.Series: """The design-based mean of y over the rows where domain is True, and its SE, on the full design (est, se).""" # Exercise 6.6: the task and examples are in the text above this cell. d = np.asarray(domain, dtype=float) w = frame["sel_final_weight"].to_numpy() values = frame[y].to_numpy(dtype=float) N_d = (w * d).sum() m = (w * d * values).sum() / N_d z = w * d * (values - m) / N_d return pd.Series({"est": m, "se": taylor_variance(frame, z) ** 0.5})Why each part is there
das numbers multiplies the domain into every sum: the rows outside count as zeros, and stay in the design.zis computed on every row and passed totaylor_variancewith the whole frame. Filtering the frame first would drop the PSUs with no member of the domain, and with them the spread between PSUs that have members and PSUs that don't.- Dividing z by N̂_d, not by N̂ (all households), is what makes it the linearized variable of the domain's mean rather than of its total share.
Exercise 6.7. Weighted estimates and the sample's counts, side by side at three levels
The task
Why it matters: this is the summary step. Every table is made national, regional and provincial, and each weighted estimate sits beside the sample's own figures: the sum of the same variable over the interviewed households, and the number of interviews behind it.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
unweighted equals weighted |
The weights were multiplied in before the sum: that is the weighted total again. | frame.groupby(by)[y], y alone |
interviews equals unweighted for units or operators |
The count is of y's sum, not of rows. | "size" |
| ValueError: No group keys passed! on the national level | frame.groupby([]): the national level has no column to group by. |
one row of frame[y].sum() and len(frame) |
| MergeError: No common columns to perform merge on | The national row merged with no on=. |
how="cross" when by is empty |
| Fewer rows than expected, or the national row missing | A level skipped, or its table left out of the concat. |
every level of LEVELS, each table added to the list |
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
Estimate every level from the design, count the same domains in the sample with pandas, and join the two on the level's domain columns, so each domain's estimate sits beside the interviews behind it.
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 side_by_side(frame: pd.DataFrame, y: str) -> pd.DataFrame: """The total of y at the three levels of LEVELS: from the survey's design, and the sample's own sum and count of interviews beside it. Columns: level, region_code, province, weighted, weighted_se, weighted_cv, unweighted, interviews.""" # Exercise 6.7: the task and examples are in the text above this cell. sample = svy.Sample(data=pl.from_pandas(frame), design=survey_design()) parts = [] for level, by in LEVELS.items(): result = sample.estimation.total(y=y, by=by or None).to_polars().to_pandas() weighted = result[[*by, "est", "se", "cv"]].rename(columns={"est": "weighted", "se": "weighted_se", "cv": "weighted_cv"}) if by: counted = frame.groupby(by)[y].agg(unweighted="sum", interviews="size").reset_index() both = weighted.merge(counted, on=by, validate="one_to_one") else: counted = pd.DataFrame({"unweighted": [frame[y].sum()], "interviews": [len(frame)]}) both = weighted.merge(counted, how="cross") parts.append(both.assign(level=level)) columns = ["level", "region_code", "province", "weighted", "weighted_se", "weighted_cv", "unweighted", "interviews"] return pd.concat(parts, ignore_index=True)[columns]Why each part is there
- The weighted figures need the design, so they come from svy; the sample's figures are plain sums and counts of rows, so they come from pandas, with no design and no SE.
by=by or Noneturns the national level's empty list intoNone, svy's default for the whole survey. svy 0.36.0 gives the same whole-survey row forby=[], so the list would do too;Nonesays what is meant.agg(unweighted="sum", interviews="size")names both columns in one call: the sum of y over the domain's households, and how many households there are.sizecounts rows;countwould count the rows where y is not blank, which differs once y has a blank.- The join is on the domain's columns, not on row position: it pairs each domain's two sets of figures whatever order svy and pandas return them in, and
validate="one_to_one"writes down that each domain appears once on each side. The national level has no column to join on, andhow="cross"pairs its one row with the other's one row. pd.concatlines the levels up by column name and leaves the national row's codes and the regions' province missing.
Exercise 6.8. A ratio of two totals, from the formula
The task
Why it matters: ratios are most of a fisheries report: boats per unit, catch per trip, large-scale units as a share of all. Writing one shows why its SE is not the SE of the numerator divided by the denominator.
Input → output: a frame and the names of two columns y and x → a Series labeled est and se. On the small design of Exercise 6.3, y over x is 0.8333 with an SE of 0.1543.
Tools: the formula above, with taylor_variance.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
est a little off |
The mean of each row's y / x, not the ratio of the totals. | Y / X |
se thousands of times too large |
z not divided by X̂. | / X |
se far too large, est right |
z = w·y: the SE of the numerator's total. | y − R·x |
ZeroDivisionError or inf |
A row's y / x with x = 0, from dividing row by row. | divide the totals |
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
A ratio of totals is linearized to the total of w(y − R·x)/X̂, whose variance the design formula gives.
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 own_ratio(frame: pd.DataFrame, y: str, x: str) -> pd.Series: """The ratio of the totals of y and x, and its linearized SE (est, se).""" # Exercise 6.8: the task and examples are in the text above this cell. w = frame["sel_final_weight"] Y, X = (w * frame[y]).sum(), (w * frame[x]).sum() R = Y / X z = w * (frame[y] - R * frame[x]) / X return pd.Series({"est": R, "se": taylor_variance(frame, z) ** 0.5})Why each part is there
R = Y / Xuses the totals, not the mean of each row's y/x: the boats per unit of all units, in which a unit counts once, not each household's ratio averaged.y − R·xis how far each household's boats are from what its units would predict at the overall ratio; only that departure varies the ratio, so only it enters the variance.- Dividing by
Xscales the departures to the ratio's units. Leaving it out gives the SE of a total in boats, thousands of times too large.
Exercise 6.9. Linear calibration, from the formula
The task
Why it matters: calibration is how a survey's weights are made to agree with what is known, and the linear case is under every other: raking and the logit distance below are iterations of the same solve. Written once, the weights a survey publishes are no longer a black box.
Input → output: the starting weights d (one per row), the auxiliaries X (a table or 2-D array, one row per row of d, one column per known total) and the known totals (one per column of X) → a numpy array of calibrated weights, one per row:
| d | x (class) | → calibrated |
|---|---|---|
| 1, 1 | class 1, known total 4 | 2, 2 |
| 2, 2, 2 | class 2, known total 9 | 3, 3, 3 |
With one 0/1 column per class, calibration is poststratification: every weight of a class is multiplied by its known total over its weighted count (4 / 2 and 9 / 6).
Tools: np.asarray(..., dtype=float), @ (matrix product), [:, None] to multiply each row of X by its weight, and np.linalg.solve.
If the check is red: common causes
| what you see | the usual cause | look at |
|---|---|---|
| The weights come back unchanged | λ solved against the totals, not the gap. | totals - X.T @ d |
| ValueError: matmul: Input operand ... has a mismatch | X's rows multiplied by d as a row, not a column. | X * d[:, None] |
| Weights of 2 and 1.5 instead of 2 and 3 | The factor g returned, not the weight. | d * (1 + X @ lam) |
| LinAlgError: Singular matrix | Two columns of X that say the same thing: a 0/1 column for every class and an intercept. | X's columns |
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 linear distance makes the calibration equations linear in λ, so the factors come from one solve: the gap between the known totals and the weighted totals, divided out by the weighted cross-products of x.
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 linear_calibration(d, X, totals) -> np.ndarray: """Weights calibrated to the totals with the linear distance (GREG): d · (1 + Xλ), λ solving the calibration equations.""" # Exercise 6.9: the task and examples are in the text above this cell. d = np.asarray(d, dtype=float) X = np.asarray(X, dtype=float) totals = np.asarray(totals, dtype=float) lam = np.linalg.solve(X.T @ (X * d[:, None]), totals - X.T @ d) return d * (1 + X @ lam)Why each part is there
X * d[:, None]multiplies each row of X by its weight;X.T @that is Σ d x xᵀ, one matrix of p × p for p known totals.totals - X.T @ dis the gap calibration has to close: zero gap gives λ = 0 and leaves the weights alone.np.linalg.solverather than inverting the matrix: the same answer, with less rounding.d * (1 + X @ lam)gives each row its factor g = 1 + xᵀλ. Rows with the same x get the same factor, which is why one 0/1 column per class is poststratification.