Poverty Indicators with the EBP in Python with svy-sae

The Molina–Rao empirical best predictor of nonlinear indicators

Tutorials
Unit-level
EBP
Poverty Mapping
Python
Estimate poverty rates, gaps, and other nonlinear indicators for small areas in Python with the Molina-Rao EBP in svy-sae: Box-Cox and log transformations, Monte Carlo simulation over the census, custom indicators, and bootstrap MSE.
Author

Mamadou S. Diallo, Ph.D.

Modified

November 8, 2026

Keywords

Molina-Rao model, empirical best prediction Python, EBP poverty mapping, poverty headcount gap severity, Box-Cox transformation SAE, nonlinear indicators small area estimation

WarningAbout these examples

This tutorial illustrates the svy-sae API; it is not a rigorous small area analysis. The models are kept simple so each step stays readable, and in many places, from the choice of covariates to the variance model, better choices could be made to improve them.

A district mean is linear in the outcome, so the BHF model predicts it from the census means of the covariates. A poverty rate, a poverty gap, or a Gini coefficient is not: it depends on the whole distribution of expenditure in the district, household by household.

The empirical best predictor (EBP) of Molina and Rao (Molina and Rao 2010) handles any such indicator. It fits the nested error model on a transformed scale, then simulates the expenditure of every census household from the model given the sample, computes the indicator for each district on each simulated population, and averages over n_mc simulations. Its MSE comes from a parametric bootstrap, each replicate of which repeats the simulation.

This tutorial demonstrates how to estimate the poverty headcount, gap, and severity (Foster, Greer, and Thorbecke 1984) and other indicators of district expenditure with UnitLevel.ebp(), choose a transformation, write a custom indicator, and weigh precision against computing time.

Setting up the inputs

We continue with the household records and census from Preparing unit-level inputs:

Rebuild the inputs from Preparing unit-level inputs
import polars as pl
import svy

import svy_sae as sae

yes_no = ["electricity", "car", "refrigerator", "tv", "cell", "bank"]
covariates = [
    "urban",
    "piped_water",
    "flush_toilet",
    *yes_no,
    "hhsize",
    "rooms",
]


def household_covariates(frame):
    return frame.with_columns(
        (pl.col("tot_exp") / pl.col("hhsize")).alias("exp_pp"),
        (pl.col("urbrur") == "Urban").cast(pl.Float64).alias("urban"),
        (pl.col("piped_water") != "No piped water")
        .cast(pl.Float64)
        .alias("piped_water"),
        (pl.col("flush_toilet") == "Flush toilet")
        .cast(pl.Float64)
        .alias("flush_toilet"),
        *[(pl.col(c) == "Yes").cast(pl.Float64).alias(c) for c in yes_no],
        pl.col("hhsize").cast(pl.Float64),
        pl.col("rooms").cast(pl.Float64),
    )


hld_data = household_covariates(svy.datasets.load("hld_sample_wb_2023").data)
hld_census = household_covariates(svy.datasets.load("hld_pop_wb_2023").data)

census_units = hld_census.select("geo1", "geo2", *covariates)
census_means = (
    hld_census.group_by("geo2")
    .agg(*[pl.col(c).mean() for c in covariates], pl.len().alias("n_hh"))
    .sort("geo2")
)

truth = (
    hld_census.group_by("geo2")
    .agg(
        pl.col("exp_pp").mean().alias("true_mean"),
        (pl.col("exp_pp") < 1800).mean().alias("true_rate"),
    )
    .sort("geo2")
)

Fitting the model

ebp() takes the census records (every household is simulated), the indicators, and the poverty line as threshold:

model = sae.UnitLevel(hld_data)

fit = model.ebp(
    y="exp_pp",
    x=covariates,
    area="geo2",
    pop_data=census_units,
    transformation="boxcox",
    indicators=["headcount", "gap", "severity", "mean"],
    threshold=1800.0,
    n_mc=100,
    n_reps=50,
    rstate=12345,
)

