Algorithm Search⌘K

Algorithmintro

Randomized response

Also called Warner randomized response.

Each person answers a yes or no question truthfully with probability p and flips it otherwise, so the population rate can still be estimated.

Time
O(n) worst
Space
O(1) extra
Where
n = the number of people (one report each)
Properties
randomizedrandomized
Origin
Stanley L. Warner, 1965

Randomized response lets each person answer a yes or no question with a random flip, so that no single answer can be trusted, but the fraction of "yes" in the population can still be estimated. Each person tells the truth with probability p=eε/(1+eε)p = e^{\varepsilon} / (1 + e^{\varepsilon}) and gives the other answer otherwise. Then each report is ε\varepsilon-locally differentially private: no one, not even the collector, needs to be trusted with the true answers. Warner (1965) proposed it as a survey method, and it is the base of the local mechanisms such as RAPPOR.

In plain words

A survey asks a question that people do not like to answer, such as "did you cheat on a test?". Each person secretly flips a biased coin. If the coin says "truth", the person gives the true answer. If not, the person gives the opposite answer. The person who reads the answer does not see the coin.

So a "yes" can be a true "yes" or a flipped "no", and each person can deny the answer. But the coin has a known bias. Over many people, the share of flipped answers is predictable, and you can correct for it. The estimate of the true share is good when many people answer, and poor for a small group.

The problem

Each of nn people j=1,…,nj = 1, \ldots, n holds a private bit vj∈{0,1}v_j \in \{0, 1\}. The goal is an estimate of the true fraction π=1n∑jvj\pi = \frac1n \sum_j v_j, such that the report of each person is ε\varepsilon-differentially private with respect to that person's own bit.

