Algorithmadvanced
O(k) approximation for k-anonymity
Also called Aggarwal k-anonymity approximation.
Groups records into clusters of at least k by a forest construction and suppresses differing cells, within O(k) of the fewest suppressions.
- Time
- O(n^2 d + n^2 log n) worst
- Space
- O(n^2) extra
- Where
- d = the number of columns; k = the least size of a cluster; n = the number of rows
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Gagan Aggarwal, Tomas Feder, Krishnaram Kenthapadi, Rajeev Motwani, Rina Panigrahy, Dilys Thomas, An Zhu, 2005
The O(k) approximation of Aggarwal et al. (2005) makes a table k-anonymous by suppressing cells, and it suppresses at most times the fewest possible cells. Finding the fewest is NP-hard for . The algorithm sees the rows as the vertices of a complete graph, with the Hamming distance as the weight of an edge. It grows a forest in which each tree has at least vertices and whose total weight is at most the optimum. Then it splits each tree with more than rows into smaller trees. Each final tree is a cluster, and in each cluster the cells of each column where its rows differ are replaced by a star.
In plain words
Two rows that differ in few columns are cheap to put together, because only those columns must be hidden. So let each small group of rows reach out to the nearest row outside it, and join that row's group. Stop when every group has at least rows. A group can become too big, which makes it costly: a column is hidden in all its rows when any two of them differ. So cut each big group into parts of at least rows, and at most .
The cost of one group is at most its number of rows times the total length of its edges, and the total length of all edges is no more than the best possible cost. That gives the factor .
The problem
The input is a table of rows , each with values, and an integer with . A release replaces some cells by so that each row is equal to at least other rows. Its cost is the number of stars, and OPT is the least cost. For a set of rows, is the number of columns on which not all rows of are equal. The output is a partition of the rows into clusters of at least rows; each cluster is released with its differing columns suppressed, at a cost of . The value of is a policy choice.
The algorithm
ANONYMIZE(V, k)- 1
w(x, y) ← the number of columns where rows x and y differ, for all pairs - 2
F ← n trees of one vertex each; each vertex is the root of its tree - 3
while some tree of F has fewer than k vertices do - 4
T ← such a tree, with the least root; u ← root(T) - 5
x ← the vertex outside T with the least w(u, x), ties to the lower index - 6
add the edge u → x; T joins the tree of x, whose root stays the root - 7
P ← the trees of F - 8
while some tree of P has more than 3k - 3 row vertices do - 9
replace that tree by the two trees of DECOMPOSE(tree, k) - 10
for each tree of P, with rows C: replace by * the cells of C in the δ(C) columns where C differs - 11
return the clusters, the released table and its cost DECOMPOSE(T, k) ▷ s = the number of row vertices of T, s ≥ 3k - 2- 12
u ← the row vertex of least index; root T at u - 13
c ← the neighbor of u with the most row vertices on its side of the edge u-c; φ ← that number - 14
if φ > s - k then u ← c and go to L13 - 15
if φ ≥ k then return the two trees made by cutting the edge u-c - 16
A ← the sides of the neighbors of u, largest first, until their row vertices number at least k - 17
return (A joined to a new Steiner copy of u, the rest with u)
A Steiner vertex is a copy of the values of a row, but it is not a row. It joins the parts of with the same edge weights they had to . Line L13 counts only row vertices. Ties in line L13 go to the neighbor of lower index. The walk of lines L13 and L14 only goes down in the tree rooted at the start vertex.
Example
Take 7 binary rows with 4 columns and : row 1 = 0000, row 2 = 0001, row 3 = 0011, row 4 = 1111, row 5 = 1110, row 6 = 1100 and row 7 = 0101.
| step | small tree, root | nearest row outside | edge | weight |
|---|---|---|---|---|
| 1 | {1}, root 1 | 2 | 1 → 2 | 1 |
| 2 | {1, 2}, root 2 | 3 | 2 → 3 | 1 |
| 3 | {4}, root 4 | 5 | 4 → 5 | 1 |
| 4 | {4, 5}, root 5 | 6 | 5 → 6 | 1 |
| 5 | {7}, root 7 | 2 | 7 → 2 | 1 |
The forest has the trees {1, 2, 3, 7} and {4, 5, 6}, with total weight 5. Both have at most rows, so DECOMPOSE is not needed. The cluster {1, 2, 3, 7} differs in columns 2, 3 and 4, and the cluster {4, 5, 6} in columns 3 and 4. So rows 1, 2, 3 and 7 become 0***, and rows 4, 5 and 6 become 11**. The cost is . A search over all partitions into clusters of at least 3 rows shows that 18 is the optimum here. The proven bound is only .
Correctness
The proof has three steps. The full proof is in proofs/correctness.md.
- The forest is cheap. Let be the distance from to its -th nearest other row. When line L6 adds the edge from , its tree has at most vertices, so one of the rows nearest to is outside, and . Each vertex starts at most one edge, because it stops being a root. In an optimal release the cluster of has other rows, and its number of differing columns is at least . Each row of that cluster pays at least that much, so the weight of the forest is at most OPT.
- A split keeps both parts large and adds no weight. The walk of line L14 stops at a vertex where each side has at most row vertices. If one side has at least , line L15 cuts it off. If not, line L16 collects sides until it has between and rows, and the rest keeps at least rows. The Steiner copy has the values of , so no edge gets heavier.
- A cluster costs at most its tree. Each column where two rows of a cluster differ changes along some edge of the path between them, so is at most the weight of the tree. With at most rows per cluster, the cost is at most times the weight of the forest, which is at most OPT.
Proof: The forest algorithm is k-anonymous and within 3k - 3 of the fewest suppressionsfull
The input is rows of values each, and . For rows and , is the number of columns where they differ. For a set of rows, is the number of columns where not all rows of are equal. The algorithm releases each row of a cluster with its cells in these columns suppressed, so its cost is .
Lemma 1 (the optimum). Let OPT be the fewest suppressed cells in a k-anonymous release of the rows. Then OPT , over all partitions of the rows into clusters of at least rows.
Proof. Take an optimal release, and group the rows by their released row. Each group has at least rows. The rows of a group are equal after suppression, so in each column where the group differs, each of its rows has a suppressed cell. So the cost is at least for this partition. Conversely, suppressing the differing columns of each cluster of a partition gives a k-anonymous release with this cost.
For a row , let be the -th smallest value of over the other rows .
Lemma 2 (the forest). Lines L1 to L6 stop with a forest on the rows, each tree of has at least vertices, and the total weight is at most OPT.
Proof. Each step of line L6 adds an edge between two different trees, so stays a forest, and the number of trees goes down by one. So the loop stops, and then no tree has fewer than vertices. A tree has exactly one root, the vertex with no outgoing edge. Line L6 adds an edge from the root of the small tree, and the root of the merged tree is the root of the tree of . So is never a root again, and each vertex is the start of at most one edge.
When line L6 adds the edge , the tree of has at most vertices. At most of the rows nearest to are in , so one of them is outside , and line L5 gives .
In an optimal partition (Lemma 1), the cluster of has at least other rows, and for each . So is at least the largest of these or more distances, which is at least . Each vertex starts at most one edge, so $W(F) \le \sum_u d_{k-1}(u) \le \sum_u \delta(C_u) = $ OPT, where is the cluster of .
In the next part, a tree may also have Steiner vertices. A Steiner vertex is a copy of the vector of some vertex, and it is not a row. The size of a tree is its number of row vertices.
Lemma 3 (one split). Let a tree have size . DECOMPOSE returns two trees of size at least each, whose row vertices are a partition of the row vertices of the tree, and whose total weight is at most the weight of the tree.
Proof. For a vertex and a neighbor , let side be the size of the part that holds when the edge - is cut. Root the tree at the start vertex of line L12. Lines L13 and L14 move to the neighbor with the largest side while that side is more than . If the walk moves from to , then the part of that holds has size , because . So the walk never moves back, it goes down in the tree rooted at , and it stops. A move needs a side of at least , so the walk never reaches a leaf, and always has a neighbor. When the walk stops, each neighbor of has side at most .
If the largest side is at least (line L15), cutting the edge - gives a tree of size and a tree of size , and both are at least .
Otherwise each side is at most . The sides add up to or , which is at least , so line L16 can take sides until their total is at least . The total before the last one is at most , so the final total is at most . The rest, with , has size at least . Line L17 joins the taken parts to a Steiner copy of and not to . Each new edge has the weight of the edge it replaces, because the copy has the vector of . Both new trees are connected, and both have size at least .
In both cases no edge gets a larger weight, and one edge goes away in the first case.
Lemma 4 (a cluster and its tree). If the rows of a cluster are the row vertices of a tree , possibly with Steiner vertices, then .
Proof. Take a column where two rows differ. The path from to in has an edge whose two ends differ in column . Map to this edge. Different columns give different pairs (edge, column), and an edge is in at most such pairs. So .
Theorem. ANONYMIZE returns clusters that partition the rows, each with between and rows. The released table is k-anonymous, and its cost is at most OPT.
Proof. By Lemma 2, line L7 starts with trees of size at least . Line L8 splits a tree only when its size is more than , and by Lemma 3 both parts have size at least , so both are smaller than the tree. So the loop stops, and each final tree has a size between and . Note that because . The row vertices of the final trees are a partition of the rows.
Line L10 suppresses, in each row of a cluster , the columns where differs. Then all rows of are equal, and has at least rows, so the table is k-anonymous. By Lemma 4, Lemma 3 and Lemma 2, the cost is
Complexity
Let be the number of rows and the number of columns. The model is the word RAM.
- Line L1 computes distances in time and keeps them in space.
- Lines L3 to L6 merge at most times, and each merge scans the rows: .
- A split of a tree with vertices takes for the rooting, the walk and the sort of line L16, and it adds at most one Steiner vertex. Each split removes at least rows from a large tree, so at most splits happen, each on at most vertices: in total.
- Line L10 takes .
In total time and space.
Properties
- Ratio . This is a theorem for all inputs with . With a finer split, Aggarwal et al. (2005) improve the ratio to , and they give better ratios for small cases: 1.5 for , and 2 for with binary values.
- Cluster sizes. Each cluster has between and rows. Small clusters keep more detail.
- Limit of the method. The algorithm uses only the distances between rows. Aggarwal et al. (2005) show two tables with the same distances whose optimal costs differ by a factor of order . So no algorithm that sees only the distances can have a ratio better than order .
- Measured quality. The ratio is a worst case. On the example above, the result is optimal. How far it is from the optimum on real tables is a question of measurement, not of this proof.
Variants and improvements
- Meyerson and Williams (2004). An ratio, , by greedy set cover over candidate clusters, in time exponential in , and an ratio in polynomial time.
- Park and Shim (2007). An ratio; see their paper for the conditions on the running time.
- Generalization in place of suppression. The same clustering idea works with ranges or hierarchy values in place of stars, as in Mondrian, but the bound above is only for suppression.
- Clustering with means. Microaggregation, for example by MDAV, forms clusters of at least rows by distances and releases the means. It is a heuristic for numeric data.
When to use it
Use it when the release must keep cells exactly or hide them, with no generalization hierarchy, and a provable bound on the loss is wanted, for example for categorical data with many columns. For numeric data, or when ranges are acceptable, Mondrian is faster and usually keeps more detail. For a uniform coding of each column, use full-domain generalization.
Pitfalls
- Any vertex as the start of the edge in line L4. The proof charges each edge to the vertex where it starts, once. If line L4 takes a vertex of that is not the root, one vertex can start two edges, and the bound OPT fails.
- The nearest vertex inside in line L5. If line L5 looks at all rows, the nearest one can be in itself. The edge then closes a cycle and the tree does not grow, so the loop never ends. Take the nearest vertex outside .
- Joining to itself in line L17. The parts of were joined only through , and so were the other parts. If takes , the rest falls apart into several pieces, which are not a tree, and the weight argument fails. Use a Steiner copy of , which is not a row.
- in line L8. Then , and line L8 tries to split each tree forever. For the table is already 1-anonymous with no stars, so return it.
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/k-anonymity-approximation/. The authors are listed in prov/3CXF3J.jsonl.
"""The forest algorithm of Aggarwal et al. for k-anonymity by cell suppression, with ratio 3k - 3.
The input is a list of n rows, each a tuple of d values. The output groups the rows into
clusters of k to 3k - 3 rows and replaces by None each cell of a column on which the rows
of its cluster differ. The tree splitting uses explicit stacks, not recursion.
"""
from typing import Hashable, Optional, Sequence
Row = tuple[Hashable, ...]
def hamming(x: Sequence[Hashable], y: Sequence[Hashable]) -> int:
"""The number of positions where x and y differ."""
return sum(1 for a, b in zip(x, y) if a != b)
def build_forest(rows: Sequence[Row], k: int) -> list[tuple[int, int]]:
"""Return the directed edges (u, x) of the forest: each tree has at least k vertices,
and its total weight is at most the cost of an optimal k-anonymous suppression.
Precondition: 2 <= k <= len(rows).
Cost: O(n^2 d) time for the weights and O(n^2) for the n - 1 merges at most.
"""
n = len(rows)
w = [[hamming(rows[i], rows[j]) for j in range(n)] for i in range(n)] # @line L1
label = list(range(n)) # @line L2
root = list(range(n)) # root[t] is the vertex of tree t with no outgoing edge
edges: list[tuple[int, int]] = []
while True:
size: dict[int, int] = {}
for t in label:
size[t] = size.get(t, 0) + 1
small = [t for t in size if size[t] < k]
if not small: # @line L3
break
t = min(small, key=lambda s: root[s])
u = root[t] # @line L4
x = min((v for v in range(n) if label[v] != t), key=lambda v: (w[u][v], v)) # @line L5
edges.append((u, x)) # @line L6
target = label[x]
for v in range(n):
if label[v] == t:
label[v] = target
return edges
def _decompose(vec: list[Row], real: list[bool], adj: dict[int, set[int]], k: int) -> tuple[set[int], set[int]]:
"""Split one tree (the vertex set of adj) with s >= 3k - 2 row vertices into two trees,
each with at least k row vertices. May add one Steiner vertex to vec, real and adj.
The walk only goes down in the tree rooted at r, so one call takes O(t log t) time
for a tree of t vertices.
"""
s = sum(1 for v in adj if real[v])
r = min(v for v in adj if real[v])
# Root the tree at r once, with an explicit stack, and count the row vertices of each subtree.
parent = {r: -1}
order = [r]
stack = [r]
while stack:
v = stack.pop()
for y in adj[v]:
if y not in parent:
parent[y] = v
order.append(y)
stack.append(y)
cnt = {v: (1 if real[v] else 0) for v in order}
for v in reversed(order):
if parent[v] >= 0:
cnt[parent[v]] += cnt[v]
u = r # @line L12
def side(y: int) -> int:
"""The row vertices on the side of y when the edge u-y is cut."""
return cnt[y] if parent[y] == u else s - cnt[u]
while True:
c = min(adj[u], key=lambda y: (-side(y), y))
phi = side(c) # @line L13
if phi <= s - k: # @line L14
break
u = c
children = sorted(adj[u], key=lambda y: (-side(y), y))
def subtree(top: int) -> set[int]:
"""The vertices on the side of top when the edge u-top is cut."""
out = {top}
st = [top]
while st:
v = st.pop()
for y in adj[v]:
if y != u and y not in out:
out.add(y)
st.append(y)
return out
if phi >= k: # @line L15
part = subtree(c)
adj[u].discard(c)
adj[c].discard(u)
return part, set(adj) - part
group: set[int] = set() # @line L16
taken: list[int] = []
got = 0
for y in children:
if got >= k:
break
group |= subtree(y)
taken.append(y)
got += side(y)
steiner = len(vec) # @line L17
vec.append(vec[u])
real.append(False)
adj[steiner] = set()
for y in taken:
adj[u].discard(y)
adj[y].discard(u)
adj[y].add(steiner)
adj[steiner].add(y)
group.add(steiner)
return group, set(adj) - group
def anonymize(rows: Sequence[Row], k: int) -> tuple[list[list[int]], list[tuple[Optional[Hashable], ...]], int]:
"""Return (clusters, table, cost). The clusters partition the row indices; each has
between k and 3k - 3 rows. In table, each cell of a column on which the rows
of its cluster differ is None. The cost is the number of None cells, and it is at
most (3k - 3) times the optimal cost.
Precondition: 2 <= k <= len(rows), and all rows have the same length d.
Cost: O(n^2 d) time for the weights and the forest, O(n^2 log n) time for at most
n / k splits of O(n log n) each, and O(n^2) space.
"""
n = len(rows)
edges = build_forest(rows, k)
vec: list[Row] = list(rows)
real = [True] * n
adj_all: dict[int, set[int]] = {v: set() for v in range(n)}
for u, x in edges:
adj_all[u].add(x)
adj_all[x].add(u)
seen: set[int] = set()
trees: list[set[int]] = [] # @line L7
for v in range(n):
if v not in seen:
comp = {v}
st = [v]
while st:
y = st.pop()
for z in adj_all[y]:
if z not in comp:
comp.add(z)
st.append(z)
seen |= comp
trees.append(comp)
done: list[set[int]] = []
work = trees
while work: # @line L8
t = work.pop()
if sum(1 for v in t if real[v]) <= 3 * k - 3:
done.append(t)
continue
adj = {v: set(y for y in adj_all[v] if y in t) for v in t}
a, b = _decompose(vec, real, adj, k) # @line L9
for v in adj:
adj_all[v] = adj[v]
work.append(a)
work.append(b)
clusters = sorted(sorted(v for v in t if real[v]) for t in done)
table: list[tuple[Optional[Hashable], ...]] = [tuple(r) for r in rows]
cost = 0
d = len(rows[0])
for cl in clusters: # @line L10
differ = [j for j in range(d) if len({rows[i][j] for i in cl}) > 1]
cost += len(cl) * len(differ)
for i in cl:
table[i] = tuple(None if j in differ else rows[i][j] for j in range(d))
return clusters, table, cost # @line L11
test_k_anonymity_approximation.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-anonymity-approximation/. The authors are listed in prov/3CXF3J.jsonl.
import random
from collections import Counter
from k_anonymity_approximation import anonymize, build_forest, hamming
ROWS = [
(0, 0, 0, 0),
(0, 0, 0, 1),
(0, 0, 1, 1),
(1, 1, 1, 1),
(1, 1, 1, 0),
(1, 1, 0, 0),
(0, 1, 0, 1),
]
def block_cost(rows, block):
d = len(rows[0])
return len(block) * sum(1 for j in range(d) if len({rows[i][j] for i in block}) > 1)
def partitions(items):
if not items:
yield []
return
first, rest = items[0], items[1:]
for part in partitions(rest):
for i in range(len(part)):
yield part[:i] + [[first] + part[i]] + part[i + 1:]
yield [[first]] + part
def optimum(rows, k):
return min(
sum(block_cost(rows, b) for b in part)
for part in partitions(list(range(len(rows))))
if all(len(b) >= k for b in part)
)
def forest_weight(rows, edges):
return sum(hamming(rows[u], rows[x]) for u, x in edges)
def check(rows, k):
clusters, table, cost = anonymize(rows, k)
n = len(rows)
assert sorted(i for c in clusters for i in c) == list(range(n))
assert all(k <= len(c) <= 3 * k - 3 for c in clusters)
assert cost == sum(block_cost(rows, c) for c in clusters)
assert cost == sum(1 for r in table for x in r if x is None)
counts = Counter(table)
assert all(counts[r] >= k for r in table)
for i in range(n):
assert all(table[i][j] is None or table[i][j] == rows[i][j] for j in range(len(rows[i])))
return clusters, cost
def test_page_example() -> None:
edges = build_forest(ROWS, 3)
assert edges == [(0, 1), (1, 2), (3, 4), (4, 5), (6, 1)]
assert forest_weight(ROWS, edges) == 5
clusters, cost = check(ROWS, 3)
assert clusters == [[0, 1, 2, 6], [3, 4, 5]]
assert cost == 4 * 3 + 3 * 2
assert optimum(ROWS, 3) == 18
def test_split_of_a_large_tree() -> None:
rows = [(i,) for i in range(8)]
clusters, cost = check(rows, 2)
assert all(len(c) <= 3 for c in clusters)
assert cost <= 3 * optimum(rows, 2)
def test_edge_cases() -> None:
assert anonymize([(1, 2), (1, 2)], 2) == ([[0, 1]], [(1, 2), (1, 2)], 0)
assert anonymize([(1, 2), (3, 4)], 2) == ([[0, 1]], [(None, None), (None, None)], 4)
same = [(5, 5, 5)] * 9
clusters, cost = check(same, 2)
assert cost == 0
def test_random_against_brute_force() -> None:
rng = random.Random(2005)
for _ in range(500):
k = rng.randint(2, 3)
n = rng.randint(k, 7)
d = rng.randint(1, 4)
sigma = rng.randint(2, 3)
rows = [tuple(rng.randrange(sigma) for _ in range(d)) for _ in range(n)]
_, cost = check(rows, k)
opt = optimum(rows, k)
assert forest_weight(rows, build_forest(rows, k)) <= opt
assert cost <= (3 * k - 3) * opt
def test_random_larger_tables() -> None:
rng = random.Random(77)
for _ in range(200):
k = rng.randint(2, 5)
n = rng.randint(k, 30)
d = rng.randint(1, 4)
rows = [tuple(rng.randrange(3) for _ in range(d)) for _ in range(n)]
check(rows, k)
History
Meyerson and Williams (2004) proved that k-anonymity by suppression is NP-hard and gave the first approximation algorithms, with ratio . Aggarwal, Feder, Kenthapadi, Motwani, Panigrahy, Thomas and Zhu (ICDT 2005) gave the forest algorithm with ratio , showed that a ternary alphabet is enough for NP-hardness, and showed that is the best ratio for methods that use only the distances. Park and Shim (2007) later lowered the ratio to .
References
- Gagan Aggarwal, Tomas Feder, Krishnaram Kenthapadi, Rajeev Motwani, Rina Panigrahy, Dilys Thomas and An Zhu, Anonymizing tables, Proceedings of ICDT 2005, LNCS 3363, pp. 246 to 258, the graph representation, the forest algorithm, the decomposition of large trees, the ratio 3k - 3 and its improvement to max(2k - 1, 3k - 5), and the lower bound for the graph representation
- Adam Meyerson and Ryan Williams, On the complexity of optimal k-anonymity, Proceedings of the 23rd ACM Symposium on Principles of Database Systems (PODS 2004), pp. 223 to 228, Section 4, the O(k log k) and O(k log m) approximations and the bound of Lemma 4.1
- Hyoungmin Park and Kyuseok Shim, Approximate algorithms for k-anonymity, Proceedings of ACM SIGMOD 2007, pp. 67 to 78, the O(log k) approximation
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 3CXF3J Edit this page History Report an error Markdown