print(fit)
╭─────── SAE: EBP (boxcox, lambda=-0.241) - MSE: Bootstrap - Unit Level ────────╮
│ Method     REML  Log Likelihood   14230.8842                                  │
│ No. Areas    59  AIC             -28433.7685                                  │
│ No. Obs    8000  BIC             -28335.9477                                  │
│                  KIC             -28419.7685                                  │
│                                                                               │
│                                                                               │
│  Term           Estimate   Std.Err         z   p-value    [0.025    0.975]    │
│  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━    │
│  Intercept        3.5018    0.0019   1842.97    0.0000    3.4980    3.5055    │
│  urban            0.0228    0.0014     16.53    0.0000    0.0201    0.0255    │
│  piped_water     -0.0090    0.0011     -8.17    0.0000   -0.0112   -0.0069    │
│  flush_toilet     0.0204    0.0012     17.72    0.0000    0.0182    0.0227    │
│  electricity      0.0190    0.0016     11.65    0.0000    0.0158    0.0222    │
│  car              0.0463    0.0013     36.86    0.0000    0.0438    0.0487    │
│  refrigerator     0.0255    0.0014     18.70    0.0000    0.0229    0.0282    │
│  tv               0.0236    0.0015     16.12    0.0000    0.0207    0.0265    │
│  cell             0.0353    0.0012     30.60    0.0000    0.0330    0.0375    │
│  bank             0.0057    0.0015      3.78    0.0002    0.0028    0.0087    │
│  hhsize          -0.0229    0.0002    -99.75    0.0000   -0.0234   -0.0225    │
│  rooms            0.0092    0.0003     29.63    0.0000    0.0086    0.0098    │
│                                                                               │
│                                                                               │
│ Variance components: area variance: 3.70601e-05; residual variance: 0.0016254 │
│                                                                               │
│ Findings:                                                                     │
│ - 12 influential areas                                                        │
╰───────────────────────────────────────────────────────────────────────────────╯

The coefficients and variance components are on the Box–Cox scale, where Checking unit-level models found the residuals close to normal.

Predictions

The predictions have one row per district and indicator:

pred = fit.to_polars("predictions")

pred.head()
shape: (5, 8)
area pred mse cv lci uci indicator in_sample
str f64 f64 f64 f64 f64 str bool
"geo_01_01" 4480.273877 8153.806208 0.020155 4303.288957 4657.258797 "Mean" true
"geo_01_01" 0.020963 0.000001 0.053487 0.018765 0.023161 "Poverty Gap" true
"geo_01_01" 0.092004 0.000023 0.05258 0.082522 0.101485 "Poverty Headcount" true
"geo_01_01" 0.007733 1.7369e-7 0.053893 0.006916 0.00855 "Poverty Severity" true
"geo_01_02" 4384.860928 27597.511195 0.037886 4059.255954 4710.465902 "Mean" true

Pivot them to one row per district:

pred.pivot(on="indicator", index="area", values="pred").head()
shape: (5, 5)
area Mean Poverty Gap Poverty Headcount Poverty Severity
str f64 f64 f64 f64
"geo_01_01" 4480.273877 0.020963 0.092004 0.007733
"geo_01_02" 4384.860928 0.017895 0.094038 0.005298
"geo_01_03" 4260.195574 0.020768 0.103963 0.006418
"geo_01_04" 4205.125283 0.024542 0.117602 0.007858
"geo_01_05" 4218.307041 0.017601 0.095204 0.005024

The two districts outside the sample are simulated from their census households alone:

pred.filter(~pl.col("in_sample")).select("area", "indicator", "pred", "cv")
shape: (8, 4)
area indicator pred cv
str str f64 f64
"geo_02_02" "Mean" 2378.129705 0.038093
"geo_02_02" "Poverty Gap" 0.12012 0.081714
"geo_02_02" "Poverty Headcount" 0.44045 0.058433
"geo_02_02" "Poverty Severity" 0.045384 0.096845
"geo_09_03" "Mean" 3068.201499 0.052279
"geo_09_03" "Poverty Gap" 0.076467 0.119643
"geo_09_03" "Poverty Headcount" 0.310186 0.089506
"geo_09_03" "Poverty Severity" 0.02656 0.141881

Indicators

Table 1: Built-in indicators
Indicator Names accepted Measures
Indicator.POVERTY_HEADCOUNT "headcount", "fgt0" Share of households below the threshold
Indicator.POVERTY_GAP "gap", "fgt1" Mean shortfall below the threshold, as a share of it
Indicator.POVERTY_SEVERITY "severity", "fgt2" Mean squared shortfall: weighs the poorest more
Indicator.MEAN "mean" Mean of the outcome
Indicator.MEDIAN "median" Median of the outcome
Indicator.GINI "gini" Gini coefficient of the outcome
Indicator.QSR "qsr" Quintile share ratio: top fifth’s share over the bottom fifth’s

The defaults are the headcount and the gap. threshold is required, also for indicators that do not use it.

