Algorithmcore
MDAV
Also called maximum distance to average vector.
Microaggregation heuristic that builds groups of k around the record farthest from the centroid and the record farthest from it, in turn.
- Time
- O(n^2 (d + log k) / k + n d) worst
- Space
- O(n) extra
- Where
- d = the number of attributes; k = the least group size; n = the number of records
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Josep Domingo Ferrer, Vicenc Torra, 2005
MDAV (maximum distance to average vector) is the standard heuristic for microaggregation of records with several numerical attributes. It forms groups of exactly records, two at a time: one group around the record farthest from the centroid of the records that are left, and one around the record farthest from that first record. When fewer than records are left, it forms at most one more group and puts the rest, between and records, in a last group. Each record is then replaced by the centroid of its group. The release is k-anonymous by construction. The loss is not optimal, because optimal multivariate microaggregation is NP-hard, but MDAV is simple, deterministic and fast, in distance work.
In plain words
Think of the records as points on a map. Find the middle of all the points. Take the point farthest from the middle: it is on the edge of the crowd, and it is the hardest point to hide. Make a group of it and its nearest neighbors, so that the group has the size you want. Then take the point farthest from that first point. It is on the other edge. Make a group around it in the same way. Remove both groups and do this again with the points that are left.
At the end a few points are left. They form the last group, which can be a little larger. Every point is then moved to the middle of its group. Each group shows one point many times, so no single point stands out.
The problem
The input is a list of records and an integer with . The attributes are on one scale, for example as z-scores. The output is a partition of the records into groups of at least records, and the masked records, where each record is replaced by the centroid of its group. The goal is a small within-group sum of squared errors,
The least SSE is NP-hard to find for (Oganian and Domingo-Ferrer 2001), so MDAV is a heuristic: only the group sizes are guaranteed. The value of is a policy choice.
The algorithm
The distance is the Euclidean distance. Ties go to the lowest index, both for the farthest record and for the nearest ones.
MDAV(X, k)- 1
R ← the indices of all records; G ← an empty list - 2
while |R| ≥ 3k do - 3
c ← the centroid of the records of R - 4
r ← the record of R farthest from c - 5
g ← r and its k - 1 nearest records in R; append g to G; R ← R \ g - 6
s ← the record of R farthest from r - 7
g ← s and its k - 1 nearest records in R; append g to G; R ← R \ g - 8
if |R| ≥ 2k then - 9
c ← the centroid of R; r ← the record of R farthest from c - 10
g ← r and its k - 1 nearest records in R; append g to G; R ← R \ g - 11
append R to G ▷ k ≤ |R| ≤ 2k - 1 - 12
for each group g of G do - 13
replace each record of g by the centroid of g - 14
return G and the replaced records
Line L6 picks after line L5 has removed the group of . Domingo-Ferrer and Torra (2005) take the record farthest from in the set before the removal. The two choices are the same except when the largest distance from is tied and the tie reaches into the nearest records, so that a farthest record has already been removed; then the version before the removal may pick a record that is gone. With the tie rule here, the version on this page can always form the second group.
Example
Take and the 10 records
| record | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| value | (1, 1) | (2, 1) | (1, 2) | (8, 8) | (9, 8) | (8, 9) | (5, 1) | (5, 2) | (6, 1) | (4, 9) |
The squared distances below are exact.
| step | what happens | group | |
|---|---|---|---|
| L3 | 10 | ||
| L4 | 10 | is farthest from , at 32.65 (: 31.25, : 25.45) | |
| L5 | 7 | the 2 nearest to are (1) and (2) | |
| L6 | 7 | is farthest from , at 113 (: 100, : 98) | |
| L7 | 4 | the 2 nearest to are (1) and (1) | |
| L2, L8 | 4 | and , so no more groups | |
| L11 | 0 | the rest |
The centroids are , and . The first three records are released as , and is released as . The SSE is , against a total sum of squares of .
The last group shows the weak point of MDAV. The record is far from , and , and alone it adds to the SSE. The optimal 3-partition, found by a search over all partitions, is , and , with SSE . MDAV never looked at : it was not the farthest record at line L4 or line L6.
Correctness
By induction on the rounds of line L2: each round runs only when , so lines L5 and L7 can each take records, and after the round . When the loop stops, . Line L8 takes one more group when , so at line L11, . The groups are therefore a partition with sizes and a last size between and . Each released value is the centroid of a group of at least records, so it occurs at least times, and the release is k-anonymous for any choice of quasi-identifier among the attributes. The centroids also keep the sum of each attribute. The full proof is in proofs/correctness.md.
Proof: MDAV returns a partition into groups of k to 2k - 1 records and a k-anonymous releasefull
The input is a list of records in and an integer with . Lines L1 to L14 are those of the page. We write for the set of indices that are in no group yet, and for the list of groups.
Lemma 1 (the loop). At each test of line L2, the groups of are pairwise disjoint, each has exactly indices, is the set of indices in no group of , and .
Proof. By induction on the number of rounds. Before the first test, is empty, , and .
Assume the claim at a test where , so the body runs. Line L4 picks . Line L5 forms from and other indices of , which exist because . So , , and after the removal . Line L6 picks in the new , which is not empty, and line L7 forms with in the same way, because . After the removal . Both new groups are taken from and then removed from , so they are disjoint from each other and from the old groups, and is again the set of indices in no group.
Lemma 2 (the tail). At line L11, .
Proof. The loop stops when , and by Lemma 1, at that test. If , lines L9 and L10 take a group of exactly indices from , as in Lemma 1, and leave . If , line L8 does nothing, and already holds.
Theorem. MDAV stops after at most rounds of the loop. It returns a list of groups that is a partition of , in which every group but the last has exactly indices and the last has between and indices. In the released records of lines L12 and L13, every record value occurs at least times, so the release is k-anonymous for any set of its attributes taken as the quasi-identifier. The sum of the released records over all records equals the sum of the original records.
Proof. Each round removes indices from , and the body runs only while , so there are at most rounds, and the algorithm stops.
By Lemma 1 at the last test and by Lemma 2, the groups appended at lines L5, L7 and L10 are disjoint sets of exactly indices, and line L11 appends the set of all other indices, with . So is a partition of with the stated sizes.
Lines L12 and L13 give every record of a group the value , the centroid of . So the value occurs at least times in the release. Two groups can have the same centroid, which only adds occurrences. Any projection of the release onto a set of attributes keeps these repeated values equal, so each combination of quasi-identifier values occurs at least times.
Last, for each group, . The groups partition the records, so the sums over all records are equal.
Cost. Let be the size of at the start of a round. Lines L3, L4 and L6 take time. Lines L5 and L7 compute distances in time and select the least with a heap of size in time. The sizes of at the rounds are , so their sum is at most . Lines L8 to L13 take time. The total is .
Remark. The theorem says nothing about the loss. The page gives a table of 10 records where MDAV has an SSE of and the optimal 3-partition has . MDAV is a heuristic for the partition; only the sizes of the groups, and so the k-anonymity of the release, are a theorem.
Complexity
Let be the number of records, the number of attributes and the group size. The model is the real RAM, with one step for each arithmetic operation on a real number.
- A round with records left computes two centroids or farthest records in time, and for lines L5 and L7 it computes distances and selects the least with a heap of size , in time.
- The sizes of at the rounds are , with a sum of at most .
- So the time is , and the extra space is for and the group labels, besides the output.
For a fixed this is quadratic in . For a large file you can first split the records into blocks of at least records, for example by the value of one attribute, and run MDAV on each block. The group sizes stay between and in each block, but the SSE is usually higher, because no group crosses a block border.
Properties
- Group sizes. All groups have exactly records, except the last, which has to . This is a theorem.
- k-anonymous. If all quasi-identifiers are among the attributes, the release is k-anonymous. This is a theorem.
- Not optimal. The SSE can be much larger than the least SSE, as the example shows. The quality is a measured property on test data, and the papers report it as a percentage loss .
- Means kept. The mean of each attribute does not change. The variance falls by .
- Deterministic. With a fixed tie rule, the same input gives the same groups. The groups do not depend on the order of the records, except through ties.
Variants and improvements
- MDAV-generic with other data types. Domingo-Ferrer and Torra (2005) use a distance and an average for each type: the mean for numbers, the median for ordinal values and the mode for nominal values. The steps stay the same.
- Variable group sizes. Variants let a group grow toward records when the next records are close to it and far from the rest. This can help in data with natural clusters, and it can keep an outlier out of the last group.
- Univariate optimum. On one attribute, or on a projection to one dimension, the optimal partition is a shortest path on the sorted values (Hansen and Mukherjee 2003). It needs no heuristic.
- Ward's method with a least size. A hierarchical alternative from the same literature (Domingo-Ferrer and Mateo-Sanz 2002), based on Ward's method, which merges the two clusters with the least growth of SSE.
When to use it
Use MDAV to microaggregate a table of a few thousand records with several numerical quasi-identifiers, when you want a k-anonymous release that keeps the numerical scale and the means. It is a good baseline for other microaggregation heuristics. Scale the attributes first. For a single attribute use the optimal univariate method. If the data has strong outliers, check the last group, or use a variable-size variant. If the release needs a formal guarantee against any background knowledge, MDAV is not enough: use differential privacy.
Pitfalls
- A group taken from all records at lines L5 and L7. The nearest records must come from , the records that are still free. If they come from the full table, a record can join two groups, and some groups have fewer than free members.
- Stopping the loop at at line L2. With the test , a round with takes records and can leave fewer than for line L11, so the last group is too small. The test must be , followed by line L8.
- Unscaled attributes at line L3. The centroid and the distances then follow the attribute with the widest range, and the other attributes lose much more than needed.
- Releasing the group label. The group number or the order of the groups adds nothing for the analyst and can link records across releases. Release the masked records in a random order.
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/mdav/. The authors are listed in prov/HMJJKR.jsonl.
"""MDAV (maximum distance to average vector), the fixed-size microaggregation heuristic.
A record is a sequence of d numbers. The distance is the Euclidean distance; the code
compares squared distances, which gives the same order. Ties go to the lowest record
index, so the result is deterministic. With int or Fraction inputs the arithmetic is exact.
"""
import heapq
from fractions import Fraction
from typing import Sequence, Union
Number = Union[int, float, Fraction]
Record = Sequence[Number]
def _centroid(records: Sequence[Record], ids: Sequence[int]) -> list[Number]:
d = len(records[ids[0]])
return [sum(Fraction(records[i][a]) if isinstance(records[i][a], int) else records[i][a] for i in ids) / len(ids) for a in range(d)]
def _dist2(x: Sequence[Number], y: Sequence[Number]) -> Number:
return sum((xa - ya) * (xa - ya) for xa, ya in zip(x, y))
def _farthest(records: Sequence[Record], ids: Sequence[int], point: Sequence[Number]) -> int:
# The largest distance wins; on a tie the lowest index wins.
return min(ids, key=lambda i: (-_dist2(records[i], point), i))
def _group_around(records: Sequence[Record], ids: Sequence[int], r: int, k: int) -> list[int]:
others = [i for i in ids if i != r]
nearest = heapq.nsmallest(k - 1, others, key=lambda i: (_dist2(records[i], records[r]), i))
return sorted([r] + nearest)
def mdav(records: Sequence[Record], k: int) -> list[list[int]]:
"""Partition the record indices into groups by MDAV.
Returns the groups in the order MDAV forms them, each as a sorted list of indices.
Every group has k records, except the last, which has between k and 2k - 1.
Precondition: 1 <= k <= n, where n = len(records), and all records have the same
dimension d.
Cost: at most n / (2k) + 2 rounds, each with O(n d) distance work and an
O(n log k) selection, so O(n^2 (d + log k) / k) time and O(n) extra space.
"""
n = len(records)
if not 1 <= k <= n:
raise ValueError("need 1 <= k <= number of records")
remaining = list(range(n)) # @line L1
groups: list[list[int]] = []
while len(remaining) >= 3 * k: # @line L2
c = _centroid(records, remaining) # @line L3
r = _farthest(records, remaining, c) # @line L4
g_r = _group_around(records, remaining, r, k) # @line L5
groups.append(g_r)
taken = set(g_r)
remaining = [i for i in remaining if i not in taken]
s = _farthest(records, remaining, records[r]) # @line L6
g_s = _group_around(records, remaining, s, k) # @line L7
groups.append(g_s)
taken = set(g_s)
remaining = [i for i in remaining if i not in taken]
if len(remaining) >= 2 * k: # @line L8
c = _centroid(records, remaining)
r = _farthest(records, remaining, c) # @line L9
g_r = _group_around(records, remaining, r, k) # @line L10
groups.append(g_r)
taken = set(g_r)
remaining = [i for i in remaining if i not in taken]
groups.append(sorted(remaining)) # @line L11
return groups
def microaggregate(records: Sequence[Record], k: int) -> tuple[list[list[int]], list[list[Number]]]:
"""Run MDAV and replace each record by the centroid of its group.
Returns (groups, masked), where masked[i] is the centroid of the group of record i.
Precondition and cost as for mdav; the replacement adds O(n d).
"""
groups = mdav(records, k)
masked: list[list[Number]] = [[] for _ in records]
for g in groups: # @line L12
c = _centroid(records, g)
for i in g:
masked[i] = list(c) # @line L13
return groups, masked # @line L14
def sse(records: Sequence[Record], groups: Sequence[Sequence[int]]) -> Number:
"""The within-group sum of squared errors, the information loss of a partition."""
total: Number = 0
for g in groups:
c = _centroid(records, g)
total += sum(_dist2(records[i], c) for i in g)
return total
test_mdav.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mdav/. The authors are listed in prov/HMJJKR.jsonl.
import random
from collections import Counter
from fractions import Fraction
import pytest
from mdav import mdav, microaggregate, sse
PAGE = [(1, 1), (2, 1), (1, 2), (8, 8), (9, 8), (8, 9), (5, 1), (5, 2), (6, 1), (4, 9)]
def ref_mdav(x, k):
"""An independent MDAV: full sorts instead of selections, sets instead of lists."""
def cen(ids):
return tuple(Fraction(sum(x[i][a] for i in ids), len(ids)) for a in range(len(x[0])))
def d2(p, q):
return sum((Fraction(a) - Fraction(b)) ** 2 for a, b in zip(p, q))
def far(ids, p):
best = max(d2(x[i], p) for i in ids)
return min(i for i in ids if d2(x[i], p) == best)
def grp(ids, r):
order = sorted(ids - {r}, key=lambda i: (d2(x[i], x[r]), i))
return {r} | set(order[: k - 1])
rest = set(range(len(x)))
out = []
while len(rest) >= 3 * k:
r = far(rest, cen(rest))
g = grp(rest, r)
out.append(g)
rest -= g
s = far(rest, x[r])
g = grp(rest, s)
out.append(g)
rest -= g
if len(rest) >= 2 * k:
r = far(rest, cen(rest))
g = grp(rest, r)
out.append(g)
rest -= g
out.append(rest)
return [sorted(g) for g in out]
def partitions(items):
if not items:
yield []
return
first, rest = items[0], items[1:]
for p in partitions(rest):
for j in range(len(p)):
yield p[:j] + [[first] + p[j]] + p[j + 1 :]
yield [[first]] + p
def best_sse(x, k):
best = None
for p in partitions(list(range(len(x)))):
if all(k <= len(g) <= 2 * k - 1 for g in p):
v = sse(x, p)
if best is None or v < best:
best = v
return best
def test_page_example() -> None:
groups = mdav(PAGE, 3)
assert groups == [[3, 4, 5], [0, 1, 2], [6, 7, 8, 9]]
_, masked = microaggregate(PAGE, 3)
assert masked[0] == [Fraction(4, 3), Fraction(4, 3)]
assert masked[3] == [Fraction(25, 3), Fraction(25, 3)]
assert masked[9] == [5, Fraction(13, 4)]
assert sse(PAGE, groups) == Fraction(593, 12)
def test_not_optimal() -> None:
x = [(1,), (1,), (3,), (3,), (4,)]
groups = mdav(x, 2)
assert groups == [[2, 4], [0, 1, 3]]
assert sse(x, groups) == Fraction(19, 6)
assert best_sse(x, 2) == Fraction(2, 3)
assert sse(x, [[0, 1], [2, 3, 4]]) == Fraction(2, 3)
def test_edge_cases() -> None:
assert mdav([(3, 4)], 1) == [[0]]
assert mdav([(1,), (2,), (3,)], 3) == [[0, 1, 2]]
assert mdav([(1,), (2,), (3,), (4,), (5,)], 3) == [[0, 1, 2, 3, 4]]
assert mdav([(0,)] * 6, 2) == [[0, 1], [2, 3], [4, 5]]
with pytest.raises(ValueError):
mdav([(1,), (2,)], 3)
with pytest.raises(ValueError):
mdav([(1,)], 0)
def test_against_reference() -> None:
rng = random.Random(20050601)
for _ in range(600):
n = rng.randint(1, 14)
d = rng.randint(1, 3)
k = rng.randint(1, min(n, 4))
x = [tuple(rng.randint(0, 6) for _ in range(d)) for _ in range(n)]
groups = mdav(x, k)
assert groups == ref_mdav(x, k)
flat = sorted(i for g in groups for i in g)
assert flat == list(range(n))
assert all(len(g) == k for g in groups[:-1])
assert k <= len(groups[-1]) <= 2 * k - 1
_, masked = microaggregate(x, k)
counts = Counter(tuple(m) for m in masked)
assert all(counts[tuple(m)] >= k for m in masked)
for a in range(d):
assert sum(m[a] for m in masked) == sum(r[a] for r in x)
def test_never_below_optimum() -> None:
rng = random.Random(7)
for _ in range(150):
n = rng.randint(2, 7)
k = rng.randint(1, min(n, 3))
x = [(rng.randint(0, 9), rng.randint(0, 9)) for _ in range(n)]
assert sse(x, mdav(x, k)) >= best_sse(x, k)
def test_float_input() -> None:
x = [(0.5, 0.25), (0.75, 0.5), (10.0, 10.5), (10.25, 9.75)]
assert mdav(x, 2) == [[2, 3], [0, 1]]
History
Microaggregation was in use at statistical offices in the 1990s. Domingo-Ferrer and Mateo-Sanz (2002) stated the optimal k-partition problem, proved that optimal groups have fewer than records, and proposed fixed-size heuristics that start from the record farthest from the centroid. Oganian and Domingo-Ferrer (2001) proved that the multivariate optimum is NP-hard. The heuristic called MDAV was implemented in the mu-Argus package for statistical disclosure control. Domingo-Ferrer and Torra (2005) gave MDAV-generic for continuous, ordinal and nominal data, and showed that joint microaggregation of the quasi-identifiers gives k-anonymity.
References
- Josep Domingo-Ferrer and Vicenc Torra, Ordinal, continuous and heterogeneous k-anonymity through microaggregation, Data Mining and Knowledge Discovery 11(2), 2005, pp. 195 to 212, the MDAV-generic algorithm, and k-anonymity by joint microaggregation of the quasi-identifiers
- Josep Domingo-Ferrer and Josep Maria Mateo-Sanz, Practical data-oriented microaggregation for statistical disclosure control, IEEE Transactions on Knowledge and Data Engineering 14(1), 2002, pp. 189 to 201, the optimal k-partition, the bound of 2k - 1 on group sizes, and fixed-size heuristics based on the farthest record from the centroid
- 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 microaggregation and its MDAV heuristic
- Anna Oganian and Josep Domingo-Ferrer, On the complexity of optimal microaggregation for statistical disclosure control, Statistical Journal of the United Nations Economic Commission for Europe 18(4), 2001, pp. 345 to 353, optimal multivariate microaggregation is NP-hard
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 HMJJKR Edit this page History Report an error Markdown