This is the local model: a randomizer RR is ε\varepsilon-LDP if Pr⁡[R(v)=r]≤eεPr⁡[R(v′)=r]\Pr[R(v) = r] \le e^{\varepsilon} \Pr[R(v') = r] for all inputs v,v′v, v' and all outputs rr. For the whole vector of reports (R(v1),…,R(vn))(R(v_1), \ldots, R(v_n)), this is ε\varepsilon-differential privacy under replace neighbors: two datasets are neighbors when nn is the same and one bit differs.

The algorithm

The parameter is the exact number eεe^{\varepsilon}, a rational number at least 1, so that the truth probability pp is an exact fraction a/qa/q. For example, ε=ln⁡3\varepsilon = \ln 3 gives eε=3e^{\varepsilon} = 3 and p=3/4p = 3/4.

  1. RANDOMIZED-RESPONSE(v, e^epsilon) ▷ run by each person on the bit v
  2. 1p <- e^epsilon / (1 + e^epsilon) ▷ p = a / q in lowest terms
  3. 2c <- 1 if a uniform integer in {0, ..., q - 1} is below a, else 0
  4. 3if c = 1 then return v ▷ tell the truth
  5. 4return 1 - v ▷ give the other answer
  6. ESTIMATE(r_1, ..., r_n, e^epsilon) ▷ run by the collector on the reports
  7. 5lambda <- (r_1 + ... + r_n) / n ▷ the observed fraction of ones
  8. 6return (lambda - (1 - p)) / (2p - 1)

Line L2 draws a coin with Pr⁡[c=1]=p\Pr[c = 1] = p exactly, with one uniform integer. Lines L3 and L4 report the bit or its complement. The collector sees only the reports. Line L5 computes the fraction λ\lambda of ones among them. Each report is 1 with probability pv+(1−p)(1−v)p v + (1 - p)(1 - v), so E[λ]=pπ+(1−p)(1−π)=(2p−1)π+(1−p)\mathbb E[\lambda] = p\pi + (1 - p)(1 - \pi) = (2p - 1)\pi + (1 - p). Line L6 solves this for π\pi. It needs p>1/2p > 1/2, which means ε>0\varepsilon > 0.

The code uses a seeded generator so that the tests can repeat each run. A deployment needs a cryptographic source of randomness and an exact coin (Mironov 2012; Canonne, Kamath and Steinke 2020). Line L2 is exact when eεe^{\varepsilon} is rational.

Example

Take ε=ln⁡3\varepsilon = \ln 3, so p=3/4p = 3/4, a=3a = 3 and q=4q = 4. Eight people hold the bits v=(1,0,1,1,0,0,1,0)v = (1, 0, 1, 1, 0, 0, 1, 0), so the true fraction is π=1/2\pi = 1/2. Line L2 draws the integers 0,3,2,1,0,2,1,10, 3, 2, 1, 0, 2, 1, 1 from {0,1,2,3}\{0, 1, 2, 3\}.

person jj vjv_j draw cc (line L2) report rjr_j
1 1 0 1 1 (line L3)
2 0 3 0 1 (line L4)
3 1 2 1 1
4 1 1 1 1
5 0 0 1 0
6 0 2 1 0
7 1 1 1 1
8 0 1 1 0

Line L5 gives λ=5/8\lambda = 5/8. Line L6 gives (5/8−1/4)/(1/2)=3/4(5/8 - 1/4) / (1/2) = 3/4. The standard deviation of the estimate is p(1−p)/(n(2p−1)2)=3/32=0.306\sqrt{p(1-p) / (n (2p-1)^2)} = \sqrt{3/32} = 0.306, so the error of 1/41/4 is within one standard deviation. With ε=1\varepsilon = 1 the truth probability is p=e/(1+e)=0.731059p = e/(1+e) = 0.731059.

Correctness

Theorem (privacy; Dwork-Roth Claim 3.5 for ε=ln⁡3\varepsilon = \ln 3). RANDOMIZED-RESPONSE is ε\varepsilon-LDP, and the vector of the nn reports is ε\varepsilon-DP under replace neighbors.

For each output rr, Pr⁡[R(v)=r]\Pr[R(v) = r] is pp if r=vr = v and 1−p1 - p otherwise. So the largest ratio is p/(1−p)=eεp / (1-p) = e^{\varepsilon}. For the vector, the reports are independent, and two neighbors differ in one bit, so all factors but one cancel.

Theorem (unbiased estimate). For every fixed dataset, E[ESTIMATE]=π\mathbb E[\text{ESTIMATE}] = \pi and Var[ESTIMATE]=p(1−p)/(n(2p−1)2)\mathrm{Var}[\text{ESTIMATE}] = p(1-p) / (n (2p - 1)^2).

The key fact is that each report is an independent indicator random variable, and that its variance is p(1−p)p(1-p) whatever the bit is. The full proofs are in the correctness proof of this page.

Proof: Randomized response is epsilon-LDP and its estimate is unbiasedfull

Fix a rational number eε≥1e^{\varepsilon} \ge 1 and let p=eε/(1+eε)=a/qp = e^{\varepsilon}/(1 + e^{\varepsilon}) = a/q in lowest terms (line L1). Write R(v)R(v) for the output of RANDOMIZED-RESPONSE on the bit vv.

Lemma 1 (the coin). Line L2 gives Pr⁡[c=1]=p\Pr[c = 1] = p.

Proof. The integer is uniform on the qq values {0,…,q−1}\{0, \ldots, q - 1\}, and exactly aa of them are below aa, because 0≤a≤q0 \le a \le q. So Pr⁡[c=1]=a/q=p\Pr[c = 1] = a/q = p. □\square

Lemma 2 (the pmf of one report). For v,r∈{0,1}v, r \in \{0, 1\}, Pr⁡[R(v)=r]=p\Pr[R(v) = r] = p if r=vr = v and 1−p1 - p if r≠vr \ne v.

Proof. Line L3 returns vv when c=1c = 1, and line L4 returns 1−v1 - v when c=0c = 0. The claim follows from Lemma 1. □\square

Theorem 1 (privacy). RR is ε\varepsilon-LDP. The vector (R(v1),…,R(vn))(R(v_1), \ldots, R(v_n)), with independent coins, is ε\varepsilon-DP under replace neighbors, and no smaller ε\varepsilon holds for it when n≥1n \ge 1.

Proof. By Lemma 2, for all v,v′,rv, v', r, the ratio Pr⁡[R(v)=r]/Pr⁡[R(v′)=r]\Pr[R(v) = r] / \Pr[R(v') = r] is 1 if v=v′v = v', and otherwise it is p/(1−p)p/(1-p) or (1−p)/p(1-p)/p. Since p/(1−p)=eεp/(1-p) = e^{\varepsilon} and (1−p)/p=e−ε(1-p)/p = e^{-\varepsilon}, the ratio is at most eεe^{\varepsilon}. This is ε\varepsilon-LDP.

Let vv and v′v' be two vectors of length nn that differ only at position jj. The coins are independent, so for every vector of reports rr,