A custom indicator

An indicator can be a function. It receives the simulated outcomes of all districts at once, padded to the largest district, and returns one value per district. It runs inside the compiled simulation, so it uses jax.numpy. The poverty severity, written out:

import jax.numpy as jnp


def fgt2(y, mask, n_units, threshold):
    shortfall = jnp.clip(1.0 - y / threshold, 0.0, None)
    return jnp.sum(shortfall**2 * mask, axis=1) / jnp.maximum(n_units, 1.0)

y holds the simulated outcomes, mask is 1 for real households and 0 for padding, n_units counts the households of each district, and threshold is the poverty line. The function’s name becomes the indicator’s label:

fit_custom = model.ebp(
    y="exp_pp",
    x=covariates,
    area="geo2",
    pop_data=census_units,
    indicators=["severity", fgt2],
    threshold=1800.0,
    n_mc=50,
    n_reps=0,
    rstate=12345,
)

fit_custom.to_polars("predictions").pivot(
    on="indicator", index="area", values="pred"
).head()
shape: (5, 3)
area Poverty Severity fgt2
str f64 f64
"geo_01_01" 0.007725 0.007725
"geo_01_02" 0.005282 0.005282
"geo_01_03" 0.006375 0.006375
"geo_01_04" 0.007801 0.007801
"geo_01_05" 0.005056 0.005056

It matches the built-in severity. n_reps=0 skips the bootstrap: the fit returns point estimates, and its MSE columns are not meaningful.

A threshold computed from the data

threshold can also be a function of the sampled outcomes, for a relative poverty line such as 60% of the median:

import numpy as np

fit_relative = model.ebp(
    y="exp_pp",
    x=covariates,
    area="geo2",
    pop_data=census_units,
    indicators=["headcount"],
    threshold=lambda y: 0.6 * np.median(y),
    n_mc=50,
    n_reps=0,
    rstate=12345,
)

fit_relative.to_polars("predictions").select("area", "pred").head()
shape: (5, 2)
area pred
str f64
"geo_01_01" 0.073545
"geo_01_02" 0.072745
"geo_01_03" 0.081351
"geo_01_04" 0.093113
"geo_01_05" 0.074044

The median is the unweighted median of the sampled households.

Transformations

Table 2: Transformations for ebp()
transformation Fit scale Options
"boxcox" (default) \(((y + s)^\lambda - 1)/\lambda\) \(\lambda\) estimated within boxcox_bounds (default \((-2, 2)\)), or fixed with boxcox_param; shift \(s\) = transform_shift
"log" \(\log(y + s)\) Shift \(s\) = transform_shift
"none" \(y\)

Compare the point estimates of the three against the true poverty rates and means:

z = 1800.0
true_values = (
    hld_census.group_by("geo2")
    .agg(
        (pl.col("exp_pp") < z).mean().alias("Poverty Headcount"),
        ((z - pl.col("exp_pp")) / z)
        .clip(lower_bound=0)
        .mean()
        .alias("Poverty Gap"),
        (((z - pl.col("exp_pp")) / z).clip(lower_bound=0) ** 2)
        .mean()
        .alias("Poverty Severity"),
        pl.col("exp_pp").mean().alias("Mean"),
    )
    .unpivot(index="geo2", variable_name="indicator", value_name="truth")
)


def rmse(fit):
    scored = fit.to_polars("predictions").join(
        true_values,
        left_on=["area", "indicator"],
        right_on=["geo2", "indicator"],
    )
    return scored.group_by("indicator").agg(
        ((pl.col("pred") - pl.col("truth")) ** 2).mean().sqrt().alias("rmse")
    )


pl.concat(
    [
        rmse(
            model.ebp(
                y="exp_pp",
                x=covariates,
                area="geo2",
                pop_data=census_units,
                transformation=t,
                indicators=["headcount", "mean"],
                threshold=z,
                n_mc=50,
                n_reps=0,
                rstate=12345,
            )
        ).with_columns(pl.lit(t).alias("transformation"))
        for t in ["none", "log", "boxcox"]
    ]
).pivot(on="indicator", index="transformation", values="rmse")
shape: (3, 3)
transformation Poverty Headcount Mean
str f64 f64
"none" 0.052044 327.061599
"log" 0.024322 175.609776
"boxcox" 0.017279 138.16737

With "none", the simulation draws expenditures that are normal around the regression, and the data are not; the poverty rates have the largest errors. The log and Box–Cox scales match the data far better.

