Differential privacy
Differential privacy adds calibrated random noise so that any single person's presence in the data cannot be detected — with a mathematical bound, not a promise.
- 14 min read
- 3 reading levels
- Updated
Read these first
On this page 8
One lesson, three depths. Pick the one that fits you today — you can switch any time.
Beginner — No maths. Plain English.
The short answer
Differential privacy adds noise on purpose, so that no answer can reveal whether any one person was in the data.
The analogy you have already lived
Imagine a class survey asking a question nobody wants to answer honestly: have you ever cheated in an exam?
Here is the trick a good teacher uses. Before answering, every student flips a coin in secret. Heads, answer truthfully. Tails, flip again and answer yes for heads, no for tails.
Now every "yes" on the sheet has an innocent explanation. A student can say the coin made them write it, and nobody can prove otherwise. That is plausible deniability, and it is real, not a feeling.
But the teacher still learns the truth about the class. Roughly a quarter of the answers are random noise in a known amount, so that amount can be subtracted. The group answer survives. The individual answer does not exist.
That is differential privacy in one paragraph. It is the oldest and cleanest idea in the field, and it dates to 1965, long before machine learning.
Why this beats deleting names
Older methods try to hide people by removing or blurring identifying columns. Attackers keep defeating those methods by combining the released data with something else they already have.
Differential privacy changes the rules. Instead of guessing which combinations are dangerous, it makes one promise:
The answer you get would be almost exactly as likely if any single person's data had been removed.
That promise holds no matter what other information the attacker has, today or in twenty years. It is the only privacy definition with that property.
The dial called epsilon
The strength of the promise is one number, written as epsilon. You will see it everywhere in this field.
- Small epsilon — more noise, stronger promise, less useful answers.
- Large epsilon — less noise, weaker promise, more useful answers.
There is no free setting. Epsilon is a policy choice made by humans, and pretending it is a technical default is how organisations end up with meaningless guarantees.
small epsilon ◄─────────────────────► large epsilon
strong privacy accurate answers
noisy answers weak privacyWhere you have already used it
- Apple collects typing and emoji statistics from iPhones with noise added on the device.
- Google Chrome used it to gather usage statistics without identifying browsers.
- The 2020 United States census published its results through a differentially private system.
In all three cases, individual records never left in a usable form. Only noisy aggregates did.
What is honestly hard here
Noise costs accuracy, and the cost lands hardest on small groups.
Counting people in a large city with noise is fine. Counting people in a village of forty is not — the noise can be as large as the answer. Differential privacy protects the individual and can make small communities statistically invisible. That is a genuine, unresolved tension in census work.
Also, the budget runs out. Every question you answer from the same data spends some privacy, and it does not come back.
Remember this
- Noise is added on purpose, in a measured amount, before anyone sees the answer.
- The promise: the answer barely changes whether or not you are in the data.
- Epsilon is the dial, small is stronger, and choosing it is a human decision.
What to learn next
- Federated learning — the other half of the private-training story.
- Privacy in machine learning — the attacks this defends against.
- Probability — the distributions the noise is drawn from.
Developer — Code and libraries.
Two mechanisms, both in twenty lines
You do not need a library to understand this. The two foundational mechanisms are short enough to write from memory.
- Randomised response — noise added on the user's device, before data is collected. This is local differential privacy.
- Laplace mechanism — noise added to an aggregate query by a trusted curator. This is central differential privacy.
Setup
pip install numpyBoth mechanisms, run end to end
import numpy as np
rng = np.random.default_rng(42)
# ---------- 1. Randomised response: privacy applied BEFORE the data leaves the phone ----------
N = 20_000
truth = (rng.random(N) < 0.30).astype(int) # 30% of people would truthfully answer "yes"
def randomised_response(bits, eps):
p = np.exp(eps) / (1 + np.exp(eps)) # probability of answering honestly
honest = rng.random(len(bits)) < p
return np.where(honest, bits, 1 - bits), p
print(f"RANDOMISED RESPONSE true proportion in this sample = {truth.mean():.3f}")
for eps in (0.5, 1.0, 2.0, 5.0):
noisy, p = randomised_response(truth, eps)
# undo the known amount of lying to recover an unbiased estimate
est = (noisy.mean() - (1 - p)) / (2 * p - 1)
print(f" eps={eps:>4} answer-honestly prob={p:.3f} "
f"raw mean={noisy.mean():.3f} corrected estimate={est:.3f}")
# ---------- 2. Laplace mechanism on a count ----------
print("\nLAPLACE MECHANISM true count = 4137 (sensitivity 1: one person changes it by 1)")
true_count = 4137
for eps in (0.1, 0.5, 1.0, 5.0):
draws = rng.laplace(0.0, 1.0 / eps, 10_000)
print(f" eps={eps:>4} noise scale={1/eps:>6.1f} "
f"typical |error|={np.abs(draws).mean():6.2f} "
f"one release -> {true_count + draws[0]:9.2f}")
# ---------- 3. What the guarantee means for ONE person ----------
print("\nINDISTINGUISHABILITY how much more likely is any output if YOU are in the data?")
for eps in (0.1, 1.0, 5.0):
print(f" eps={eps:>4} at most {np.exp(eps):.2f} times more likely")RANDOMISED RESPONSE true proportion in this sample = 0.301 eps= 0.5 answer-honestly prob=0.622 raw mean=0.455 corrected estimate=0.315 eps= 1.0 answer-honestly prob=0.731 raw mean=0.407 corrected estimate=0.298 eps= 2.0 answer-honestly prob=0.881 raw mean=0.346 corrected estimate=0.298 eps= 5.0 answer-honestly prob=0.993 raw mean=0.303 corrected estimate=0.301 LAPLACE MECHANISM true count = 4137 (sensitivity 1: one person changes it by 1) eps= 0.1 noise scale= 10.0 typical |error|= 9.95 one release -> 4158.02 eps= 0.5 noise scale= 2.0 typical |error|= 2.01 one release -> 4137.17 eps= 1.0 noise scale= 1.0 typical |error|= 0.99 one release -> 4137.24 eps= 5.0 noise scale= 0.2 typical |error|= 0.20 one release -> 4136.97 INDISTINGUISHABILITY how much more likely is any output if YOU are in the data? eps= 0.1 at most 1.11 times more likely eps= 1.0 at most 2.72 times more likely eps= 5.0 at most 148.41 times more likely
Reading the three blocks
Randomised response recovers the population and destroys the individual. At eps=1.0 every person answers honestly only 73% of the time, so the raw mean is 0.407 — badly wrong. Correcting for the known lying rate recovers 0.298 against a truth of 0.301. No individual answer is trustworthy; the aggregate is.
Noise scale is 1/eps, so the cost of privacy is not linear in intuition. Going from eps=1.0 to eps=0.1 multiplies the typical error tenfold. On a count of 4,137 an error of 10 is nothing. On a count of 12 it is everything. Sensitivity to noise depends entirely on the size of the true answer, which is why small groups suffer.
The last block is the guarantee, stated plainly. At eps=1.0, any released output is at most 2.72 times more likely with your record than without it. At eps=5.0 that factor is 148, which is a weak promise wearing a formal-looking coat. Whenever a product claims differential privacy, ask for epsilon and for the unit it applies to.
Line by line
p = np.exp(eps) / (1 + np.exp(eps)) is the honesty probability that makes binary randomised response satisfy epsilon-DP exactly. The ratio between the two possible output probabilities is p / (1 - p) = exp(eps), which is the definition.
(noisy.mean() - (1 - p)) / (2 * p - 1) inverts the known noise. This is the debiasing step, and forgetting it is the most common bug — the raw mean is always pulled toward 0.5.
rng.laplace(0.0, 1.0 / eps, ...) uses sensitivity 1, correct for a counting query where adding or removing one person changes the count by at most one. Get sensitivity wrong and the guarantee is void. For a sum over an unbounded value, sensitivity is unbounded, and you must clip the value first.
The composition rule you cannot avoid
Answer two questions at eps=1.0 each from the same dataset and you have spent eps=2.0 total. Basic composition adds.
That makes epsilon a budget, not a setting. Once spent, it is gone; re-querying the same data does not restore it. Advanced composition and Rényi DP give tighter accounting — roughly growing with the square root of the number of queries rather than linearly — which is what makes DP-SGD feasible over thousands of training steps.
Training a model with DP
The standard algorithm is DP-SGD (Abadi et al., 2016), and it changes two lines of a training loop:
- Clip each per-example gradient to a maximum norm
C. This bounds one person's influence, which is sensitivity. - Add Gaussian noise to the summed gradient before the optimiser step.
In practice use a maintained library — Opacus for PyTorch, TensorFlow Privacy — because the privacy accountant is where the subtle bugs live. Expect real costs: slower steps, a large batch size requirement, and an accuracy drop that is severe on small datasets and modest on large ones.
Common mistakes
Rolling your own accountant. The mechanism is easy and the accounting is not. Use opacus.accountants or dp_accounting and report the epsilon it computes.
Not clipping before summing. Without a bound on each contribution, sensitivity is unbounded and no amount of noise gives a guarantee.
Reporting epsilon without the unit. Per query, per user per day, or over the whole training run? An epsilon without a scope is not a claim.
Tuning hyperparameters on the private data and not counting it. Every evaluation on the real data spends budget. This is widely ignored in published results.
Applying DP and skipping the deduplication and access-control work. DP bounds inference from the released output. It does nothing about the copy of the raw data sitting in an unsecured bucket.
Try it yourself
Change true_count to 12 — a query about a small village rather than a city — and rerun the Laplace block. At eps=0.1 the noise routinely exceeds the answer, and negative counts appear. That is the moment the privacy-utility trade stops being abstract.
What to learn next
- Federated learning — the other half of the private-training story.
- Privacy in machine learning — the attacks this defends against.
- Probability — the distributions the noise is drawn from.
Researcher — Mathematics and papers.
Definition
A randomised mechanism $\mathcal{M}$ with domain $\mathcal{D}$ and range $\mathcal{R}$ satisfies $(\varepsilon, \delta)$-differential privacy if for all neighbouring datasets $D, D'$ differing in one record, and all measurable $S \subseteq \mathcal{R}$:
$$ \Pr[\mathcal{M}(D) \in S] \;\le\; e^{\varepsilon} \Pr[\mathcal{M}(D') \in S] + \delta $$
- $\varepsilon \ge 0$ — the privacy loss parameter; smaller is stronger.
- $\delta \ge 0$ — the probability of the guarantee failing outright. Convention requires $\delta \ll 1/n$, since $\delta = 1/n$ admits a mechanism that publishes a random record in full.
- Neighbouring — under add/remove adjacency, $|D \triangle D'| = 1$; under replace-one, $|D| = |D'|$ and they differ in one entry. The two give different constants and are frequently conflated in papers.
$\delta = 0$ is pure $\varepsilon$-DP.
Properties that make it usable
Post-processing immunity. For any function $g$, if $\mathcal{M}$ is $(\varepsilon,\delta)$-DP then $g \circ \mathcal{M}$ is too. No downstream analysis can undo the guarantee.
Group privacy. A group of $k$ correlated individuals is protected at $k\varepsilon$. This degrades quickly, which matters when records are not independent — families, repeated visits, one user with many rows.
Composition. Basic: $k$ mechanisms at $\varepsilon_i$ compose to $\sum_i \varepsilon_i$. Advanced (Dwork, Rothblum, Vadhan, 2010): for $k$ mechanisms each $(\varepsilon, \delta)$-DP, the composition is $(\varepsilon', k\delta + \delta')$-DP with
$$ \varepsilon' = \sqrt{2k \ln(1/\delta')}\,\varepsilon + k\varepsilon(e^{\varepsilon} - 1) $$
The $\sqrt{k}$ leading term is what makes iterative training tractable.
Mechanisms
Laplace. For $f: \mathcal{D} \to \mathbb{R}^k$ with $\ell_1$-sensitivity $\Delta_1 f = \max_{D \sim D'} |f(D) - f(D')|_1$, releasing $f(D) + \text{Lap}(\Delta_1 f / \varepsilon)^k$ is $\varepsilon$-DP.
Gaussian. For $\ell_2$-sensitivity $\Delta_2 f$, adding $\mathcal{N}(0, \sigma^2)$ with $\sigma \ge \Delta_2 f \sqrt{2\ln(1.25/\delta)}/\varepsilon$ gives $(\varepsilon,\delta)$-DP for $\varepsilon < 1$. Balle and Wang (2018) give the exact analytic calibration, which is tighter and valid for all $\varepsilon$.
Exponential. For non-numeric outputs with a utility function $u(D, r)$, sample $r$ with probability $\propto \exp(\varepsilon u(D,r) / (2\Delta u))$.
Rényi DP and the moments accountant
Composition under $(\varepsilon,\delta)$-DP is lossy. Mironov (2017) defines $(\alpha, \bar\varepsilon)$-RDP via the Rényi divergence of order $\alpha$:
$$ D_\alpha\big(\mathcal{M}(D) \,|\, \mathcal{M}(D')\big) \le \bar\varepsilon $$
RDP composes by simple addition of $\bar\varepsilon$ at fixed $\alpha$, and converts to $(\varepsilon,\delta)$-DP at the end. Abadi et al. (2016) introduced the equivalent moments accountant, which reduced the reported epsilon for deep learning by roughly an order of magnitude versus advanced composition — the result that made DP deep learning practical.
Privacy amplification by subsampling is the other essential ingredient: running an $\varepsilon$-DP mechanism on a random $q$-fraction of the data yields roughly $O(q\varepsilon)$-DP. Sampling is not a Poisson formality here; the accountant's correctness depends on the sampling scheme actually implemented matching the one assumed.
DP-SGD
Per step: sample a lot by Poisson sampling with rate $q$; compute per-example gradients $g_i$; clip $\bar g_i = g_i / \max(1, |g_i|_2 / C)$; release $\frac{1}{L}\left(\sum_i \bar g_i + \mathcal{N}(0, \sigma^2 C^2 I)\right)$.
Empirical findings that reliably transfer:
- Large batches help. The signal-to-noise ratio of the averaged gradient improves with lot size, and the sampling rate is accounted separately.
- The clipping norm matters more than the learning rate. Tune $C$ first; a common heuristic is the median per-example gradient norm.
- Pretraining transforms the trade-off. De et al. (2022) show that DP fine-tuning of a publicly pretrained model reaches accuracy close to non-private baselines at moderate $\varepsilon$, whereas DP training from scratch on the same task does not.
- Cost falls on the tail. Bagdasaryan et al. (2019) show DP-SGD degrades accuracy disproportionately on under-represented subgroups. Privacy and fairness interact adversarially, and reporting only aggregate accuracy hides it.
What epsilon values mean in practice
There is no consensus threshold, and honest reporting acknowledges that. Deployed examples span a wide range: the 2020 US Census used a per-attribute budget in the low tens; Apple has reported per-day, per-use-case budgets in the single digits to low tens; academic work on image classification commonly reports $\varepsilon \in [1, 8]$.
Two cautions. Epsilons are not comparable across different adjacency definitions, granularities (record versus user), or accounting methods. And the guarantee is worst-case over all adversaries, so a large formal $\varepsilon$ can still correspond to a small empirical attack success — which is an argument for reporting both, not for reporting neither.
Papers
- Dwork, McSherry, Nissim and Smith, Calibrating Noise to Sensitivity in Private Data Analysis, TCC 2006
- Dwork and Roth, The Algorithmic Foundations of Differential Privacy, 2014 — the standard reference text
- Abadi et al., Deep Learning with Differential Privacy, CCS 2016 — arxiv.org/abs/1607.00133
- Mironov, Rényi Differential Privacy, CSF 2017 — arxiv.org/abs/1702.07476
- Balle and Wang, Improving the Gaussian Mechanism, ICML 2018 — arxiv.org/abs/1805.06530
- De et al., Unlocking High-Accuracy Differentially Private Image Classification through Scale, 2022 — arxiv.org/abs/2204.13650
- Bagdasaryan, Poursaeed and Shmatikov, Differential Privacy Has Disparate Impact on Model Accuracy, NeurIPS 2019
- Warner, Randomized Response, JASA 1965 — the original mechanism
What to learn next
- Federated learning — the other half of the private-training story.
- Privacy in machine learning — the attacks this defends against.
- Probability — the distributions the noise is drawn from.