Pr⁡[R(v)=r]Pr⁡[R(v′)=r]=∏i=1nPr⁡[R(vi)=ri]Pr⁡[R(vi′)=ri]=Pr⁡[R(vj)=rj]Pr⁡[R(vj′)=rj]≤eε.\frac{\Pr[R(v) = r]}{\Pr[R(v') = r]} = \prod_{i=1}^{n} \frac{\Pr[R(v_i) = r_i]}{\Pr[R(v'_i) = r_i]} = \frac{\Pr[R(v_j) = r_j]}{\Pr[R(v'_j) = r_j]} \le e^{\varepsilon}.

For a set SS of vectors, sum the inequality Pr⁡[R(v)=r]≤eεPr⁡[R(v′)=r]\Pr[R(v) = r] \le e^{\varepsilon} \Pr[R(v') = r] over r∈Sr \in S. The ratio equals eεe^{\varepsilon} when rj=vjr_j = v_j, so no smaller ε\varepsilon holds. □\square

Theorem 2 (the estimate). Let π=1n∑ivi\pi = \frac1n \sum_i v_i and π^\hat\pi the output of ESTIMATE on the reports, with ε>0\varepsilon > 0. Then E[π^]=π\mathbb E[\hat\pi] = \pi and Var[π^]=p(1−p)/(n(2p−1)2)\mathrm{Var}[\hat\pi] = p(1-p)/(n(2p-1)^2).

Proof. Let ri=R(vi)r_i = R(v_i). By Lemma 2, rir_i is an indicator variable with Pr⁡[ri=1]=pvi+(1−p)(1−vi)=(2p−1)vi+(1−p)\Pr[r_i = 1] = p v_i + (1-p)(1 - v_i) = (2p - 1) v_i + (1 - p). By linearity of expectation, λ\lambda of line L5 has

E[λ]=1n∑i((2p−1)vi+(1−p))=(2p−1)π+(1−p).\mathbb E[\lambda] = \frac1n \sum_{i} \big((2p - 1) v_i + (1 - p)\big) = (2p - 1)\pi + (1 - p).

Since ε>0\varepsilon > 0, p>1/2p > 1/2 and 2p−1>02p - 1 > 0. Line L6 is π^=(λ−(1−p))/(2p−1)\hat\pi = (\lambda - (1-p))/(2p-1), an affine map of λ\lambda, so E[π^]=((2p−1)π+(1−p)−(1−p))/(2p−1)=π\mathbb E[\hat\pi] = ((2p-1)\pi + (1-p) - (1-p))/(2p-1) = \pi.

For the variance, Pr⁡[ri=1]\Pr[r_i = 1] is pp if vi=1v_i = 1 and 1−p1 - p if vi=0v_i = 0. In both cases Var[ri]=p(1−p)\mathrm{Var}[r_i] = p(1-p). The rir_i are independent, so Var[λ]=1n2⋅n p(1−p)=p(1−p)/n\mathrm{Var}[\lambda] = \frac{1}{n^2} \cdot n\,p(1-p) = p(1-p)/n. The affine map divides the variance by (2p−1)2(2p-1)^2, which gives the claim. □\square

Theorem 1 gives the privacy of each report and of the vector of reports. Theorem 2 shows that the collector's estimate is unbiased, with the stated variance, for every fixed dataset. ■\blacksquare

Complexity

The model is the word RAM with words of O(log⁡q+log⁡n)O(\log q + \log n) bits.

  • Per report. Line L1 is O(1)O(1) arithmetic on the fraction, line L2 is one uniform integer and one comparison, and lines L3 and L4 are O(1)O(1). So each report takes O(1)O(1) time and one random draw.
  • Estimate. Line L5 sums nn bits in O(n)O(n) time, and line L6 is O(1)O(1). The extra space is O(1)O(1) besides the reports.
  • Total. The nn reports and the estimate take O(n)O(n) time in the worst case.

Properties

  • Local. Each person randomizes before the data leaves the device. The collector learns the same thing as anyone who reads the reports.
  • Exact. With a rational eεe^{\varepsilon}, every probability is a fraction, and the privacy loss is exactly ε\varepsilon (a theorem). The tests check it with exact arithmetic, and they check that the claim fails for ε−0.01\varepsilon - 0.01.
  • Unbiased, with a large variance. The variance p(1−p)/(n(2p−1)2)p(1-p)/(n(2p-1)^2) is about 1/(nε2)1/(n\varepsilon^2) for small ε\varepsilon. A central mechanism such as the Laplace mechanism on the count has error about 1/(nε)1/(n\varepsilon) on the fraction. So the local model costs a factor of about n\sqrt n in the error.
  • Not always in range. Line L6 can give a value below 0 or above 1, for example −1/2-1/2 or 3/23/2 when all reports are 0 or 1 with p=3/4p = 3/4. Clamping to [0,1][0, 1] is post-processing, so it keeps the privacy, but it adds a bias.

Variants and improvements

  • Two coins. Dwork and Roth flip a fair coin: on heads, tell the truth; on tails, flip a second fair coin and report it. Then p=3/4p = 3/4 and ε=ln⁡3\varepsilon = \ln 3. This is the case eε=3e^{\varepsilon} = 3 of the algorithm above.
  • Warner's original design. Warner (1965) gave each person a spinner that picks the statement "I am in group A" with probability pp and "I am not in group A" otherwise. The person answers the chosen statement truly. The reports have the same distribution as above.
  • More than two values. Generalized randomized response reports the true value of dd values with probability eε/(eε+d−1)e^{\varepsilon}/(e^{\varepsilon} + d - 1) and each other value otherwise. For large dd, optimized local hashing and RAPPOR have a smaller variance.
  • Repeated reports. A person who answers the same question again with a fresh coin spends ε\varepsilon again. RAPPOR stores one randomized answer and randomizes it again for each report, so that repeated reports do not add up the loss.
  • Shuffling. If a trusted shuffler removes the link between reports and people, the reports satisfy central DP with a much smaller ε\varepsilon (privacy amplification by shuffling).

When to use it

Use randomized response when no party can be trusted with the true bits, and when the population is large: the error is about 1/(εn)1/(\varepsilon\sqrt n) on the fraction. When a trusted curator exists, the Laplace or the geometric mechanism on the count gives an error that is smaller by a factor of about n\sqrt n. For values from a large domain, use a frequency oracle such as optimized local hashing.

Pitfalls

  • A float coin. Line L2 written as "random float < p" with p=eε/(1+eε)p = e^{\varepsilon}/(1+e^{\varepsilon}) in floats gives a probability that differs a little from pp, and the claimed ε\varepsilon is then not exact. Line L2 must compare a uniform integer in {0,…,q−1}\{0, \ldots, q-1\} with the numerator aa of the exact fraction, or use an exact Bernoulli sampler.
  • A second fresh answer to the same question. Running lines L2 to L4 again for the same person and the same bit leaks more: two independent reports are only 2ε2\varepsilon-LDP. Store the first report and send it again, or count the loss with the sequential composition theorem.
  • No correction in the estimate. Line L6 replaced by λ\lambda itself gives a biased estimate, because E[λ]=(2p−1)π+(1−p)\mathbb E[\lambda] = (2p-1)\pi + (1-p). For p=3/4p = 3/4 and π=0\pi = 0, λ\lambda is about 1/41/4. Line L6 must subtract 1−p1 - p and divide by 2p−12p - 1.
  • The wrong truth probability. Line L1 with p=eεp = e^{\varepsilon} over 2, or with p=1−e−εp = 1 - e^{-\varepsilon}, does not give the ratio p/(1−p)=eεp/(1-p) = e^{\varepsilon}. Line L1 must use p=eε/(1+eε)p = e^{\varepsilon}/(1 + e^{\varepsilon}).

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.

dpkit.pyI0RawGitHub
# 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
randomized_response.py 74 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-response/. The authors are listed in prov/935KM5.jsonl.
"""Randomized response (Warner 1965) with the truth probability of epsilon-LDP.

The privacy parameter is passed as the exact value e^epsilon, a positive
Fraction or int, so that the coin is exact and the pmf can be checked with
fractions. random.Random is used only so that the tests are reproducible; a
deployment needs a cryptographic source of randomness.
"""

from __future__ import annotations

import random
from fractions import Fraction
from typing import Sequence, Union

Rational = Union[int, Fraction]


def truth_probability(exp_epsilon: Rational) -> Fraction:
    """p = e^epsilon / (1 + e^epsilon). Precondition: exp_epsilon >= 1."""
    e = Fraction(exp_epsilon)
    if e < 1:
        raise ValueError("e^epsilon must be at least 1")
    return e / (1 + e)


def randomized_response(v: int, exp_epsilon: Rational, rng: random.Random) -> int:
    """Report the bit v with probability p = e^epsilon / (1 + e^epsilon), else report 1 - v.

    Precondition: v is 0 or 1, and exp_epsilon is a rational number >= 1.
    The report is epsilon-locally differentially private.
    Cost: O(1) word operations and one uniform draw from {0, ..., den(p) - 1}.
    """
    if v not in (0, 1):
        raise ValueError("v must be 0 or 1")
    p = truth_probability(exp_epsilon)  # @line L1
    c = 1 if rng.randrange(p.denominator) < p.numerator else 0  # @line L2
    if c == 1:  # @line L3
        return v
    return 1 - v  # @line L4


def estimate_fraction(reports: Sequence[int], exp_epsilon: Rational) -> Fraction:
    """The unbiased estimate (lambda - (1 - p)) / (2 p - 1) of the true fraction of ones.

    lambda is the fraction of ones among the reports. Precondition: at least
    one report, and exp_epsilon > 1 so that 2 p - 1 > 0. Cost: O(n).
    """
    if not reports:
        raise ValueError("need at least one report")
    p = truth_probability(exp_epsilon)
    if p == Fraction(1, 2):
        raise ValueError("epsilon = 0 gives no information")
    lam = Fraction(sum(reports), len(reports))  # @line L5
    return (lam - (1 - p)) / (2 * p - 1)  # @line L6


def report_pmf(v: int, exp_epsilon: Rational) -> dict[int, Fraction]:
    """The exact pmf of the report on input bit v."""
    p = truth_probability(exp_epsilon)
    return {v: p, 1 - v: 1 - p}


def estimate_variance(n: int, exp_epsilon: Rational) -> Fraction:
    """Var of the estimate on a fixed dataset of n bits: p (1 - p) / (n (2 p - 1)^2).

    Each report flips its bit with probability 1 - p, so each report has
    variance p (1 - p) whatever its true bit is. The value does not depend on
    the data. (Warner's formula for a random sample of a population adds the
    sampling variance pi (1 - pi) / n.)
    """
    p = truth_probability(exp_epsilon)
    return p * (1 - p) / (n * (2 * p - 1) ** 2)
test_randomized_response.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/randomized-response/. The authors are listed in prov/935KM5.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

import dpkit
from randomized_response import (
    estimate_fraction,
    estimate_variance,
    randomized_response,
    report_pmf,
    truth_probability,
)

BITS = (0, 1)


def one_bit_pmf(x):
    return report_pmf(x[0], 3)


def vector_pmf(x, exp_epsilon):
    """Exact pmf of the vector of reports, one independent coin per record."""
    out = {}
    for y in itertools.product(BITS, repeat=len(x)):
        pr = Fraction(1)
        for v, r in zip(x, y):
            pr *= report_pmf(v, exp_epsilon)[r]
        out[y] = pr
    return out


def test_check_values():
    assert truth_probability(3) == Fraction(3, 4)
    assert abs(float(truth_probability(Fraction(math.exp(1)))) - 0.731059) < 5e-7
    assert truth_probability(1) == Fraction(1, 2)


def test_two_coin_version_equals_exp_epsilon_three():
    # Dwork and Roth: flip a coin; on tails answer truthfully, on heads answer with a second coin.
    for v in BITS:
        two_coin = {v: Fraction(1, 2) + Fraction(1, 4), 1 - v: Fraction(1, 4)}
        assert report_pmf(v, 3) == two_coin


def test_one_bit_is_exactly_ln3_dp():
    pairs = [((0,), (1,))]
    assert dpkit.is_pure_dp(one_bit_pmf, pairs, math.log(3))
    assert not dpkit.is_pure_dp(one_bit_pmf, pairs, math.log(3) - 0.01)
    p, q = one_bit_pmf((0,)), one_bit_pmf((1,))
    assert abs(dpkit.max_privacy_loss(p, q) - math.log(3)) < 1e-15


def test_privacy_loss_equals_epsilon_for_random_rationals():
    rng = random.Random(3)
    for _ in range(500):
        e = Fraction(rng.randint(10, 200), 10)
        p, q = report_pmf(0, e), report_pmf(1, e)
        assert p[0] / q[0] == e
        assert q[1] / p[1] == e
        assert abs(dpkit.max_privacy_loss(p, q) - math.log(e)) < 1e-12


def test_vector_of_reports_under_replace_neighbors():
    # Each person randomizes alone, so a change of one bit costs epsilon.
    e = Fraction(5, 2)
    for n in range(1, 5):
        for x in itertools.product(BITS, repeat=n):
            pairs = [(x, y) for y in dpkit.neighbors_replace(x, BITS)]
            mech = lambda d: vector_pmf(d, e)
            assert dpkit.is_pure_dp(mech, pairs, math.log(e))
            assert not dpkit.is_pure_dp(mech, pairs, math.log(e) - 0.01)


def test_estimate_is_unbiased_and_variance_matches_exactly():
    rng = random.Random(7)
    for _ in range(500):
        n = rng.randint(1, 6)
        x = tuple(rng.choice(BITS) for _ in range(n))
        e = Fraction(rng.randint(11, 60), 10)
        pmf = vector_pmf(x, e)
        assert sum(pmf.values()) == 1
        mean = sum(pr * estimate_fraction(y, e) for y, pr in pmf.items())
        assert mean == Fraction(sum(x), n)
        var = sum(pr * (estimate_fraction(y, e) - mean) ** 2 for y, pr in pmf.items())
        assert var == estimate_variance(n, e)


def test_sampler_matches_pmf():
    rng = random.Random(2024)
    n = 2000
    t = dpkit.hoeffding_margin(n, 1e-6)
    for e in (Fraction(1), Fraction(3), Fraction(27, 10), Fraction(19)):
        for v in BITS:
            reports = [randomized_response(v, e, rng) for _ in range(n)]
            freq = dpkit.empirical_pmf(reports).get(v, 0.0)
            assert abs(freq - float(truth_probability(e))) <= t


def test_estimate_of_population_is_accurate():
    rng = random.Random(99)
    n = 2000
    beta = 1e-6
    for e in (Fraction(3), Fraction(7)):
        x = [1 if rng.random() < 0.3 else 0 for _ in range(n)]
        reports = [randomized_response(v, e, rng) for v in x]
        p = truth_probability(e)
        # lambda is a mean of n independent bits, so Hoeffding applies to it.
        bound = dpkit.hoeffding_margin(n, beta) / float(2 * p - 1)
        assert abs(float(estimate_fraction(reports, e)) - sum(x) / n) <= bound


def test_edge_cases():
    rng = random.Random(0)
    with pytest.raises(ValueError):
        randomized_response(2, 3, rng)
    with pytest.raises(ValueError):
        truth_probability(Fraction(1, 2))
    with pytest.raises(ValueError):
        estimate_fraction([], 3)
    with pytest.raises(ValueError):
        estimate_fraction([0, 1], 1)
    # The estimate can leave [0, 1]; that is the price of unbiasedness.
    assert estimate_fraction([0, 0, 0], 3) == Fraction(-1, 2)
    assert estimate_fraction([1, 1, 1], 3) == Fraction(3, 2)

History

Warner (1965) introduced randomized response in the Journal of the American Statistical Association, as a way to get honest answers to questions about stigmatized behavior. He gave the maximum likelihood estimate of the proportion and its variance under random sampling. The method was used in many surveys after that. Dwork and Roth (2014) showed that the coin version is (ln⁡3)(\ln 3)-differentially private, which links the survey method to differential privacy. It is now the standard first example of local differential privacy.

References

  1. Stanley L. Warner, Randomized response, a survey technique for eliminating evasive answer bias, Journal of the American Statistical Association 60(309), 1965, pages 63 to 69, the randomizing device, the maximum likelihood estimate of the population proportion and its variance
  2. Cynthia Dwork and Aaron Roth, The Algorithmic Foundations of Differential Privacy, Foundations and Trends in Theoretical Computer Science 9(3-4), 2014, pages 211 to 407, Section 3.2, the coin-flip version and Claim 3.5 (it is (ln 3, 0)-differentially private)
  3. Ilya Mironov, On significance of the least significant bits for differential privacy, ACM CCS 2012, pages 650 to 661, why the samplers of a deployment must be exact
  4. Clement L. Canonne, Gautam Kamath and Thomas Steinke, The discrete Gaussian for differential privacy, NeurIPS 2020, exact sampling of Bernoulli variables with rational and irrational parameters

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example