Algorithmadvanced
k-degree anonymization
Also called Liu-Terzi algorithm.
Makes each degree of a graph shared by at least k vertices; a dynamic program finds the cheapest such degree sequence, then edges are added to realize it.
- Time
- O(n log n + n k + n r) worst
- Space
- O(n) extra
- Where
- k = the anonymity parameter; n = the number of vertices; r = the largest number of edges a vertex must gain
- Model
- Word RAM
- Properties
- deterministicnot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kun Liu, Evimaria Terzi, 2008
k-degree anonymization changes a graph so that every vertex shares its degree with at least other vertices. The goal is to stop one kind of re-identification: in a social network released with the names removed, an attacker who knows that a person has, say, 97 friends can find the person if only one vertex has degree 97. Liu and Terzi (SIGMOD 2008) asked for a k-degree anonymous supergraph of the input with the fewest added edges. Their method has two steps. A dynamic program finds, in time for vertices, the k-anonymous degree sequence closest to the input in the distance; this step is exact. A graph construction step then tries to add edges that give each vertex its new degree; this step is a heuristic, which may answer "unknown". When it succeeds, the result has the fewest possible added edges. The value of is a policy choice, and the protection covers only an attacker whose knowledge is the degree.
In plain words
In a friendship graph, one person may have far more friends than anyone else. If you know that number, you can find the person even without names.
The fix is to add some friendships so that each friend count is shared by at least people. Adding edges can only raise counts, so the plan first decides the new counts. It sorts the people by count, cuts the sorted list into runs of at least people, and raises everyone in a run to the largest count of the run. A dynamic program picks the cuts that need the least total raising.
Then the plan adds the edges. It takes the person who needs the most new friends and links them to the people who also need the most, skipping people who are friends already. If it gets stuck, it reports that it could not finish.
The problem
The input is a simple graph with vertices and an integer . A vector of integers is k-anonymous if every value in it appears at least times (Definition 1 of the paper). A graph is k-degree anonymous if its degree sequence is k-anonymous (Definition 2). Problem 1 of the paper asks for a k-degree anonymous simple graph with and as small as possible.
By the handshake lemma, , where and are the degree sequences (Equation 1). So the problem splits into two:
- Degree anonymization. Given sorted with , find a k-anonymous with the least .
- Graph construction. Given and , find a supergraph of with degree sequence .
A complete graph is always k-degree anonymous, so a solution exists when .
The algorithm
Write for the cost of raising the positions to of the sorted sequence to , and for the least cost of a k-anonymous raise of the first positions.
K-DEGREE-ANONYMIZE(G, k) ▷ n ≥ k- 1
d ← the degrees of G, sorted so that d(1) ≥ ... ≥ d(n) - 2
for i ← 1 to n do - 3
if i < 2k then DA(i) ← I(1, i), cut(i) ← 0 - 4
else DA(i) ← min of DA(t) + I(t + 1, i) over max(k, i − 2k + 1) ≤ t ≤ i − k, cut(i) ← the best t - 5
follow cut from n back to 0; raise each group (t, i] to d(t + 1), giving d̂ - 6
a(v) ← d̂(v) − d(v) for every vertex v - 7
if the sum of a is odd then return UNKNOWN - 8
while some a(v) > 0 do - 9
v ← a vertex with the largest a(v) - 10
W ← the a(v) vertices w ≠ v, not adjacent to v, with a(w) > 0 and a(w) as large as possible - 11
if |W| < a(v) then return UNKNOWN - 12
for each w in W, add the edge (v, w) and set a(w) ← a(w) − 1 - 13
a(v) ← 0 - 14
return G with the added edges
Lines L1 to L5 are the DP algorithm of the paper with its faster recursion (Equation 4). In an optimal , the vertices that end with the same degree form a run of the sorted sequence (Observation 1), and the run is raised to its first value. Line L3 covers prefixes shorter than , which cannot hold two runs of at least . Line L4 tries every last run of length between and ; a longer run never helps, because it can be cut into two runs of at least without raising the cost. Lines L6 to L13 are Supergraph (Section 5.2). The paper picks an arbitrary vertex at line L9; the code takes the largest and breaks ties by the position in the sorted order.
Example
The graph has seven synthetic vertices and the edges , , , , , , . Its sorted degree sequence is for . Take .
| rule | candidates | cut | ||
|---|---|---|---|---|
| 1 | 0 | 0 | ||
| 2 | 1 | 0 | ||
| 3 | 3 | 0 | ||
| 4 | 1 | 2 | ||
| 5 | , | 1 | 2 | |
| 6 | , | 2 | 4 | |
| 7 | , | 2 | 5 |
Line L5 follows the cuts , so the runs are , and , and . The cost is , so at least one edge must be added. Line L6 gives , and 0 elsewhere; the sum is even. Line L9 takes , line L10 finds , which is not adjacent to , and line L12 adds the edge . The new degrees are : every degree appears at least twice, and one added edge is the least possible.
Correctness
The DP part is exact (Theorem 1 of the paper). By Observation 1, an optimal cuts the sorted sequence into runs of at least positions, and the cost of a run is . The optimal cost of the first positions is the best last run plus the optimal cost of what comes before it, which is the principle of optimality. Line L4 may skip runs of or more: such a run splits into and , both of at least positions, and raising the second part to costs no more. So over all k-anonymous .
The construction part keeps the invariant that the current graph is a simple supergraph of and that each vertex still needs edges to reach . Line L10 only picks vertices not adjacent to and that still need edges, so no edge is repeated and no vertex goes past its target. If the loop ends, all are 0, so the graph has degree sequence , which is k-anonymous, with exactly added edges. Any k-degree anonymous supergraph needs at least added edges, because its degree sequence is a k-anonymous vector at least . So a graph returned at line L14 is optimal. UNKNOWN does not mean that no such supergraph exists; Supergraph is not an oracle, unlike ConstructGraph for graphs built from nothing (Algorithm 1, based on the Erdős-Gallai condition). The full proof is in proofs/correctness.md.
Proof: The degree dynamic program is optimal, and a graph that Supergraph returns adds the fewest edgesfull
Let be the sorted degrees of a simple graph and let . A vector is k-anonymous if each of its values occurs at least times. Let be the least over all k-anonymous with . Write .
Claim 1 (runs). Some optimal cuts the positions into runs of consecutive positions, each of length at least and at most (or a single run when ), and sets every position of a run to . Its cost is the sum of over the runs.
Proof. Take any k-anonymous and group the positions by the value of . Each group has at least positions. Replacing the value of a group by the largest in it keeps , keeps the groups, and does not raise the cost, so assume this. Now sort the groups by value. If a group with value holds a position and a group with a smaller value holds a position , then , and . Swap the two positions between the groups: position now gets and gets , so still holds, the group sizes do not change, and the cost changes by . Repeat until each group holds consecutive positions; each swap moves a position of a larger value to the left, so this ends. Each group is then a run , and after the replacement above its value is , its largest degree.
A run with splits into and , both of length at least . The second part gets the value , which still is at least each in it and costs no more. So some optimal has all runs shorter than , except a single run when makes two runs impossible.
Claim 2 (the recursion). After line L4 for position , is the least cost of cutting into runs as in Claim 1.
Proof. By induction on . If , the prefix cannot hold two runs of at least , so the only cut is one run, of cost , which line L3 sets. If , the last run has , so ; it is not the only run, since a single run would be or longer, so the runs before it cover with . Their least cost is by induction. Line L4 takes the minimum of over exactly these .
By Claims 1 and 2, , and line L5 follows the stored cuts to build a of cost : each run is set to , so , and each run has at least positions, so is k-anonymous. (Runs next to each other may end with the same value, which only makes the groups larger.)
Claim 3 (the lower bound). Every k-degree anonymous simple graph on the same vertices adds at least edges.
Proof. The degree of each vertex can only grow, so the degree sequence of , listed in the order of , is a k-anonymous vector at least . By the handshake lemma, the number of added edges is half the total growth of the degrees, which is at least .
Claim 4 (Supergraph). If lines L6 to L14 return a set of edges, adding it to gives a simple graph with degree sequence and exactly added edges, which is the least possible.
Proof. Keep the invariant: the current graph is a simple supergraph of , and for every vertex , with . Line L6 makes it true with . In one pass, line L10 picks only vertices that are not adjacent to in and have , so the new edges are new, have two distinct ends, and are distinct from each other. Line L12 adds 1 to and takes 1 from for each of them, and gains edges, after which line L13 sets . So the invariant holds after the pass. Each pass makes zero for a vertex with and never raises any , so the loop ends. If it ends at line L14, every , so . The number of added edges is , which by Claim 3 is the least possible.
UNKNOWN is not a proof of impossibility. For with one edge on three vertices and , the only least-cost is , whose sum is odd, so line L7 answers UNKNOWN, while the triangle is a 2-degree anonymous supergraph with two added edges.
Cost. Sorting takes time and the prefix sums , after which each takes time. Line L4 tries at most values of , so the DP takes time and space. Line L5 takes time. In the code each pass of the construction scans and sorts candidates and there are at most passes, for time.
Complexity
- Line L1 sorts in time, or with a counting sort, since degrees are below .
- With prefix sums , each takes time. Line L4 tries at most values of , so lines L2 to L4 take time (Section 4). The paper notes that the factor can be removed with more bookkeeping, for time.
- Line L5 takes time.
- The paper gives time for Supergraph with bucket arrays of vertices by residual degree, where is the largest . The code is simpler: each pass of line L9 scans all vertices and sorts the candidates, which costs in the worst case.
- The extra space is besides the graph.
Properties
- Additions only. Every edge of stays. Running the same method on the complement graph gives the version with deletions only (Section 2).
- Monotone in . A k-degree anonymous graph is also -degree anonymous for every (Proposition 1).
- Exact first step, heuristic second step. The degree sequence is optimal; the graph may not exist as a supergraph of , and Supergraph may miss one that does.
- Deterministic as coded. The paper's Supergraph picks an arbitrary vertex at line L9; the code fixes the choice.
Variants and improvements
- Greedy degree anonymization. The paper also gives a greedy method that starts each run with vertices and decides for each next vertex whether to join the run or start a new one by comparing two costs. It is not exact; in their experiments its cost was at most 1.5 times the DP cost (a measurement, Section 7.2).
- Probing. When Supergraph answers UNKNOWN, the Probing scheme of Section 5.3 (Algorithm 2) adds a little random noise to the input degrees, recomputes and tries again, at the price of a few more edges. Their noise slightly raises the degrees of low-degree vertices, which gives the high-degree vertices more partners. The loop ends at the latest when all degrees reach .
- The relaxed problem. Section 6 drops the rule and asks only for a large overlap. Greedy_Swap (Algorithm 3) builds a graph with degree sequence from nothing and then makes edge swaps that keep the degrees and increase the overlap with . The Priority algorithm instead prefers edges of while it builds.
- Additions and deletions together. Section 8 shows that the same framework, with small changes, handles graphs that may both gain and lose edges.
- Stronger structural models. Hay et al. (PVLDB 2008) group vertices into supernodes and publish only counts of edges within and between groups, which protects against attackers who know more than the degree, such as the shape of a neighbourhood.
- Differential privacy instead. Hay, Li, Miklau and Jensen (ICDM 2009) publish the degree distribution itself under differential privacy with edge neighbors, where two graphs are neighbors if they differ in one edge. Node neighbors, which differ in one vertex and all its edges, give a far stronger guarantee for a person and need much more noise.
When to use it
Use k-degree anonymization when a graph must be released as a graph, the threat is an attacker who knows degrees, and the added edges are an acceptable distortion. Liu and Terzi measured how close the anonymized graphs stay to the input, with the clustering coefficient, the average path length and other structural measures, on synthetic and real graphs of up to about 8000 vertices (Section 7). Do not use it as a general protection. An attacker who knows a neighbourhood, or who planted accounts before the release as in the active attack on social graphs, is not stopped by equal degrees, and de-anonymization by structure uses much more than degrees. For statistics of a graph, a differentially private release is the safer choice.
Pitfalls
- Allowing at line L4. If the range of starts below , the first run can be shorter than , and the result is not k-anonymous. Both ends of the range matter: for the first runs and for the last.
- Raising a run to the wrong value at line L5. Raising a run to its smallest or its mean degree needs edge deletions for the vertices above that value, which Problem 1 does not allow. With additions only, a run must go to its largest degree .
- Picking adjacent vertices at line L10. If line L10 does not skip the vertices already adjacent to , it adds an edge that already exists, and the result is not a simple graph. The degrees on paper are then wrong.
- Skipping the parity test at line L7. If the sum of is odd, no set of new edges can add exactly to each vertex, because each edge adds 2 to the sum. Without the test, the loop ends with one vertex short.
- Reading UNKNOWN at lines L7 and L11 as "impossible". Take one edge on three vertices and . The DP gives with cost 1, whose sum is odd, so line L7 answers UNKNOWN. Yet adding the two missing edges gives a triangle, which is 2-degree anonymous. Probing, or a different choice at line L9, can find a graph that the first try misses.
- Treating degree anonymity as anonymity. The guarantee covers only an attacker whose knowledge is one number per person. Backstrom, Dwork and Kleinberg and later work show that structure beyond degrees re-identifies people in released graphs.
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-degree-anonymization/. The authors are listed in prov/X8DF57.jsonl.
from collections.abc import Sequence
Edge = tuple[int, int]
def anonymize_degrees(d: Sequence[int], k: int) -> tuple[list[int], int]:
"""Return the k-anonymous sequence closest to d in L1 distance with no entry lowered, and that distance.
Precondition: d is sorted in non-increasing order, k >= 1, and len(d) is 0
or at least k. Ties go to the smallest cut. Cost: O(n k) time, O(n) space.
"""
n = len(d)
if 0 < n < k or k < 1:
raise ValueError("need k >= 1 and n = 0 or n >= k")
prefix = [0] * (n + 1)
for j in range(n):
prefix[j + 1] = prefix[j] + d[j]
def cost(a: int, b: int) -> int:
# I(a, b) for the 1-based positions a..b: raise them all to d(a)
return (b - a + 1) * d[a - 1] - (prefix[b] - prefix[a - 1])
da = [0] * (n + 1)
cut = [0] * (n + 1)
for i in range(1, n + 1): # @line L2
if i < 2 * k: # @line L3
da[i], cut[i] = cost(1, i), 0
else: # @line L4
best_t = max(k, i - 2 * k + 1)
best = da[best_t] + cost(best_t + 1, i)
for t in range(best_t + 1, i - k + 1):
c = da[t] + cost(t + 1, i)
if c < best:
best, best_t = c, t
da[i], cut[i] = best, best_t
out = list(d)
i = n
while i > 0: # @line L5
t = cut[i]
for j in range(t, i):
out[j] = d[t]
i = t
return out, da[n]
def k_degree_anonymize(n: int, edges: Sequence[Edge], k: int) -> list[Edge] | None:
"""Return edges to add to the simple graph so that it becomes k-degree anonymous, or None for UNKNOWN.
The vertices are 0..n-1. When a list comes back, its length is the least
possible number of added edges. None means that Supergraph got stuck, not
that no answer exists. Precondition: the edges form a simple graph and
n = 0 or n >= k >= 1. Cost: O(n log n + n k) for the degree step and
O(n^2 log n) for the construction step as coded.
"""
adj: list[set[int]] = [set() for _ in range(n)]
for u, v in edges:
adj[u].add(v)
adj[v].add(u)
order = sorted(range(n), key=lambda v: (-len(adj[v]), v)) # @line L1
target, _ = anonymize_degrees([len(adj[v]) for v in order], k)
rank = {v: r for r, v in enumerate(order)}
a = [0] * n
for r, v in enumerate(order): # @line L6
a[v] = target[r] - len(adj[v])
if sum(a) % 2: # @line L7
return None
added: list[Edge] = []
while any(x > 0 for x in a): # @line L8
v = max(range(n), key=lambda u: (a[u], -rank[u])) # @line L9
cand = sorted((w for w in range(n) if w != v and w not in adj[v] and a[w] > 0), key=lambda w: (-a[w], rank[w]))
chosen = cand[: a[v]] # @line L10
if len(chosen) < a[v]: # @line L11
return None
for w in chosen: # @line L12
adj[v].add(w)
adj[w].add(v)
a[w] -= 1
added.append((min(v, w), max(v, w)))
a[v] = 0 # @line L13
return added # @line L14
test_k_degree_anonymization.py 117 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/k-degree-anonymization/. The authors are listed in prov/X8DF57.jsonl.
import itertools
import random
from collections import Counter
import pytest
from k_degree_anonymization import anonymize_degrees, k_degree_anonymize
# vertices a..g are 0..6
EDGES = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 2), (1, 5), (3, 4)]
def degrees(n: int, edges: list[tuple[int, int]]) -> list[int]:
deg = [0] * n
for u, v in edges:
deg[u] += 1
deg[v] += 1
return deg
def is_k_anonymous(values: list[int], k: int) -> bool:
return all(c >= k for c in Counter(values).values())
def test_example() -> None:
assert degrees(7, EDGES) == [4, 3, 2, 2, 2, 1, 0]
assert anonymize_degrees([4, 3, 2, 2, 2, 1, 0], 2) == ([4, 4, 2, 2, 2, 1, 1], 2)
assert k_degree_anonymize(7, EDGES, 2) == [(1, 6)]
def test_edges() -> None:
assert anonymize_degrees([], 3) == ([], 0)
assert k_degree_anonymize(0, [], 2) == []
assert anonymize_degrees([3, 1, 0], 3) == ([3, 3, 3], 5)
assert anonymize_degrees([2, 2, 1, 1], 1) == ([2, 2, 1, 1], 0)
with pytest.raises(ValueError):
anonymize_degrees([1, 1], 3)
# a star on 4 vertices with k = 4 must become complete
star = [(0, 1), (0, 2), (0, 3)]
added = k_degree_anonymize(4, star, 4)
assert added is not None and sorted(added) == [(1, 2), (1, 3), (2, 3)]
# one edge on 3 vertices, k = 2: the best sequence (1, 1, 1) has an odd sum, so the answer is UNKNOWN,
# although adding two edges gives the triangle, which is 2-degree anonymous
assert anonymize_degrees([1, 1, 0], 2) == ([1, 1, 1], 1)
assert k_degree_anonymize(3, [(0, 1)], 2) is None
def set_partitions(n: int) -> list[list[int]]:
out: list[list[int]] = [[]]
for _ in range(n):
out = [s + [b] for s in out for b in range((max(s) + 2) if s else 1)]
return out
PARTITIONS = {n: set_partitions(n) for n in range(1, 8)}
def brute_da(d: list[int], k: int) -> int:
"""Least L1 raise to a k-anonymous vector: every group of equal final values goes to its maximum."""
best = None
for labels in PARTITIONS[len(d)]:
groups: dict[int, list[int]] = {}
for b, x in zip(labels, d):
groups.setdefault(b, []).append(x)
if any(len(g) < k for g in groups.values()):
continue
c = sum(max(g) * len(g) - sum(g) for g in groups.values())
best = c if best is None or c < best else best
assert best is not None
return best
def test_dp_against_brute_force() -> None:
rng = random.Random(21)
for _ in range(500):
n = rng.randint(1, 7)
k = rng.randint(1, n)
d = sorted((rng.randint(0, n - 1) for _ in range(n)), reverse=True)
out, cost = anonymize_degrees(d, k)
assert cost == brute_da(d, k)
assert cost == sum(x - y for x, y in zip(out, d))
assert all(x >= y for x, y in zip(out, d))
assert is_k_anonymous(out, k)
def test_graph_against_brute_force() -> None:
rng = random.Random(22)
found = 0
for _ in range(300):
n = rng.randint(1, 5)
k = rng.randint(1, n)
pairs = list(itertools.combinations(range(n), 2))
edges = [e for e in pairs if rng.random() < 0.4]
missing = [e for e in pairs if e not in edges]
least = None
for r in range(len(missing) + 1):
for extra in itertools.combinations(missing, r):
if is_k_anonymous(degrees(n, edges + list(extra)), k):
least = r
break
if least is not None:
break
assert least is not None
_, cost = anonymize_degrees(sorted(degrees(n, edges), reverse=True), k)
assert 2 * least >= cost
added = k_degree_anonymize(n, edges, k)
if added is not None:
found += 1
assert len(set(added)) == len(added)
assert not set(added) & set(edges)
assert all(u != v for u, v in added)
assert is_k_anonymous(degrees(n, edges + added), k)
assert 2 * len(added) == cost == 2 * least
assert found > 200
History
Backstrom, Dwork and Kleinberg showed in 2007 that replacing names by random identifiers does not protect a social graph. Liu and Terzi answered with k-degree anonymity at SIGMOD 2008, adapting k-anonymity to graphs with the degree as the quasi-identifier. In the same year Hay et al. studied stronger structural knowledge and proposed supernodes. From 2009, work on graphs moved towards differential privacy, starting with degree distributions under edge neighbors.
References
- Kun Liu and Evimaria Terzi, Towards identity anonymization on graphs, ACM SIGMOD 2008, pages 93-106, Section 2 (Definitions 1 and 2, Proposition 1, Problem 1 and Equation 1), Section 4 (Observation 1, the DP Recursions 2 to 4, Theorem 1 and the Greedy algorithm), Section 5.1 (Lemma 1 and Algorithm 1, ConstructGraph), Section 5.2 (Definition 4, Lemma 2 and Supergraph), Section 5.3 (Algorithm 2, Probing), Section 6 (Greedy_Swap and Priority for the relaxed problem), Section 7 (the experiments) and Section 8 (additions and deletions together)
- Michael Hay, Gerome Miklau, David Jensen, Don Towsley and Philip Weis, Resisting structural re-identification in anonymized social networks, PVLDB 1(1), 2008, pages 102-114, the degree-based and other structural knowledge of an attacker, and the defense that groups vertices into supernodes
- Lars Backstrom, Cynthia Dwork and Jon Kleinberg, Wherefore art thou R3579X? Anonymized social networks, hidden patterns, and structural steganography, WWW 2007, pages 181-190, the attacks on graphs released with random identifiers, which motivate structural anonymity
- Michael Hay, Chao Li, Gerome Miklau and David Jensen, Accurate estimation of the degree distribution of private networks, IEEE ICDM 2009, pages 169-178, the release of a degree distribution under differential privacy with edge neighbors
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 X8DF57 Edit this page History Report an error Markdown