Algorithmcore
Datafly
Also called Datafly algorithm.
Greedily generalizes the quasi-identifier attribute with the most distinct values until few records violate k-anonymity, then suppresses those.
- Time
- O(h n d) worst
- Space
- O(n d) extra
- Where
- d = the number of quasi-identifier attributes; h = the sum of the hierarchy heights; n = the number of rows
- Model
- Word RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Latanya Sweeney, 1997
Datafly is the greedy algorithm of Sweeney for k-anonymity by full-domain generalization and suppression. It starts from the raw table. While more than rows are in classes of fewer than rows, it raises by one level the quasi-identifier attribute that has the most distinct values. Then it suppresses the rows that are still in small classes. The release is always k-anonymous, and the algorithm is fast, but the result is not always a minimal generalization: it is a greedy heuristic for the choice of the levels.
In plain words
The attribute with the most different values is the one that makes rows look different from each other, such as a full date of birth. So coarsen it first: write the date as year and month. Look again at the table. If many rows are still alone or in very small groups, coarsen the attribute that now has the most different values. Stop when only a few rows, at most , are still in small groups. Delete those rows and release the rest.
Each step is a good local move, but it does not look ahead. It can coarsen an attribute that did not need it.
The problem
The input is a table of rows with quasi-identifier attributes, a tree hierarchy for each attribute with levels , where level maps all values to one value, and an integer . The output is a vector with and a set of at most rows such that generalized by , without the rows of , is k-anonymous. Let . The value of is a policy choice.
The algorithm
DATAFLY(T, H, k)- 1
v ← (0, ..., 0) - 2
loop - 3
T' ← T generalized by v - 4
s ← the rows of T' whose tuple occurs fewer than k times in T' - 5
if |s| ≤ k then exit the loop - 6
a ← the attribute with the most distinct values in T', ties to the lowest index - 7
v_a ← v_a + 1 - 8
return (v, s)
The release is without the rows of , in a random order. Line L4 counts the tuples with a hash table.
Sweeney's Figure 8 has a further step. Her version replaces the values of the suppressed rows by stars and keeps the rows, so these rows form a class of their own, and a last step makes that class k-anonymous too. The version here removes the suppressed rows, so that step is not needed. The stop test of line L5 bounds the number of removed rows by .
Example
Take the 9 rows of Ciriani et al. (2007), with race, date of birth (yy/mm/dd), sex and ZIP:
| row | race | birth | sex | ZIP |
|---|---|---|---|---|
| 1 | asian | 64/04/12 | F | 94142 |
| 2 | asian | 64/09/13 | F | 94141 |
| 3 | asian | 64/04/15 | F | 94139 |
| 4 | asian | 63/03/13 | M | 94139 |
| 5 | asian | 63/03/18 | M | 94139 |
| 6 | black | 64/09/27 | F | 94138 |
| 7 | black | 64/09/27 | F | 94139 |
| 8 | white | 64/09/27 | F | 94139 |
| 9 | white | 64/09/27 | F | 94141 |
The hierarchies are: race to person; birth to yy/mm, to yy, to *; sex to *; ZIP to 4 digits and a star, to 3 digits, to *. Let .
| v (race, birth, sex, ZIP) | distinct values | rows in small classes | action |
|---|---|---|---|
| (0, 0, 0, 0) | 3, 6, 2, 4 | 9 | raise birth |
| (0, 1, 0, 0) | 3, 3, 2, 4 | 7 | raise ZIP |
| (0, 1, 0, 1) | 3, 3, 2, 2 | 5 | raise race (tie with birth, lower index) |
| (1, 1, 0, 1) | 1, 3, 2, 2 | 2 | stop, suppress rows 1 and 3 |
The release has the classes = (person, 64/09, F, 9414*), = (person, 63/03, M, 9413*) and = (person, 64/09, F, 9413*). With the run goes on to (1, 2, 0, 1) and suppresses rows 4 and 5.
The vector (0, 1, 0, 2), of the same height 3, keeps the race and leaves only 1 row to suppress. Datafly does not find it, because at the third step it raised race and not ZIP.
Correctness
If the loop goes on, some attribute has at least 2 distinct values in . Otherwise all rows of are equal, and is 0 (when ) or , so line L5 stops. Line L6 then picks an attribute with at least 2 values, which is not at its top level, because the top level has one value. So line L7 keeps , and the height grows by one in each round. The loop stops after at most rounds. At the stop, each row outside is in a class of at least rows of , and all rows of that class are outside , so the release is k-anonymous. The full proof is in proofs/correctness.md.
Proof: Datafly stops and releases a k-anonymous tablefull
The table has rows and quasi-identifier attributes. Attribute has a hierarchy with levels , and level maps every value of to one value. Let , and let . We write for generalized by the vector . Line L4 computes , the set of rows of whose combination of values occurs fewer than times in .
Lemma 1. If line L5 does not stop the loop, then line L6 picks an attribute with .
Proof. Assume that each attribute has one distinct value in . Then all the rows of are equal. If , no row is in a group of fewer than rows, so . If , all rows are in , so . In both cases , and line L5 stops the loop. So if the loop goes on, some attribute has at least 2 distinct values in , and line L6 picks an attribute with the most distinct values, so with at least 2. Level gives one value, so .
Theorem. DATAFLY stops after at most rounds of the loop of line L2. It returns with for each and , and the table without the rows of is k-anonymous.
Proof. Line L1 sets . By Lemma 1, each round that does not stop raises one level by one with before the step (line L7). So stays true, and the height goes up by one in each such round. The height is at most , so at most rounds go on, and the next round stops. This gives at most rounds.
The loop stops only at line L5, so at line L8. Let be the rows of that are not in . Each row of has a combination of values that occurs at least times in . All the rows with this combination are outside , because holds a row exactly when its combination occurs fewer than times. So each combination of occurs at least times in , and is k-anonymous.
Remark. The theorem says nothing about the quality of . The page gives a table where Datafly returns a vector of height 2 while a vector of height 1 also has at most rows to suppress. Datafly is a heuristic for the choice of , and only the k-anonymity of the release is a theorem.
Complexity
Let be the number of rows, the number of attributes and the sum of the hierarchy heights. The model is the word RAM with hashing.
- One round generalizes the rows (line L3), counts the tuples (line L4) and counts the distinct values per attribute (line L6): expected time.
- There are at most rounds, so the time is expected, and the space is .
This is much less than the of Samarati's algorithm, where is the size of the lattice, because Datafly follows one path up the lattice.
Properties
- Always k-anonymous. This is a theorem, for each input.
- Not minimal. The result is a heuristic choice. Sweeney (2002) says that Datafly can generalize more than needed. A small case: attribute A with values 0 to 3 and levels (value, value div 2, *), attribute B with values 0 to 2 and levels (value, *), and the rows (3, 0), (2, 2), (1, 0), (2, 1), (0, 0), (0, 0) with . Datafly returns (1, 1). The lower vector (0, 1) leaves only rows 1 and 3 to suppress, which is at most .
- At most k suppressed rows. The limit on suppression is tied to and is not a separate parameter, as MaxSup is in Samarati's algorithm.
- Deterministic, with the tie rule of line L6.
Variants and improvements
- The Datafly system. Sweeney (1997) describes a whole system for the release of medical records, with more inputs and choices than the core algorithm. The core algorithm here is the part that Sweeney (2002) analyzes.
- Other greedy rules. Choose the attribute that most reduces the number of rows in small classes, or that loses the least precision per step. These are also heuristics.
- Exact searches. Samarati's algorithm finds a vector of least height, and Incognito finds all k-anonymous vectors.
- Multidimensional cuts. Mondrian is also greedy, but it cuts boxes of the value space and loses less detail on numeric data.
When to use it
Use Datafly when the lattice is too large to search, a fast and always k-anonymous answer is enough, and some extra generalization is acceptable. It is also a good baseline for the exact algorithms. If the least generalization matters, use Samarati's algorithm or Incognito on the same hierarchies.
Pitfalls
- A table with at most k rows. If , then at once, and line L5 stops at the raw table with every row in . Nothing is released. Check first.
- Distinct values of the raw table in line L6. The counts must come from the current table . With the counts of the raw table, the same attribute stays the largest, and line L7 raises it to its top before it looks at any other.
- Keeping the suppressed rows with stars in line L8. If the rows of are released with all quasi-identifier values replaced by stars, they form one class of rows, and can be less than . Remove them, or add the last step of Sweeney's Figure 8.
- A top level with more than one value. Then line L7 can push past . Each hierarchy must end in a single value.
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/datafly/. The authors are listed in prov/JK6NEV.jsonl.
"""Sweeney's Datafly heuristic for k-anonymity by full-domain generalization and row suppression.
A table is a list of rows. Each row is a tuple of d quasi-identifier values.
A hierarchy for attribute a is a list of dicts: hierarchy[a][l] maps each raw
value of attribute a to its value at level l, hierarchy[a][0] is the identity,
and the last level maps every value of the attribute to one value.
"""
from collections import Counter
from typing import Hashable, Sequence
Row = tuple[Hashable, ...]
Hierarchy = Sequence[Sequence[dict[Hashable, Hashable]]]
def datafly(table: Sequence[Row], hierarchy: Hierarchy, k: int) -> tuple[tuple[int, ...], list[int]]:
"""Return (v, s): the generalization vector chosen by Datafly and the sorted indices of the
rows to suppress. The table generalized by v, without the rows in s, is k-anonymous,
and s has at most k rows.
Precondition: k >= 1, every row has d values, and the top level of each hierarchy
maps all values of its attribute to one value.
Cost: at most h + 1 rounds, where h is the sum of the hierarchy heights, and
O(n d) expected time per round for n rows and d attributes.
"""
d = len(hierarchy)
v = [0] * d # @line L1
while True: # @line L2
gen = [tuple(hierarchy[a][v[a]][row[a]] for a in range(d)) for row in table] # @line L3
counts = Counter(gen)
s = [i for i, g in enumerate(gen) if counts[g] < k] # @line L4
if len(s) <= k: # @line L5
break
distinct = [len({g[a] for g in gen}) for a in range(d)]
best = max(range(d), key=lambda a: (distinct[a], -a)) # @line L6
v[best] += 1 # @line L7
return tuple(v), s # @line L8
test_datafly.py 107 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/datafly/. The authors are listed in prov/JK6NEV.jsonl.
import random
from datafly import datafly
ROWS = [
("asian", "64/04/12", "F", "94142"),
("asian", "64/09/13", "F", "94141"),
("asian", "64/04/15", "F", "94139"),
("asian", "63/03/13", "M", "94139"),
("asian", "63/03/18", "M", "94139"),
("black", "64/09/27", "F", "94138"),
("black", "64/09/27", "F", "94139"),
("white", "64/09/27", "F", "94139"),
("white", "64/09/27", "F", "94141"),
]
RACES = ["asian", "black", "white"]
DOBS = sorted({r[1] for r in ROWS})
ZIPS = sorted({r[3] for r in ROWS})
HIER = [
[{x: x for x in RACES}, {x: "person" for x in RACES}],
[{x: x for x in DOBS}, {x: x[:5] for x in DOBS}, {x: x[:2] for x in DOBS}, {x: "*" for x in DOBS}],
[{"F": "F", "M": "M"}, {"F": "*", "M": "*"}],
[{z: z for z in ZIPS}, {z: z[:4] + "*" for z in ZIPS}, {z: z[:3] + "**" for z in ZIPS}, {z: "*" for z in ZIPS}],
]
def test_page_example() -> None:
assert datafly(ROWS, HIER, 2) == ((1, 1, 0, 1), [0, 2])
assert datafly(ROWS, HIER, 3) == ((1, 2, 0, 1), [3, 4])
def test_not_minimal() -> None:
hier = [
[{i: i for i in range(4)}, {i: i // 2 for i in range(4)}, {i: 0 for i in range(4)}],
[{i: i for i in range(3)}, {i: 0 for i in range(3)}],
]
rows = [(3, 0), (2, 2), (1, 0), (2, 1), (0, 0), (0, 0)]
assert datafly(rows, hier, 2) == ((1, 1), [])
# The vector (0, 1) is strictly lower and leaves only 2 = k rows to suppress.
assert violators(rows, hier, (0, 1), 2) == [0, 2]
def test_edge_cases() -> None:
assert datafly([], HIER, 2) == ((0, 0, 0, 0), [])
assert datafly(ROWS[:1], HIER, 2) == ((0, 0, 0, 0), [0])
assert datafly(ROWS, HIER, 1) == ((0, 0, 0, 0), [])
same = [ROWS[0]] * 5
assert datafly(same, HIER, 5) == ((0, 0, 0, 0), [])
assert datafly(same, HIER, 6) == ((0, 0, 0, 0), [0, 1, 2, 3, 4])
assert datafly(ROWS, HIER, 8) == ((1, 3, 1, 2), [])
# With n <= k the stop test holds at once, and every row is suppressed.
assert datafly(ROWS, HIER, 9) == ((0, 0, 0, 0), list(range(9)))
def violators(rows, hier, v, k):
keys = [tuple(hier[a][v[a]][r[a]] for a in range(len(v))) for r in rows]
return [i for i, key in enumerate(keys) if keys.count(key) < k]
def random_hierarchy(rng: random.Random, r: int) -> list[dict[int, int]]:
"""A chain of coarser and coarser partitions of range(r), ending in one block."""
block = list(range(r))
levels = [dict(enumerate(block))]
while len(set(block)) > 1:
labels = sorted(set(block))
rng.shuffle(labels)
cut = rng.randint(2, len(labels))
merged = set(labels[:cut])
new_label = min(merged)
block = [new_label if b in merged else b for b in block]
levels.append(dict(enumerate(block)))
return levels
def oracle(rows, hier, k):
"""Datafly from its definition, with the stop test and the choice written out again."""
d = len(hier)
v = [0] * d
while len(violators(rows, hier, v, k)) > k:
keys = [tuple(hier[a][v[a]][r[a]] for a in range(d)) for r in rows]
best, best_count = 0, -1
for a in range(d):
count = len(set(key[a] for key in keys))
if count > best_count:
best, best_count = a, count
v[best] += 1
return tuple(v), violators(rows, hier, v, k)
def test_random_against_definition() -> None:
rng = random.Random(1997)
for _ in range(800):
d = rng.randint(1, 4)
sizes = [rng.randint(1, 5) for _ in range(d)]
hier = [random_hierarchy(rng, r) for r in sizes]
n = rng.randint(0, 20)
rows = [tuple(rng.randrange(r) for r in sizes) for _ in range(n)]
k = rng.randint(1, 5)
v, s = datafly(rows, hier, k)
assert (v, s) == oracle(rows, hier, k)
assert len(s) <= k
assert all(0 <= v[a] < len(hier[a]) for a in range(d))
kept = [r for i, r in enumerate(rows) if i not in set(s)]
keys = [tuple(hier[a][v[a]][r[a]] for a in range(d)) for r in kept]
assert all(keys.count(key) >= k for key in keys)
History
Sweeney built the Datafly system for the release of medical records and described it at the AMIA symposium in 1997. In 2002 she gave the core Datafly algorithm, together with the exact but slow MinGen, and showed that Datafly can generalize more than a minimal generalization. Later work, such as Incognito (2005), compared exact full-domain search with such greedy methods.
References
- Latanya Sweeney, Guaranteeing anonymity when sharing medical data, the Datafly system, Proceedings of the AMIA Annual Fall Symposium, 1997, pp. 51 to 55, the Datafly system and its generalization of the attributes with the most distinct values
- Latanya Sweeney, Achieving k-anonymity privacy protection using generalization and suppression, International Journal of Uncertainty, Fuzziness and Knowledge-Based Systems 10(5), 2002, pp. 571 to 588, Figure 8, the core Datafly algorithm, and the discussion of why its result need not be minimal
- Valentina Ciriani, Sabrina De Capitani di Vimercati, Sara Foresti and Pierangela Samarati, k-Anonymity, in Secure Data Management in Decentralized Systems, Springer, Advances in Information Security, 2007, Section 4, the summary of the greedy algorithm of Sweeney among the algorithms for k-anonymity
- Kristen LeFevre, David J. DeWitt and Raghu Ramakrishnan, Incognito, efficient full-domain k-anonymity, Proceedings of ACM SIGMOD 2005, pp. 49 to 60, the discussion of greedy full-domain algorithms that do not find a minimal generalization
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 JK6NEV Edit this page History Report an error Markdown