Algorithmcore
Post-randomization method
Also called PRAM masking.
Replaces each categorical value by a random value drawn from a published Markov matrix, so that analysts can correct for it.
- Time
- O(n K + K^3) worst
- Space
- O(K^2) extra
- Where
- K = the number of categories; n = the number of records
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter Kooiman, Leon Willenborg, Jose Gouweleeuw, 1997
The post-randomization method (PRAM) masks a categorical attribute of a microdata file. The agency replaces each value by a random value , drawn with probability from row of a transition matrix , independently for each record, and it publishes together with the data. A person who links a released record to a known person cannot trust its value, because it may be a random replacement. An analyst can still estimate the true counts without bias by solving , where are the released counts. It is the agency side of randomized response, where the respondent does the random step. A variant called invariant PRAM chooses the matrix so that the expected released counts equal the true counts. PRAM with a matrix that has no zero entries is also locally differentially private, with set by the largest ratio in a column.
In plain words
An office releases a file where each person has a region. Before it publishes, it rolls a die for each person. Most of the time the region stays the same. Sometimes it changes to another region, with chances that the office fixes in a table. The office publishes the table of chances with the data.
A reader who finds a line that looks like a neighbor cannot be sure of the region on that line. But a researcher who counts the people in each region can undo the effect on average. She knows how many people the die moves out of each region and into it, so she can solve for the counts before the die.
The more the die changes, the more privacy, and the noisier the corrected counts.
The problem
The input is a list of values of a categorical attribute with categories , and a matrix with and for each . Such a matrix is the transition matrix of a Markov chain. The output is a released list with , independently for each . An analyst who has and wants the true counts . The choice of is a policy choice of the agency: large diagonal entries keep the data close to the truth, small ones protect more.
The algorithm
PRAM(x, P)- 1
for i ← 1 to n do - 2
k ← x_i - 3
u ← a uniform random number in [0, 1) - 4
l ← the least l with p_k1 + p_k2 + ... + p_kl > u - 5
y_i ← l - 6
return y ESTIMATE(y, P)- 7
T* ← the count of each category in y - 8
solve P^T T̂ = T* for T̂ ▷ by Gaussian elimination; P must be invertible - 9
return T̂
Lines L1 to L6 run at the agency, and lines L7 to L9 at the analyst. Line L4 is the inverse of the cumulative distribution of row . The test is strict, so a category with is never chosen. With the cumulative sums stored, a binary search makes line L4 take time.
Invariant PRAM. Let be the true counts and the expected released count of . Gouweleeuw et al. (1998, Section 5) define and the matrix . Then : PRAM with releases counts whose expectation is the truth, so the analyst can use the released counts directly. The matrix depends on the data. The agency computes it from the true counts and applies PRAM with in place of .
Example
Three regions, with the matrix
| true \ released | 1 | 2 | 3 |
|---|---|---|---|
| 1 | 4/5 | 1/10 | 1/10 |
| 2 | 1/10 | 4/5 | 1/10 |
| 3 | 0 | 1/5 | 4/5 |
and the true counts . By the linearity of expectation, the expected released counts are . The raw released counts are biased: region 1 seems smaller than it is.
Say one run releases . Line L8 solves
which gives . Each released count can differ from its mean by a few units, and the inverse spreads the error over the estimate. On the mean , the solve gives back exactly.
For invariant PRAM, take two categories, the matrix of randomized response with , and :
| row 1 | (3/4, 1/4) | 50 | (9/10, 1/10) | (4/5, 1/5) |
| row 2 | (1/4, 3/4) | 30 | (1/2, 1/2) | (3/5, 2/5) |
The check is . The ratios in the columns are 3 for and 2 for , so as a local mechanism is -private and is -private. The matrix of the example with three regions has a 0 in a column with positive entries, so it is not locally private for any : a released 1 proves that the true region was not 3.
Correctness
By the inverse of the distribution function, lines L3 to L5 give exactly when falls in an interval of length , so . By linearity, . The solve of line L8 is a linear map, so , and is unbiased. For invariant PRAM, and . The full proofs, with the covariance of and the local privacy bound, are in proofs/correctness.md.
Proof: PRAM draws from the rows of P, and the inverse of P gives unbiased countsfull
The categories are . The PRAM matrix has and for each . The input is a list of values , and is the number of with . Lines L1 to L9 are those of the page. Line L3 draws uniformly from , independently for each record. We write and , so .
Lemma 1 (one draw). For a record with , lines L3 to L5 set with probability exactly .
Proof. Line L4 picks the least with . Since , such an exists. The least such is exactly when , because the sums do not decrease. The probability of this interval under the uniform law is . If the interval is empty, and is never chosen.
Theorem 1 (the expected released counts). Let be the number of with , as at line L7. Then , that is, .
Proof. . By Lemma 1 and the linearity of expectation, .
Theorem 2 (the estimate). If is invertible, the vector of lines L8 and L9, the solution of , satisfies . Its covariance is , where and is row of as a column vector.
Proof. is invertible together with , so line L8 has the unique solution . This map is linear, so by Theorem 1, . The released indicator vectors are independent. For a record with value , is a draw of a multinomial with one trial and probabilities , with covariance . Summing over the records gives , and a linear map gives with .
Theorem 3 (invariant PRAM). Let . Define by when , and when . Then is a PRAM matrix, and . So PRAM with has , and the released counts need no correction.
Proof. Each row of is a probability vector: for , , and for it is a unit vector. A product of two matrices whose rows are probability vectors has the same property, so is a PRAM matrix. Next, , so
If both sides are 0. If , then implies , so the last sum runs over all with and equals 1. Hence . By Theorem 1 with in place of , .
Theorem 4 (local differential privacy). Assume that each column of is either all zero or all positive, and let over the positive columns. Then the release of one record by lines L3 to L5 is -locally differentially private with , and no smaller holds. If some column has both a zero and a positive entry, no finite holds.
Proof. By Lemma 1, the output law for the input is row . For outputs in a positive column, , and outputs in a zero column have probability 0 for every input. So the bound holds for every set of outputs, which is the definition with . The pair and the column where the maximum is reached give equality, so a smaller fails. If , the output is possible under and impossible under , and no factor bounds the ratio.
Remark. Theorem 4 is about one record and the matrix only. The privacy of a release by PRAM in the sense of statistical disclosure control is a policy question, and the matrix is chosen by the agency. Theorem 2 is the reason why the matrix is published.
Complexity
The model is the word RAM, with one step for each operation on a probability.
- Lines L1 to L6 take time with a linear scan at line L4, or with stored cumulative sums and a binary search.
- Line L7 takes time, and line L8 takes by Gaussian elimination.
- The extra space is for the matrix and the elimination.
The matrix of invariant PRAM takes time to compute.
Properties
- Unbiased estimate. when is invertible. This is a theorem.
- The cost of the noise. with . A matrix close to singular makes the variance large. This is also a theorem.
- Invariant PRAM keeps the expected counts. Univariate counts need no correction. Cross tables of the masked attribute with other attributes still need one.
- Local privacy. With all entries positive, the release of one record is -locally differentially private with , and this value is tight.
- Independent of the other records. Each draw depends only on the value of its own record, unlike data swapping, where a change needs a partner.
Variants and improvements
- PRAM on several attributes together. Apply one matrix to the combinations of two attributes, so that combinations that cannot occur, such as an age of 5 with a status of married, are never released.
- PRAM in strata. Use a different matrix for each value of another attribute, for example for each region. The analyst corrects within each stratum.
- Maximum likelihood. The moment estimate of line L8 can have negative entries. A maximum likelihood estimate, for example by expectation-maximization, stays in the set of valid counts.
- Randomized response. Randomized response uses the same matrix at the collection step, by the respondent. The estimate is the same.
- Local differential privacy. Choosing to minimize the variance of for a given is the design problem of local differential privacy.
When to use it
Use PRAM to mask categorical attributes of a public use file when analysts need unbiased frequency tables and accept more variance, and when the agency is willing to publish the matrix. Use invariant PRAM when most users will not correct the counts. If most of the risk comes from a few rare combinations, generalization and suppression or data swapping of those records can lose less. For a formal guarantee over all records and all analyses, use a mechanism designed for differential privacy and account for its total privacy loss.
Pitfalls
- P instead of P^T at line L8. The released counts are , so the system to solve is . Solving is wrong whenever is not symmetric. In the example, on the mean released counts , it gives instead of .
- A test with ≥ at line L4. With the test , a draw of picks the first category even when its probability is 0. The test must be strict.
- Negative estimates. With small counts, line L8 can give . Do not round to 0 and keep the rest, because the total then changes. Report the moment estimate with its variance, or use a maximum likelihood estimate.
- A secret matrix. If is not published, the bias cannot be corrected, and PRAM becomes a form of noise with unknown effect. The protection must come from the randomness of the draws, not from the secrecy of .
- A weak random source. The tests use a seeded generator so that they repeat. A release needs a cryptographic source, because an attacker who can predict can undo the masking.
- Impossible combinations. PRAM on one attribute ignores the others. A released record can be a combination that cannot occur, which shows that it was changed and harms the analysis of cross tables.
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
# Part of https://algorithm.tamnd.com/post-randomization-method/. The authors are listed in prov/4VVPMW.jsonl.
"""The post-randomization method (PRAM) of Gouweleeuw, Kooiman, Willenborg and de Wolf.
Categories are the integers 0 .. K-1. A PRAM matrix P is a list of K rows, where
P[k][l] is the probability that a true value k is released as l. Each row sums to 1.
Use Fraction entries for exact results. The rng argument needs only a method
random() that returns a number in [0, 1); random.Random is fine for tests, but a
real release needs a cryptographic source of randomness.
"""
from fractions import Fraction
from typing import Optional, Protocol, Sequence, Union
Number = Union[int, Fraction]
Matrix = Sequence[Sequence[Number]]
class UniformSource(Protocol):
def random(self) -> float: ...
def check_matrix(P: Matrix) -> None:
"""Raise ValueError unless P is a square matrix of probabilities with rows that sum to 1."""
size = len(P)
if size == 0 or any(len(row) != size for row in P):
raise ValueError("P must be a non-empty square matrix")
for row in P:
if any(p < 0 for p in row) or sum(row) != 1:
raise ValueError("each row of P must be a probability vector")
def pram(values: Sequence[int], P: Matrix, rng: UniformSource) -> list[int]:
"""Release each value k as l with probability P[k][l], independently.
Precondition: P passes check_matrix and each value is in 0 .. K-1.
Cost: O(n K) time for n values, O(n) space for the output.
"""
check_matrix(P)
out: list[int] = []
for k in values: # @line L1
row = P[k] # @line L2
u = rng.random() # @line L3
acc: Number = 0
y = len(row) - 1
for j, p in enumerate(row): # @line L4
acc += p
if acc > u:
y = j
break
out.append(y) # @line L5
return out # @line L6
def counts(values: Sequence[int], size: int) -> list[int]:
"""The frequency of each category 0 .. size-1. Cost: O(n + size)."""
t = [0] * size
for v in values:
t[v] += 1
return t
def transpose_times(P: Matrix, t: Sequence[Number]) -> list[Number]:
"""P^T t, the expected released counts for true counts t. Cost: O(K^2)."""
size = len(P)
return [sum(P[k][l] * t[k] for k in range(size)) for l in range(size)]
def solve(A: Matrix, b: Sequence[Number]) -> Optional[list[Fraction]]:
"""Solve A z = b exactly by Gaussian elimination; None if A is singular.
Cost: O(K^3) arithmetic operations on fractions.
"""
size = len(A)
m = [[Fraction(A[i][j]) for j in range(size)] + [Fraction(b[i])] for i in range(size)]
for col in range(size):
piv = next((r for r in range(col, size) if m[r][col] != 0), None)
if piv is None:
return None
m[col], m[piv] = m[piv], m[col]
for r in range(size):
if r != col and m[r][col] != 0:
f = m[r][col] / m[col][col]
m[r] = [a - f * c for a, c in zip(m[r], m[col])]
return [m[i][size] / m[i][i] for i in range(size)]
def estimate(released: Sequence[int], P: Matrix) -> Optional[list[Fraction]]:
"""The unbiased estimate of the true counts: solve P^T T = T* for T.
Returns None if P is singular. The estimate can have negative entries.
Precondition: P passes check_matrix. Cost: O(n + K^3).
"""
check_matrix(P)
size = len(P)
t_star = counts(released, size) # @line L7
pt = [[P[k][l] for k in range(size)] for l in range(size)]
t_hat = solve(pt, t_star) # @line L8
return t_hat # @line L9
def invariant_matrix(P: Matrix, t: Sequence[Number]) -> list[list[Fraction]]:
"""R = P Q with Q[l][k] = P[k][l] t[k] / sum_j P[j][l] t[j], so that t^T R = t^T.
Precondition: P passes check_matrix, t has K entries >= 0, and every category with
t[k] > 0 has some released value. A column l with no mass gets Q[l] = unit vector l.
Cost: O(K^3).
"""
check_matrix(P)
size = len(P)
col = [sum(Fraction(P[j][l]) * t[j] for j in range(size)) for l in range(size)]
q = []
for l in range(size):
if col[l] == 0:
q.append([Fraction(int(k == l)) for k in range(size)])
else:
q.append([Fraction(P[k][l]) * t[k] / col[l] for k in range(size)])
return [[sum(Fraction(P[i][l]) * q[l][j] for l in range(size)) for j in range(size)] for i in range(size)]
def ldp_ratio(P: Matrix) -> Optional[Fraction]:
"""The least c with P[k][l] <= c P[k'][l] for all k, k', l; None if no c exists.
PRAM with matrix P is epsilon-locally differentially private for epsilon = ln c.
A column of zeros is a value that is never released and is skipped.
Cost: O(K^2).
"""
check_matrix(P)
worst = Fraction(1)
for l in range(len(P)):
column = [Fraction(row[l]) for row in P]
hi, lo = max(column), min(column)
if hi == 0:
continue
if lo == 0:
return None
worst = max(worst, hi / lo)
return worst
test_post_randomization_method.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/post-randomization-method/. The authors are listed in prov/4VVPMW.jsonl.
import itertools
import random
from fractions import Fraction as F
import pytest
from post_randomization_method import (
check_matrix,
counts,
estimate,
invariant_matrix,
ldp_ratio,
pram,
solve,
transpose_times,
)
P3 = [[F(4, 5), F(1, 10), F(1, 10)], [F(1, 10), F(4, 5), F(1, 10)], [F(0), F(1, 5), F(4, 5)]]
RR = [[F(3, 4), F(1, 4)], [F(1, 4), F(3, 4)]]
class Fixed:
def __init__(self, us):
self.us = list(us)
def random(self) -> float:
return self.us.pop(0)
def det(a):
"""The Leibniz formula, independent of the elimination in solve."""
size = len(a)
total = F(0)
for perm in itertools.permutations(range(size)):
inv = sum(1 for i in range(size) for j in range(i + 1, size) if perm[i] > perm[j])
term = F(-1) ** inv
for i in range(size):
term *= a[i][perm[i]]
total += term
return total
def cramer(a, b):
d = det(a)
if d == 0:
return None
out = []
for c in range(len(a)):
m = [[b[i] if j == c else a[i][j] for j in range(len(a))] for i in range(len(a))]
out.append(det(m) / d)
return out
def random_matrix(rng, size):
rows = []
for _ in range(size):
w = [rng.randint(0, 6) for _ in range(size)]
if sum(w) == 0:
w[rng.randrange(size)] = 1
rows.append([F(x, sum(w)) for x in w])
return rows
def test_page_example() -> None:
assert transpose_times(P3, [50, 30, 20]) == [43, 33, 24]
released = [0] * 45 + [1] * 31 + [2] * 24
assert estimate(released, P3) == [F(370, 7), F(190, 7), F(20)]
assert estimate([0] * 43 + [1] * 33 + [2] * 24, P3) == [50, 30, 20]
r = invariant_matrix(RR, [60, 20])
assert r == [[F(4, 5), F(1, 5)], [F(3, 5), F(2, 5)]]
assert transpose_times(r, [60, 20]) == [60, 20]
assert ldp_ratio(RR) == 3
assert ldp_ratio(r) == 2
assert ldp_ratio(P3) is None
def test_sampling_boundaries() -> None:
# Row 0 of P3 has the cumulative sums 4/5, 9/10, 1.
assert pram([0, 0, 0, 0, 0], P3, Fixed([0.0, 0.79, 0.8, 0.85, 0.9])) == [0, 0, 1, 1, 2]
# A zero entry is never chosen.
assert pram([2, 2], P3, Fixed([0.0, 0.19])) == [1, 1]
assert pram([], P3, Fixed([])) == []
def test_bad_matrix() -> None:
with pytest.raises(ValueError):
check_matrix([[F(1, 2), F(1, 3)], [F(1, 2), F(1, 2)]])
with pytest.raises(ValueError):
check_matrix([[F(3, 2), F(-1, 2)], [F(0), F(1)]])
with pytest.raises(ValueError):
check_matrix([[F(1)], [F(1)]])
assert solve([[F(1, 2), F(1, 2)], [F(1, 2), F(1, 2)]], [1, 1]) is None
assert estimate([0, 1], [[F(1, 2), F(1, 2)], [F(1, 2), F(1, 2)]]) is None
def test_against_oracles() -> None:
rng = random.Random(1998)
for _ in range(600):
size = rng.randint(1, 3)
p = random_matrix(rng, size)
t = [rng.randint(0, 9) for _ in range(size)]
pt = [[p[k][l] for k in range(size)] for l in range(size)]
t_star = [rng.randint(0, 9) for _ in range(size)]
released = [l for l in range(size) for _ in range(t_star[l])]
rng.shuffle(released)
assert counts(released, size) == t_star
assert estimate(released, p) == cramer(pt, t_star)
if det(pt) != 0:
expected = transpose_times(p, t)
assert solve(pt, expected) == t
if sum(t) > 0:
r = invariant_matrix(p, t)
assert all(sum(row) == 1 and min(row) >= 0 for row in r)
assert transpose_times(r, t) == t
ratio = ldp_ratio(p)
pairs = [(p[a][l], p[b][l]) for a in range(size) for b in range(size) for l in range(size)]
if any(x > 0 and y == 0 for x, y in pairs):
assert ratio is None
else:
assert ratio == max([F(1)] + [x / y for x, y in pairs if y > 0])
def test_sampling_matches_inverse_cdf() -> None:
rng = random.Random(4)
for _ in range(500):
size = rng.randint(1, 4)
p = random_matrix(rng, size)
values = [rng.randrange(size) for _ in range(rng.randint(0, 8))]
seed = rng.randrange(10**9)
got = pram(values, p, random.Random(seed))
twin = random.Random(seed)
want = []
for k in values:
u = twin.random()
cum = list(itertools.accumulate(p[k]))
want.append(min(l for l in range(size) if cum[l] > u))
assert got == want
def test_frequencies() -> None:
# 2000 draws from row 0 of P3. By the Hoeffding inequality, each frequency is
# within 0.05 of its probability except with probability 2 exp(-10) < 1e-4.
out = pram([0] * 2000, P3, random.Random(77))
for l, p in enumerate(P3[0]):
assert abs(out.count(l) / 2000 - float(p)) < 0.05
# The estimate from a large release is close to the truth.
truth = [0] * 1000 + [1] * 600 + [2] * 400
t_hat = estimate(pram(truth, P3, random.Random(5)), P3)
assert all(abs(float(a) - b) < 60 for a, b in zip(t_hat, [1000, 600, 400]))
History
Warner (1965) proposed randomized response, where a respondent answers a sensitive question with a known random change, and gave the unbiased estimate. Kooiman, Willenborg and Gouweleeuw (1997) at Statistics Netherlands moved the random step to the agency, after the data is collected, and named it PRAM. Gouweleeuw, Kooiman, Willenborg and de Wolf (1998) gave the theory, the moment estimate with the inverse matrix, and invariant PRAM. PRAM is one of the methods of the mu-Argus software and of the textbook of Hundepool et al. (2012). Later work on local differential privacy studies the same matrices with a formal privacy bound.
References
- Jose M. Gouweleeuw, Peter Kooiman, Leon C. R. J. Willenborg and Peter-Paul de Wolf, Post randomisation for statistical disclosure control, theory and implementation, Journal of Official Statistics 14(4), 1998, pp. 463 to 478, the PRAM matrix, the unbiased moment estimate with the inverse of the matrix, and invariant PRAM in Section 5
- Peter Kooiman, Leon Willenborg and Jose Gouweleeuw, PRAM, a method for disclosure limitation of microdata, Research paper 9705, Statistics Netherlands, 1997, the first description of the method
- Anco Hundepool, Josep Domingo-Ferrer, Luisa Franconi, Sarah Giessing, Eric Schulte Nordholt, Keith Spicer and Peter-Paul de Wolf, Statistical Disclosure Control, Wiley, 2012, Chapter 3, Microdata, the section on PRAM among the perturbative masking methods for categorical data
- Leon Willenborg and Ton de Waal, Elements of Statistical Disclosure Control, Lecture Notes in Statistics 155, Springer, 2001, the chapters on perturbative methods for microdata
- Stanley L. Warner, Randomized response, a survey technique for eliminating evasive answer bias, Journal of the American Statistical Association 60(309), 1965, pp. 63 to 69, the randomized response design and its unbiased estimate
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 4VVPMW Edit this page History Report an error Markdown