Differential privacy: definition, mechanisms and proofs
Introduce differential privacy and its guarantee under auxiliary information. Develop its definition and hypothesis-testing interpretation, randomized response, sensitivity and the Laplace mechanism, postprocessing, group privacy and basic composition, with empirical checks and implementation pitfalls.
After this lesson you can
- State (ε, δ)-DP with its adjacency relation and explain what it does and does not protect.
- Prove randomized response and the Laplace mechanism are ε-DP and calculate their error.
- Prove postprocessing, group privacy and basic composition.
- Translate an (ε, δ) guarantee into a bound on membership-test TPR and FPR.
- Empirically check the DP inequality for an implementation and detect failures such as missing clipping.
Before you start
A guarantee about changes to one individual
Anonymization can reduce direct identifiers without preventing other sources from helping infer information. Differential privacy starts with an explicit adjacency relation: for example, databases differing by the presence of one record. A randomized mechanism is -DP if, for every ordered pair of neighboring databases and every measurable output set ,
The relation is usually symmetric, so the condition is also required in the other direction. The guarantee limits the effect of an individual change under that adjacency; it does not prevent inference of population statistics or automatically protect other outputs not included in the mechanism. The book by Dwork and Roth develops the definition and its mechanisms.
Before calculating , fix what counts as a unit: a record, a conversation or all contributions of one user. If a user contributes ten records and adjacency changes just one, a per-record guarantee is not automatically a per-user guarantee with the same budget. Identify the full channel too: releasing the model, validation metrics and selection decisions can reveal more than releasing only the output of a private mechanism.
The inequality does not assume the observer lacks external information: any rule combining a private output with fixed auxiliary information is postprocessing. This does not make every prior belief false or remove correlations between people; the interpretation concerns distributional change when the protected unit changes.
The size of matters in the application context: with , the multiplicative factor is , so the bound can be very wide. A “DP” label without parameters, protected unit and complete mechanism does not itself communicate how much protection is offered.
With pure privacy and two simple hypotheses about neighboring databases, Bayes offers another reading: if prior probabilities are positive, posterior odds are prior odds multiplied by a likelihood ratio bounded between and almost surely. The guarantee limits how much the output can move that comparison; it does not require posterior membership probability to be small if it was already high before observation. For this pointwise interpretation needs more care: is not generally the probability that the entire guarantee “fails” for one person.
Reading it as a statistical test
The testing interpretation takes as outputs leading to a “member” declaration. If includes the person and does not, the definition gives . The complementary inequality and swapping databases also restrict the possible region; this line alone is a necessary bound, not the whole region. Empirically observed rates have uncertainty and do not by themselves prove violation of a population guarantee.
For example, if , and population FPR is 0.01, that inequality bounds TPR by 0.02. It does not say every test achieves that rate. In practice both are estimated from finite samples; a TPR lower bound and FPR upper bound can support an audit provided threshold selection and joint interval coverage are incorporated into the procedure.
If both rates and are exactly known, the same calculation gives for when that expression is positive. The figure applies this calculation to synthetic counts from the previous lesson as a mathematical hypothesis; it does not present those finite counts as population probabilities. If a plausible FPR interval includes larger values, the inferred bound can fall substantially. Thus a useful audit separates the set choosing the threshold from the set measuring rates.
To construct the figure’s two boundaries, write , and . Applying DP to the positive event gives and, swapping databases, . Applying it to the negative event gives and . Solving for and combining with yields
When both boundaries coincide with : an output identically distributed for both databases does not let that test distinguish them better than its own false-positive rate. For larger parameters the region widens. This is not a performance prediction for a specific attack; a particular mechanism may offer less information than its bound permits.
Randomized response
In randomized response, with probability answer with the true bit and otherwise with a fair independent bit. Final correctness probability is and the maximum ratio between probabilities of an output for opposite bits is . For ,
To check this without trusting the formula, consider output “yes”. If the true bit is one, its probability is . If zero, only the random branch can give “yes”, with probability . The ratio is as stated; for output “no” the same two values are swapped. Since the output space has two elements, the bound on both outputs covers any event. If the answer is independent of the bit and ; if , an output possible for one bit has zero probability for the other and there is no finite of pure privacy.
If , the final answer is correct with probability and . If is the probability of choosing the truthful answer before the random branch, final accuracy is and . These are two different parameterizations.
If the true fraction is , the probability of a “yes” answer is . For , is unbiased and, under i.i.d. responses, its variance is . The smaller is, the smaller is, but estimation error increases. This is local privacy: each person randomizes their answer before sending it.
Unbiasedness follows by substituting : subtracting the expected coin contribution leaves , and dividing by leaves . For variance, a randomized response is Bernoulli with parameter under the population model, so ; dividing by multiplies variance by . This calculation does not require observing each person’s true answer. It does require the mechanism used to be as described and participants not to share a coin in a way that makes their answers dependent.
Central privacy sets a different trust boundary: an aggregator with access to original records calculates a result and adds noise before releasing it. The central guarantee constrains public output under defined adjacency, while the aggregator still sees input. In the local version, the aggregator receives an already randomized answer. No utility comparison is complete without stating who is trusted with input and what is released.
The estimator may fall below zero or above one in a finite sample. Clipping it to the valid interval can ease presentation but introduces bias and is another operation that must be documented. The figure shows the unclipped estimate and an approximate normal interval; near boundaries or with few answers, an appropriate binomial interval is preferable to treating that approximation as exact.
The variance above models true bits as independent draws from a population. If the bits of the people are considered a fixed population and only the mechanism is repeated, condition on those bits and calculate variance by summing conditional variances of their answers. The two experiments do not answer exactly the same question. In both cases, doubling reduces standard error by a factor near if other parameters stay fixed, not by half.
Sensitivity and Laplace
Global sensitivity is the maximum of over neighboring databases. The Laplace mechanism adds independent noise of scale to each component of a vector query. For a scalar output, the density ratio is bounded by thanks to the triangle inequality. For a count with add/remove adjacency, : if , , mean absolute error is 2 and standard deviation is .
In one dimension the density is proportional to . Its log ratio for versus is , at most . The bound holds for each output and integrating it gives the bound for any event. In several dimensions exponents add and the norm gives the same conclusion. This proves the mechanism’s property in ideal arithmetic; a sample of values is insufficient to prove it.
In a histogram where each record belongs to one category, adding or removing a record changes one coordinate by one, so sensitivity is 1. Replacing one category with another can decrement one coordinate and increment another: sensitivity can be 2. The same noise code with scale 1/ε does not cover both conventions without adjusting the analysis.
Histograms also show why a contribution must be defined: if a person can appear in several categories, one person can modify more than one coordinate. Bound how many they contribute or clip their whole vector before using per-person sensitivity. Also, publishing the histogram and then its sum is postprocessing the same output; querying the database again for another sum is an additional release requiring its own accounting.
The Gaussian comparison merits a distinction. For two normal outputs with means 0 and 1 and common standard deviation , log ratio is unbounded over all . The event maximizing is that where the log ratio exceeds , namely . For this pair, the smallest additive term in that direction is
The reverse direction has the same value by symmetry. For example, and give approximately 0.1269. The figure evaluates this expression using a numerical approximation of and shows a finite window; the value of uses full tails. Balle and Wang analyze Gaussian calibration. This calculation for one pair does not replace checking global sensitivity and all neighboring pairs in an application.
For a sum of records clipped to divided by a fixed public number , with absence represented by zero and , add/remove sensitivity is . Replacing one value by another gives . A mean with variable private denominator requires another analysis or a privatized count: do not simply reuse a fixed-size formula. Clipping is part of the mechanism and its bounds must be fixed without using private data.
Global sensitivity takes the worst case over all admissible neighboring databases, not just the largest change observed in a test sample. If before adding noise you calculate a minimum or maximum from private data and use it as a clipping bound, that step also accesses data and must be incorporated into the guarantee. Choosing public bounds too narrow reduces noise but clips values and can introduce bias; choosing them too wide increases sensitivity and error. That decision is part of the utility tradeoff, not a universal constant.
Operations on guarantees
Database-independent postprocessing applied to a private output does not worsen its parameters. Basic composition adds and across successive releases, including adaptive ones under standard conditions. For changes of up to records, pure privacy gives group bound ; under approximate privacy also grows and must be calculated. Repeating a query consumes budget even if its answers are averaged.
To see why, a randomized function of the output is represented by a kernel assigning each original output a probability of landing in a final event. Integrating the DP inequality against that kernel, which does not query the database, preserves the bound. For pure composition of two mechanisms, the joint probability ratio decomposes into the ratio for the first output and conditional ratio for the second; if the latter meets its guarantee for each first output, factors multiply and logarithms add. Arguments for also control exceptional masses and yield the summed basic bound.
Group privacy is obtained by chaining databases differing by one record. With per record, a bound is , with the second parameter capped at 1 if necessary. This cost does not say every real group suffers exactly that loss; it is a general guarantee derived from the definition.
In an adaptive implementation, the next query can depend on previous results. Basic composition still applies when each mechanism, conditioned on every allowed history, has the declared guarantee. If history is also used to select parameters through additional access to private data, that access is part of the mechanism. Accounting must include all queries actually released, not only those appearing in the final visualization.
The figure fixes a count’s true value and assumes independent noise in each query. Laplace noise of scale has variance ; the mean of independent copies has variance . This statistical improvement explains why repeating queries is a privacy decision, not merely an innocuous repetition. Bound holds whether all answers or only a function of them are delivered; in the latter case a tighter bound may exist, but must be proved for that specific output.
Do not confuse reusing an answer with rerunning a query. If you already published a private count, plotting it and communicating the same value again postprocesses that output. If you ask the database for the count again and add fresh noise, you have run another mechanism. Likewise, setting a usage limit in an interface does not prove budget accounting: logs must cover all access paths and relevant releases.
Laboratory: checking without confusing simulation and proof
The simulation checks one randomized-response instance; the Laplace bound is checked algebraically on a grid. A finite grid or histogram never certifies the inequality for all outputs. The NumPy generator is educational and does not itself constitute a production implementation resistant to finite-precision leakage. Mironov studies how naive floating-point implementations can violate ideal-mechanism properties.
When running the cell, compare the survey estimate with 0.3 and observed absolute errors with . They need not match exactly: each uses finitely many draws. The last line compares standard deviation of averaging twenty noise samples with . This error reduction does not justify forgetting the twenty accesses: joint answers have the composed budget described above.
import numpy as np
rng = np.random.default_rng(30)
q, p, n = .5, .3, 100000
truth = rng.random(n) < p
answer = np.where(rng.random(n) < q, truth, rng.random(n) < .5)
estimate = (answer.mean()-(1-q)/2)/q
print('proporción estimada', round(estimate,4), 'real', p, 'epsilon', round(np.log((1+q)/(1-q)),4))
epsilon, sensitivity = .5, 1.
b = sensitivity/epsilon
z = np.linspace(-20,20,10001)
log_ratio = (np.abs(z-sensitivity)-np.abs(z))/b
print('máximo log-cociente en rejilla', round(log_ratio.max(),4))
assert log_ratio.max() <= epsilon+1e-12
# Histograma con un registro por categoría: sensibilidad L1 de añadir/quitar = 1.
counts = np.array([4., 3., 2.])
print('histograma ruidoso sintético', np.round(counts+rng.laplace(0,1/epsilon,3),3))
# Una suma recortada dividida por N público; ausencia representada por cero.
bounded = np.clip([.2, .8, 1.4], 0, 1); N = 10
print('media de plazas fija con ruido', round(float(bounded.sum()/N+rng.laplace(0,1/(N*epsilon))),3))
for eps in (.25, .5, 1., 2.):
noise = rng.laplace(0,1/eps,20000)
print('epsilon',eps,'error absoluto medio',round(float(np.abs(noise).mean()),3),
'esperado',1/eps)
many = rng.laplace(0,1/epsilon,(10000,20)).mean(axis=1)
print('desviación al promediar 20',round(float(many.std()),3),
'teórica',round(float(np.sqrt(2)/(epsilon*np.sqrt(20))),3))Detecting a sensitivity failure
Suppose ε=1 is claimed for a sum divided by ten public slots and Laplace noise of scale 0.1 is added, as if all values lay in [0,1]. Without clipping, two neighboring databases can differ by value 100: their outputs are centered at 0 and 10. The event “output greater than 5” has very different probabilities. The following calculation uses analytic Laplace tails and logarithmic arithmetic; it demonstrates a counterexample to the idealized mechanism, not every possible implementation.
import math
b = .1
log_p_out = math.log(.5)-5/b
p_in = 1-.5*math.exp(-5/b)
log_ratio = math.log(p_in)-log_p_out
print('log cociente del evento', round(log_ratio,3), 'epsilon anunciado', 1)
assert log_ratio > 1The proof of that failure need not recover any real record. Construct two synthetic databases allowed by the implementation and identify an output event whose ratio violates the claimed bound. The contrast between unclipped value 100 and assumed [0,1] produces a change of 10 in the mean of ten slots, one hundred times the assumed sensitivity of 0.1. If values are unbounded, global sensitivity is also unbounded. An event’s probability ratio can exceed even when every individual run returns a plausible number.
To correct the mechanism, clipping must happen before summation and bounds must be public or obtained by an accounted private procedure. Then calibrate noise to sensitivity of the clipped result for the declared adjacency. If changing from add/remove to replacement, or deciding to divide by the observed record count, changing a label is insufficient: rederive the maximum change of the entire query.
Exercises
Step 1 of 2. What bounds the logarithm of the density ratio?
Step 1 of 2. Why does postprocessing the output not increase ε?
def private_fixed_sum_mean(x, lower, upper, N, epsilon, rng):
pass