WarningUnbounded indicators under Box–Cox

The inverse Box–Cox transform raises its argument to the power \(1/\lambda\), so a single extreme simulated draw can back-transform to an enormous value and dominate a district’s mean. svy-sae warns when an estimate exceeds ten times the largest observed outcome. The headcount, gap, and severity look only below the poverty line and cannot be affected, nor can the median; the mean, Gini, and QSR can. For those, prefer "log" or "none" if the warning appears, or raise n_mc.

Precision and computing time

Two settings control the cost:

  • n_mc (default 200): simulations behind each estimate. It sets the Monte Carlo error of the estimates.
  • n_reps (default 100): bootstrap replicates for the MSE. Each replicate repeats the whole simulation over the census, so the cost grows with n_reps; n_reps=0 returns point estimates only.

The indicators differ in cost. The poverty measures and the mean add little to a fit; the median, Gini, and QSR need the simulated outcomes sorted in every district, which multiplies the time of a bootstrap several times over. Their point estimates are cheap:

fit_distribution = model.ebp(
    y="exp_pp",
    x=covariates,
    area="geo2",
    pop_data=census_units,
    indicators=["median", "gini", "qsr"],
    threshold=1800.0,
    n_mc=50,
    n_reps=0,
    rstate=12345,
)

fit_distribution.to_polars("predictions").pivot(
    on="indicator", index="area", values="pred"
).head()
shape: (5, 4)
area Gini Coefficient Median Quintile Share Ratio
str f64 f64 f64
"geo_01_01" 0.317406 3764.086919 5.034687
"geo_01_02" 0.315215 3672.984619 4.902429
"geo_01_03" 0.317591 3550.040669 4.948283
"geo_01_04" 0.324968 3478.118281 5.147294
"geo_01_05" 0.305966 3553.615444 4.656023

The settings here keep the tutorial quick to run; production estimates use more of both. The first fit on a machine also compiles the simulation, which svy_sae.warmup() does ahead of time (see Installation).

How close did we get?

Compare each indicator of the main fit with the truth: error, average MSE, average squared error, and intervals that contain the true value:

scored = pred.join(
    true_values, left_on=["area", "indicator"], right_on=["geo2", "indicator"]
)
error2 = (pl.col("pred") - pl.col("truth")) ** 2
covered = (pl.col("truth") >= pl.col("lci")) & (
    pl.col("truth") <= pl.col("uci")
)

scored.group_by("indicator").agg(
    error2.mean().sqrt().alias("rmse"),
    pl.col("mse").mean().alias("mean mse"),
    error2.mean().alias("mean squared error"),
    covered.sum().alias("interval covers truth"),
).sort("indicator")
shape: (4, 5)
indicator rmse mean mse mean squared error interval covers truth
str f64 f64 f64 u32
"Mean" 138.579052 7895.356656 19204.153736 42
"Poverty Gap" 0.006887 0.000022 0.000047 42
"Poverty Headcount" 0.01741 0.000173 0.000303 48
"Poverty Severity" 0.003595 0.000004 0.000013 34

The poverty rate’s error is about half that of the area-level Fay–Herriot model (0.033) on the same districts, and the mean’s is below both the BHF model’s (333) and the area-level model’s (197). On a scale that fits the data, the household records carry information that district aggregates lose.

The MSE is again below the actual squared error, and fewer intervals than intended contain the truth. Fifty replicates leave a noisy MSE, and the model, though much closer to the data than the BHF model, still simplifies it.

Summary

This tutorial estimated poverty indicators with UnitLevel.ebp():

  1. Simulation over the census: every household, n_mc times, on a Box–Cox or log scale
  2. Indicators: the poverty headcount, gap, and severity, the mean, median, Gini, and QSR, and custom functions
  3. Thresholds as a number or a function of the sample
  4. Transformations: the fit scale matters most for poverty rates
  5. Cost: n_reps repeats the simulation; rank-based indicators cost more
  6. Accuracy: about half the error of the area-level model for the poverty rates

Next steps

The EBP treats the sample as if it were drawn at random within districts. When the selection depends on the outcome, survey weights can correct for it.

Use the survey weights
Continue to Weighted EBP →

References

Foster, J, J Greer, and E Thorbecke. 1984. “A Class of Decomposable Poverty Measures.” Econometrica 52: 761–66.
Molina, Isabel, and J. N. K. Rao. 2010. “Small Area Estimation of Poverty Indicators.” Canadian Journal of Statistics 38 (3): 369–85.