Algorithmcore
Output perturbation
Also called sensitivity-based model perturbation.
Trains a model by regularized empirical risk minimization and adds noise scaled to the sensitivity of the minimizer.
- Time
- O(K n d) worst
- Space
- O(d) extra
- Where
- K = the number of solver iterations; d = the dimension; n = the number of examples
- Model
- Real RAM
- Properties
- randomizedrandomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kamalika Chaudhuri, Claire Monteleoni, Anand D. Sarwate, 2008
Output perturbation trains a model in the normal way and then adds random noise to the trained parameters. The training is regularized empirical risk minimization: minimize the average loss plus . The regularizer makes the minimizer stable, so that it moves by at most when one of the examples changes. Noise scaled to that sensitivity then makes the released model -differentially private. Chaudhuri and Monteleoni (2008) used it for logistic regression, and Chaudhuri, Monteleoni and Sarwate (2011) stated it for strongly convex losses as their Algorithm 1. It is the simplest private learner for convex models, and the baseline that objective perturbation improves on.
In plain words
Train the model on the private data as usual, but with a penalty on large weights. That penalty has a side effect: changing one example can move the trained weights only a little, and we can compute how much at most.
So add random noise to the weights, large enough to cover that small move. An observer who sees the noisy weights cannot tell whether any one example was in the data.
More data or a larger penalty makes the possible move smaller, and so the noise smaller. With few examples the noise can be larger than the weights.
The problem
The data is with , and . The neighbor relation is replace: is with one example changed to another, and is public. The loss is for a convex differentiable with ; the code uses the logistic loss . The goal is an -DP vector with a small regularized risk
The algorithm
OUTPUT-PERTURBATION(D, Lambda, epsilon)- 1
f* <- argmin over f of J_D(f) ▷ exact minimizer, unique since J_D is strongly convex - 2
beta <- n Lambda epsilon / 2 ▷ 2/(n Lambda) is the L2 sensitivity of f* - 3
b <- a vector with density proportional to exp(-beta |b|) - 4
return f* + b
Line L1 is the non-private training. The code runs gradient descent with the step , since the logistic risk is -smooth, and stops when the gradient norm is at most . Line L2 sets the rate of the noise from the sensitivity bound of Lemma 7 and Corollary 8 of Chaudhuri, Monteleoni and Sarwate. Line L3 draws the noise in two parts: the norm is a sum of independent exponential draws of rate , which is the Gamma law of shape , and the direction is a Gaussian vector divided by its norm. In one dimension this is the Laplace mechanism with scale . In dimensions it is not the same as Laplace noise in each coordinate: the noise is a function of the L2 norm, to match the L2 sensitivity. Line L4 releases the noisy model. Any use of it afterwards is private by post-processing.
The code uses floats and a seeded generator, which shows the algorithm but is not a safe deployment. The analysis assumes exact real noise, and floating-point samplers can leak (Mironov 2012). A deployment needs a cryptographic source of randomness and a sampler built for DP, such as the discrete Gaussian for the Gaussian variant.
Example
Take examples in the plane, and .
| 1 | (0.6, 0.8) | +1 |
| 2 | (1, 0) | +1 |
| 3 | (-0.6, 0) | -1 |
| 4 | (0, -1) | -1 |
Line L1 gives , with . Replace example 4 by : the minimizer becomes , at distance from , below the bound . Line L2 gives . With the seed 9 the code draws , of norm , and returns .
The noise here is larger than the model, whose norm is . The table shows how the noise shrinks with for , and ; the mean norm of is .
| sensitivity | mean | ||
|---|---|---|---|
| 4 | 1 | 1 | 2 |
| 100 | 0.04 | 25 | 0.08 |
| 1000 | 0.004 | 250 | 0.008 |
| 10000 | 0.0004 | 2500 | 0.0008 |
Correctness
Lemma (sensitivity). For replace neighbors, . The proof uses only the -strong convexity of and the bound .
Theorem (privacy). The output of line L4 is -DP under replace. The output density on is with , and the triangle inequality bounds the log ratio of the two densities by .
An inexact solver. If line L1 returns a point within of the minimizer for every input, the same proof gives . The stopping rule of the code gives . A solver that stops after a fixed number of steps with no such bound gives no proved guarantee.
The correctness proof of this page proves all three claims. The tests check the minimizer against bisection in one dimension, the sensitivity bound on 500 random replace pairs, the log density ratio on a grid, and the law of the noise norm.
Proof: Output perturbation of regularized ERM is epsilon-DPfull
The data is with and . The neighbor relation is replace: differs from in one example. The loss is convex and differentiable with for all ; the logistic loss has . Let
and (line L1). is -strongly convex, so exists and is unique.
Lemma 1 (sensitivity; Chaudhuri, Monteleoni and Sarwate, Corollary 8). For replace neighbors , .
Proof. Say replaces example by . Write , so . The gradient of is , of norm at most . So for all .
Let and . Then and . A -strongly convex differentiable function satisfies . With the Cauchy-Schwarz inequality,
which gives the claim (it is trivial when ).
Lemma 2 (the noise). Let . If is a sum of independent variables and is an independent uniform unit vector in , then has the density with . A Gaussian vector divided by its norm is a uniform unit vector.
Proof. A sum of independent variables has the Gamma density on . In polar coordinates, the density is a function of only, so its direction is uniform and independent of the norm, and the norm has the density , since the sphere of radius has area . The two laws match. Integrating against this area gives . The standard Gaussian density on depends only on the norm, so the direction of a Gaussian vector is uniform.
Theorem 1 (privacy). With (line L2), the output (lines L3 and L4) is -DP under replace.
Proof. By Lemma 2 the output has the density on and on . For every , by the triangle inequality and Lemma 1,
Integrating over an event gives .
Theorem 2 (an approximate minimizer). Suppose line L1 is a deterministic solver whose output satisfies for every . Then the mechanism with in place of is -DP. The gradient descent of the code stops at , which gives .
Proof. The triangle inequality gives , and the proof of Theorem 1 then gives . For the stopping rule, strong convexity gives .
Theorem 3 (the size of the noise). .
Proof. By Lemma 2, is a sum of variables of mean .
Theorem 1 is the privacy claim of the page. Theorem 2 shows that the claim survives an inexact solver only with a larger , and Theorem 3 gives the cost in accuracy. The code samples from floats, so it follows the analysis only up to floating-point effects; that is a limit of the code, not of the theorem.
Complexity
The model is the real RAM, with one exponential or Gaussian draw counted as .
- Training. One gradient costs . Gradient descent on a -strongly convex and -smooth risk needs steps to reach the gradient norm , so line L1 costs .
- Noise. Line L3 costs draws, and line L4 costs .
- Space. The extra space is beyond the data.
The private part adds almost nothing to the cost of training.
Properties
- A black box. Any solver can be used for line L1, as long as it returns the exact minimizer or a point with a known distance bound. The private step only touches the output.
- Pure DP. The guarantee is -DP with , under replace neighbors.
- Needs strong convexity. Without the regularizer, the minimizer can jump far when one example changes, and the sensitivity has no bound. The noise grows like , so a small costs accuracy through the noise and a large costs accuracy through the bias.
- Noise of order . The expected norm of is . Chaudhuri, Monteleoni and Sarwate prove learning bounds for it and show that objective perturbation needs fewer examples for the same accuracy in their bounds and experiments.
- The hypotheses matter. The bound needs and . The squared loss has no such bound on , so linear regression needs bounded labels and a bounded domain for before the method applies.
Variants and improvements
- Gaussian noise. With and for , the Gaussian mechanism gives -DP. Its noise norm grows like , not .
- Objective perturbation. Put the noise into the objective before minimizing it, not into the minimizer. It needs a twice differentiable loss and usually gives better accuracy.
- Output perturbation of SGD. For a fixed number of passes of SGD on a strongly convex loss, the sensitivity of the final iterate can be bounded directly, and the same noise applies. Wu et al. (SIGMOD 2017) built a system on this idea.
- Other models. The same step applies to any statistic with a known sensitivity, for example a private mean. When the sensitivity is not known in advance, subsample and aggregate gives a bound by design.
- Noisy training. DP-SGD adds noise during training, so it does not need convexity or an exact minimizer.
When to use it
Use output perturbation for a convex model with a strongly convex regularizer, such as -regularized logistic regression or a support vector machine with a smooth loss, when the training code must stay as it is. It is simple to audit: the only private step is one line of noise. When accuracy matters more, try objective perturbation first. For non-convex models it does not apply, and DP-SGD is the usual choice.
Pitfalls
- Noise per coordinate. Line L3 with independent Laplace noise of scale in each coordinate is calibrated to the L1 sensitivity, which can be times the L2 bound, so it does not give -DP for . Line L3 must draw the norm from the Gamma law and a uniform direction, or use the L1 sensitivity .
- A stopped solver. Line L1 run for a fixed number of steps with no bound on the distance to the minimizer breaks the sensitivity bound. Line L1 must stop at a known gradient norm , and line L2 must then use in place of to keep the total at .
- Features out of the ball. Line L1 run on data with breaks the bound of line L2. Scale or clip each to the unit ball with a rule that does not depend on the data, before line L1.
- A data-dependent . Line L2 with picked by cross-validation on the private data leaks through the choice. Line L2 must use a fixed in advance, or the tuning must be private and counted in the budget.
- Add/remove neighbors. Line L2 assumes replace neighbors with a public . Under add/remove the size changes, and the bound must be recomputed for that relation.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the security and privacy pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Checkers for differential privacy on small finite examples.
A dataset is a tuple of records from a finite universe. A pmf is a dict from
outputs to probabilities; the probabilities may be fractions.Fraction (exact)
or float. A mechanism pmf is a function from a dataset to the pmf of the
output of the mechanism on that dataset.
This module holds the neighbor relations, the privacy loss, the hockey-stick
and Renyi divergences, the pure and approximate DP checks over a list of
neighbor pairs, an empirical pmf, the Hoeffding margin for Monte Carlo
checks, and a grid check of a log density ratio. It holds no mechanism, no
noise sampler and no accountant: those belong to the pages that define them.
Natural logarithms are used throughout, as in the DP literature.
"""
from __future__ import annotations
import math
from fractions import Fraction
from typing import Callable, Hashable, Iterable, Mapping, Sequence, Union
Number = Union[int, float, Fraction]
Pmf = Mapping[Hashable, Number]
Dataset = tuple
Pair = tuple[Dataset, Dataset]
def neighbors_add_remove(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets at add/remove distance 1 from dataset.
A neighbor removes one record, or appends one record from the universe.
Datasets are treated as multisets: a removal keeps the order of the other
records, and equal results are listed once. Cost: O(n (n + |universe|)).
"""
x = tuple(dataset)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
y = x[:i] + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
for v in universe:
y = x + (v,)
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def neighbors_replace(dataset: Sequence[Hashable], universe: Iterable[Hashable]) -> list[Dataset]:
"""All datasets of the same size that differ from dataset in one record.
The record at index i is replaced by a different value of the universe.
Equal multisets are listed once. Cost: O(n^2 |universe|).
"""
x = tuple(dataset)
values = list(universe)
out: list[Dataset] = []
seen: set[Dataset] = set()
for i in range(len(x)):
for v in values:
if v == x[i]:
continue
y = x[:i] + (v,) + x[i + 1:]
key = tuple(sorted(y, key=repr))
if key not in seen:
seen.add(key)
out.append(y)
return out
def _ratio(a: Number, b: Number) -> Number:
if isinstance(a, (int, Fraction)) and isinstance(b, (int, Fraction)):
return Fraction(a) / Fraction(b)
return float(a) / float(b)
def privacy_loss(p: Pmf, q: Pmf) -> dict[Hashable, float]:
"""The privacy loss ln(p(y) / q(y)) at each output y with p(y) > 0 or q(y) > 0.
The value is +inf where q(y) = 0 < p(y) and -inf where p(y) = 0 < q(y).
Outputs with p(y) = q(y) = 0 are left out. Cost: O(|support|).
"""
out: dict[Hashable, float] = {}
for y in set(p) | set(q):
a, b = p.get(y, 0), q.get(y, 0)
if a == 0 and b == 0:
continue
if b == 0:
out[y] = math.inf
elif a == 0:
out[y] = -math.inf
else:
out[y] = math.log(_ratio(a, b))
return out
def max_privacy_loss(p: Pmf, q: Pmf) -> float:
"""The largest privacy loss ln(p(y) / q(y)) over the outputs y with p(y) > 0.
Returns -inf when p has no output of positive probability. Cost: O(|support|).
"""
best = -math.inf
for y, v in privacy_loss(p, q).items():
if p.get(y, 0) > 0 and v > best:
best = v
return best
def hockey_stick(p: Pmf, q: Pmf, epsilon: float) -> float:
"""The hockey-stick divergence: the sum over y of max(0, p(y) - e^epsilon q(y)).
It is sup over sets S of P(S) - e^epsilon Q(S). Cost: O(|support|).
"""
a = math.exp(epsilon)
total = 0.0
for y in set(p) | set(q):
d = float(p.get(y, 0)) - a * float(q.get(y, 0))
if d > 0:
total += d
return total
def is_pure_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, tol: float = 1e-12) -> bool:
"""True if max privacy loss <= epsilon + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if max_privacy_loss(p, q) > epsilon + tol or max_privacy_loss(q, p) > epsilon + tol:
return False
return True
def is_approx_dp(mech_pmf: Callable[[Dataset], Pmf], pairs: Iterable[Pair], epsilon: float, delta: float, tol: float = 1e-12) -> bool:
"""True if the hockey-stick divergence at e^epsilon is <= delta + tol for both orders of every pair.
Precondition: mech_pmf returns the exact output pmf of the mechanism.
Cost: O(|pairs|) calls of mech_pmf and O(|support|) work per call.
"""
for x, y in pairs:
p, q = mech_pmf(x), mech_pmf(y)
if hockey_stick(p, q, epsilon) > delta + tol or hockey_stick(q, p, epsilon) > delta + tol:
return False
return True
def renyi_divergence(p: Pmf, q: Pmf, alpha: float) -> float:
"""The Renyi divergence of order alpha > 1: ln(sum_y p(y)^alpha q(y)^(1 - alpha)) / (alpha - 1).
Returns +inf when q(y) = 0 < p(y) for some y. Cost: O(|support|).
"""
if alpha <= 1:
raise ValueError("alpha must be greater than 1")
s = 0.0
for y in set(p) | set(q):
a, b = float(p.get(y, 0)), float(q.get(y, 0))
if a == 0:
continue
if b == 0:
return math.inf
s += a * (a / b) ** (alpha - 1)
return math.log(s) / (alpha - 1)
def empirical_pmf(samples: Iterable[Hashable]) -> dict[Hashable, float]:
"""The fraction of the samples equal to each value. Cost: O(number of samples)."""
counts: dict[Hashable, int] = {}
n = 0
for s in samples:
counts[s] = counts.get(s, 0) + 1
n += 1
if n == 0:
return {}
return {k: c / n for k, c in counts.items()}
def hoeffding_margin(n: int, beta: float) -> float:
"""The margin t = sqrt(ln(2 / beta) / (2 n)).
For n independent samples of a [0, 1] variable, the empirical mean is
within t of the true mean with probability at least 1 - beta (Hoeffding).
"""
if n <= 0 or not 0 < beta < 1:
raise ValueError("need n >= 1 and 0 < beta < 1")
return math.sqrt(math.log(2 / beta) / (2 * n))
def log_ratio_grid(logpdf_x: Callable[[float], float], logpdf_y: Callable[[float], float], grid: Iterable[float]) -> float:
"""The largest |logpdf_x(z) - logpdf_y(z)| over the points z of the grid.
Use it to check the log density ratio of a continuous mechanism on two
neighbors. Cost: O(|grid|) calls of each function.
"""
best = 0.0
for z in grid:
d = abs(logpdf_x(z) - logpdf_y(z))
if d > best:
best = d
return best
output_perturbation.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/output-perturbation/. The authors are listed in prov/DE6SYB.jsonl.
"""Output perturbation for regularized logistic regression (Chaudhuri, Monteleoni and Sarwate, Algorithm 1).
The regularized empirical risk is
J(f, D) = (1/n) sum_i ln(1 + exp(-y_i f.x_i)) + (Lambda/2) |f|^2,
with |x_i| <= 1 and y_i in {-1, +1}. Its minimizer moves by at most 2/(n Lambda)
in L2 norm when one example is replaced. The algorithm releases the minimizer
plus a noise vector b with density proportional to exp(-beta |b|), with
beta = n Lambda epsilon / 2, which is epsilon-DP under replace neighbors.
The minimizer is found by gradient descent with the step 1/(1/4 + Lambda), so
it is exact only up to the tolerance. Floats and random.Random are used for
the noise, so this code shows the algorithm and is not a safe deployment.
"""
from __future__ import annotations
import math
import random
from typing import Sequence
Vector = list[float]
Example = tuple[Sequence[float], int]
def dot(a: Sequence[float], b: Sequence[float]) -> float:
return sum(x * y for x, y in zip(a, b))
def norm(a: Sequence[float]) -> float:
return math.sqrt(dot(a, a))
def _sigmoid(z: float) -> float:
if z >= 0:
return 1 / (1 + math.exp(-z))
e = math.exp(z)
return e / (1 + e)
def risk(f: Sequence[float], data: Sequence[Example], lam: float) -> float:
"""J(f, D): the mean logistic loss plus (lam/2) |f|^2."""
total = 0.0
for x, y in data:
z = -y * dot(f, x)
total += z + math.log1p(math.exp(-z)) if z > 0 else math.log1p(math.exp(z))
return total / len(data) + lam / 2 * dot(f, f)
def risk_gradient(f: Sequence[float], data: Sequence[Example], lam: float) -> Vector:
"""The gradient of J: (1/n) sum_i -y_i x_i sigmoid(-y_i f.x_i) + lam f."""
n = len(data)
g = [lam * fi for fi in f]
for x, y in data:
s = _sigmoid(-y * dot(f, x))
for j, xj in enumerate(x):
g[j] -= y * xj * s / n
return g
def minimize_risk(data: Sequence[Example], lam: float, tol: float = 1e-11, max_steps: int = 100000) -> Vector:
"""The minimizer of J by gradient descent with step 1/(1/4 + lam).
J is lam-strongly convex and (1/4 + lam)-smooth when |x_i| <= 1, so the
iteration converges linearly. It stops when |grad J| <= tol, which puts the
iterate within tol/lam of the minimizer. Cost: O(n d) per iteration.
"""
d = len(data[0][0])
f = [0.0] * d
step = 1 / (0.25 + lam)
for _ in range(max_steps):
g = risk_gradient(f, data, lam)
if norm(g) <= tol:
return f
f = [fi - step * gi for fi, gi in zip(f, g)]
return f
def sample_noise(d: int, beta: float, rng: random.Random) -> Vector:
"""A vector b in R^d with density proportional to exp(-beta |b|).
The norm |b| has the Gamma(d, 1/beta) law, the sum of d Exp(beta) draws,
and the direction is uniform on the sphere. Cost: O(d) draws.
"""
r = sum(rng.expovariate(beta) for _ in range(d))
while True:
u = [rng.gauss(0.0, 1.0) for _ in range(d)]
s = norm(u)
if s > 0:
return [r * ui / s for ui in u]
def output_perturbation(data: Sequence[Example], lam: float, epsilon: float, rng: random.Random) -> Vector:
"""An epsilon-DP model for regularized logistic regression (replace neighbors).
Precondition: n >= 1, |x_i| <= 1, y_i in {-1, +1}, lam > 0, epsilon > 0.
Cost: O(n d) per iteration of the minimizer plus O(d) for the noise.
"""
if lam <= 0 or epsilon <= 0:
raise ValueError("need lam > 0 and epsilon > 0")
if any(norm(x) > 1 + 1e-12 or y not in (-1, 1) for x, y in data):
raise ValueError("need |x| <= 1 and y in {-1, +1}")
n = len(data)
f_star = minimize_risk(data, lam) # @line L1
beta = n * lam * epsilon / 2 # @line L2
b = sample_noise(len(f_star), beta, rng) # @line L3
return [fi + bi for fi, bi in zip(f_star, b)] # @line L4
def sensitivity_bound(n: int, lam: float) -> float:
"""2 / (n lam), the L2 sensitivity of the minimizer under replace (CMS Corollary 8)."""
return 2 / (n * lam)
def output_log_density(z: Sequence[float], center: Sequence[float], beta: float) -> float:
"""The log density of the output at z, given the minimizer center; the normalizer is included."""
d = len(z)
# The normalizer of exp(-beta |b|) in R^d is 2 pi^(d/2) Gamma(d) / (Gamma(d/2) beta^d).
log_norm = math.log(2) + d / 2 * math.log(math.pi) + math.lgamma(d) - math.lgamma(d / 2) - d * math.log(beta)
return -beta * norm([a - b for a, b in zip(z, center)]) - log_norm
test_output_perturbation.py 147 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/output-perturbation/. The authors are listed in prov/DE6SYB.jsonl.
import math
import random
import pytest
import dpkit
from output_perturbation import (
minimize_risk,
norm,
output_log_density,
output_perturbation,
risk,
risk_gradient,
sample_noise,
sensitivity_bound,
)
def random_point(d, rng):
"""A point of the unit ball."""
while True:
x = [rng.uniform(-1, 1) for _ in range(d)]
if norm(x) <= 1:
return x
def random_data(n, d, rng):
return [(random_point(d, rng), rng.choice((-1, 1))) for _ in range(n)]
EXAMPLE = [((0.6, 0.8), 1), ((1.0, 0.0), 1), ((-0.6, 0.0), -1), ((0.0, -1.0), -1)]
def test_check_values():
f = minimize_risk(EXAMPLE, 0.5)
assert abs(f[0] - 0.4368) < 1e-4 and abs(f[1] - 0.3532) < 1e-4
other = EXAMPLE[:3] + [((0.0, 1.0), -1)]
g = minimize_risk(other, 0.5)
assert abs(g[0] - 0.4568) < 1e-4 and abs(g[1] + 0.0642) < 1e-4
assert abs(norm([a - b for a, b in zip(f, g)]) - 0.4178) < 1e-4
assert sensitivity_bound(4, 0.5) == 1.0
assert sensitivity_bound(100, 0.1) == pytest.approx(0.2)
def test_bad_input():
with pytest.raises(ValueError):
output_perturbation(EXAMPLE, 0.0, 1.0, random.Random(0))
with pytest.raises(ValueError):
output_perturbation([((2.0, 0.0), 1)], 0.5, 1.0, random.Random(0))
def bisect_1d(data, lam):
"""Independent oracle in one dimension: the zero of the increasing derivative of J, by bisection."""
lo, hi = -10.0, 10.0
for _ in range(200):
mid = (lo + hi) / 2
if risk_gradient([mid], data, lam)[0] > 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
def test_minimizer_against_bisection():
rng = random.Random(1)
for _ in range(500):
n = rng.randint(1, 8)
lam = rng.uniform(0.2, 1.0)
data = random_data(n, 1, rng)
assert abs(minimize_risk(data, lam)[0] - bisect_1d(data, lam)) < 1e-9
def test_sensitivity_bound_on_random_replace_pairs():
rng = random.Random(2)
worst = 0.0
for _ in range(500):
n = rng.randint(1, 8)
d = rng.randint(1, 2)
lam = rng.uniform(0.2, 1.0)
data = random_data(n, d, rng)
other = list(data)
other[rng.randrange(n)] = (random_point(d, rng), rng.choice((-1, 1)))
f1 = minimize_risk(data, lam)
f2 = minimize_risk(other, lam)
gap = norm([a - b for a, b in zip(f1, f2)])
assert gap <= sensitivity_bound(n, lam) + 1e-9
worst = max(worst, gap * n * lam / 2)
assert worst > 0.3
def test_minimizer_is_stationary_and_minimal():
rng = random.Random(3)
data = random_data(10, 3, rng)
f = minimize_risk(data, 0.3)
assert norm(risk_gradient(f, data, 0.3)) < 1e-10
for _ in range(50):
g = [fi + rng.uniform(-0.1, 0.1) for fi in f]
assert risk(g, data, 0.3) >= risk(f, data, 0.3)
def test_output_density_ratio_is_at_most_epsilon():
rng = random.Random(4)
for _ in range(20):
n = rng.randint(2, 6)
lam = rng.uniform(0.2, 1.0)
eps = rng.uniform(0.2, 2.0)
data = random_data(n, 2, rng)
other = list(data)
other[0] = (random_point(2, rng), -other[0][1])
f1, f2 = minimize_risk(data, lam), minimize_risk(other, lam)
beta = n * lam * eps / 2
grid = [(i / 4, j / 4) for i in range(-24, 25) for j in range(-24, 25)]
loss = dpkit.log_ratio_grid(
lambda z: output_log_density(z, f1, beta),
lambda z: output_log_density(z, f2, beta),
grid,
)
assert loss <= eps + 1e-9
assert loss <= beta * norm([a - b for a, b in zip(f1, f2)]) + 1e-9
def gamma_cdf_integer_shape(t, d, beta):
s = sum((beta * t) ** k / math.factorial(k) for k in range(d))
return 1 - math.exp(-beta * t) * s
def test_noise_norm_and_direction():
rng = random.Random(5)
n = 2000
d, beta = 3, 2.0
samples = [sample_noise(d, beta, rng) for _ in range(n)]
margin = dpkit.hoeffding_margin(n, 1e-6)
for t in (0.5, 1.0, 1.5, 2.5):
emp = sum(1 for b in samples if norm(b) <= t) / n
assert abs(emp - gamma_cdf_integer_shape(t, d, beta)) <= margin
for j in range(d):
emp = sum(1 for b in samples if b[j] > 0) / n
assert abs(emp - 0.5) <= margin
def test_private_model_runs_and_is_reproducible():
a = output_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
b = output_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
assert a == b and len(a) == 2
History
Dwork, McSherry, Nissim and Smith (TCC 2006) defined the sensitivity method: add noise scaled to how much one record can change the output. Chaudhuri and Monteleoni (NIPS 2008) applied it to regularized logistic regression, bounded the sensitivity of the minimizer, and proposed objective perturbation as a better method. Chaudhuri, Monteleoni and Sarwate (JMLR 2011) extended both methods to general strongly convex ERM and to kernels, proved generalization bounds, and compared the methods on real data.
References
- Kamalika Chaudhuri, Claire Monteleoni and Anand D. Sarwate, Differentially private empirical risk minimization, Journal of Machine Learning Research 12, 2011, pages 1069 to 1109, Algorithm 1 (Section 3.1), Theorem 6 (its privacy), Lemma 7 (the sensitivity of a strongly convex minimizer) and Corollary 8 (the bound 2/(n Lambda))
- Kamalika Chaudhuri and Claire Monteleoni, Privacy-preserving logistic regression, Advances in Neural Information Processing Systems 21 (NIPS 2008), the sensitivity method for regularized logistic regression and its comparison with objective perturbation
- Cynthia Dwork, Frank McSherry, Kobbi Nissim and Adam Smith, Calibrating noise to sensitivity in private data analysis, TCC 2006, adding noise scaled to the sensitivity of a function
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DE6SYB Edit this page History Report an error Markdown