Privacy vs. Utility in Data Anonymization:
Anyone who releases microdata (patient records, customer logs, survey responses) runs into the same tension. The more you mask, the safer the data gets, and the less useful it becomes. Coarsen ages into decades and truncate ZIP codes to one digit, and nobody can single out an individual, but your regression model loses most of what it could explain. Leave everything raw and the model performs well, but almost every record becomes uniquely identifiable.
In this article we turn that tension into an explicit constrained optimization problem. Our goal is to keep the re-identification risk below a fixed threshold while making the anonymized data as useful as possible for analysis. We then solve it in Python.
The Problem Setting
A health insurer wants to share 30,000 member records with an external analytics team. The team will build a model that predicts annual medical cost. Each record contains:
| Attribute | Role |
|---|---|
| Age (18–89) | Quasi-identifier |
| Gender | Quasi-identifier |
| 5-digit ZIP code | Quasi-identifier |
| Annual income | Quasi-identifier |
| Annual medical cost | Sensitive / target variable |
None of these attributes names a person directly. Combined, though, they act as a fingerprint. “A 47-year-old woman in ZIP 31402 earning $62,300” is almost certainly one specific person.
The insurer can apply generalization to each quasi-identifier:
- Age: bin width $w_a \in {1, 2, 5, 10, 20, 40}$ years
- ZIP code: keep the first $d_z \in {5, 4, 3, 2, 1, 0}$ digits
- Income: bin width $w_i \in {1\text{k}, 5\text{k}, 10\text{k}, 25\text{k}, 50\text{k}, 100\text{k}}$
That gives $6 \times 6 \times 6 = 216$ candidate anonymization schemes, which together form a generalization lattice.
Formalizing the Trade-off
Equivalence classes and k-anonymity
After generalization, records that share the same quasi-identifier values form an equivalence class. Let $|E(r)|$ be the size of the class that contains record $r$. A dataset is $k$-anonymous when
$$
\min_{r} |E(r)| \ge k .
$$
Strict $k$-anonymity is often too harsh, because a single outlier can force the whole dataset into very coarse bins. A common relaxation is to cap the share of records at risk:
$$
R_{\text{at-risk}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \mathbf{1}\bigl[,|E_\theta(r)| < k,\bigr],
$$
where $\theta = (w_a, d_z, w_i)$ is the generalization scheme. The few records still at risk can be suppressed or handled individually.
We also report the average prosecutor risk. This is the expected probability that an attacker who knows a target’s quasi-identifiers picks the right record:
$$
R_{\text{avg}}(\theta) = \frac{1}{N}\sum_{r=1}^{N} \frac{1}{|E_\theta(r)|}.
$$
Utility
Utility is measured by what the analysts actually care about: the out-of-sample $R^2$ of a cost-prediction model trained on the generalized data.
$$
U(\theta) = R^2_{\text{test}}(\theta) = 1 - \frac{\sum_{j \in \text{test}} (y_j - \hat y_j)^2}{\sum_{j \in \text{test}} (y_j - \bar y)^2}.
$$
The optimization problem
$$
\theta^* = \arg\max_{\theta \in \Theta} ; U(\theta)
\quad \text{s.t.} \quad R_{\text{at-risk}}(\theta) \le \varepsilon,
$$
with $k = 5$ and $\varepsilon = 0.05$. In words: at most 5% of the records may sit in an equivalence class smaller than 5.
The Data-Generating Process
We generate synthetic data whose true cost structure is known, so the effect of each generalization can be interpreted directly:
$$
y = 1500 + 4,(a-18)^{1.6} + 350,g + \alpha_{d_1} + \beta_{d_1 d_2} + \gamma_{d_1 d_2 d_3} - 0.012,x + \epsilon ,
$$
where $a$ is age, $g$ is gender, $x$ is income, $\epsilon \sim \mathcal{N}(0, 700^2)$, and the regional effects form a hierarchy:
$$
\alpha_{d_1} \sim \mathcal{N}(0, 900^2), \quad
\beta_{d_1 d_2} \sim \mathcal{N}(0, 600^2), \quad
\gamma_{d_1 d_2 d_3} \sim \mathcal{N}(0, 400^2).
$$
So the first three ZIP digits carry real signal, and digits 4–5 are pure noise from the model’s point of view but highly identifying. This mirrors reality, where coarse geography explains a lot and fine geography mostly fingerprints people.
Source Code
1 | import numpy as np |
Code Walkthrough
1. Synthetic microdata
We draw 30,000 members with uniform ages from 18 to 89, a binary gender, and a 5-digit ZIP code built from three parts (d1, d2, d345). Income is log-normal and drifts slightly upward with age, so income and age are mildly correlated, as they are in real data.
The cost formula implements the data-generating process above. The term 4.0 * (age - 18) ** 1.6 makes cost rise convexly with age, which is why very wide age bins will hurt. The regional effects state_eff, region_eff and area_eff are indexed by the first one, two and three ZIP digits, so geography matters in layers.
The data is split 70/30 into train and test sets (is_train). Each record also gets a fold index (fold), used later for leakage-free target encoding.
2. Generalization operators
generalize(age_w, zip_d, inc_w) turns one lattice point $\theta$ into masked attributes:
a_bin = age // age_wis the integer bin ID, used for risk computation.a_midis the bin midpoint, the value the analyst would actually see and use in a model.z_pre = zip // 10**(5 - zip_d)keeps only the leadingzip_ddigits. Whenzip_d = 0every record maps to 0, so the ZIP code is fully suppressed.- Income gets the same treatment as age.
3. Re-identification risk, computed fast
This is where most of the speed comes from. A naive approach would call df.groupby([age, gender, zip, income]).transform("size") for each of the 216 configurations. Multi-column groupby on DataFrames is slow, because pandas has to hash tuples of mixed types.
Instead, we pack the four quasi-identifiers into a single int64 key with a mixed-radix encoding:
$$
\text{key} = \bigl((a_{\text{bin}} \cdot 100001 + z_{\text{pre}}) \cdot 2 + g\bigr) \cdot 1000 + i_{\text{bin}} .
$$
The multipliers are larger than the range of the next field (ZIP prefix < 100,000, gender ∈ {0, 1}, income bin < 1,000), so the encoding is injective. Two records share a key if and only if they share every quasi-identifier.
Then a single np.unique(key, return_inverse=True, return_counts=True) returns each class’s size, and cnt[inv] maps it back to every record. This runs in $O(N \log N)$ inside compiled NumPy code, and the whole risk evaluation for one configuration takes a few milliseconds.
From the class sizes we compute:
at_risk: the share of records with $|E(r)| < 5$avg_risk: the mean of $1/|E(r)|$k_min: the effective $k$ of the release
4. Utility measurement
The analyst’s model is an ordinary least squares regression on features they can build from the released data:
- A cubic polynomial in the age-bin midpoint, centered and scaled for numerical stability: $\tilde a = (a_{\text{mid}} - 50)/10$, with $\tilde a, \tilde a^2, \tilde a^3$
- Gender
- The income-bin midpoint, scaled by $10^4$
- Hierarchical target encodings of the ZIP prefix, one per retained level $L = 1, \dots, d_z$
ZIP codes are categorical with up to 100,000 levels, so one-hot encoding is out. For each level we replace the prefix with a smoothed mean of the target:
$$
\text{enc}(c) = \frac{\sum_{r \in c} y_r + m,\bar y}{n_c + m}, \qquad m = 20 .
$$
The prior weight $m$ pulls small categories toward the global mean $\bar y$, which prevents overfitting on sparse prefixes.
There is a classic trap here. If a training row’s own $y$ is included when computing its encoding, the feature leaks the target. The model then learns to trust the encoding far too much, and the test $R^2$ collapses. We avoid this with 5-fold out-of-fold encoding. Each training row’s encoding is computed only from the other four folds. Test rows are encoded using the full training set, which is exactly what would happen in production.
Including all levels $1, \dots, d_z$ rather than only the finest one lets the model rely on coarse geography when the fine levels are too sparse to be informative. As a result, keeping more digits never removes information the model could use, and the comparison across configurations is fair.
Finally, np.linalg.lstsq fits the coefficients and we compute the test-set $R^2$.
5. Exhaustive search over the lattice
Three nested loops visit all 216 schemes. For each one we record the risk metrics and the utility. Then we:
- Use the identity configuration $(1, 5, 1000)$ as the “raw data” baseline
- Filter for feasibility, $R_{\text{at-risk}} \le 0.05$
- Pick the feasible scheme with the highest $R^2$, breaking ties by larger $k_{\min}$
- Compute the Pareto front: sort by risk ascending, then sweep and keep every point whose $R^2$ beats all lower-risk points. Each Pareto point is a scheme that no other scheme beats on both privacy and utility at once.
The full search finishes in a few seconds. Most of that time goes to the target encoding, not the risk computation, so there is no need for a smarter lattice search (such as Incognito or OLA-style pruning) at this scale. With dozens of quasi-identifiers, monotonicity pruning would become worthwhile. If a scheme already satisfies the risk constraint, every coarser scheme does too.
6. Visualization
The figure is a 2×3 grid:
- Utility surface (3D): $R^2$ over age bin width × ZIP digits, with income fixed at the optimum’s bin width
- Risk surface (3D): the share of records at risk over the same grid, cut by a translucent cyan plane at the 5% threshold
- Generalization lattice (3D scatter): all 216 schemes in the space $(w_a, d_z, w_i)$. Feasible ones are colored by $R^2$, infeasible ones are gray crosses, and the optimum is a red star.
- Privacy–utility trade-off: $R^2$ against risk on a symlog axis, with the Pareto front and the threshold line
- Feasibility heatmap: for each (age, ZIP) pair, the best $R^2$ achievable while meeting the risk budget, maximized over income bins. A dash means no income bin can make that pair feasible.
- Equivalence class size distribution: log-log histograms of $|E(r)|$ for the raw data and for the optimal release
Execution Results
Configurations evaluated : 216 (24.16 s)
Raw data : R2 = 0.7770, records at risk (k<5) = 100.000%
Feasible configurations (risk <= 5%) : 46
Optimal configuration:
age bin width = 5 years, ZIP digits kept = 1, income bin width = 50,000
R2 = 0.6231 (80.2% of raw utility)
records at risk = 1.730%, average risk = 0.0368, k_min = 1
Top 5 feasible configurations:
age_w zip_d inc_w at_risk avg_risk k_min r2
5 1 50000 0.017300 0.036767 1 0.623082
10 1 25000 0.024200 0.037767 1 0.622082
40 2 50000 0.040967 0.065333 1 0.621828
10 1 50000 0.009667 0.021133 1 0.615203
40 2 100000 0.029000 0.039800 1 0.610392

Interpreting the Results
The raw data is a privacy disaster
With all attributes at full resolution, essentially 100% of records are unique. Every record sits in an equivalence class of size 1. You can see this in the bottom-right histogram, where the entire red mass is piled at $|E| = 1$. Releasing this data would give an attacker who knows a neighbor’s age, gender, ZIP and approximate income a near-certain match.
The raw data also gives the best model, with an out-of-sample $R^2$ of roughly 0.78. This is the ceiling against which every anonymized release is judged.
Risk falls off a cliff, not a slope
The risk surface (top middle) is the most instructive plot. Risk does not decrease smoothly with generalization. It stays near 1.0 across most of the grid and then drops sharply only when the ZIP code is cut to 1–2 digits. The reason is combinatorial. With 30,000 records spread over $10^{d_z}$ ZIP prefixes × age bins × income bins × 2 genders, the expected class size is
$$
\mathbb{E}|E| \approx \frac{N}{10^{d_z} \cdot n_a \cdot n_i \cdot 2}.
$$
Equivalence classes reach an average size of 5 only once the denominator falls to roughly 6,000. ZIP code is by far the most identifying attribute, because each extra digit multiplies the number of cells by ten.
Utility degrades gracefully, and unevenly
The utility surface (top left) behaves very differently.
- Dropping ZIP digits 4–5 costs almost nothing. They carry no signal in the true model, only identifying power. This is the “free lunch” region of anonymization.
- Dropping digit 3 costs a little, since $\gamma$ has a standard deviation of 400.
- Dropping digits 1–2 costs a lot, because $\alpha$ and $\beta$ are large regional effects.
- Age generalization is cheap up to about 10 years. The cubic polynomial fitted on bin midpoints still tracks the convex age curve well. At 40-year bins only about three age groups remain and the curvature is lost.
The optimum
Among the 46 feasible schemes, the winner keeps 5-year age bins, only the first ZIP digit, and 50k income bins. It retains about 80% of the raw utility ($R^2 \approx 0.62$) while only about 1.7% of records remain at risk, well inside the 5% budget.
The runners-up in the console’s top-5 table show that the solution space is quite flat near the top:
- (10-year age, 1 ZIP digit, 25k income) is within 0.001 in $R^2$.
- (40-year age, 2 ZIP digits, 50k income) reaches almost the same $R^2$ by a completely different route. It gives up nearly all age detail in exchange for the second ZIP digit and the large regional effect $\beta$.
This second route matters in practice. Two schemes with the same headline utility can serve very different analyses. A geographic health-equity study would prefer the 2-digit ZIP version. An actuarial age-pricing model would prefer the 5-year age version. “Maximize utility” always has to be read as “maximize utility for a specific downstream task”.
The Pareto front shows where to negotiate
The bottom-left plot is the one to bring to a data governance meeting. The Pareto front rises in steps, and each step corresponds to giving up or restoring one ZIP digit:
- Around $R_{\text{at-risk}} \approx 10^{-3}$, $R^2$ jumps from about 0.5 to about 0.6. That is the gain from keeping the first ZIP digit instead of suppressing ZIP entirely.
- Just to the right of the 5% line, $R^2$ jumps again to about 0.7. That is the second ZIP digit, which the constraint forbids.
So the key policy question is simply: is a 5% at-risk budget the right one? Relaxing it to around 10% would buy about 0.1 of $R^2$. Tightening it to 0.5% costs only a few hundredths. A plot like this makes the price of every privacy decision explicit, instead of leaving it as an argument between “privacy people” and “data people”.
The heatmap: which combinations can work at all
The feasibility heatmap (bottom middle) shows that keeping 3 or more ZIP digits is never feasible, however coarse age and income become. Two digits work only together with 40-year age bins. Almost all usable releases live in the “1 ZIP digit” column, where the darkest cells (5–10 year age bins) are the sweet spot.
Equivalence class distribution
The bottom-right histogram compares the raw and optimal releases. After optimal generalization, the bulk of records moves into classes of size 30–80, far above $k = 5$. A small tail (the ~1.7% at-risk records) remains below the dashed $k = 5$ line. In a real release these would be handled by local suppression, either masking a cell or dropping the record. Because they are so few, this barely affects utility, which is exactly why the at-risk-share formulation beats strict global $k$-anonymity in practice.
Takeaways
- Treat anonymization as constrained optimization. Fix the risk budget $\varepsilon$, define utility as performance on the real downstream task, and search the generalization lattice.
- Attributes are not equal. High-cardinality quasi-identifiers such as ZIP code dominate risk, while the signal often sits in their coarse levels. Truncate those aggressively first.
- Measure utility honestly. Target encoding without out-of-fold computation leaks the label and can make heavily masked data look better than raw data. That artifact would quietly push you toward the wrong release.
- Engineer the risk computation. Packing quasi-identifiers into a single integer key and using
np.uniquemakes evaluating hundreds of schemes on tens of thousands of records nearly instant. - Show the Pareto front, not only the optimum. The threshold is a policy choice, and stakeholders deserve to see what each point of privacy costs in analytical power.















