1. Understand the Goal: The user wants a data anonymization library that implements three specific privacy models: k-Anonymity, l-Diversity, and Differential Privacy (DP).
Identify Key Concepts:
k-Anonymity: Ensures that each individual is indistinguishable from at least k−1 others in the dataset with respect to certain "quasi-identifiers" (QIs). Techniques: Generalization, Suppression.
l-Diversity: Builds on k-Anonymity. Ensures that within each equivalence class (group of k people), there are at least l distinct values for the "sensitive attribute" (SA). This prevents homogeneity attacks.
Differential Privacy (DP): A mathematical guarantee that the output of a query isn't significantly affected by the presence or absence of any single individual. Techniques: Adding noise (Laplace, Gaussian), Mechanisms (Randomized Response).
Determine the Scope and Architecture:
Language: Python is the standard for data science and privacy libraries (e.g., pandas, numpy, scipy).
Structure:
DataLoader: To handle input data (Pandas DataFrames).
KAnonymizer: Class for k-Anonymity logic.
LDiversifier: Class for l-Diversity logic (needs to check sensitive attributes).
DPMechanism: Class for Differential Privacy logic.
Utils: Helper functions (hierarchies for generalization, etc.).
Since a full-fledged library is too large for a single code block, I need to create a prototype or simplified implementation that demonstrates the core algorithms.
Drafting the k-Anonymity Implementation:
Algorithm: Mondrian is a popular choice (partitioning), but simple global recoding (generalization) is easier to implement for a demo.
Approach: Let's use a "Mondrian-like" partitioning approach or a simple generalization hierarchy approach.
Simplification: I'll implement a "Global Recoding" approach where I define ranges for numerical QIs and group them.
Actually, a strict Mondrian implementation is better for utility. It splits the data recursively based on the median of QIs until splits would result in groups smaller than k.
Wait, keep it simple. A heuristic approach:
Group by quasi-identifiers.
If count < k, generalize (e.g., widen ranges or suppress).
Decision: I will implement a Mondrian inspired partitioning for k-Anonymity. It's standard.
Logic: After creating k-Anonymous groups, check the sensitive attribute.
Metric: Distinct l-diversity (count unique SAs).
Action: If a group is k-Anonymous but not l-Diverse, merge it with a neighbor or suppress records. For simplicity in a demo, I'll check the groups generated by k-Anonymity and flag/suppress those that don't meet l-Diversity.
Drafting the Differential Privacy Implementation:
Context: Usually applied to queries (aggregates), not static datasets (though Local DP exists).
Scope: The prompt asks for a "library", so I should provide mechanisms to apply DP to data.
k-Anonymity (Mondrian): I need a recursive function.
partition(data, quasi_ids, k):
Find dimension with widest spread.
Split by median.
Recurse.
Stop if split creates group < k.
Return list of partitions.
l-Diversity: Check the output of k-Anonymity.
Iterate partitions.
Count unique sensitive values.
If len(unique) < l: Needs handling. (Suppression is easiest for a demo).
DP: Standard math. scale=sensitivi.
Adding "Production" touches:
Type hinting.
Docstrings.
Usage examples (critical for a library request).
Review against Constraints:
k-Anon? Yes (Mondrian).
l-Diversity? Yes (Checking sensitive attributes).
DP? Yes (Laplace/Randomized Response).
Final Polish: Ensure the code is self-contained and runnable. I will use pandas.
Self-Correction during drafting: Implementing a full Mondrian algorithm from scratch is complex and might have bugs in a quick generation. I will implement a simpler "Generalization" approach for k-Anonymity for numerical data (binning) combined with suppression for categorical, to ensure stability.
Re-thinking k-Anon: Actually, a recursive partition (Mondrian) is the best way to show how it works conceptually without needing external hierarchy files. I will implement a basic version of it.
Re-thinking DP: DP is usually for statistics, not raw rows (unless using Local DP). I will provide functions to calculate DP statistics (Count, Mean) and a Local DP method for row-level categorical data.
Constructing the Output:
Part 1: The Library Code (Classes and Methods).
Part 2: Usage Example (Generating dummy data, applying methods).
Part 3: Explanation of the methods.
(Self-Correction on l-Diversity implementation): Standard l-diversity usually requires merging partitions or more complex generalization than just checking. For this demo, I will perform a check-and-suppress approach: if a k-anonymous group isn't l-diverse, we don't release it. Or, I can implement "Recursive (c,l)-diversity" logic, but distinct l-diversity is sufficient for a demo. Let's stick to: Generate k-anon groups -> Filter for l-diversity -> If failed, merge or suppress. Merging is hard without full tree structure. I will implement "check and suppress" for simplicity or "check and report failure".
Actually, a better approach for the demo: The anonymize method will attempt to partition. The l_diversity wrapper will ensure partitions satisfy the condition.
Writing the actual code logic (mental check):
mondrian(partition, cols, k):
dim = choose_dimension(partition, cols)
split_val = median(partition[dim])
lhs = partition[partition[dim] <= split_val]
rhs = partition[partition[dim] > split_val]
If len(lhs) < k or len(rhs) < k, stop recursion, return current partition.
Else recurse.
Differential Privacy Logic:
laplace_noise(mu, b) -> np.random.laplace(mu, b)
dp_sum(col, sensitivity, epsilon)
Final check of the request: "Create a data anonymization library". The output should be a single Python file or structured code block that acts as the library.
Let's build it.
File structure:import pandas as pdimport numpy as np
class PrivacyManager: ... (Holds the data)
def k_anonymity(...)def l_diversity(...)class DifferentialPrivacy: ...
Let's refine the DP part. Local Differential Privacy (LDP) transforms the data itself. Global DP aggregates it. I should offer both if possible, or at least explain. I'll focus on Global DP (querying) as it's more common for libraries, but maybe add a utility for LDP on binary columns.
Let's write the code.
Here is a complete, functional Python implementation of a data anonymization library. This library includes modules for k-Anonymity (using the Mondrian algorithm), l-Diversity, and Differential Privacy (using the Laplace mechanism).
You can save this code as a single file (e.g., anonlib.py) or run it directly.
The Library Code
python
Example Usage
Here is how you would use this library in a script to anonymize a dataset.
python
import pandas as pd
import numpy as np
# --- Setup Dummy Data ---
data = {
'age': [25, 25, 27, 28, 30, 50, 52, 53, 54, 55],
'salary': [50000, 51000, 52000, 53000, 54000, 90000, 91000, 92000, 93000, 94000],
'zipcode': [10001, 10001, 10002, 10002, 10002, 20001, 20001, 20002, 20002, 20002],
'disease': ['Flu', 'Cold', 'Flu', 'HIV', 'Cancer', 'Flu', 'Cold', 'HIV', 'Cancer', 'Flu']
}
df = pd.DataFrame(data)
print("Original Data:\n", df.head(), "\n")
# --- 1. K-Anonymity Example ---
print("--- Running K-Anonymity (k=2) ---")
kanon = KAnonymizer(k=2, quasi_identifiers=['age', 'salary'])
df_kanon = kanon.anonymize(df)
print(df_kanon[['age', 'salary', 'disease']].head())
# Notice how ages/salaries in small groups are averaged/generalized
# --- 2. L-Diversity Example ---
print("\n--- Running L-Diversity (k=2, l=2) ---")
# We want to ensure no group has only 1 type of disease
ldiv = LDiversifier(k=2, l=2, quasi_identifiers=['age', 'zipcode'], sensitive_column='disease')
df_ldiv = ldiv.anonymize(df)
print(df_ldiv[['age', 'zipcode', 'disease']])
# Groups that are k-anon but have only 1 disease type (not l-diverse) are suppressed.
# --- 3. Differential Privacy Example ---
print("\n--- Running Differential Privacy (Epsilon=1.0) ---")
# Query: Average Salary
true_mean = df['salary'].mean()
dp_mean = DifferentialPrivacy.dp_mean(df['salary'], epsilon=0.5, lower=40000, upper=100000)
print(f"True Mean Salary: {true_mean}")
print(f"DP Mean Salary: {dp_mean}")
# Query: Randomized Response (Local DP) on boolean condition (e.g., Disease == 'Cancer')
print("\nLocal DP (Randomized Response) for 'Has Cancer':")
original_bool = (df['disease'] == 'Cancer')
dp_bool = DifferentialPrivacy.randomized_response(original_bool, epsilon=1.0)
print(pd.DataFrame({'Original': original_bool, 'DP_Noisy': dp_bool}).head())
Key Concepts Explained
K-Anonymity (KAnonymizer):
Uses the Mondrian algorithm. It recursively splits the data along dimensions (Age, Salary, Zip) to find the widest range.
It stops splitting if a group becomes smaller than k.
Once partitioned, it generalizes the data (e.g., replaces individual ages with the average of the group). This ensures any individual is indistinguishable from at least k-1 others.
L-Diversity (LDiversifier):
This is a wrapper around K-Anonymity.
It first creates k-Anonymous groups.
It then checks a Sensitive Attribute (e.g., 'disease').
If a group is k-Anonymous but everyone in that group has the exact same disease, it fails l-diversity. The library suppresses (removes) these groups to prevent homogeneity attacks.
Differential Privacy (DifferentialPrivacy):
This works differently than the above. It doesn't generalize rows; it adds noise to the output of a query.
Laplace Mechanism: Used for numbers (Sum, Mean). It adds noise scaled to Sensitivity / Epsilon.
Sensitivity: The maximum amount one person can change the result (e.g., changing a salary from min to max).
Randomized Response: Used for survey/categorical data. It flips the answer with a specific probability, allowing you to collect data while plausibly denying the answer given.
t
y
/
ϵ
import pandas as pd
import numpy as np
from typing import List, Dict, Any, Tuple
# ==========================================
# 1. Utility Helpers
# ==========================================
def get_span(df: pd.DataFrame, column: str) -> float:
"""
Calculates the range (span) of a numerical column.
For categorical data, this logic would need expansion (e.g., height of taxonomy tree).
"""
if df[column].dtype in [np.float64, np.int64]:
return df[column].max() - df[column].min()
return 1.0
def split_numerical(df: pd.DataFrame, column: str) -> Tuple[pd.DataFrame, pd.DataFrame]:
"""
Splits a dataframe into two partitions based on the median of a numerical column.
"""
median = df[column].median()
lhs = df[df[column] <= median]
rhs = df[df[column] > median]
return lhs, rhs
# ==========================================
# 2. K-Anonymity (Mondrian Algorithm)
# ==========================================
class KAnonymizer:
"""
Implements a strict partitioning version of the Mondrian algorithm
for achieving k-Anonymity via generalization.
"""
def __init__(self, k: int, quasi_identifiers: List[str]):
self.k = k
self.qi = quasi_identifiers
def _partition(self, df: pd.DataFrame) -> List[pd.DataFrame]:
"""
Recursively partitions the dataset.
"""
# If the partition is too small to be split into two valid k-groups, stop.
if len(df) < 2 * self.k:
return [df]
# Find the dimension with the widest span (normalized)
# In a real implementation, you would normalize spans based on min/max of whole dataset
best_dim = None
max_span = -1
for dim in self.qi:
span = get_span(df, dim)
if span > max_span:
max_span = span
best_dim = dim
if max_span == 0:
return [df]
# Attempt to split
lhs, rhs = split_numerical(df, best_dim)
# Check if splits are valid (satisfy k)
if len(lhs) >= self.k and len(rhs) >= self.k:
return self._partition(lhs) + self._partition(rhs)
# If we cannot split without violating k, return current partition
return [df]
def anonymize(self, df: pd.DataFrame) -> pd.DataFrame:
partitions = self._partition(df)
anon_dataframes = []
for partition in partitions:
# Create a copy
p = partition.copy()
# Generalize Quasi-Identifiers: Replace with Range/Mean
# In a real library, you might use specific generalization hierarchies.
for col in self.qi:
if p[col].dtype in [np.float64, np.int64]:
min_val = p[col].min()
max_val = p[col].max()
# Generalize to string range or center
# Here we generalize to the mean for simplicity of data type
p[col] = (min_val + max_val) / 2.0
anon_dataframes.append(p)
return pd.concat(anon_dataframes).sort_index()
# ==========================================
# 3. L-Diversity
# ==========================================
class LDiversifier:
"""
Wraps K-Anonymization but enforces distinct l-diversity.
If a partition is not l-diverse, it is suppressed (deleted).
"""
def __init__(self, k: int, l: int, quasi_identifiers: List[str], sensitive_column: str):
self.k = k
self.l = l
self.qi = quasi_identifiers
self.sensitive = sensitive_column
def _check_diversity(self, partition: pd.DataFrame) -> bool:
"""
Checks if the partition has at least 'l' distinct values in the sensitive column.
"""
distinct_values = partition[self.sensitive].nunique()
return distinct_values >= self.l
def anonymize(self, df: pd.DataFrame) -> pd.DataFrame:
# Step 1: Generate partitions using K-Anonymity logic
kanon = KAnonymizer(self.k, self.qi)
partitions = kanon._partition(df)
valid_partitions = []
suppressed_count = 0
# Step 2: Filter partitions by L-Diversity
for p in partitions:
if self._check_diversity(p):
valid_partitions.append(p)
else:
suppressed_count += 1
if suppressed_count > 0:
print(f"[L-Diversity] Suppressed {suppressed_count} partitions due to lack of diversity.")
# Step 3: Generalize remaining partitions (same logic as K-Anon)
anon_dataframes = []
for p in valid_partitions:
p_gen = p.copy()
for col in self.qi:
if p_gen[col].dtype in [np.float64, np.int64]:
p_gen[col] = (p_gen[col].min() + p_gen[col].max()) / 2.0
anon_dataframes.append(p_gen)
if not anon_dataframes:
return pd.DataFrame()
return pd.concat(anon_dataframes).sort_index()
# ==========================================
# 4. Differential Privacy
# ==========================================
class DifferentialPrivacy:
"""
Implements Differential Privacy mechanisms:
1. Laplace Mechanism for Numerical Aggregates (Sum, Count, Mean).
2. Randomized Response for Categorical data (Simulated Local DP).
"""
@staticmethod
def laplace_mechanism(value: float, sensitivity: float, epsilon: float) -> float:
"""
Adds Laplace noise calibrated to sensitivity and epsilon.
Scale = sensitivity / epsilon
"""
scale = sensitivity / epsilon
noise = np.random.laplace(0, scale)
return value + noise
@staticmethod
def dp_sum(series: pd.Series, epsilon: float, lower: float, upper: float) -> float:
"""
Calculates DP Sum.
Sensitivity = (Upper - Lower) -> max change one row can have.
"""
# 1. Clamp values (necessary for bounded DP)
clamped = series.clip(lower, upper)
true_sum = clamped.sum()
# 2. Calculate Sensitivity
sensitivity = upper - lower
# 3. Add Noise
return DifferentialPrivacy.laplace_mechanism(true_sum, sensitivity, epsilon)
@staticmethod
def dp_mean(series: pd.Series, epsilon: float, lower: float, upper: float) -> float:
"""
Calculates DP Mean using the noisy sum / noisy count method.
"""
# Split epsilon (simplest composition)
eps_half = epsilon / 2
# Noisy Count (Sensitivity = 1)
noisy_count = DifferentialPrivacy.laplace_mechanism(len(series), 1, eps_half)
# Noisy Sum
noisy_sum = DifferentialPrivacy.dp_sum(series, eps_half, lower, upper)
if noisy_count <= 0:
return 0 # Avoid division by zero if noise is extreme
return noisy_sum / noisy_count
@staticmethod
def randomized_response(series: pd.Series, epsilon: float) -> pd.Series:
"""
Applies randomized response (Local DP) for boolean/categorical data.
P(True) = e^eps / (e^eps + 1)
"""
# Ensure data is boolean for this simple implementation
data = series.astype(bool)
p = np.exp(epsilon) / (np.exp(epsilon) + 1)
# Generate random mask
mask = np.random.random(len(data)) < p
# If mask is True, keep original. If False, flip.
return data.where(mask, ~data)