The user wants a data anonymization library in Python that implements specific privacy models: k-Anonymity, l-Diversity, and Differential Privacy (DP). They also requested tests.
1. Understanding the Core Concepts:
- k-Anonymity: Ensures that each individual is indistinguishable from at least k−1 other individuals with respect to certain "quasi-identifiers" (QIs). This usually involves generalizing or suppressing data.
- l-Diversity: An extension of k-Anonymity. It ensures that within each group of k indistinguishable individuals (equivalence class), there are at least l distinct values for each "sensitive attribute" (SA). This prevents homogeneity attacks (where everyone in a group has the same disease, for example).
- Differential Privacy (DP): A mathematical guarantee. It adds noise to query results or individual data points such that the output doesn't change much whether any single individual is in the dataset or not. Common mechanisms: Laplace (for numerical), Exponential (for categorical).
2. Scope and Architecture of the Library:
- Language: Python is the standard for data science.
- Data Structure: Pandas DataFrames are the industry standard for tabular data. I should build the library around Pandas.
- Modularity:
- A main class or function set for each privacy model.
- A utility for handling hierarchies (important for k-Anon generalization).
- A testing suite (using
pytest or standard unittest).
3. Implementation Details - k-Anonymity:
- Approach: Implementing a full optimization algorithm (like Mondrian or Incognito) is too complex for a single code snippet response. I should provide a functional but simpler heuristic approach (e.g., recursive clustering or a basic generalization loop) or a simulation of the concept. However, to make it a "library," I should implement a basic generalization strategy based on predefined hierarchies.
- Algorithm: I'll use a simple approach: Generalize columns until groups of size ≥k are formed.
- Hierarchy: I need a way to represent generalization levels (e.g., Age -> Age Range).
4. Implementation Details - l-Diversity:
- Approach: This builds on top of k-Anonymity.
- Logic: After k-Anonymization, check the sensitive attribute distribution in each group. If a group isn't diverse enough, we might need to generalize further (though this is hard to implement simply) or suppress records. For this demo, I will implement a validator and a modifier that suppresses non-diverse groups or applies noise (though noise is usually DP). A strict l-Diversity algorithm usually requires better generalization logic. Let's stick to a validation and simple suppression approach for the demo, or just the calculation of the metric on a k-Anonymized dataset.
- Refinement: Actually, let's make a function that takes data and ensures l-diversity. A common simple way is to group by QIs and check the sensitive attribute count. If count < l, suppress the group.
5. Implementation Details - Differential Privacy:
- Mechanism: Laplace Mechanism is the standard for numeric data.
- Formula: f(x)+Lap(Δf/ϵ), where Δf is sensitivity.
- Implementation: Create a function that takes a value/series, sensitivity, and epsilon.
6. Structure of the Response:
- Library Code (
anon_lib.py):
- Imports.
KAnonymizer class.
LDiversityValidator class.
DifferentialPrivacy static methods.
- Test Code (
test_anon.py):
- Setup sample data.
- Test k-Anonymity (check min group size).
- Test l-Diversity (check distinct values in groups).
- Test DP (check noise magnitude/distribution).
7. Refining the k-Anon Implementation (Self-Correction):
Writing a full automatic generalization engine is very heavy. I will implement a specific algorithm: Datafly (basic version) or just a Hierarchy-based generalizer.
Plan: Define a Hierarchy dictionary. The function generalize_k_anon will iterate through QIs, increasing their generalization level until k is satisfied.
Simplification: For the sake of a readable example, I will implement a Mondrian-style partitioning (Median-based) if the data is numeric, or a simple generalization lookup for categorical. Actually, let's stick to a hierarchy-based approach because it's easier to visualize textually.
Better Plan: I will implement a class that accepts a Pandas DataFrame and configuration (quasi-identifiers, sensitive attributes).
For k-Anon: I'll simulate the "Mondrian" algorithm logic for numerical data (partitioning) as it's standard and clean.
Wait, categorical data is harder. Let's provide a "Generalization Hierarchy" dict approach.
Let's stick to a robust "Library" feel:
-
K-Anonymity: I'll implement a simplified "global recoding" or "local suppression" approach? No, let's do Generalization. I will provide a helper to generate generalizations.
Actually, let's implement a Mondrian-like partitioning for Numerical data and assume categorical data can be encoded numerically or ignored for the core algorithm to keep the code snippet concise.
Alternative: Just implement a validator and a simple randomizer that enforces it? No, the user wants a library that does the anonymization.
Decision: I will implement a K-Anonymity class that uses a "Generalization Hierarchy" approach. The user passes in levels of generalization (e.g., "Age" -> "Age Range"). The library iterates until k is met.
Actually, let's do a simpler heuristic: Datafly algorithm basics.
Okay, to ensure the code actually works and is copy-pasteable:
I will implement:
k_anonymize: Groups data by QI columns. If a group is <k, it suppresses it (removes it). This is the most basic "valid" k-anonymity implementation (Suppression-based).
- Correction: Suppression loses data. The user likely wants Generalization.
- Let's write a function that generalizes based on provided rules.
Let's pivot to a strict, understandable implementation:
- DP: Easy. Laplace noise.
- k-Anon: Partitioning. If
len(group) < k, generalize attributes. Since generalization logic requires user input (hierarchies), I will implement a class that applies rules.
8. Drafting the Code (Mental or Scratchpad):
-
DP:
def add_laplace_noise(value, sensitivity, epsilon):
noise = np.random.laplace(0, sensitivity/epsilon)
return value + noise
-
k-Anon:
def k_anonymize(df, quasi_ids, k):
# Group by QIs
# If count < k, we need to generalize.
# For this demo, let's use Binning for numeric and suppression for outliers.
pass
Actually, a "Datafly" implementation is standard for examples.
- Find the QI with most distinct values.
- Generalize it.
- Repeat until all groups are size k.
I will implement a simplified version of this using a
Hierarchy dictionary passed by the user.
-
l-Diversity:
Check groups. If sensitive_col nunique < l, drop group.
9. Refinement for Quality:
The request asks for a "library". It should be Object-Oriented.
class PrivacyManager:
anonymize_k(...)
check_l_diversity(...)
apply_dp(...)
Let's separate them for clarity.
Step-by-Step Implementation Plan:
- Imports:
pandas, numpy.
- Differential Privacy Module: A class
DifferentialPrivacy with laplace_mechanism.
- K-Anonymity Module: A class
KAnonymity. It needs a generalize method. I'll implement a simple "binning" strategy for numbers and a "parent mapping" strategy for categories to show how hierarchies work.
- L-Diversity Module: A class
LDiversity that filters the output of K-Anonymity.
- Tests: A
unittest.TestCase suite to prove it works.
Code specifics:
- Hierarchy: I'll define a dummy hierarchy (e.g., Age: 20->20s, 30->30s).
- Mondrian (Median Partition): This is the best algorithmic approach for a code snippet because it doesn't require pre-defined hierarchies, just an ordering.
- Algorithm:
- Sort data by a dimension.
- Split at median.
- Check if splits are >= k.
- If yes, recurse. If no, stop and summarize.
- This is much better than pre-defined hierarchies for a generic library.
Final Decision on k-Anon Algorithm: Strict "Mondrian" partitioning on numerical quasi-identifiers. It's robust, algorithmic, and fits in a single file nicely. For categorical, I'll use simple grouping.
Let's write the code.
- K-Anon: Recursive partitioning.
- Input: DataFrame, QIs, Sensitive Attr, k.
- Logic: Split space into rectangles (partitions).
- Output: Anonymized DataFrame where QIs are ranges.
- L-Diversity: Post-processing check on the partitions.
- DP: Simple wrapper.
Let's refine the output. The user wants a library. I will structure it with classes.
Class 1: DifferentialPrivacy
add_noise(data, epsilon, sensitivity)
Class 2: MondrianKAnonymizer (Specific implementation of k-Anon)
anonymize(df, quasi_identifiers, sensitive_column, k)
- Returns a DF where QIs are generalized into ranges (for numeric) or generalized labels (if implemented, but I'll focus on numeric ranges for the demo to keep it self-contained).
Class 3: LDiversityValidator
validate(df, k, l, sensitive_column) -> Returns sanitized DF.
Tests:
- Generate mock data (Age, Zip, Salary).
- Run Anonymizer.
- Assert min group size >= k.
- Assert distinct SA in group >= l.
- Check DP noise.
Self-Correction during coding thoughts:
The Mondrian algorithm returns partitions. I need to convert these partitions back to a flat DataFrame for the user.
I will create a "PrivacyToolkit" file structure in the response.
Let's simplify the Mondrian implementation to be readable.
- Find the widest dimension (range).
- Split at median.
- Recurse.
- If a partition cannot be split further without violating k, stop.
- Summarize partition (replace QIs with mean or range).
L-Diversity Implementation:
Usually, l-diversity requires modifying the partitioning strategy (don't just split at median, ensure diversity).
However, for a "library" example, I will implement it as a Validator/Sanitizer:
- Perform k-Anon.
- Iterate through groups.
- If a group has < l distinct sensitive values, suppress the group (or add noise). Suppression is the standard fallback in basic l-diversity implementations if generalization isn't sufficient.
Resulting Structure:
dp.py / DPMechanisms
kanon.py / KAnonymizer
ldiv.py / LDiversityChecker
test_privacy.py
I will combine this into a cohesive, copy-pasteable response with a main library block and a testing block.
Specifics for K-Anon Algorithm in code:
I will use a top-down greedy approach.
Columns must be numerical for the standard Mondrian.
Helper function: build_anonymized_df(partitions).
Specifics for DP:
Just Laplace.
Let's go.
Here is a complete, modular Python implementation of a data anonymization library.
This library includes:
Anonymizer: A class implementing the Mondrian algorithm for k-Anonymity (using median partitioning for generalization).
LDiversity: A validator/enforcer for l-Diversity on top of k-Anonymized data.
DifferentialPrivacy: A class implementing the Laplace Mechanism for numerical data.
- Unit Tests: A comprehensive test suite using
unittest.
The Library (anon_lib.py)
You can save the following code into a single file.
import pandas as pd
import numpy as np
import random
from collections import Counter
from typing import List, Dict, Tuple, Union
# ==============================================================================
# 1. K-ANONYMITY (Mondrian Algorithm)
# ==============================================================================
class KAnonymizer:
"""
Implements a basic version of the Mondrian algorithm for k-Anonymity.
It supports numerical generalization via median partitioning.
"""
def __init__(self, k: int):
self.k = k
def _get_median(self, series: pd.Series) -> Union[int, float]:
"""Calculates the median of a series."""
return series.median()
def _partition(self, df: pd.DataFrame, quasi_identifiers: List[str], sensitive_column: str) -> List[pd.DataFrame]:
"""
Recursive partitioning step of Mondrian.
Splits data along the widest range QI until no further splits are possible
without violating k-anonymity.
"""
# If the partition is too small to split, return it
if len(df) < 2 * self.k:
return [df]
# Find the dimension (QI) with the widest range to split on
# For simplicity, we assume numerical QIs for range calculation
ranges = {}
for qi in quasi_identifiers:
if df[qi].dtype in ['int64', 'float64']:
ranges[qi] = df[qi].max() - df[qi].min()
else:
# Categorical: use unique count as a proxy for "width"
ranges[qi] = df[qi].nunique()
# Choose dimension with max range
dim = max(ranges, key=ranges.get)
# If range is 0 (all values same), cannot split further
if ranges[dim] == 0:
return [df]
# Split at median
median = self._get_median(df[dim])
# Create partitions
# lhs: <= median, rhs: > median
lhs = df[df[dim] <= median]
rhs = df[df[dim] > median]
# Check if splits satisfy k-anonymity
if len(lhs) >= self.k and len(rhs) >= self.k:
# Recursively partition
return self._partition(lhs, quasi_identifiers, sensitive_column) + \
self._partition(rhs, quasi_identifiers, sensitive_column)
# If split fails, return current partition as final
return [df]
def _summarize_partition(self, df: pd.DataFrame, quasi_identifiers: List[str]) -> Dict:
"""
Generalizes the QIs in a partition to a range or common value.
"""
summary = {}
for qi in quasi_identifiers:
if df[qi].dtype in ['int64', 'float64']:
# Generalize to [min, max] interval
summary[qi] = (df[qi].min(), df[qi].max())
else:
# Generalize to set of values (or simply the set if small)
summary[qi] = tuple(df[qi].unique())
return summary
def anonymize(self, data: pd.DataFrame, quasi_identifiers: List[str], sensitive_column: str) -> pd.DataFrame:
"""
Main entry point. Returns a DataFrame satisfying k-Anonymity.
"""
# 1. Partition
partitions = self._partition(data, quasi_identifiers, sensitive_column)
# 2. Generalize
anonymized_rows = []
for partition in partitions:
if len(partition) < self.k:
# Suppression: Discard small partitions (optional strategy)
continue
summary = self._summarize_partition(partition, quasi_identifiers)
# Create rows for the output
for _, row in partition.iterrows():
new_row = row.copy()
for qi in quasi_identifiers:
# Represent the generalized value as a string "min-max"
if isinstance(summary[qi], tuple) and len(summary[qi]) == 2:
val = summary[qi]
new_row[qi] = f"{val[0]}-{val[1]}"
else:
new_row[qi] = str(summary[qi])
anonymized_rows.append(new_row)
return pd.DataFrame(anonymized_rows)
# ==============================================================================
# 2. L-DIVERSITY
# ==============================================================================
class LDiversityEnforcer:
"""
Ensures that each equivalence class (group of identical QIs) has at least
'l' distinct values for the sensitive attribute.
"""
def __init__(self, l: int):
self.l = l
def check_and_sanitize(self, data: pd.DataFrame, quasi_identifiers: List[str], sensitive_column: str) -> pd.DataFrame:
"""
Groups by QIs and filters out groups that do not satisfy l-diversity.
"""
valid_rows = []
# Group by the generalized QIs
grouped = data.groupby(quasi_identifiers)
for _, group in grouped:
distinct_sensitive = group[sensitive_column].nunique()
if distinct_sensitive >= self.l:
valid_rows.append(group)
else:
# In a real system, you might try to merge this group with a neighbor.
# Here we suppress (drop) it for strict compliance.
pass
if not valid_rows:
return pd.DataFrame()
return pd.concat(valid_rows)
# ==============================================================================
# 3. DIFFERENTIAL PRIVACY
# ==============================================================================
class DifferentialPrivacyMechanism:
"""
Implements Differential Privacy using the Laplace Mechanism for numerical queries.
"""
def __init__(self, epsilon: float, sensitivity: float):
"""
epsilon: Privacy budget (lower = more privacy, more noise).
sensitivity: The maximum amount the query result changes if one row is changed.
"""
self.epsilon = epsilon
self.sensitivity = sensitivity
def add_noise(self, value: float) -> float:
"""
Adds Laplace noise to a single value.
Scale = sensitivity / epsilon
"""
scale = self.sensitivity / self.epsilon
noise = np.random.laplace(0, scale)
return value + noise
def apply_to_column(self, data: pd.Series) -> pd.Series:
"""
Applies noise to an entire column (assuming independent sensitivity).
"""
return data.apply(lambda x: self.add_noise(x))
# ==============================================================================
# 4. TESTING
# ==============================================================================
import unittest
class TestAnonymizationLibrary(unittest.TestCase):
def setUp(self):
# Create a dummy dataset
data = {
'age': [25, 25, 25, 27, 30, 31, 45, 45, 50, 60],
'zip': [10001, 10001, 10002, 10002, 10003, 10003, 10004, 10004, 10005, 10006],
'income': [50000, 50000, 60000, 60000, 70000, 80000, 90000, 100000, 120000, 150000], # Sensitive Numerical
'disease': ['Cold', 'Flu', 'Cold', 'HIV', 'Cancer', 'Flu', 'Cold', 'Flu', 'Cancer', 'Cold'] # Sensitive Categorical
}
self.df = pd.DataFrame(data)
self.quasi_ids = ['age', 'zip']
self.sensitive_col = 'disease'
def test_k_anonymity(self):
"""Test if K-Anonymity holds."""
k = 2
anonymizer = KAnonymizer(k=k)
anon_df = anonymizer.anonymize(self.df, self.quasi_ids, self.sensitive_col)
# Group by generalized columns and check counts
# Note: In this implementation, generalized columns are strings like "25-27"
counts = anon_df.groupby(self.quasi_ids).size()
# Assert all counts >= k
for count in counts:
self.assertGreaterEqual(count, k)
def test_l_diversity(self):
"""Test if L-Diversity holds after K-Anonymization."""
k = 2
l = 2
# 1. K-Anonymize
anonymizer = KAnonymizer(k=k)
anon_df = anonymizer.anonymize(self.df, self.quasi_ids, self.sensitive_col)
# 2. Enforce L-Diversity
l_enforcer = LDiversityEnforcer(l=l)
final_df = l_enforcer.check_and_sanitize(anon_df, self.quasi_ids, self.sensitive_col)
# Check L-Diversity in the result
grouped = final_df.groupby(self.quasi_ids)
for _, group in grouped:
distinct_diseases = group[self.sensitive_col].nunique()
self.assertGreaterEqual(distinct_diseases, l)
def test_differential_privacy(self):
"""Test Differential Privacy mechanism."""
# Sensitivity 1 (if we count unique users, changing one user changes count by 1)
# Epsilon 1.0
dp = DifferentialPrivacyMechanism(epsilon=1.0, sensitivity=1.0)
true_mean = self.df['income'].mean()
noisy_series = dp.apply_to_column(self.df['income'])
noisy_mean = noisy_series.mean()
print(f"\nDP Test: True Mean={true_mean}, Noisy Mean={noisy_mean}")
# Statistical test: The values should likely not be exactly equal (due to noise)
# but close enough (utility vs privacy tradeoff).
# We just verify noise was added (it's not exactly the same).
# Note: In very rare cases noise could be 0, but with float precision it's unlikely.
self.assertNotEqual(true_mean, noisy_mean)
if __name__ == '__main__':
unittest.main()
Explanation of the Components
1. K-Anonymity (KAnonymizer)
- Algorithm: It uses a simplified Mondrian approach. It recursively splits the dataset along the dimensions (Quasi-Identifiers) with the widest range of values.
- Partitioning: It splits at the median value. If splitting results in groups smaller than
k, it stops splitting.
- Generalization: Once the data is partitioned into groups (equivalence classes), numerical values are replaced by a range string (e.g.,
25 becomes 25-30).
2. L-Diversity (LDiversityEnforcer)
- Purpose: k-Anonymity can fail if everyone in a "k-group" has the same sensitive attribute (e.g., everyone in Zip Code 10001 has Cancer). l-Diversity ensures there are at least
l different values for the sensitive column in every group.
- Implementation: This acts as a filter. It takes the k-Anonymized output, groups by the generalized QIs, and drops any group that doesn't have at least
l distinct sensitive values.
3. Differential Privacy (DifferentialPrivacyMechanism)
- Concept: Unlike the others which group data, DP adds mathematical noise to individual data points or aggregates.
- Mechanism: It uses the Laplace Mechanism. The noise is drawn from a Laplace distribution centered at 0. The magnitude (scale) of the noise is determined by
Sensitivity / Epsilon.
- Usage: This is best used when releasing aggregate statistics (like "Average Income") or perturbing specific numerical columns.
How to Run
- Ensure you have pandas and numpy installed:
pip install pandas numpy
- Save the code above into a file named
anon_lib.py.
- Run the file to execute the tests:
python anon_lib.py
Expected Output
You will see the test results. The DP Test line will show the difference between the true mean and the noisy mean.
Ran 3 tests in 0.XXXs
OK
DP Test: True Mean=85000.0, Noisy Mean=85123.456... (Example)