Algorithmadvanced
Objective perturbation
Also called Chaudhuri-Monteleoni-Sarwate perturbation.
Adds a random linear term to a strongly convex empirical risk before minimizing it, which gives differentially private learning.
- 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
Objective perturbation trains a model privately by changing the training problem, not the trained model. It adds a random linear term to a strongly convex regularized empirical risk, and releases the exact minimizer of the new objective. The noise vector has a density proportional to . Since the minimizer and the noise determine each other one to one, the density of the output has a closed form, and one example can change it by at most a factor . Chaudhuri and Monteleoni (2008) introduced the method for logistic regression, and Chaudhuri, Monteleoni and Sarwate (2011) stated it for convex losses with a bounded second derivative as their Algorithm 2. For those losses it usually gives better accuracy than output perturbation at the same .
In plain words
Output perturbation trains a model and then shakes the result. Objective perturbation shakes the question instead. Before training, it tilts the training goal by a small random amount, and then it trains as usual on the tilted goal.
The tilt is chosen so that any trained model could have come from many different tilts. If one person's data changes, a slightly different tilt gives the same model, and that tilt is almost as likely. So an observer cannot tell whether that person was in the data.
The tilt is divided by the number of examples, so with more data it has less effect on the model.
The problem
The data is with , and . The neighbor relation is replace: is with one example changed, and is public. The loss is convex and twice differentiable with and ; the code uses the logistic loss, with . The goal is an -DP vector with a small regularized risk
The algorithm
OBJECTIVE-PERTURBATION(D, Lambda, epsilon, c)- 1
epsilon' <- epsilon - ln(1 + 2c/(n Lambda) + c^2/(n^2 Lambda^2)) - 2
if epsilon' > 0 then Delta <- 0 - 3
else Delta <- c / (n (e^(epsilon/4) - 1)) - Lambda; epsilon' <- epsilon / 2 - 4
b <- a vector with density proportional to exp(-(epsilon'/2) |b|) - 5
f_priv <- argmin over f of J_D(f) + (1/n) b.f + (Delta/2) |f|^2 - 6
return f_priv
Lines L1 to L3 split the budget between two sources of privacy loss. The noise term pays . The curvature of the loss pays the rest: one example changes the Hessian of the objective by a rank-one matrix, and that changes the density of the output by the factor or less. Line L1 reserves twice that factor, as in the analysis of Chaudhuri, Monteleoni and Sarwate. When is too small for that, is not positive, and line L3 adds the extra regularizer , chosen so that the curvature part costs at most and the noise gets the other half.
Line L4 draws the noise as in output perturbation: the norm is a sum of exponential draws of rate and the direction is uniform. Line L5 is a normal training run. The objective is -strongly convex, so the minimizer is unique; the code finds it by gradient descent with the step and stops at a gradient norm of . The noise in line L5 enters through its gradient: the minimizer is the point where the gradient of equals .
The code uses floats and a seeded generator, so it shows the algorithm but is not a safe deployment. The analysis assumes exact real noise and an exact minimizer, and floating-point samplers can leak (Mironov 2012). A deployment needs a cryptographic source of randomness and samplers built for DP, such as the discrete Gaussian for the Gaussian variant.
Example
Take the data of the output perturbation page: 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 , so line L2 sets , and line L4 uses . With the seed 9 the code draws , of norm . Line L5 then gives , against the non-private minimizer . With four examples the tilt is large, and the model even changes sign.
Replace example 4 by . On a grid of models , the largest log ratio of the two output densities is , below . The table shows the budget split for other settings, with .
| branch | |||||
|---|---|---|---|---|---|
| 4 | 0.5 | 1 | L2 | 0.7644 | 0 |
| 4 | 0.05 | 0.5 | L3 | 0.25 | 0.4194 |
| 1000 | 0.01 | 0.1 | L2 | 0.0506 | 0 |
| 1000 | 0.001 | 0.1 | L3 | 0.05 | 0.0089 |
Correctness
Theorem (Chaudhuri, Monteleoni and Sarwate, Theorem 9). Lines L1 to L6 are -DP under replace.
The proof has three steps. First, for each the objective has one minimizer, and can be recovered from it: . So is a bijection, and the change of variables formula gives the output density , where . Second, one example changes by a vector of norm at most 2, since , so the factor changes by at most . Third, one example changes by a rank-one term, and the matrix determinant lemma bounds the ratio of the determinants by . Lines L1 to L3 make the two factors multiply to at most .
The correctness proof of this page gives all the steps. It bounds the determinant ratio by one factor of , which is sharper than the squared factor of the paper, so the algorithm as stated has some slack. The tests check the minimizer against bisection in one dimension, the recovery of from the output, the density formula against the exact law in one dimension, and the density ratio on a grid in both branches.
Proof: Objective perturbation of regularized ERM is epsilon-DPfull
The data is with , and . The neighbor relation is replace: differs from in one example, and is public. The loss is convex and twice continuously differentiable with and for all . The logistic loss has and , where , so . Let and
Lines L1 to L3 compute and , line L4 draws with the density for , and line L5 returns the minimizer of
Lemma 1 (the noise determines the output, and back). For every , has a unique minimizer . Define
Then if and only if . So is a bijection of with the inverse .
Proof. is -strongly convex and differentiable, so it has exactly one minimizer, and it is the only point where the gradient is zero. That gradient is zero exactly when . Every has the minimizer with , so is onto. If , both points minimize the same function, so .
Lemma 2 (the density of the output). Let . The output has the density
Proof. is continuously differentiable with the Jacobian matrix , since . is symmetric and , so the Jacobian is invertible everywhere. By Lemma 1 and the inverse function theorem, is a bijection with a inverse. The change of variables formula gives, for every event ,
and because is positive definite.
Lemma 3 (the noise moves little). For replace neighbors and every , .
Proof. Say replaces by . The sums for and share all terms but one, and the term is the same. So . Each of the two vectors has norm at most .
Lemma 4 (the determinant moves little). For replace neighbors and every , .
Proof. Let , so . With and , we have and . The matrix determinant lemma gives , and the same for . So
since , the largest eigenvalue of is at most , and .
Chaudhuri, Monteleoni and Sarwate bound the same ratio by in the proof of their Theorem 9, with their Lemma 10 on the eigenvalues of a rank-two update. Lemma 4 is sharper by one factor. Algorithm 2 is set for the weaker bound, so it stays correct, and the proof below shows the slack.
Theorem (privacy). Lines L1 to L6 are -DP under replace.
Proof. By Lemma 2, for every ,
by the triangle inequality, Lemma 3 and Lemma 4. Note that , so line L1 sets . There are two cases.
- Line L2, and . The bound is .
- Line L3, . Then , so , and . Now , so . The new gives the bound .
In both cases for every , and integrating over an event gives .
What the proof needs. The proof uses the exact minimizer of line L5: it is a bijection of the noise, and its density has the closed form of Lemma 2. A solver that stops early returns a different random variable, and the theorem does not cover it. The code stops at a gradient norm of and samples with floats, so it follows the analysis only up to these numerical effects. The proof also needs to be twice differentiable with a bounded , which rules out the hinge loss, and .
Complexity
The model is the real RAM, with one exponential or Gaussian draw counted as .
- Training. One gradient costs . The objective of line L5 is -strongly convex and -smooth, so gradient descent needs steps to reach the gradient norm , and line L5 costs .
- The rest. Lines L1 to L3 cost and line L4 costs .
- Space. The extra space is beyond the data.
The cost is the cost of one non-private training run.
Properties
- Pure DP. The guarantee is -DP with , under replace neighbors with a public .
- Needs a smooth loss. The proof needs to exist and be bounded. The logistic loss and the Huber loss qualify; the hinge loss of the standard support vector machine does not. Chaudhuri, Monteleoni and Sarwate use a Huber version of the SVM for this reason.
- Needs the exact minimizer. The density formula holds only for the exact minimizer of line L5. A solver that stops early, or a constrained problem, changes the output law and is not covered.
- Better accuracy than output perturbation. Chaudhuri, Monteleoni and Sarwate prove bounds on the number of examples needed for a given generalization error, and the bound for objective perturbation is smaller than the bound for output perturbation. Their experiments on real data show the same order.
- The regularizer is part of the privacy. must be fixed in advance. Picking it on the private data leaks, and the paper gives a private tuning method that uses held-out parts of the data.
Variants and improvements
- Gaussian noise. Kifer, Smith and Thakurta (2012) gave an version with Gaussian noise and support for convex constraints and some non-smooth regularizers. Its noise norm grows like , not .
- Approximate minimizers. Iyengar et al. (2019) studied versions that allow an approximate solver for line L5, at the cost of extra noise on the output.
- Other regularizers. The analysis of Chaudhuri, Monteleoni and Sarwate allows any 1-strongly convex, twice differentiable regularizer in place of .
- Kernels. The paper also handles kernel methods by first mapping the data to random features, then running objective perturbation on them.
- No convexity. For non-convex models, DP-SGD is the usual choice.
When to use it
Use objective perturbation for a convex model with a smooth loss and an regularizer, such as regularized logistic regression, when a pure guarantee is required and the solver can reach the minimizer to high precision. It usually beats output perturbation in accuracy. Use output perturbation when the training code cannot be changed, and DP-SGD when the model is not convex or the data is too large to solve to high precision.
Pitfalls
- Skipping the budget split. Line L4 with in place of ignores the loss through the determinant, and the result is not -DP. Lines L1 to L3 must run, and line L4 must use .
- A negative budget. Line L2 run when gives a noise rate of zero or below, which has no meaning. Line L3 must replace by and add in that case.
- Forgetting the extra regularizer. Line L5 without the term after line L3 has set breaks the bound of the determinant. Line L5 must use the same .
- Scaling the noise wrong. Line L5 with the term in place of uses an objective whose risk part has a different scale from the one in the analysis. Keep the factor that matches , or rescale both.
- A non-smooth loss. Line L5 with the hinge loss has no bounded , and the determinant bound fails. Use a smooth loss, such as the Huber loss, with its in line L1.
- Early stopping. Line L5 run for a fixed small number of steps does not return the minimizer that the proof needs. Run the solver to a tight tolerance, or use a variant built for approximate solvers.
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
objective_perturbation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/objective-perturbation/. The authors are listed in prov/HFPG7H.jsonl.
"""Objective perturbation for regularized logistic regression (Chaudhuri, Monteleoni and Sarwate, Algorithm 2).
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}. The logistic loss l(z) = ln(1 + e^(-z))
has |l'| <= 1 and 0 < l'' <= c = 1/4. The algorithm draws a noise vector b
with density proportional to exp(-beta |b|) and returns the minimizer of
J(f, D) + (1/n) b.f + (Delta/2) |f|^2,
which is epsilon-DP under replace neighbors.
The minimizer is found by gradient descent, 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]
C_LOGISTIC = 0.25 # the bound on the second derivative of the logistic loss
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 perturbed_objective(f: Sequence[float], data: Sequence[Example], lam: float, b: Sequence[float], extra: float) -> float:
"""J(f, D) + (1/n) b.f + (extra/2) |f|^2, the objective of line L5."""
return risk(f, data, lam) + dot(b, f) / len(data) + extra / 2 * dot(f, f)
def perturbed_gradient(f: Sequence[float], data: Sequence[Example], lam: float, b: Sequence[float], extra: float) -> Vector:
"""The gradient of the objective of line L5."""
n = len(data)
return [g + bi / n + extra * fi for g, bi, fi in zip(risk_gradient(f, data, lam), b, f)]
def minimize_perturbed(data: Sequence[Example], lam: float, b: Sequence[float], extra: float,
tol: float = 1e-11, max_steps: int = 200000) -> Vector:
"""The minimizer of the objective of line L5 by gradient descent with step 1/(1/4 + lam + extra).
The objective is (lam + extra)-strongly convex and (1/4 + lam + extra)-smooth
when |x_i| <= 1, so the iteration converges linearly. It stops when the
gradient norm is at most tol. Cost: O(n d) per iteration.
"""
f = [0.0] * len(b)
step = 1 / (C_LOGISTIC + lam + extra)
for _ in range(max_steps):
g = perturbed_gradient(f, data, lam, b, extra)
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 privacy_parameters(n: int, lam: float, epsilon: float, c: float = C_LOGISTIC) -> tuple[float, float]:
"""The pair (epsilon', Delta) of lines L1 to L3. Cost: O(1)."""
eps_prime = epsilon - math.log(1 + 2 * c / (n * lam) + c * c / (n * n * lam * lam)) # @line L1
if eps_prime > 0:
extra = 0.0 # @line L2
else:
extra = c / (n * (math.exp(epsilon / 4) - 1)) - lam # @line L3
eps_prime = epsilon / 2
return eps_prime, extra
def objective_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 not data or any(norm(x) > 1 + 1e-12 or y not in (-1, 1) for x, y in data):
raise ValueError("need n >= 1, |x| <= 1 and y in {-1, +1}")
n, d = len(data), len(data[0][0])
eps_prime, extra = privacy_parameters(n, lam, epsilon)
b = sample_noise(d, eps_prime / 2, rng) # @line L4
f_priv = minimize_perturbed(data, lam, b, extra) # @line L5
return f_priv # @line L6
def noise_of(f: Sequence[float], data: Sequence[Example], lam: float, extra: float) -> Vector:
"""The unique b for which f minimizes the objective of line L5: b = -n (grad J(f) + extra f)."""
n = len(data)
return [-n * (g + extra * fi) for g, fi in zip(risk_gradient(f, data, lam), f)]
def jacobian_matrix(f: Sequence[float], data: Sequence[Example], lam: float, extra: float) -> list[Vector]:
"""A(f) = sum_i l''(y_i f.x_i) x_i x_i^T + n (lam + extra) I, minus the Jacobian of noise_of."""
n, d = len(data), len(f)
a = [[n * (lam + extra) if i == j else 0.0 for j in range(d)] for i in range(d)]
for x, y in data:
s = _sigmoid(y * dot(f, x))
w = s * (1 - s)
for i in range(d):
for j in range(d):
a[i][j] += w * x[i] * x[j]
return a
def log_det(a: Sequence[Sequence[float]]) -> float:
"""ln det a for a symmetric positive definite matrix, by Gaussian elimination. Cost: O(d^3)."""
m = [list(row) for row in a]
d = len(m)
total = 0.0
for k in range(d):
p = max(range(k, d), key=lambda i: abs(m[i][k]))
m[k], m[p] = m[p], m[k]
pivot = m[k][k]
if pivot <= 0:
raise ValueError("matrix is not positive definite")
total += math.log(pivot)
for i in range(k + 1, d):
r = m[i][k] / pivot
for j in range(k, d):
m[i][j] -= r * m[k][j]
return total
def output_log_density(f: Sequence[float], data: Sequence[Example], lam: float, epsilon: float) -> float:
"""The log density of the output of objective_perturbation at f, normalizer included.
By the change of variables b = noise_of(f), the density is
nu(noise_of(f)) det A(f), with nu(b) = exp(-beta |b|) / Z.
"""
n, d = len(data), len(f)
eps_prime, extra = privacy_parameters(n, lam, epsilon)
beta = eps_prime / 2
log_z = math.log(2) + d / 2 * math.log(math.pi) + math.lgamma(d) - math.lgamma(d / 2) - d * math.log(beta)
b = noise_of(f, data, lam, extra)
return -beta * norm(b) - log_z + log_det(jacobian_matrix(f, data, lam, extra))
test_objective_perturbation.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/objective-perturbation/. The authors are listed in prov/HFPG7H.jsonl.
import math
import random
import pytest
import dpkit
from objective_perturbation import (
C_LOGISTIC,
jacobian_matrix,
log_det,
minimize_perturbed,
noise_of,
norm,
objective_perturbation,
output_log_density,
perturbed_gradient,
perturbed_objective,
privacy_parameters,
sample_noise,
)
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():
eps_prime, extra = privacy_parameters(4, 0.5, 1.0)
assert eps_prime == pytest.approx(1 - 2 * math.log(1.125)) and extra == 0.0
assert eps_prime == pytest.approx(0.764434, abs=1e-6)
eps_prime, extra = privacy_parameters(4, 0.05, 0.5)
assert eps_prime == 0.25 and extra == pytest.approx(0.419401, abs=1e-6)
f = minimize_perturbed(EXAMPLE, 0.5, [0.0, 0.0], 0.0)
assert abs(f[0] - 0.4368) < 1e-4 and abs(f[1] - 0.3532) < 1e-4
g = objective_perturbation(EXAMPLE, 0.5, 1.0, random.Random(9))
assert abs(g[0] + 0.2786) < 1e-4 and abs(g[1] + 0.5192) < 1e-4
def test_bad_input():
with pytest.raises(ValueError):
objective_perturbation(EXAMPLE, 0.5, 0.0, random.Random(0))
with pytest.raises(ValueError):
objective_perturbation([((0.0, 1.5), 1)], 0.5, 1.0, random.Random(0))
def test_extra_regularizer_is_nonnegative_and_balances_the_budget():
rng = random.Random(1)
for _ in range(500):
n = rng.randint(1, 50)
lam = rng.uniform(0.001, 1.0)
eps = rng.uniform(0.05, 3.0)
eps_prime, extra = privacy_parameters(n, lam, eps)
assert eps_prime > 0 and extra >= 0
# The two parts of the privacy loss add up to at most epsilon.
assert eps_prime + 2 * math.log(1 + C_LOGISTIC / (n * (lam + extra))) <= eps + 1e-12
def bisect_1d(data, lam, b, extra):
"""Independent oracle in one dimension: the zero of the increasing derivative, by bisection."""
lo, hi = -100.0, 100.0
for _ in range(200):
mid = (lo + hi) / 2
if perturbed_gradient([mid], data, lam, [b], extra)[0] > 0:
hi = mid
else:
lo = mid
return (lo + hi) / 2
def test_minimizer_against_bisection():
rng = random.Random(2)
for _ in range(500):
n = rng.randint(1, 8)
lam = rng.uniform(0.2, 1.0)
extra = rng.choice((0.0, rng.uniform(0.0, 0.5)))
data = random_data(n, 1, rng)
b = rng.uniform(-5, 5)
f = minimize_perturbed(data, lam, [b], extra)
assert abs(f[0] - bisect_1d(data, lam, b, extra)) < 1e-9
def test_noise_is_recovered_from_the_output():
rng = random.Random(3)
for _ in range(100):
n = rng.randint(1, 6)
d = rng.randint(1, 3)
lam = rng.uniform(0.2, 1.0)
extra = rng.choice((0.0, 0.3))
data = random_data(n, d, rng)
b = sample_noise(d, rng.uniform(0.3, 2.0), rng)
f = minimize_perturbed(data, lam, b, extra)
back = noise_of(f, data, lam, extra)
assert norm([u - v for u, v in zip(back, b)]) < 1e-8
for _ in range(5):
g = [fi + rng.uniform(-0.1, 0.1) for fi in f]
assert perturbed_objective(g, data, lam, b, extra) >= perturbed_objective(f, data, lam, b, extra)
def test_log_det_against_closed_form():
rng = random.Random(4)
for _ in range(100):
a, c = rng.uniform(1, 3), rng.uniform(1, 3)
b = rng.uniform(-0.9, 0.9)
assert log_det([[a, b], [b, c]]) == pytest.approx(math.log(a * c - b * b))
@pytest.mark.parametrize("lam, eps", [(0.5, 1.0), (0.05, 0.5)])
def test_output_density_ratio_is_at_most_epsilon(lam, eps):
"""Both branches: Delta = 0 for (0.5, 1.0) and Delta > 0 for (0.05, 0.5), with n = 4."""
rng = random.Random(5)
grid = [(i / 4, j / 4) for i in range(-12, 13) for j in range(-12, 13)]
worst = 0.0
for _ in range(10):
data = random_data(4, 2, rng)
other = list(data)
other[rng.randrange(4)] = (random_point(2, rng), rng.choice((-1, 1)))
loss = dpkit.log_ratio_grid(
lambda f: output_log_density(f, data, lam, eps),
lambda f: output_log_density(f, other, lam, eps),
grid,
)
assert loss <= eps + 1e-9
worst = max(worst, loss)
assert worst > 0.1 * eps
def test_density_matches_the_exact_law_in_one_dimension():
"""In one dimension, f_priv <= t exactly when b >= noise_of(t), and b is Laplace."""
rng = random.Random(6)
data = random_data(5, 1, rng)
lam, eps = 0.3, 1.0
eps_prime, extra = privacy_parameters(5, lam, eps)
beta = eps_prime / 2
def exact_cdf(t):
u = noise_of([t], data, lam, extra)[0]
return 0.5 * math.exp(-beta * u) if u >= 0 else 1 - 0.5 * math.exp(beta * u)
# The integral of the density, by the trapezoid rule, matches the exact law.
lo, h = -60.0, 0.005
total, prev, t = 0.0, math.exp(output_log_density([lo], data, lam, eps)), lo
checks = {-2.0: None, -0.5: None, 0.0: None, 0.5: None, 2.0: None}
while t < 2.0 - 1e-12:
t += h
cur = math.exp(output_log_density([t], data, lam, eps))
total += (prev + cur) * h / 2
prev = cur
for key in checks:
if abs(t - key) < h / 2:
checks[key] = total
for key, value in checks.items():
assert value == pytest.approx(exact_cdf(key), abs=1e-3)
# The sampler matches the exact law.
m = 2000
samples = [objective_perturbation(data, lam, eps, rng)[0] for _ in range(m)]
margin = dpkit.hoeffding_margin(m, 1e-6)
for key in checks:
emp = sum(1 for s in samples if s <= key) / m
assert abs(emp - exact_cdf(key)) <= margin
def test_jacobian_matches_finite_differences():
rng = random.Random(7)
data = random_data(4, 2, rng)
f = [0.3, -0.2]
a = jacobian_matrix(f, data, 0.4, 0.1)
h = 1e-6
for j in range(2):
fp = list(f)
fp[j] += h
fm = list(f)
fm[j] -= h
col = [(u - v) / (2 * h) for u, v in zip(noise_of(fp, data, 0.4, 0.1), noise_of(fm, data, 0.4, 0.1))]
for i in range(2):
assert -col[i] == pytest.approx(a[i][j], abs=1e-5)
History
Chaudhuri and Monteleoni (NIPS 2008) studied private logistic regression. They bounded the sensitivity of the regularized minimizer for output perturbation, and they introduced objective perturbation as a new method with better accuracy. Chaudhuri, Monteleoni and Sarwate (JMLR 2011) extended it to convex losses with a bounded second derivative, added the extra regularizer for small , gave a private method to tune , extended it to kernels, and compared both methods on real data. Kifer, Smith and Thakurta (2012) extended it to constraints and to Gaussian noise.
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 2 (Section 3.2) and Theorem 9 (its privacy, with Lemma 10 on the determinant), the logistic loss with c = 1/4, and the comparison with Algorithm 1
- Kamalika Chaudhuri and Claire Monteleoni, Privacy-preserving logistic regression, Advances in Neural Information Processing Systems 21 (NIPS 2008), the new method that perturbs the objective of regularized logistic regression
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 HFPG7H Edit this page History Report an error Markdown