Method 02 · Python · a practitioner's guide
Predicting a rare outcome
- Question
- How to predict a rare and sensitive survey answer that many respondents skipped, so that the share of positive answers can be used in further analysis.
- Input
- Respondents with their characteristics and an observed answer, and non-respondents with the same characteristics.
- Output
- A share of positive answers for every school, grade and gender cell, built from the observed answers and the predicted probabilities of the non-respondents, together with what this share can and cannot be used for.
- Use it when
- The predictions enter a second stage as a share or a rate, rather than being used to make decisions about individuals.
Survey questions on sensitive behavior are often left unanswered, and the behavior they ask about is often rare. In applied work, the individual answers are frequently not the object of interest. What enters the analysis is a share, such as the proportion of students in a school cohort who report a behavior, used as a measure of peer exposure. If the students who skip the question differ from those who answer it, a share computed from respondents alone is biased, and the missing answers have to be predicted first.
Three literatures address parts of this problem. The machine-learning literature on class imbalance studies how to classify individual cases, and often recommends rebalancing the training data with the Synthetic Minority Over-sampling Technique (SMOTE; Chawla et al., 2002). The evidence on whether this helps is mixed: applied work reports large gains in recall, for example Campedelli et al. (2024) when predicting mafia infiltration of city councils, while Elor and Averbuch-Elor (2022) find across many datasets that rebalancing does not improve strong classifiers such as gradient-boosted trees. The literature on quantification studies how to estimate the share of a class within a group rather than to classify individuals, and shows that labelling each case and counting the labels is biased when the share differs across groups (Forman, 2008; González et al., 2017). Finally, Battaglia et al. (2024) show that using variables generated by machine learning as regressors biases second-stage estimates and invalidates standard inference.
On this page, I bring the three together in the pipeline I use for this problem, on simulated data in which the true answer of every student is known. Each experiment is repeated on five independently simulated surveys, and I report the average and the range. Two results stand out. First, for gradient-boosted trees, oversampling does not improve how well the model ranks students by their risk. It raises the predicted probabilities, so that more students pass a fixed cutoff of 0.5, but the probabilities then no longer measure the chance of a yes answer. Second, when the goal is a share, the predicted probabilities should be recalibrated and summed rather than turned into yes or no labels and counted. Summed recalibrated probabilities give the most accurate cell shares of the methods I compare and, unlike the alternatives, leave the coefficient of a second-stage regression on the share approximately unbiased. They do not, however, fully remove the bias from non-response, and second-stage standard errors still have to account for the first stage.
The problem is not hypothetical. In Risky Peers and Crime (with Olivier Marie and Max Steinhardt), the share of risk-prone peers in a school cohort has to be constructed from a risk-preference question that only part of the Add Health respondents answered, and that share is the regressor in a peer-effects design of the kind described above. The pipeline on this page is the simulated, self-contained version of the one I use there.
The rest of this page is organized as follows. Section 1 describes the simulated survey. Sections 2 to 5 present the four steps of the pipeline: imputing missing features, handling the imbalance, building the shares, and validating and using them. Section 6 summarizes which approach to use in which situation.
01The simulated survey
Consider a school-based survey that asks students whether they carried a weapon on school property in the past 30 days. I simulate such a survey with a structure loosely modelled on Add Health (Harris et al., 2009): 99,758 students in grades 7 to 12, enrolled in 80 schools whose size ranges from 489 to 2,977 students (median 1,208). Because the question is sensitive, 35 percent of students do not answer it. Among the 64,583 who do, 1,681 answer yes, a share of 2.6 percent.
Whether a student answers depends on their observed characteristics: students whose other answers indicate a higher risk skip the question more often. As a result, 3.8 percent of the students who skip it carry a weapon, against 2.6 percent of those who answer, and the share among respondents understates the true share of 3.0 percent. Given the observed characteristics, however, answering does not depend on the answer itself, i.e., the answers are missing at random. Filling in the gaps relies on this assumption, and Section 5 discusses what happens when it fails.
The quantity of interest is the share of yes answers in each school, grade, and gender cell, which in a peer-effects design would measure a student's exposure to peers who carry weapons. The prediction therefore does not need to be correct for each individual student, but it needs to reproduce the share in each cell. Because school sizes differ, some cells are too small for their share to be measured with any precision.
The probability of a yes answer depends on the students' characteristics in a way that is known by construction. To make clear which variables matter, each feature is named after the role it plays in the simulation (Table 1).
| features | count | role in the simulation |
|---|---|---|
sig_01–sig_04 |
4 | Define three regions of the feature space in which the probability of a yes answer is high. The effect is non-linear and depends on the 4 variables jointly. |
sig_05–sig_20 |
16 | Enter the outcome linearly, with moderate coefficients. They also drive whether a student answers. |
sig_21–sig_50 |
30 | Enter the outcome linearly, with small coefficients. |
noise_001–noise_100 |
100 | Independent standard normal draws, unrelated to the outcome. |
| school, grade, female | 3 | Identify the cell, and shift the probability of a yes answer across cells. |
In total, 50 of the 153 features carry information on the outcome and 100 do not, so that 65 percent of the feature space is noise. This is deliberate. Survey data used for prediction typically include many variables with little or no relation to the outcome, and a method that only works when the relevant variables are known in advance is of limited use in practice.
The noise variables also matter for the choice of method in Section 3. SMOTE creates synthetic positive cases by interpolating between a positive student and one of their nearest neighbours, where the distance between students is computed over all features. When most features are noise, most of the distance between two students is noise as well, and the nearest neighbour of a positive student is not necessarily similar to them in the variables that determine the outcome.
Pythoncode/imbalanced_prediction_demo.pyhow the outcome and the features are generated
k_sig, k_noise = cfg["n_signal"], cfg["n_noise"]
pdim, n_mid = cfg["proto_dims"], cfg["n_mid"]
S = rng.normal(size=(n, k_sig))
centres = rng.normal(size=(cfg["n_prototypes"], pdim))
centres /= np.linalg.norm(centres, axis=1, keepdims=True)
centres *= 1.7
d2 = np.stack([((S[:, :pdim] - c) ** 2).sum(axis=1) for c in centres])
proximity = np.exp(-d2 / (2 * cfg["proto_scale"] ** 2)).max(axis=0)
lo, hi = pdim, pdim + n_mid
w_mid = np.linspace(0.42, -0.28, n_mid)
w_weak = np.linspace(0.14, -0.08, k_sig - hi)
linear = (np.einsum("ij,j->i", S[:, lo:hi], w_mid)
+ np.einsum("ij,j->i", S[:, hi:], w_weak))
lin = cfg["proto_strength"] * proximity + linear + df["cell_fx"].to_numpy()
lin = lin + calibrate_intercept(lin, cfg["prevalence"])
p_true = sigmoid(lin)
y_true = (rng.random(n) < p_true).astype(int)
feat = {f"sig_{i + 1:02d}": S[:, i] for i in range(k_sig)}
feat.update({f"noise_{j + 1:03d}": rng.normal(size=n) for j in range(k_noise)})
df = pd.concat([df.drop(columns="cell_fx"), pd.DataFrame(feat)], axis=1)
df["y_true"] = y_true
df["p_true"] = p_true # kept for anyone who wants the ceiling
02Step 1: Imputing missing features without the outcome
14 percent of feature values are missing. As in real survey data, item non-response is not uniform across questions: the 4 variables that define the high-risk regions are missing for 4.2 percent of students, while the variables at the end of the simulated questionnaire are missing far more often. If all features were missing at the same average rate, about 38 percent of students would lack at least one of the 4 core variables, and the results would largely reflect the quality of the imputation rather than the method. With the rates above, 15 percent of students lack at least one of them.
I fill in the missing values with iterative imputation, in which each feature is regressed on all other features with a Ridge regression, and the procedure is repeated until the imputed values stabilize. The outcome is never included in the imputation model. Including it would write information on the answer into the features of the students who did not answer, and the model would appear to predict well for reasons that do not carry over to real data. The imputer is fitted once on all respondents and then applied, without refitting, to the non-respondents. Because it is fitted before the split into training and test samples, test observations contribute to the imputation through their features, which makes the test metrics slightly optimistic.
For gradient-boosted trees, this step is not strictly necessary, since XGBoost assigns missing values a default direction at each split. I keep it because the point about excluding the outcome applies to any model that requires complete data. The experiments in Part 2 of the script use mean imputation to keep the running time manageable.
03Step 2: Handling the imbalance
With 2.6 percent of positive answers among respondents, a model that predicts no for every student is correct 97 percent of the time, and classifiers trained on such data tend to assign low probabilities to almost everyone. Three responses are common: doing nothing, weighting the positive cases more heavily in the loss function, and rebalancing the training data with SMOTE. To compare them, I train the same model with the same hyperparameters on each of the five simulated surveys, and vary only the treatment of the imbalance (Table 2).
I report two measures of performance. The area under the precision-recall curve (PR-AUC) measures how well the model ranks students by their risk, independently of any cutoff, and is more informative than the ROC curve when positive cases are rare (Saito & Rehmsmeier, 2015). Recall at a cutoff of 0.5 measures the share of positive students whose predicted probability exceeds 0.5, the default rule for classifying a student as positive.
| treatment | PR-AUC | ROC-AUC | recall @0.5 | precision @0.5 | classified positive | mean probability |
|---|---|---|---|---|---|---|
| nothing | 0.298[0.235, 0.342] | 0.891[0.862, 0.909] | 0.027[0.010, 0.053] | 0.585 | 0.11% | 0.014[0.013, 0.014] |
| class weighting | 0.265[0.209, 0.305] | 0.880[0.853, 0.899] | 0.292[0.219, 0.347] | 0.359 | 2.06% | 0.052[0.047, 0.058] |
| SMOTE, ratio 0.3 | 0.200[0.127, 0.244] | 0.860[0.808, 0.882] | 0.082[0.031, 0.138] | 0.394 | 0.50% | 0.031[0.027, 0.034] |
| SMOTE, balanced | 0.176[0.117, 0.214] | 0.852[0.806, 0.876] | 0.132[0.079, 0.192] | 0.287 | 1.15% | 0.043[0.033, 0.046] |
Notes: Average over 5 independently simulated surveys, with the range across surveys in small print. In each survey, the model is trained on three quarters of the respondents and evaluated on the rest. All four rows use the same XGBoost hyperparameters. “SMOTE, ratio 0.3” oversamples the positive class to 30 percent of the size of the negative class; “SMOTE, balanced” to equal size. The last column is the mean predicted probability in the evaluation sample, whose observed share of positives is 0.025 on average.
PR-AUC recall at the 0.5 cutoff
The two measures move in opposite directions. Rebalancing the training data to equal shares raises recall at 0.5 from 0.027 to 0.132 on average, and raises it in all five surveys. At the same time, PR-AUC falls from 0.298 to 0.176, and is lower than without any treatment in all five surveys; with the milder ratio of 0.3, it is lower in all five surveys. Oversampling therefore does not improve the model's ability to distinguish positive from negative students. It raises the predicted probabilities of all students, so that more of them pass the cutoff of 0.5: the mean predicted probability rises from 0.014 to 0.043, against an observed share of 0.025. Class weighting has the same effect on recall, which rises to 0.292, at a smaller cost in ranking: its PR-AUC is below that of the untreated model in all five surveys but by less than with oversampling.
This mechanism reconciles the apparently contradictory findings in the literature. Campedelli et al. (2024) predict mafia infiltration of city councils, with 0.83 percent of positive cases, and report that recall rises from 0.72 to 0.96 when they rebalance the training data with ADASYN, a variant of SMOTE. Their aim is a list of councils to inspect, for which recall is the relevant measure, and their gain in recall corresponds to the first and last rows of Table 2. Elor and Averbuch-Elor (2022) instead evaluate how well models rank observations, and find no gain from rebalancing for strong classifiers. Both results are consistent with the pattern above. For the purpose of this page, the important consequence is that after rebalancing, the predicted probabilities no longer estimate the chance of a yes answer, which matters in Section 4.
A natural follow-up question is whether oversampling becomes useful when the outcome is rarer, and more generally how the performance of the model changes with the share of positive cases. To answer both, I lower this share while holding the number of students fixed (Table 3).
| prevalence | positives | PR-AUC | ROC-AUC | lift | SMOTE / weighting |
|---|---|---|---|---|---|
| 2.6% | 1,669 | 0.349[0.311, 0.403] | 0.908[0.894, 0.915] | 15.6[14.2, 17.3] | 0.56[0.39, 0.73] |
| 1.7% | 1,115 | 0.268[0.224, 0.314] | 0.911[0.898, 0.923] | 20.0[16.6, 23.1] | 0.57[0.37, 0.69] |
| 0.8% | 550 | 0.151[0.108, 0.236] | 0.907[0.887, 0.927] | 25.9[20.2, 37.3] | 0.53[0.33, 0.70] |
Notes: Average over 5 surveys of about 64,924 respondents each, without missing features, with the range in small print. Prevalence and positives refer to respondents. PR-AUC, ROC-AUC and lift refer to the model with class weighting, evaluated on a quarter of the respondents. Lift is the share of positives among the students with the highest predicted risk, as many as there are positive cases, divided by the share of positives. The last column divides the PR-AUC with SMOTE (ratio 0.3) by the PR-AUC with class weighting.
The three measures of performance lead to different conclusions. Between 2.6 and 0.8 percent, PR-AUC falls from 0.349 to 0.151. ROC-AUC, the probability that a randomly drawn positive student receives a higher predicted risk than a randomly drawn negative one, moves from 0.908 to 0.907, and the lift from 15.6 to 25.9. The fall in PR-AUC does not by itself mean that the model ranks students worse. The PR-AUC of random ranking equals the share of positive cases, so the scale of the measure shifts down with this share, and PR-AUC is not comparable across outcomes of different rarity.
Regarding the choice of method, the PR-AUC with SMOTE is below that with class weighting in all five surveys at 2.6 percent and in all five surveys at 0.8 percent, with an average ratio of 0.56 and 0.53. With fewer positive cases, the neighbours from which SMOTE interpolates are drawn from a smaller set, in a feature space that is 65 percent noise.
Two practical points apply if oversampling is used nonetheless. First, the degree of oversampling is a hyperparameter. The common default rebalances the classes to equal shares, which in this sample would mean that most of the positive training cases are interpolated; when the ratio is tuned by cross-validation on the main survey, the search selects 0.2. Second, SMOTENC has to be a step of the model pipeline rather than a preprocessing step applied to the whole sample. It is then applied only when the model is fitted, and every validation fold and the test sample keep the true share of positive cases. SMOTENC also treats school and grade as categorical, so that synthetic students are assigned an existing school and grade rather than an interpolated one.
Pythoncode/imbalanced_prediction_demo.pythe four treatments
def arm_pipelines(y, cat_idx, n_jobs=1):
spw = float((y == 0).sum() / (y == 1).sum())
cast = ("cast", FunctionTransformer(cast_cats, validate=False))
return {
"nothing": [cast, ("xgb", make_xgb(n_jobs, **FIXED_XGB))],
"class weighting": [cast, ("xgb", make_xgb(n_jobs, scale_pos_weight=spw, **FIXED_XGB))],
"SMOTE, ratio 0.3": [
("smote", SMOTENC(categorical_features=cat_idx, k_neighbors=5,
sampling_strategy=0.3, random_state=RANDOM_STATE)),
cast, ("xgb", make_xgb(n_jobs, **FIXED_XGB))],
"SMOTE, balanced": [
("smote", SMOTENC(categorical_features=cat_idx, k_neighbors=5,
sampling_strategy=1.0, random_state=RANDOM_STATE)),
cast, ("xgb", make_xgb(n_jobs, **FIXED_XGB))],
}
04Step 3: From predictions to shares
The second stage requires the share of yes answers in each cell. Respondents keep their observed answer, and each non-respondent contributes a prediction. There are two ways to turn predictions into a share. The first, called classify and count in the quantification literature (Forman, 2008), classifies each non-respondent as yes or no at a threshold and counts the yes answers. The threshold is usually chosen so that the share of yes predictions among respondents matches their observed share. The second sums the predicted probabilities (Bella et al., 2010). If the probabilities are calibrated, i.e., if among students with a predicted probability of 0.1 about one in ten answers yes, their sum estimates the expected number of yes answers in any group.
The probabilities produced by the model are not calibrated. Among respondents, the mean predicted probability of the selected model is 0.0424, against an observed share of 0.0260. As Table 2 shows, class weighting and oversampling raise the level of the probabilities, but the untreated model is not calibrated either: its mean predicted probability of 0.014 is below the observed share. I therefore recalibrate the probabilities with an isotonic regression of the observed answer on the predicted probability, which brings the mean to 0.0261. Wherever a recalibrated probability is later compared with the answers of the same respondents, the recalibration is estimated on the folds that exclude them.
All predictions are cross-fitted. Each of five models is fitted on all but one fold of the respondents. Every respondent is predicted by the model that was not fitted on them, and every non-respondent by the average of the five models. The threshold for classify and count and the recalibration are therefore estimated from the same models that produce the predictions for non-respondents. Table 4 compares the resulting shares with the true shares of all students.
Pythoncode/imbalanced_prediction_demo.pycross-fitting and recalibration
# From predictions to shares
# =====================================================================
# What the second stage needs is the share of yes answers in each cell.
# Respondents keep their own answer and each non-respondent contributes
# a prediction. There are two ways to turn predictions into a share:
#
# classify and count label each non-respondent yes or no at a
# threshold and count the yes labels. The
# threshold reproduces the respondents' share, so
# the method carries that share over to groups in
# which it is different (Forman, 2008).
# sum probabilities add up each non-respondent's probability of a
# yes (Bella et al., 2010). This estimates the
# expected number of yes answers when the
# probabilities are calibrated, which they are not
# after class weighting or oversampling; hence the
# recalibration below.
#
# Both use cross-fitted predictions. Each of K models is fitted on K-1
# folds of the respondents; every respondent is predicted by the one model
# that did not see it, and every non-respondent by the average of the K
# models. The threshold and the calibration are therefore estimated from
# the same models that produce the predictions.
def cross_fit(pipe, X_r, y_r, X_n, k, seed):
cv = StratifiedKFold(k, shuffle=True, random_state=seed)
oof = np.zeros(len(y_r))
fold_id = np.zeros(len(y_r), dtype=int)
new = np.zeros(len(X_n))
importance = np.zeros(X_r.shape[1])
for f, (trn, val) in enumerate(cv.split(X_r, y_r)):
m = clone(pipe).set_params(xgb__n_jobs=-1).fit(X_r.iloc[trn], y_r.iloc[trn])
oof[val] = m.predict_proba(X_r.iloc[val])[:, 1]
fold_id[val] = f
new += m.predict_proba(X_n)[:, 1] / k
importance += m.named_steps["xgb"].feature_importances_ / k
return oof, new, importance, fold_id
def recalibrate(oof, y_r):
"""Isotonic regression of the observed answer on the out-of-fold
probability. Undoes the inflation from class weighting or oversampling."""
return IsotonicRegression(out_of_bounds="clip", y_min=0, y_max=1).fit(oof, y_r)
def recalibrate_oof(oof, y_r, fold_id):
"""Recalibrated probability for each respondent, with the calibration
estimated on the folds that EXCLUDE them. The check in Part 1 compares
these to the observed answers, so no student's own answer may enter
their recalibrated probability."""
y_r = np.asarray(y_r)
out = np.zeros_like(oof)
for f in np.unique(fold_id):
m = fold_id == f
out[m] = recalibrate(oof[~m], y_r[~m]).predict(oof[m])
return out
| how the share is built | error in the overall share (pp) | correlation | RMSE (pp) | second-stage coefficient |
|---|---|---|---|---|
| respondents only | -0.46[-0.48, -0.41] | 0.798 | 1.53 | 0.77[0.74, 0.81] |
| classify and count, refitted model | 0.41[0.24, 0.69] | 0.782 | 1.65 | 0.68[0.61, 0.72] |
| classify and count, fold models | -0.22[-0.30, -0.12] | 0.806 | 1.43 | 0.80[0.75, 0.85] |
| sum of probabilities, not recalibrated | 1.14[0.82, 1.48] | 0.819 | 1.73 | 0.77[0.71, 0.82] |
| sum of probabilities, recalibrated | -0.22[-0.27, -0.14] | 0.846 | 1.22 | 1.02[0.98, 1.05] |
| sum of the true probabilities (unattainable) | -0.01[-0.02, 0.02] | 0.899 | 0.98 | 1.02[0.98, 1.05] |
Notes: Average over 5 independently simulated surveys, with the range across surveys in small print. The true share of a cell is the share of yes answers among all its students, respondents and non-respondents. Correlation, root mean squared error (RMSE) and the second-stage coefficient are computed across cells with at least 35 students. The second-stage coefficient is the coefficient that a regression of an outcome on the estimated share recovers when the coefficient on the true share is one. The last row uses the probabilities from which the answers were simulated, which are unknown in practice.
The share computed from respondents alone understates the true share by 0.46 percentage points on average, and understates it in all five surveys, because respondents are less at risk than non-respondents. Summing the recalibrated probabilities reduces the error in the overall share to -0.22 percentage points, and gives more accurate cell shares than classify and count in all five surveys (RMSE of 1.22 against 1.43 percentage points) and than the respondents-only share in all five surveys. Summing the probabilities without recalibrating them shifts the overall share by 1.14 percentage points.
Filling in the gaps does not remove the bias from non-response entirely. Both ways of filling them in understate the share among non-respondents: in the main survey, the true share among the 35,175 students who skipped the question is 0.0382, classify and count gives 0.0325, and the sum of recalibrated probabilities gives 0.0320. I suspect the reason is that the model is fitted on respondents, who are less at risk, and the calibration is estimated on them as well, so that both are least reliable for the higher-risk students who skip the question. On the overall level, the two ways of filling in perform similarly (-0.22 and -0.22 percentage points). The advantage of summing probabilities lies in the cell shares. Counting labels is only unbiased for groups whose share of positive cases equals the share at which the threshold was set (Forman, 2008), and cell shares vary. When the threshold is computed from the fold models but applied to a model refitted on all respondents, which is stronger than the fold models, the error grows further (second row of Table 4).
05Step 4: Validating and using the shares
In real data, the true answers of non-respondents are unknown, and the predictions can only be checked against the respondents. For each cell, I compare the share predicted for its respondents, from probabilities that are predicted and recalibrated out of fold, with their observed share. Across the 902 cells with at least 35 respondents, a regression of the observed on the predicted share has a slope of 0.91 and an intercept of 0.0022, against one and zero for predictions that are correct on average. The correlation between the two is 0.600. Its maximum is not one, because observed shares in small cells are noisy, and there is no simple formula for it: a model that uses each student's own characteristics can predict part of that noise.
Pythoncode/imbalanced_prediction_demo.pythe check that needs no true shares
# With real data, the predictions can only be checked against the
# respondents. For each cell, the share predicted for its respondents
# (from the out-of-fold probabilities) is compared with their observed
# share. If the predictions are right on average at the cell level, a
# regression of the observed on the predicted share has a slope of one and
# an intercept of zero. The correlation is reported as well, but there is
# no simple ceiling for it: the observed shares are noisy, and a model
# that uses each student's own characteristics can predict part of that
# noise, so the usual reliability bound does not apply.
def cell_calibration(pred, actual):
slope = np.cov(pred, actual)[0, 1] / np.var(pred, ddof=1)
return dict(slope=float(slope), intercept=float(np.mean(actual) - slope * np.mean(pred)),
corr=float(np.corrcoef(pred, actual)[0, 1]))
The share is then used as a regressor, and the prediction error it carries affects the second stage. The last column of Table 4 reports the coefficient that a second-stage regression recovers when the true coefficient on the share is one. With the respondents-only share it is 0.77, because shares computed from fewer students are noisier, and with classify and count it is 0.80. With the sum of recalibrated probabilities it is 1.02, between 0.98 and 1.05 across surveys. This is what one would expect. When the probabilities are calibrated, the error in the filled-in share is uncorrelated with the share itself, a form of measurement error known as Berkson error, which does not bias the coefficient of a linear regression. Counting labels, or dropping the non-respondents, produces errors that are correlated with the estimated share and attenuate the coefficient.
An unbiased coefficient is not the same as valid inference. The filled-in share is estimated, and standard errors in the second stage that treat it as data are too small. Battaglia et al. (2024) derive bias corrections and valid confidence intervals for regressions on variables generated by machine learning, including imputed labels as here. At a minimum, the standard errors should account for the first stage, for example by bootstrapping the whole pipeline, with schools resampled as clusters and the imputation and the model refitted in each draw.
The approach as a whole rests on the assumption that, given the observed characteristics, whether a student answers does not depend on the answer itself. For a question on carrying weapons, this is a strong assumption: students who carry weapons may skip the question because they do. In that case, no prediction from observed characteristics recovers the true share, and the simulation, which imposes the assumption, cannot detect the problem. A transparent complement is to report bounds that do not rely on the assumption (Manski, 1989). Setting every missing answer to no gives a lower bound on the overall share, and setting every missing answer to yes gives an upper bound. In the main survey, these bounds are 1.7 and 36.9 percent. With a third of answers missing and a rare outcome, they are wide, which itself shows how much the filled-in share relies on the assumption.
Finally, because the data are simulated, the feature importances can be compared with the roles assigned in the simulation (Table 5). Of the fifteen most important features, 100 percent are signal variables or cell identifiers, in a feature space in which 65 percent of the variables are noise.
| feature | importance (gain) | role |
|---|---|---|
| sig_01 | 0.0377 | signal |
| sig_04 | 0.0363 | signal |
| sig_03 | 0.0335 | signal |
| sig_02 | 0.0249 | signal |
| school | 0.0197 | cell identifier |
| female | 0.0146 | cell identifier |
| sig_05 | 0.0139 | signal |
| sig_06 | 0.0104 | signal |
| sig_07 | 0.0096 | signal |
| sig_09 | 0.0094 | signal |
Notes: Gain importance averaged over the 5 fold models of the main survey.
The importance of the school identifier raises a concern for applications. When school enters the model as a predictor, the predicted answers of all non-respondents in a school shift together with the estimated school effect, so that part of the variation in predicted shares across schools comes from the model rather than from the students. The concern is smaller when the second stage compares cohorts within the same school, as in the design of Hoxby (2000), since school fixed effects absorb any shift common to all cohorts of a school. A simple check is to re-estimate the model without the cell identifiers and compare the predicted shares.
06Which approach to use
Table 6 summarizes the recommendations of the previous sections.
| Situation | Approach | Reason |
|---|---|---|
| The predictions are used to select individuals, and a false positive is cheap | Oversampling or class weighting, evaluated by recall | Both raise predicted probabilities, which increases recall at a fixed cutoff |
| The predictions are aggregated into a share or used as a regressor | Sum of recalibrated probabilities, rather than classify and count | Calibrated probabilities estimate the expected number of positives in any group, while a threshold is only right for groups with the share at which it was set |
| The probabilities come from a rebalanced or boosted model | Recalibration on out-of-fold predictions before using them as probabilities | Rebalancing shifts the level of the predicted probabilities, and here even the untreated model is not calibrated |
| The model is distance-based, such as k-nearest neighbours or a support vector machine | Oversampling | These models need enough positive cases close to each other to separate them from negative cases |
| The model is a gradient-boosted tree or a random forest | No treatment, or class weighting | Trees can isolate small regions of the feature space from few positive cases |
| Many features are unrelated to the outcome | Reducing the feature set before any oversampling | SMOTE computes distances over all features, so noise variables make its synthetic cases uninformative |
| Oversampling is used | A ratio tuned by cross-validation, with resampling inside the pipeline | Full rebalancing is rarely optimal, and resampling before the split leaks information into the validation folds |
| The positive class is below 1 percent | PR-AUC reported together with ROC-AUC and lift | PR-AUC falls with the share of positive cases, so it is not comparable across outcomes of different rarity |
| The predicted share is used as a regressor | A bias correction for generated regressors, or at least a bootstrap of the whole pipeline | Standard errors that ignore the first stage are too small, and shares built from labels or from respondents only also bias the coefficient |
| Whether a person answers may depend on the answer itself | Bounds on the share, reported next to the filled-in estimate | No prediction from observed characteristics corrects this kind of selection |
| Approaches are compared | PR-AUC, rather than recall at 0.5 or accuracy | Recall at a fixed cutoff rises whenever probabilities are inflated, and accuracy rewards predicting no for every observation |
References
- Ash, E., Galletta, S. & Giommoni, T. (2025). A machine learning approach to analyze and support anticorruption policy. American Economic Journal: Economic Policy 17(2), 162–93.Predicts corruption in local governments with gradient-boosted trees. Their ROC-AUC of 0.78 is a useful benchmark for applied prediction in economics.
- Battaglia, L., Christensen, T., Hansen, S. & Sacher, S. (2024). Inference for Regression with Variables Generated by AI or Machine Learning. arXiv:2402.15585.Shows that regressions on variables generated by machine learning, including imputed labels, are biased and that standard inference is invalid, and derives corrections. Discussed in Section 5.
- Bella, A., Ferri, C., Hernández-Orallo, J. & Ramírez-Quintana, M. J. (2010). Quantification via probability estimators. Proceedings of the IEEE International Conference on Data Mining, 737–742.Estimates a share by averaging predicted probabilities instead of counting labels.
- Campedelli, G. M., Daniele, G. & Le Moglie, M. (2024). Mafia, Politics and Machine Predictions. CEPR Discussion Paper 19322.Predicts mafia infiltration of city councils with 0.83 percent of positive cases, and reports recall rising from 0.72 to 0.96 with ADASYN oversampling. Discussed in Section 3.
- Chawla, N. V., Bowyer, K. W., Hall, L. O. & Kegelmeyer, W. P. (2002). SMOTE: Synthetic Minority Over-sampling Technique. Journal of Artificial Intelligence Research 16, 321–357.Introduces SMOTE. SMOTENC, used here, is its variant for data with categorical and numeric features.
- Elor, Y. & Averbuch-Elor, H. (2022). To SMOTE, or not to SMOTE? arXiv:2201.08528.Finds across many datasets that rebalancing helps weak classifiers but not strong ones such as gradient-boosted trees, and that tuning the threshold is an alternative.
- Forman, G. (2008). Quantifying counts and costs via classification. Data Mining and Knowledge Discovery 17(2), 164–206.Names classify and count, and shows that it is biased when the share of positives in a group differs from the share at which the classifier was set.
- González, P., Castaño, A., Chawla, N. V. & del Coz, J. J. (2017). A review on quantification learning. ACM Computing Surveys 50(5), 74.An introduction to the literature on estimating shares rather than classifying individuals.
- Harris, K. M., Halpern, C. T., Whitsel, E., Hussey, J., Tabor, J., Entzel, P. & Udry, J. R. (2009). The National Longitudinal Study of Adolescent to Adult Health: Research Design.The design of Add Health, on which the structure of the simulated survey is loosely based.
- Hoxby, C. (2000). Peer Effects in the Classroom: Learning from Gender and Race Variation. NBER Working Paper 7867.Identifies peer effects from variation in composition across cohorts within the same school.
- Manski, C. F. (1989). Anatomy of the selection problem. Journal of Human Resources 24(3), 343–360.Bounds on a population quantity when some outcomes are missing and nothing is assumed about why. Discussed in Section 5.
- Saito, T. & Rehmsmeier, M. (2015). The precision-recall plot is more informative than the ROC plot when evaluating binary classifiers on imbalanced datasets. PLOS ONE 10(3): e0118432.Shows why PR-AUC is more informative than ROC-AUC when positive cases are rare.
imbalanced-learn(Python package)Provides SMOTENC and the pipeline that applies resampling only within the training folds.
Run it
python code/imbalanced_prediction_demo.py
The script runs in about
28 minutes: the pipeline on one survey of 99,758
simulated students with 153 features, followed by the experiments in
Tables 2 to 4 on 5 further surveys. Change seeds in
CFG to run them on fewer or more surveys. All numbers on this
page are read from the results file the script writes.