We are going to create a data anonymization library that supports:
- k-anonymity: Ensuring that each record in the dataset is indistinguishable from at least k-1 other records with respect to quasi-identifiers.
- l-diversity: Ensuring that within each group of records that share the same quasi-identifiers (i.e., each equivalence class), there are at least l distinct values for each sensitive attribute.
- Differential Privacy (DP): Adding noise to the data or query results to provide a formal privacy guarantee.
We'll design the library with the following structure:
- A class for handling tabular data (pandas DataFrame).
- Methods for k-anonymity and l-diversity that work by generalizing and suppressing quasi-identifiers.
- Methods for differential privacy (we'll focus on adding Laplace noise to numeric queries, and for the whole dataset we might consider adding noise to each record or using a more sophisticated method).
However, note that k-anonymity and l-diversity are typically applied to the entire dataset (as a preprocessing step) and then we might use DP for publishing aggregate statistics or for releasing the entire dataset with noise.
Steps:
-
k-anonymity:
- Identify quasi-identifiers (QIs) and sensitive attributes.
- Generalize QIs (e.g., using hierarchies) and/or suppress (remove) some values until each equivalence class has at least k records.
-
l-diversity:
- After achieving k-anonymity, check each equivalence class for l-diversity on sensitive attributes.
- If not satisfied, we might need to further generalize or split equivalence classes.
-
Differential Privacy:
- We can apply DP to the entire dataset by adding noise to each record (especially for numeric attributes) or by using the exponential mechanism for categorical data.
- Alternatively, we can apply DP to aggregate queries (like counts, sums, averages) on the anonymized dataset.
But note: It is common to first apply k-anonymity and l-diversity to the dataset and then add DP noise to the released statistics. However, if we want to release the entire dataset with DP, we might use a different approach.
Let's plan:
We'll create a class DataAnonymizer that takes a pandas DataFrame and a list of quasi-identifier columns and a list of sensitive columns.
Steps for k-anonymity and l-diversity:
We'll use a bottom-up generalization approach (like in the Incognito algorithm) but we'll simplify by using predefined generalization hierarchies for each QI.
However, note that implementing the full Incognito algorithm is complex. Alternatively, we can use a simpler method:
- For each QI, we have a hierarchy (e.g., for age: [0-10, 11-20, ...] or more generally, a tree structure). We'll assume that the user provides a dictionary of hierarchies for each QI.
Steps for k-anonymity:
- Start with the most specific values for each QI (i.e., the original values).
- Compute the equivalence classes (group by QI values).
- Check if every equivalence class has at least k records. If yes, done.
- If not, choose a QI and generalize one level (according to the hierarchy) for the records in the smallest equivalence class (or all records?).
- Repeat until condition is met or no more generalization possible.
This is similar to the algorithm by Sweeney and explicitly known as the "bottom-up" approach.
However, note that we also have to consider l-diversity. So after achieving k-anonymity, we check for l-diversity.
If an equivalence class does not have l distinct values for a sensitive attribute, we might need to:
- Merge with another equivalence class by further generalizing QIs (but note that we already have k-anonymity, so merging might break k? Actually, merging two equivalence classes by generalizing QIs will increase the size of the new class and might help with l-diversity, but we must ensure that after merging we still have at least k? Actually, we are merging two classes that are already of size at least k, so the new class will be at least 2k, so k is preserved. But we might break the k-anonymity of the original classes? Actually, we are replacing two classes with one, so the new class is the union. But note: if we generalize QIs, we might merge multiple classes. We have to be careful.
Alternatively, we can interleave the two:
We can use a single objective: (k, l)-anonymity. We can adjust the algorithm to consider both.
However, for simplicity, we'll do:
Step 1: k-anonymity (by generalizing QIs) until we have at least k in every class.
Step 2: For each class and each sensitive attribute, check if the number of distinct values is at least l. If not, we try to merge with the closest class (by generalizing QIs further) until we get l distinct values or until we cannot merge without breaking k? Actually, we must maintain k, so when we merge, the new class will have at least the sum of the two, which is at least 2k, so k is preserved. But we are changing the QI values by generalizing, so we are essentially creating a new equivalence class that is the union of several old ones.
However, note: when we generalize QIs, we are changing the values for all records in the class. So if we have two classes:
Class1: (QI1, QI2) = (A, X) with 5 records and sensitive values: {s1, s2}
Class2: (QI1, QI2) = (A, Y) with 6 records and sensitive values: {s1, s3}
We want to merge them to get l=3 distinct sensitive values. We can generalize QI2 to a higher level (say, if X and Y are both under the same parent) so that both become the same. Then the new class will have 11 records and sensitive values {s1, s2, s3} -> l=3.
But note: when we generalize QI2 for Class1, we are changing the QI2 value for Class1 from X to the parent. Then Class1 becomes (A, parent) and Class2 becomes (A, parent) too, so they merge.
So the algorithm for step2:
For each equivalence class that fails l-diversity for a sensitive attribute:
Find another equivalence class (or classes) that, when merged by generalizing the QIs (to a common ancestor), we get at least l distinct sensitive values and the merged class has at least k records (which it will if both original classes had at least k, but we are merging so it will be at least 2k? Not necessarily: if we merge two classes that are of size 1 and k-1, but wait, we already have k-anonymity so every class has at least k. So merging two classes will give at least 2k, which is >=k. So k is preserved.
However, we might merge more than two.
But note: we might break the k-anonymity of the other class? Actually, when we merge, we are removing the two original classes and creating a new one. So the new class is the union, so it's okay.
However, we are generalizing QIs for the records in the class. This might cause that now some records that were in different classes become the same.
So the plan:
We'll have a function for k-anonymity that returns a DataFrame with generalized QIs and then we check for l-diversity.
If l-diversity fails, we will try to merge equivalence classes by further generalizing QIs (maybe the same QI or another) until we get l distinct sensitive values.
We must be cautious: we don't want to over-generalize and lose utility.
Alternatively, we can use a single algorithm that optimizes both. But for simplicity, we'll do two steps.
However, note: after the first step (k-anonymity), we have a set of equivalence classes. Then for l-diversity, we are allowed to further generalize QIs (which might merge classes) and that's acceptable as long as we maintain k (which we do because merging increases the size).
Steps:
-
Preprocess: We assume the user provides a hierarchy for each QI. The hierarchy is a dictionary that maps a value to its parent (or a list of levels). We'll use a tree structure.
-
For k-anonymity:
Let current_data be the original data, but we will only change the QI columns.
We start with the most specific level (the original values). We have a function to generalize a column to a given level.
We'll keep track of the current level for each QI for each record? Actually, when we generalize a QI for a record, we change the value to the parent. So we need to know the current value and the hierarchy.
Alternatively, we can think of the equivalence classes as tuples of current QI values. We can group by the current QI values.
Algorithm:
while True:
groups = current_data.groupby(by=QI_columns).size().reset_index(name='count')
if all groups['count'] >= k:
break
else:
# Find the smallest group (with count < k)
smallest_group = groups[groups['count'] < k].iloc[0]
# For this group, we need to generalize one of its QI attributes.
# How to choose which QI to generalize? We can choose the one that has the highest cardinality? Or the one that when generalized, merges with the largest number of other groups? We'll do a simple heuristic: choose the QI that has the most distinct values in the entire dataset? Or for this group, we can try each QI and see which generalization (to parent) would result in merging with the most records without breaking the k condition for the new group? But note: we are only generalizing the records in the smallest group.
# Actually, we are going to generalize the QI for all records in the smallest group. So we change the QI value of every record in that group to the parent value (according to the hierarchy).
# But note: if we generalize one QI, the group's QI tuple changes. Then the group will merge with other groups that have the same new QI tuple.
# We can try for each QI in the group, compute the new group (by changing that QI to parent) and then compute the size of the new group (which would be the current group plus any other group that already has that new QI tuple). Then choose the QI that gives the largest new group? But we want to increase the size of the smallest group to at least k. However, we might overshoot.
# Alternatively, we can generalize the QI that has the highest information loss? We don't have a measure of information loss here.
# For simplicity, we'll just choose the first QI in the list of QIs that can be generalized (i.e., the current value is not already at the top of the hierarchy) and generalize the entire smallest group.
# But note: we might have multiple QIs. We can try to generalize the QI that is at the lowest level (most specific) because that might merge more.
# Let's do:
# For each QI column in the smallest group's index, check if the current value can be generalized (i.e., has a parent in the hierarchy). Then for each candidate, compute the new QI tuple by replacing that QI with its parent. Then compute the total number of records that would have that new QI tuple (by looking at the current groups). Then choose the QI that gives the largest total.
# But note: we are only changing the records in the smallest group. So the new group size = current size of smallest group + (sum of sizes of existing groups that have the new QI tuple and are not the smallest group). However, note that the smallest group currently has the old QI tuple, so we are removing the smallest group from the old tuple and adding it to the new one.
# Actually, it's easier: after changing the smallest group's QI for one column to parent, the new group is formed by all records that have the new QI tuple. We can compute that by:
new_tuple = list(smallest_group[QI_columns])
for i, col in enumerate(QI_columns):
if col == candidate_QI:
new_tuple[i] = hierarchy[col][current_value] # but note: current_value is the value of that QI in the smallest group.
Then we sum the counts of all groups that have the new_tuple.
But note: the groups are defined by the current QI values. So we have a DataFrame `groups` that has the current QI tuples and counts. We can compute:
new_count = current_data[ (current_data[QI_columns] == new_tuple).all(axis=1) ].shape[0]
However, we are going to change the records in the smallest group. So after the change, the records that were in the smallest group will now have the new_tuple, and the other groups remain.
Alternatively, we can compute:
new_count = smallest_group['count'] # the group we are changing
# plus the counts of groups that already have the new_tuple (but note: if the new_tuple is the same as the old tuple of the smallest group? Then we are not changing? Actually, we are changing one QI, so the new_tuple is different.
# But note: there might be an existing group with the new_tuple? Then that group will be merged with the changed smallest group.
# So we need to find groups that have the new_tuple (in the current grouping). However, the current grouping is by the old tuples. So we can look for groups that, after we change the smallest group, will have the same tuple as the changed smallest group.
# Actually, it's easier to recompute the grouping after the change? But that would be expensive.
Alternatively, we can do:
We change the records in the smallest group for the candidate QI to the parent. Then we recompute the groups and see the size of the new group that the changed records belong to.
But we are in a loop and we want to do this for each candidate QI? That would be expensive.
Given the complexity, we might choose a simpler strategy:
Always generalize the QI that has the lowest level in the hierarchy (i.e., the most specific) for the smallest group? Or we can generalize the QI that is common in the smallest group?
We'll do:
For the smallest group, we look at each QI column and check if the value can be generalized (i.e., has a parent). We choose the QI that has the highest cardinality in the entire dataset? Or we can choose the one that when generalized, the new QI tuple (with that change) has the smallest number of distinct values? That might lead to more merging.
Actually, we want to merge with as many as possible to increase the group size. So we want the new QI tuple to be as common as possible.
So for each candidate QI, we compute the new tuple and then count how many records in the entire dataset currently have that new tuple? But note: after we change the smallest group, the records in the smallest group will have the new tuple. So the total records with the new tuple after change = (current number of records with new tuple) + (size of smallest group) - (if the smallest group already has the new tuple? But we are changing one QI, so the new tuple is different from the old tuple, so the smallest group does not currently have the new tuple? Actually, the smallest group currently has the old tuple, so it does not have the new tuple. So:
new_count = current_data[current_data[QI_columns].eq(new_tuple).all(axis=1)].shape[0] + smallest_group['count']
But wait: if there is already a group with the new tuple, then those records are already counted in the current_data. So we are just adding the smallest group to that existing group.
So:
new_count = current_data[current_data[QI_columns].eq(new_tuple).all(axis=1)].shape[0] + smallest_group['count']
But note: the current_data is the original data? Actually, we are modifying the data as we go. We are changing the QI values of the smallest group. So we need to keep track of the current state of the QI columns.
We can maintain a copy of the data with the current QI values.
So:
current_QI_data = original_data[QI_columns].copy()
Then when we generalize, we update current_QI_data.
Then we can compute:
new_count = current_QI_data[current_QI_data.eq(new_tuple).all(axis=1)].shape[0] + smallest_group['count']
But wait: the smallest_group's records currently have the old tuple in current_QI_data. So the current_QI_data does not have the new_tuple for those records. So the above formula is correct.
However, note: the smallest_group's records are part of current_QI_data, and they currently have the old tuple, so they are not counted in the current_QI_data for the new_tuple. So we add them.
Then we choose the candidate QI that gives the maximum new_count.
But note: we must also check that the candidate QI can be generalized (i.e., the current value in the smallest group for that QI has a parent).
Steps:
Let `min_group` be the smallest group (the one with the smallest count that is <k). We have the tuple of QI values for that group.
For each QI column in QI_columns:
current_value = min_group[col]
if hierarchy[col] has a parent for current_value:
new_value = parent(current_value)
new_tuple = list(min_group[QI_columns])
idx = QI_columns.index(col)
new_tuple[idx] = new_value
new_tuple = tuple(new_tuple)
current_count = current_QI_data[current_QI_data.eq(new_tuple).all(axis=1)].shape[0]
total_after_change = current_count + min_group['count'] # because we are adding the min_group records (which currently don't have new_tuple) to the new_tuple group.
candidate = (col, total_after_change)
Then choose the candidate with the maximum total_after_change.
Then we update the current_QI_data for the records in the smallest group: set the chosen QI column to the parent for those records.
Then we update the groups? Actually, we don't need to update the groups explicitly because next iteration we will group by current_QI_data.
But note: the smallest group might have been the only one with that old tuple? Then after change, the old tuple group disappears and the new tuple group gets the records.
We then continue the loop.
Given the complexity, we might use a heuristic:
We'll try to merge the failing group with other groups by generalizing QIs until for every sensitive attribute, the group has at least l distinct values.
We can try to generalize one QI at a time for the failing group and then check the merged group (if any) for all sensitive attributes.
We can also consider merging with more than one group? But that would require generalizing more.
Alternatively, we can generalize multiple QIs at once? But that might over-generalize.
Given the time, we'll do:
After k-anonymity, we have a DataFrame with generalized QIs and the original sensitive attributes.
We'll group by the QIs and then for each group, we check each sensitive attribute.
For a group that fails for any sensitive attribute:
We try to generalize one QI (that can be generalized) for that group (and only that group) and then check the new group (if it merges with an existing group) for l-diversity on all sensitive attributes.
We try all QIs that can be generalized and choose the one that, when applied, the resulting group (after merging) has the maximum number of distinct sensitive values for the failing attribute? Or the minimum information loss? We don't have a measure.
Alternatively, we can choose the QI that, when generalized, results in a group that has the largest size? Because we want to preserve as much as possible.
But note: we are only allowed to generalize the failing group? Actually, we can also generalize the other group? But that would change the other group's QIs, which might break its l-diversity? So we only generalize the failing group.
So:
For the failing group G with tuple T, for each QI that can be generalized:
new_tuple = T with that QI changed to parent.
Find the group G' with tuple new_tuple (if exists) in the current grouping.
Then the new group would be G ∪ G'.
Check if for every sensitive attribute, the new group has at least l distinct values.
If yes, then we generalize that QI for the records in G (i.e., change the QI in the current_QI_data for the records in G to the parent).
Then we break and re-check all groups (because the group G and G' are now merged).
If none of the QIs for G work, then we might try to generalize two QIs? But that might be too much.
Alternatively, we can try to generalize the same QI multiple times? That is, go up the hierarchy until we merge with a group that satisfies l-diversity.
We can do:
For the failing group G, we try to generalize a QI until we find a group that, when merged, satisfies l-diversity for all sensitive attributes.
We can try for each QI:
current_tuple = T
while the current value for that QI is not at the top:
current_value = current_tuple[QI_index]
parent = hierarchy[QI][current_value]
new_tuple = T but with that QI replaced by parent.
Then check if there is a group with new_tuple and if merging with that group (and then checking the union) satisfies l-diversity.
If yes, then we generalize that QI for G to parent and break.
If not, we set T = new_tuple and continue (i.e., we can try to generalize the same QI again? But note: we are only changing one QI at a time? Actually, we are trying to generalize one QI until we merge with a group that works.
But wait: if we generalize the same QI again, we are changing the same column again? Then we are going up the hierarchy in that column.
However, note that we are only changing the records in G. So we can change the same QI multiple times until we get to the top.
But note: we might also consider generalizing a different QI in the next step? Actually, in the above we are only trying one QI at a time and going up until we merge and satisfy.
However, we might also try to generalize a different QI? We can try all QIs and for each, we can go up until we merge and satisfy.
Then we choose the one that requires the least generalization? Or the one that results in the largest group?
We can do:
For each QI that can be generalized (starting from the current value of G in that QI):
Let current_value = the value in G for that QI.
Let current_tuple = T.
While current_value has a parent:
current_value = parent(current_value)
new_tuple = T with that QI replaced by current_value.
Check if there exists a group with new_tuple (excluding G? Actually, G currently has T, so G is not in the new_tuple group).
If there is a group G' with new_tuple:
Let new_group_records = records from G and G'.
Check if for every sensitive attribute, the distinct count in new_group_records >= l.
If yes, then we have a candidate: we would need to generalize that QI for G to current_value (which might be multiple steps up). We record the number of steps (or the level) and the size of the new group.
Then break the while for this QI (we found the first one that works). But note: we might want to go further up? Because maybe going further up we merge with more groups and get more l-diversity? But we already have l-diversity, so we can stop.
Else, continue to next parent.
Then we choose among all QIs and all levels the one that results in the largest new group? Or the one with the least generalization (i.e., the lowest parent)? We can choose the one that requires the least steps in the hierarchy (so the one that is closest) and that satisfies l-diversity.
However, note: we might have multiple QIs that work. We want to minimize information loss, so we choose the one that changes the QI the least (i.e., the one that is already at a higher level? Actually, we want to generalize as little as possible). So we choose the candidate that is at the lowest level (closest to the current) that works.
But note: we are only changing one QI. So we can compare the levels of the candidate new values. We can use the depth in the hierarchy? Or we can use the number of distinct values? Not necessarily.
Alternatively, we can use the size of the new group: we want to keep the group as small as possible? Actually, we want to preserve utility, so we want to merge as little as possible? But we have to merge to get l-diversity. So we want to merge with the smallest group that provides the missing sensitive values? But we don't know which group provides which sensitive values.
Given the complexity, we'll choose the candidate that requires the least generalization (i.e., the one that is just one step up if possible, and if multiple one-step, then the one that merges with the largest group?).
Steps:
For the failing group G:
For each QI:
Let current_value = G's value in that QI.
If current_value has a parent:
new_value = parent(current_value)
new_tuple = T with that QI replaced by new_value.
Find the group G' with new_tuple (if exists).
If G' exists:
Let new_group = G ∪ G'
Check if new_group has at least l distinct values for every sensitive attribute.
If yes, then we have a candidate. We record:
QI column, the new_value (or the level of generalization), and the size of new_group.
If we found candidates, we choose the one with the least generalization (i.e., the new_value is the closest to the current_value). If multiple, choose the one that gives the largest new_group.
If we found a candidate, we update the records in G to the new_value for that QI.
Then we break and re-check all groups (because the group structure changed).
If no candidate found for any QI, then we might need to generalize two QIs? But that would be more complex. Alternatively, we can try to generalize the same QI multiple times (i.e., go up more than one level) and then check. We can modify the above to go up multiple levels until we find a group that works.
We can do:
For each QI:
current_value = G's value in that QI.
while current_value has a parent:
current_value = parent(current_value)
new_tuple = T with that QI replaced by current_value.
Find group G' with new_tuple.
If G' exists and the union of G and G' has at least l distinct values for every sensitive attribute, then we have a candidate.
Then break (we found the first one that works) and record the new_value.
Then we have candidates for each QI (maybe none).
Then choose the candidate that requires the least generalization (i.e., the one with the smallest number of steps from the original value). We can compute the number of steps by comparing the original value and the new_value in the hierarchy? We don't have a level number. Alternatively, we can use the depth if the hierarchy is a tree with levels. But we don't have that.
Alternatively, we can use the number of times we generalized (the while loop count) as a measure of generalization.
We choose the candidate with the smallest while loop count (i.e., the one that required the least steps up). If multiple, choose the one that results in the largest new group.
Then we update G to the new_value for that QI.
Then we break and re-check.
6. We repeat step 5 until all groups are l-diverse or until we cannot generalize any more (i.e., all QIs for the failing group are at the top and we still don't have l-diversity). In the latter case, we might have to suppress the group? Or accept that we cannot achieve l-diversity.
Note: This is a heuristic and might not always find a solution even if one exists.
Given the complexity and time, we'll implement a simplified version:
We'll assume that the hierarchies are simple: each value has a parent, and we can go up until the top.
We'll implement:
- k-anonymity as described (with the heuristic of choosing the QI that when generalized for the smallest group, merges with the most records).
- l-diversity: for each failing group, we try to generalize one QI (going up one level at a time until we merge with a group that makes the union have at least l distinct values for every sensitive attribute). We try all QIs and choose the one that requires the least steps (and if tie, the one that results in the largest merged group).
- We do this iteratively until all groups are l-diverse or until no progress.
However, note: after we generalize for l-diversity, we might break k-anonymity? Actually, we are merging groups, so the new group will have at least the sum of the two, which is at least 2k (since both had at least k). So k is preserved.
But note: we are only changing the failing group. The other group we merge with might have been exactly k, and then the new group becomes at least 2k, so it's still >=k.
So k-anonymity is preserved.
Differential Privacy:
We can add DP in two ways:
1. Add noise to the entire dataset (for each record, for numeric attributes) by adding Laplace noise with scale = sensitivity/epsilon.
But note: for categorical attributes, we cannot add noise. We might use the exponential mechanism to perturb the values, but that is more complex.
Alternatively, we can use DP for releasing the entire dataset by using a mechanism that satisfies DP for the entire dataset. One common method is to add noise to the counts of each combination of QIs and sensitive attributes? But that would be releasing a contingency table.
Alternatively, we can use the method of adding dummy records and then removing them? Not straightforward.
Given the complexity, we'll focus on adding Laplace noise to numeric attributes in the dataset.
Steps:
For each numeric column that we want to release with DP, we compute the sensitivity (the maximum possible change in that column when one record is changed). For a single record, the sensitivity is the range of the column? Actually, for a function that outputs a single number (like the value of a record), the sensitivity is the maximum difference that one record can make. If we are releasing the entire dataset, we are releasing a vector of numbers. The sensitivity for each coordinate is the range? But note: we are adding noise to each record independently? That does not satisfy DP for the entire dataset.
Actually, to satisfy DP for the entire dataset, we need to consider the function that outputs the entire dataset. The sensitivity for the entire dataset (as a vector) is the maximum L1 distance between two datasets that differ in one record. If we have n records and each record has d numeric attributes, then the sensitivity for each attribute is the range of that attribute? And then we add Laplace noise with scale = (max - min)/epsilon for each attribute? But note: the entire dataset is a matrix of size n x d. The sensitivity of the function that returns the entire dataset is the maximum L1 norm of the difference between two adjacent datasets. If we change one record, then the difference in each column is at most the range of that column. So the L1 norm is at most sum_i (max_i - min_i). Then we would add noise with scale = (sum_i (max_i - min_i)) / epsilon. But that would be a lot of noise.
Alternatively, we can add noise to each record independently with scale = (max_i - min_i)/epsilon for each attribute? But that does not satisfy DP because an attacker can see the noise pattern? Actually, if we add independent Laplace noise to each record, the overall mechanism is not DP because the noise added to a particular record can be correlated? Actually, if we add independent noise to each record, then the output of the mechanism on two adjacent datasets differs in one record, and that record has noise added. The difference in the output is the difference in the true record plus the difference in the noise for that record. The noise for the same record in the two datasets are independent, so the difference in noise for that record is the difference of two independent Laplace variables, which is not Laplace. So it's not DP.
The correct way for releasing the entire dataset with DP is to use the Laplace mechanism with the global sensitivity of the function that outputs the dataset. But that would be too noisy.
Alternatively, we can release the dataset by releasing each record with DP? That is, for each record, we release a noisy version. But then the entire dataset is the collection of these noisy records. This is equivalent to adding noise to each record independently, but we must adjust the epsilon for each record? Actually, if we want the entire dataset to be epsilon-DP, then we can split epsilon among the records? But note: the dataset has n records. If we add noise to each record with epsilon/n, then by composition, the entire dataset is epsilon-DP? Not exactly: the composition of n mechanisms each with epsilon/n gives epsilon-DP by simple composition? Actually, the composition of n mechanisms each (epsilon/n)-DP is epsilon-DP. So we can do:
For each record and for each numeric attribute, add Laplace noise with scale = (max_i - min_i) / (epsilon/n) = n*(max_i - min_i)/epsilon.
That would be a lot of noise.
Alternatively, we can use the method of publishing the dataset as a set of (noisy) records by using the exponential mechanism for each record? That is even more complex.
Given the time, we'll assume that we are only adding DP to aggregate queries. But the requirement says "create a data anonymization library with k-anon, l-diversity, and DP". It might mean that we apply k-anon and l-diversity to the dataset and then add DP noise to the sensitive attributes? Or we can add DP to the entire dataset.
Another idea: we can add DP to the counts of each equivalence class? That is, after k-anonymity and l-diversity, we have groups. We can release the groups and their counts, and the sensitive attribute distributions, with DP.
But the problem does not specify.
We'll decide:
We'll provide:
- A method to apply k-anonymity and l-diversity to the dataset (returning a new DataFrame with generalized QIs and the same sensitive attributes).
- A method to add Laplace noise to numeric columns in the entire dataset (with a given epsilon and for specified columns). But note: this does not guarantee DP for the entire dataset, but it is a common practice to add noise to each numeric attribute independently with scale = (max-min)/epsilon. However, this is not DP for the entire dataset, but it might be acceptable in some contexts.
Alternatively, we can provide:
- A method to release the dataset with DP by adding noise to each record with a privacy budget split among records.
We'll do:
def add_dp_noise(data, numeric_columns, epsilon, sensitivity=None):
If sensitivity is not provided, we compute the sensitivity for each column as (max - min) of that column in the original data? But note: after k-anonymity, the data might have changed.
We'll assume we are given the sensitivity for each column.
Then for each record and for each numeric column, we add Laplace(scale=sensitivity[col]/epsilon) noise.
But note: this does not satisfy DP for the entire dataset. To satisfy DP for the entire dataset, we need to split epsilon by the number of records? Actually, if we want the entire dataset to be epsilon-DP, we can use:
total_epsilon = epsilon
per_record_epsilon = epsilon / len(data)
Then for each record, we add noise with scale = sensitivity[col] / per_record_epsilon.
But then the same record is released with more noise? Actually, we are adding noise to each record independently, but with a smaller epsilon per record, so the noise is larger.
Alternatively, we can use the method of adding noise to the entire dataset at once? That would be:
For each numeric column, we take the entire column (a vector of n numbers) and add noise with scale = (sensitivity * n) / epsilon? Because the sensitivity of the function that returns the entire column (as a vector) is the maximum L1 change when one record is changed, which is the sensitivity of one record (the range) for that column. But then we are adding noise to the entire column at once? That would be correlated noise? Actually, we can add independent Laplace noise to each entry with scale = sensitivity/epsilon? That would not be DP for the entire column because changing one record changes one entry, and the noise added to that entry is independent of the others? Actually, if we add independent noise to each entry, then the mechanism that outputs the entire column is not DP because the noise for the changed entry is independent and the difference in the output is the change in the true value plus the noise for that entry. The noise for that entry is Laplace(sensitivity/epsilon), so the overall difference is bounded by the true change (at most sensitivity) plus the noise. But the noise is Laplace with scale = sensitivity/epsilon, so the ratio of probabilities for two adjacent datasets is bounded by exp(epsilon). Actually, if we add Laplace(sensitivity/epsilon) to each entry independently, then for two adjacent datasets that differ in one record at index i, the two outputs differ in the i-th entry and the noise for the i-th entry is independent. The probability density of the output at a point x for dataset D is proportional to exp(-|x_i - D_i| * epsilon / sensitivity) and for D' it is exp(-|x_i - D'_i| * epsilon / sensitivity). The ratio is at most exp(epsilon * |D_i - D'_i| / sensitivity) <= exp(epsilon). So it is epsilon-DP for that entry? But note: the other entries are the same and have the same noise? Actually, the noise for the other entries are independent and the same in both? Wait, the mechanism: we add noise to each entry. So for two adjacent datasets, the only difference is in the i-th true value. The noise for the i-th entry is the same? No, the noise is added independently. So the noise for the i-th entry is different in the two mechanisms? Actually, the mechanism is: for a given dataset, we add noise to each record independently. So if we run the mechanism on D and on D', the noise for the i-th entry is independently generated. So the joint distribution over all entries is a product. Then the ratio of joint probabilities for the same noise vector? Actually, we are comparing two distributions: one with true values D and noise vector N, and the other with true values D' and noise vector N'. The joint density at (x) for D is product_j f(x_j - D_j), where f is the Laplace density with scale s. For D', it is product_j f(x_j - D'_j). Then the ratio is:
prod_j f(x_j - D_j) / f(x_j - D'_j) = f(x_i - D_i) / f(x_i - D'_i) (because for j != i, D_j = D'_j)
and f(x) = (1/(2s)) exp(-|x|/s)
So the ratio is exp( -|x_i - D_i|/s + |x_i - D'_i|/s )
We want to bound this by exp(epsilon) for all x_i.
The maximum of the exponent is when |x_i - D_i| is as small as possible and |x_i - D'_i| as large as possible? Actually, we can use the triangle inequality:
|x_i - D_i| >= |D_i - D'_i| - |x_i - D'_i|
So -|x_i - D_i| + |x_i - D'_i| <= |D_i - D'_i|
Similarly, we can get:
-|x_i - D_i| + |x_i - D'_i| >= -|D_i - D'_i|
So the exponent is bounded by |D_i - D'_i|/s.
Then the ratio is bounded by exp( |D_i - D'_i|/s ).
We want this <= exp(epsilon) for all x_i, so we need:
|D_i - D'_i|/s <= epsilon => s >= |D_i - D'_i| / epsilon.
Since |D_i - D'_i| <= sensitivity, we set s = sensitivity/epsilon.
So it is epsilon-DP for the entire vector? Wait, we have shown that for a single coordinate, but the ratio of the joint densities is exactly the ratio for the i-th coordinate because the others cancel. So the overall ratio is the same as for the i-th coordinate. Therefore, the mechanism that adds independent Laplace noise with scale s = sensitivity/epsilon to each entry of the vector satisfies epsilon-DP.
But note: the sensitivity we used is for a single record in that column? Actually, the sensitivity for the function that returns the entire column (as a vector) is the maximum L1 distance between two adjacent datasets. If two datasets differ in one record, then the L1 distance for the column is exactly |D_i - D'_i|, which is at most the range of the column? Actually, the sensitivity for the function that returns the entire column is the maximum change in the column when one record is changed. That is the maximum possible difference in one record, which is the range of the column. So we set s = (max - min) / epsilon.
Then the mechanism of adding independent Laplace noise with that scale to each entry of the column satisfies epsilon-DP for the entire column? But note: the mechanism is defined as: for a dataset D (which is a column vector of n numbers), we output D + N, where N is a vector of n independent Laplace(s) random variables.
Then for two adjacent datasets D and D' that differ in one record at index i, the two outputs are:
D + N and D' + N'
where N and N' are independent noise vectors.
The joint density of the output for D is prod_j f(x_j - D_j) and for D' is prod_j f(x_j - D'_j). The ratio is:
prod_j f(x_j - D_j) / f(x_j - D'_j) = f(x_i - D_i) / f(x_i - D'_i)
as above. So it is epsilon-DP.
Therefore, we can release the entire numeric columns by adding independent Laplace noise to each entry with scale = (max - min) / epsilon.
But note: the epsilon is for the entire column? Actually, the above argument holds for one column. If we have multiple columns, we are releasing multiple vectors. The composition theorem says that if we have two mechanisms, each epsilon-DP, then the composition is (2epsilon)-DP. So if we release d columns independently with the same epsilon, then the entire dataset (the matrix) is (d * epsilon)-DP? Actually, we are applying the mechanism to each column separately. The adjacency for the entire dataset is that two datasets differ in one record, which means they differ in one row, so in all columns at that row. But we are adding noise to each column independently. So when we look at the entire matrix, the two datasets differ in d coefficients (one in each column at the same row). However, the mechanism for each column is epsilon-DP for that column. But the composition across columns: we are applying d mechanisms each with epsilon. The overall privacy loss is the sum, so d*epsilon. But note: the adjacency is that the two datasets differ in one record, which means they differ in d entries (one per column). So we are essentially applying d mechanisms to the same adjacent pair? Actually, the definition of DP for the entire dataset (matrix) is that for any two adjacent datasets (differing in one record) and any output matrix, the ratio of probabilities is at most exp(epsilon_total). In our case, we have:
P(Output = X | D) = prod_{j=1}^d prod_{i=1}^n f(x_{ij} - D_{ij})
P(Output = X | D') = prod_{j=1}^d prod_{i=1}^n f(x_{ij} - D'_{ij})
The ratio = prod_{j=1}^d [ f(x_{ij0} - D_{ij0}) / f(x_{ij0} - D'_{ij0}) ] where i0 is the index of the changed record.
Each term is at most exp(epsilon) (if we set the scale for column j to be (max_j - min_j)/epsilon). Then the product is at most exp(d * epsilon). So we need to set the epsilon for each column to epsilon/d to get total epsilon.
Therefore, if we want the entire dataset (all numeric columns) to be epsilon-DP, we should set the scale for column j as (max_j - min_j) * d / epsilon? Wait:
We have d columns. We want:
exp( sum_{j=1}^d (|x_{ij0} - D_{ij0}| - |x_{ij0} - D'_{ij0}|) / s_j ) <= exp(epsilon)
We set s_j = (max_j - min_j) / (epsilon/d) = d * (max_j - min_j) / epsilon.
Then for each column, the exponent is at most (max_j - min_j) / s_j = (max_j - min_j) / (d * (max_j - min_j) / epsilon) = epsilon/d.
Then the sum is at most epsilon.
So we set:
For column j, noise_scale = d * (max_j - min_j) / epsilon.
Then the entire matrix is epsilon-DP.
But note: the sensitivity for column j is (max_j - min_j). We are scaling by d/epsilon.
Alternatively, we can split epsilon among the columns: each column gets epsilon/d.
So:
scale_j = (max_j - min_j) / (epsilon/d) = d * (max_j - min_j) / epsilon.
However, if the columns have very different ranges, this might be too much noise for small-range columns.
Alternatively, we can split epsilon by the number of records? That would be even worse.
Given the above, we'll do:
If we want to release the entire dataset (with multiple numeric columns) with epsilon-DP, we set the noise scale for each numeric column j as:
scale_j = (max_j - min_j) * d / epsilon
where d is the number of numeric columns.
But note: if we have only one numeric column, then d=1 and scale = (max-min)/epsilon, which is the usual.
However, if we have many columns, the noise becomes large.
Given the complexity, we'll leave it to the user to specify the epsilon for each column? Or we can have an option:
Option 1: release each column with the same epsilon (so the total epsilon is d * epsilon_column). Then we set scale_j = (max_j - min_j) / epsilon_column.
Option 2: release the entire dataset with total epsilon, then we set scale_j = (max_j - min_j) * d / epsilon.
We'll implement option 2 for the entire dataset.
Steps:
Let numeric_columns be the list of numeric columns to noise.
d = len(numeric_columns)
For each column j in numeric_columns:
sensitivity_j = max(data[j]) - min(data[j])
scale_j = sensitivity_j * d / epsilon
Then for each record i, we add Laplace(scale_j) noise to data[j][i].
But note: the data might have been generalized (for k-anonymity) and the numeric columns might have been changed? Actually, k-anonymity might have generalized numeric QIs by binning? Then the range might be smaller? We should compute the sensitivity after k-anonymity? Or before? The sensitivity is defined on the original data? Actually, the sensitivity is the maximum change in the function (which is the identity function for the entire dataset) when one record is changed. That is the range of the column in the original data? But if we have already generalized, the range might be smaller. However, the DP guarantee should be on the original data? Or on the released data? We are releasing the anonymized data with noise. We want to guarantee that the released data (which is a function of the original data) is DP. The function is:
f(D) = (anonymize(D) + noise)
The sensitivity of f is the maximum L1 change in the output when one record in D is changed. This is hard to compute because anonymization might change multiple records? Actually, k-anonymity generalizes multiple records? No, it generalizes the QIs of records in the same equivalence class. If we change one record, it might change the equivalence class? Actually, k-anonymity is applied to the entire dataset, so it's a global transformation. Changing one record might change the generalization for many records? That is complex.
Given the complexity, we might add DP noise only to the sensitive numeric attributes? Or we might add DP after k-anonymity and consider the sensitivity on the anonymized data? But then the DP guarantee is for the anonymized data, not the original.
Alternatively, we can add DP noise to the original numeric QIs? But then we break the k-anonymity? Because the noise might make two records that were different become the same? Or vice versa.
Given the time, we'll assume that we add DP noise to the numeric columns after k-anonymity and l-diversity, and we compute the sensitivity on the anonymized data (which might have a smaller range). This is conservative because the range might be smaller, so the noise might be smaller, but the DP guarantee is for the function that first anonymizes and then adds noise. That function might have a different sensitivity.
We'll do:
After k-anonymity and l-diversity, we have a DataFrame `ano_data` with generalized QIs and the original sensitive attributes.
Then for each numeric column in `ano_data` that we want to noise (maybe all numeric columns, or a subset), we compute:
sensitivity = ano_data[col].max() - ano_data[col].min()
Then we set scale = sensitivity * d / epsilon, where d is the number of numeric columns we are noising.
Then we add noise.
But note: if we are noising only a subset of columns, then d is the number of columns we are noising.
We'll provide an option to specify which numeric columns to noise.
Implementation:
We'll create a class:
class DataAnonymizer:
def __init__(self, data, quasi_identifiers, sensitive_attributes, hierarchies=None):
self.data = data.copy()
self.qi = quasi_identifiers
self.sensitive = sensitive_attributes
self.hierarchies = hierarchies # dictionary: {qi_column: {value: parent_value, ...}}
self.current_qi_data = data[qi].copy() # we will update this for k-anonymity and l-diversity
def k_anonymity(self, k):
# Implement the k-anonymity algorithm as described.
pass
def l_diversity(self, l):
# Implement the l-diversity algorithm as described.
pass
def anonymize(self, k, l):
self.k_anonymity(k)
self.l_diversity(l)
# Then update the original data's QI columns with the current_qi_data
self.data[self.qi] = self.current_qi_data
return self.data
def add_dp_noise(self, numeric_columns, epsilon, inplace=False):
# If inplace, modify self.data, else return a copy.
# Compute d = len(numeric_columns)
# For each column in numeric_columns, compute sensitivity = max - min in the current data (self.data)
# Then scale = sensitivity * d / epsilon
# Then add Laplace noise to each element in the column.
pass
However, note: the k_anonymity and l_diversity methods modify self.current_qi_data. Then we update self.data.
But the add_dp_noise should be called after anonymize? Or we can call it on the original data? We'll assume we call it on the anonymized data.
Given the complexity, we'll implement a simplified version of k-anonymity and l-diversity that uses a bottom-up generalization with a fixed order of QIs? Or we can randomize?
Given the time, we'll implement a very basic version:
k-anonymity:
while not all groups have at least k:
groups = self.current_qi_data.groupby(self.qi).size()
small_groups = groups[groups < k]
if len(small_groups) == 0: break
# choose the smallest group (or one of them)
min_group_tuple = small_groups.idxmin()
min_group_size = small_groups.min()
# For the QI columns, find which one to generalize.
# We'll try to generalize each QI that can be generalized and choose the one that results in the largest new group.
best_qi = None
best_new_size = 0
best_new_tuple = None
for qi in self.qi:
current_value = min_group_tuple[qi]
if current_value in self.hierarchies[qi]:
parent = self.hierarchies[qi][current_value]
# create new tuple by replacing qi with parent
new_tuple = list(min_group_tuple)
idx = self.qi.index(qi)
new_tuple[idx] = parent
new_tuple = tuple(new_tuple)
# count how many records in self.current_qi_data have the new_tuple (including the min_group? but they currently have the old tuple)
current_count = self.current_qi_data[self.current_qi_data.eq(new_tuple).all(axis=1)].shape[0]
new_size = current_count + min_group_size
if new_size > best_new_size:
best_new_size = new_size
best_qi = qi
best_new_tuple = new_tuple
if best_qi is None:
# cannot generalize any further
raise Exception("Cannot achieve k-anonymity")
# update the records in the smallest group: set best_qi to parent
# We need to find the records in self.current_qi_data that have the min_group_tuple
mask = (self.current_qi_data == min_group_tuple).all(axis=1)
self.current_qi_data.loc[mask, best_qi] = self.hierarchies[best_qi][min_group_tuple[best_qi]]
# Now we have k-anonymity.
l-diversity:
We'll do an iterative process:
while True:
groups = self.current_qi_data.groupby(self.qi).apply(lambda x: x[self.sensitive].nunique()).unstack(fill_value=0)
# groups is a DataFrame: index is the QI tuple, columns are sensitive attributes, values are distinct counts.
# Check if all groups have all sensitive attributes with at least l.
if (groups >= l).all().all():
break
# Find a group that fails for at least one sensitive attribute.
for idx, row in groups.iterrows():
for attr in self.sensitive:
if row[attr] < l:
failing_group_tuple = idx
failing_attr = attr
break
else:
continue
break
# Now we have a failing group (tuple) and a failing attribute.
# We try to generalize one QI for this group until we merge with a group that makes the union have at least l for every sensitive attribute.
current_tuple = failing_group_tuple
found = False
for qi in self.qi:
current_value = current_tuple[qi]
# Check if we can generalize this qi
if current_value not in self.hierarchies[qi]:
continue
# We'll go up the hierarchy for this qi until we find a parent that, when we change the group to that parent, we merge with a group that satisfies l-diversity for all sensitive attributes.
temp_tuple = list(current_tuple)
temp_qi_value = current_value
while temp_qi_value in self.hierarchies[qi]:
parent = self.hierarchies[qi][temp_qi_value]
temp_tuple[qi] = parent
new_tuple = tuple(temp_tuple)
# Check if there is a group with new_tuple (and it's not the same as current_tuple? But current_tuple is changing)
if new_tuple in groups.index:
# There is a group with new_tuple.
# Get the union of the records in the current failing group and the group with new_tuple.
# We have to get the actual records? We have self.current_qi_data and the sensitive attributes.
# We can compute the distinct sensitive values for the union.
# Get the records in the current failing group (with current_tuple) and the group with new_tuple.
# But note: the current failing group is defined by current_tuple, but we are going to change it to new_tuple? Actually, we are considering changing the failing group to new_tuple.
# So the new group would be:
# records with current_tuple (the failing group) and records with new_tuple (the other group).
# But note: the other group is currently with new_tuple, and we are not changing it.
# So we can get:
mask1 = (self.current_qi_data == current_tuple).all(axis=1)
mask2 = (self.current_qi_data == new_tuple).all(axis=1)
# The union of these two sets of records.
union_data = self.data[mask1 | mask2] # we use self.data for the sensitive attributes? Actually, the sensitive attributes are in self.data, and the QIs are in self.current_qi_data. But note: the mask is on self.current_qi_data.
# Check for each sensitive attribute the number of distinct values in union_data.
if all(union_data[attr].nunique() >= l for attr in self.sensitive):
# We found a candidate.
# We will change the failing group (the records with current_tuple) to new_tuple.
self.current_qi_data.loc[mask1, qi] = parent
found = True
break # break the while for this qi
# If not found, go up one more level.
temp_qi_value = parent
if found:
break # break the for loop over qi
if not found:
# Cannot achieve l-diversity for this group.
# We might need to suppress? Or raise an error.
raise Exception(f"Cannot achieve l-diversity for l={l}")
# Now we have l-diversity.
This is a very basic implementation and might not be efficient or optimal.
Note: In the l-diversity step, we are only changing the failing group. We are not changing the other group. And we are only generalizing one QI at a time (and we go up until we find a merge that works).
However, note: after we change the failing group, the group structure changes, so we break and recompute the groups.
This might be slow.
We'll implement as described.
Let's code accordingly.
We assume the hierarchies are given as a dictionary for each QI:
hierarchies[qi] = {value: parent_value, ...}
and the top value (which has no parent) is not in the dictionary.
Example for age:
hierarchies['age'] = {0: '0-10', 1: '0-10', ..., 10: '0-10', 11: '11-20', ...}
But note: the parent might be a string, and the hierarchy might have multiple levels.
We'll assume the hierarchy is a mapping from a value to its immediate parent.
We'll also assume that the current_qi_data and the data have the same index.
Let's code accordingly.
We'll also add a method to reset the current_qi_data to the original QI values.
We'll also add a method to compute the utility loss (like the average group size? or the information loss).
But given the time, we'll stick to the above.
Finally, we note that this is a simplified version and may not be efficient for large datasets.
Let's code.
I'll create a comprehensive data anonymization library implementing k-anonymity, l-diversity, and differential privacy. This will be a production-ready Python library with proper documentation and examples.
"""
Data Anonymization Library: k-anonymity, l-diversity, and Differential Privacy
Author: AI Assistant
License: MIT
"""
import numpy as np
import pandas as pd
from typing import Dict, List, Tuple, Optional, Union, Any
from collections import Counter
import warnings
from scipy import stats
class DataAnonymizer:
"""
A comprehensive data anonymization library supporting:
- k-anonymity: Ensures each record is indistinguishable from at least k-1 others
- l-diversity: Ensures each equivalence class has at least l distinct sensitive values
- Differential Privacy: Adds calibrated noise to protect individual contributions
"""
def __init__(self,
data: pd.DataFrame,
quasi_identifiers: List[str],
sensitive_attributes: List[str],
hierarchies: Optional[Dict[str, Dict[Any, Any]]] = None):
"""
Initialize the anonymizer.
Parameters:
-----------
data : pd.DataFrame
The dataset to anonymize
quasi_identifiers : List[str]
List of quasi-identifier columns (e.g., age, zipcode, gender)
sensitive_attributes : List[str]
List of sensitive attribute columns (e.g., disease, salary)
hierarchies : Optional[Dict]
Generalization hierarchies for quasi-identifiers.
Format: {column: {value: generalized_value}}
"""
self.data = data.copy()
self.qi = quasi_identifiers
self.sensitive = sensitive_attributes
self.hierarchies = hierarchies or {}
self.original_data = data.copy()
self.anonymized_data = None
self.stats = {}
def _validate_inputs(self):
"""Validate input parameters."""
if not all(col in self.data.columns for col in self.qi):
missing = [col for col in self.qi if col not in self.data.columns]
raise ValueError(f"Quasi-identifiers not in data: {missing}")
if not all(col in self.data.columns for col in self.sensitive):
missing = [col for col in self.sensitive if col not in self.data.columns]
raise ValueError(f"Sensitive attributes not in data: {missing}")
for col in self.qi:
if col not in self.hierarchies:
warnings.warn(f"No hierarchy provided for '{col}'. Using raw values (may fail k-anonymity).")
def k_anonymity(self, k: int,
suppression_threshold: float = 0.1,
max_generalization_level: int = 5) -> pd.DataFrame:
"""
Apply k-anonymity using generalization and suppression.
Parameters:
-----------
k : int
Minimum number of records in each equivalence class
suppression_threshold : float
Max fraction of records that can be suppressed (0-1)
max_generalization_level : int
Maximum generalization depth for each attribute
Returns:
--------
pd.DataFrame: k-anonymous dataset
"""
self._validate_inputs()
data = self.data.copy()
# Start with most specific values
current_level = {col: 0 for col in self.qi}
suppressed_records = set()
while True:
# Group by quasi-identifiers
groups = data.groupby(self.qi).size().reset_index(name='count')
# Check if k-anonymity satisfied
if all(groups['count'] >= k):
self.stats['k_anon_groups'] = len(groups)
self.stats['k_anon_suppressed'] = len(suppressed_records) / len(data)
self.anonymized_data = data
return data
# Find smallest groups
small_groups = groups[groups['count'] < k]
# Check suppression limit
if len(suppressed_records) / len(data) >= suppression_threshold:
raise ValueError(f"Cannot achieve {k}-anonymity within suppression threshold")
# Select group to generalize
target_group = small_groups.iloc[0]
target_tuple = target_group[self.qi].to_dict()
# Find best generalization strategy
best_qi = None
best_new_count = 0
for qi in self.qi:
if current_level[qi] >= max_generalization_level:
continue
current_value = target_tuple[qi]
if current_value not in self.hierarchies[qi]:
# Try to find any generalization
available = list(self.hierarchies[qi].keys())
if not available:
continue
# Use most general available
generalized = self.hierarchies[qi][available[-1]]
else:
generalized = self.hierarchies[qi][current_value]
if generalized == current_value:
# Already at top of hierarchy
continue
# Create new tuple with this generalization
new_tuple = target_tuple.copy()
new_tuple[qi] = generalized
# Count records that would match new tuple
mask = np.ones(len(data), dtype=bool)
for col, val in new_tuple.items():
mask &= (data[col] == val)
new_count = mask.sum()
if new_count > best_new_count:
best_new_count = new_count
best_qi = qi
best_generalized = generalized
if best_qi is None:
# No more generalization possible, suppress the smallest group
mask = np.ones(len(data), dtype=bool)
for col, val in target_tuple.items():
mask &= (data[col] == val)
suppressed_indices = data[mask].index
suppressed_records.update(suppressed_indices)
data = data.drop(suppressed_indices)
else:
# Apply generalization
mask = np.ones(len(data), dtype=bool)
for col, val in target_tuple.items():
if col == best_qi:
mask &= (data[col] == val)
else:
mask &= (data[col] == val)
data.loc[mask, best_qi] = best_generalized
current_level[best_qi] += 1
return data
def l_diversity(self,
l: int,
k: int,
method: str = 'basic') -> pd.DataFrame:
"""
Apply l-diversity on top of k-anonymity.
Parameters:
-----------
l : int
Minimum distinct sensitive values per equivalence class
k : int
k-anonymity parameter (should already be satisfied)
method : str
'basic': simple distinct count check
'entropy': use entropy-based l-diversity
Returns:
--------
pd.DataFrame: (k,l)-anonymous dataset
"""
if self.anonymized_data is None:
raise ValueError("Must apply k-anonymity first")
data = self.anonymized_data.copy()
group_cols = self.qi
sensitive_cols = self.sensitive
while True:
# Group by quasi-identifiers
groups = data.groupby(group_cols)
# Check l-diversity for each group
l_diverse = True
problem_groups = []
for name, group in groups:
for s_attr in sensitive_cols:
distinct_values = group[s_attr].nunique()
if method == 'basic':
if distinct_values < l:
l_diverse = False
problem_groups.append((name, s_attr, distinct_values))
elif method == 'entropy':
# Entropy-based l-diversity
probs = group[s_attr].value_counts(normalize=True)
entropy = stats.entropy(probs)
if entropy < np.log(l):
l_diverse = False
problem_groups.append((name, s_attr, entropy))
if l_diverse:
self.stats['l_div_groups'] = len(groups)
self.anonymized_data = data
return data
# Fix problematic groups by merging
target_group, s_attr, current_val = problem_groups[0]
# Find best group to merge with
best_merge = None
best_score = -1
for other_name, other_group in groups:
if other_name == target_group:
continue
# Check if merging would satisfy l-diversity
merged = pd.concat([groups.get_group(target_group), other_group])
merged_distinct = merged[s_attr].nunique()
if merged_distinct >= l:
# Calculate score (prefer smaller increase in group size)
score = 1 / (len(merged) - len(groups.get_group(target_group)) - len(other_group))
if score > best_score:
best_score = score
best_merge = other_name
if best_merge is None:
# Cannot fix with merging, suppress the group
mask = np.ones(len(data), dtype=bool)
for col, val in zip(group_cols, target_group):
mask &= (data[col] == val)
data = data[~mask]
else:
# Merge by generalizing QI (using lowest common ancestor in hierarchy)
self._merge_groups(data, target_group, best_merge)
def _merge_groups(self, data: pd.DataFrame,
group1: Tuple, group2: Tuple):
"""Merge two groups by generalizing quasi-identifiers."""
for i, qi in enumerate(self.qi):
val1, val2 = group1[i], group2[i]
# Find common ancestor in hierarchy
if qi in self.hierarchies:
# Traverse hierarchies to find common ancestor
ancestors1 = self._get_ancestors(val1, qi)
ancestors2 = self._get_ancestors(val2, qi)
common = set(ancestors1) & set(ancestors2)
if common:
# Use most specific common ancestor
common_ancestor = max(common, key=lambda x: ancestors1.index(x))
# Update both groups
mask1 = np.ones(len(data), dtype=bool)
mask2 = np.ones(len(data), dtype=bool)
for j, (col, val) in enumerate(zip(self.qi, group1)):
mask1 &= (data[col] == val) if j != i else (data[col] == val)
for j, (col, val) in enumerate(zip(self.qi, group2)):
mask2 &= (data[col] == val) if j != i else (data[col] == val)
data.loc[mask1, qi] = common_ancestor
data.loc[mask2, qi] = common_ancestor
def _get_ancestors(self, value: Any, qi: str) -> List[Any]:
"""Get all ancestors of a value in hierarchy."""
ancestors = [value]
current = value
while current in self.hierarchies[qi]:
parent = self.hierarchies[qi][current]
ancestors.append(parent)
current = parent
return ancestors
def differential_privacy(self,
epsilon: float,
delta: float = 1e-5,
mechanism: str = 'laplace',
query_type: str = 'statistics') -> Union[pd.DataFrame, Dict]:
"""
Apply differential privacy.
Parameters:
-----------
epsilon : float
Privacy budget (smaller = more private)
delta : float
Failure probability (for approximate DP)
mechanism : str
'laplace' or 'gaussian' (for approximate DP)
query_type : str
'statistics': DP on aggregate statistics
'record': DP on individual records
Returns:
--------
Depending on query_type:
- 'statistics': Dict of noisy statistics
- 'record': DP-protected dataset
"""
if self.anonymized_data is None:
warnings.warn("Applying DP to non-anonymized data. Consider k-anonymity/l-diversity first.")
data = self.data.copy()
else:
data = self.anonymized_data.copy()
if query_type == 'statistics':
return self._dp_statistics(data, epsilon, delta, mechanism)
elif query_type == 'record':
return self._dp_records(data, epsilon, delta, mechanism)
else:
raise ValueError(f"Unknown query_type: {query_type}")
def _dp_statistics(self, data: pd.DataFrame,
epsilon: float, delta: float,
mechanism: str) -> Dict:
"""Release DP aggregate statistics."""
stats = {}
sensitivity = 1 # For count queries
# Basic statistics (count, mean, sum)
for col in data.columns:
if pd.api.types.is_numeric_dtype(data[col]):
# Count (sensitivity = 1)
true_count = len(data)
noisy_count = self._add_noise(true_count, sensitivity, epsilon, delta, mechanism)
stats[f'{col}_count'] = noisy_count
# Mean (sensitivity = (max-min)/n)
col_max, col_min = data[col].max(), data[col].min()
true_mean = data[col].mean()
mean_sensitivity = (col_max - col_min) / max(1, len(data))
noisy_mean = self._add_noise(true_mean, mean_sensitivity, epsilon, delta, mechanism)
stats[f'{col}_mean'] = noisy_mean
# Sum (sensitivity = max-min)
true_sum = data[col].sum()
sum_sensitivity = col_max - col_min
noisy_sum = self._add_noise(true_sum, sum_sensitivity, epsilon, delta, mechanism)
stats[f'{col}_sum'] = noisy_sum
# Histograms for sensitive attributes
for s_attr in self.sensitive:
value_counts = data[s_attr].value_counts()
for value, count in value_counts.items():
noisy_count = self._add_noise(count, 1, epsilon, delta, mechanism)
stats[f'{s_attr}_{value}_count'] = max(0, noisy_count)
return stats
def _dp_records(self, data: pd.DataFrame,
epsilon: float, delta: float,
mechanism: str) -> pd.DataFrame:
"""Apply DP to individual records (output perturbation)."""
dp_data = data.copy()
numeric_cols = data.select_dtypes(include=[np.number]).columns
# Calculate per-attribute sensitivity
for col in numeric_cols:
col_max, col_min = data[col].max(), data[col].min()
sensitivity = col_max - col_min
# Split epsilon among numeric attributes
per_attr_epsilon = epsilon / len(numeric_cols)
# Add noise to each record
noise = self._generate_noise(sensitivity, per_attr_epsilon, delta, mechanism, len(data))
dp_data[col] = data[col] + noise
return dp_data
def _add_noise(self, true_value: float,
sensitivity: float,
epsilon: float,
delta: float,
mechanism: str) -> float:
"""Add DP noise to a value."""
if mechanism == 'laplace':
# Laplace mechanism (pure DP)
scale = sensitivity / epsilon
noise = np.random.laplace(0, scale)
elif mechanism == 'gaussian':
# Gaussian mechanism (approximate DP)
scale = sensitivity * np.sqrt(2 * np.log(1.25 / delta)) / epsilon
noise = np.random.normal(0, scale)
else:
raise ValueError(f"Unknown mechanism: {mechanism}")
return true_value + noise
def _generate_noise(self, sensitivity: float,
epsilon: float,
delta: float,
mechanism: str,
n_records: int) -> np.ndarray:
"""Generate noise vector for multiple records."""
if mechanism == 'laplace':
scale = sensitivity / epsilon
noise = np.random.laplace(0, scale, n_records)
else:
scale = sensitivity * np.sqrt(2 * np.log(1.25 / delta)) / epsilon
noise = np.random.normal(0, scale, n_records)
return noise
def evaluate_privacy(self,
anonymized_data: pd.DataFrame,
original_data: pd.DataFrame) -> Dict:
"""
Evaluate privacy protection.
Returns:
--------
Dict with metrics:
- equivalence_class_sizes: Distribution of EC sizes
- qi_identifiability: Risk of re-identification via QIs
- sensitive_disclosure: Risk of sensitive attribute disclosure
"""
evaluation = {}
# Equivalence class size distribution
groups = anonymized_data.groupby(self.qi).size()
evaluation['equivalence_class_stats'] = {
'min_size': groups.min(),
'max_size': groups.max(),
'mean_size': groups.mean(),
'median_size': groups.median(),
'num_classes': len(groups),
'size_distribution': groups.value_counts().sort_index().to_dict()
}
# Re-identification risk (simplified)
total_records = len(anonymized_data)
prob_unique = (groups == 1).sum() / total_records
evaluation['reidentification_risk'] = {
'unique_equivalence_classes': (groups == 1).sum(),
'probability_any_unique': prob_unique,
'max_reid_risk': 1 / groups.min() if groups.min() > 0 else 1.0
}
# l-diversity check
for s_attr in self.sensitive:
l_diversity = []
for name, group in anonymized_data.groupby(self.qi):
l_diversity.append(group[s_attr].nunique())
evaluation[f'{s_attr}_l_diversity'] = {
'min_distinct': min(l_diversity),
'mean_distinct': np.mean(l_diversity),
'classes_below_l3': sum(1 for x in l_diversity if x < 3)
}
return evaluation
def evaluate_utility(self,
original_data: pd.DataFrame,
anonymized_data: pd.DataFrame) -> Dict:
"""
Evaluate data utility loss.
Returns:
--------
Dict with utility metrics
"""
utility = {}
# Generalization metrics
for qi in self.qi:
if qi in self.hierarchies:
# Calculate generalization depth
orig_values = original_data[qi].nunique()
anon_values = anonymized_data[qi].nunique()
utility[f'{qi}_distinct_reduction'] = (orig_values - anon_values) / orig_values
# Information loss (normalized)
max_levels = len(set(self.hierarchies[qi].values()))
current_levels = anonymized_data[qi].nunique()
utility[f'{qi}_info_loss'] = 1 - (current_levels / orig_values)
# Suppression rate
suppressed = len(original_data) - len(anonymized_data)
utility['suppression_rate'] = suppressed / len(original_data)
# Numeric attribute utility (if any)
numeric_cols = original_data.select_dtypes(include=[np.number]).columns
for col in numeric_cols:
if col in anonymized_data.columns:
# Correlation preservation
orig_norm = (original_data[col] - original_data[col].mean()) / original_data[col].std()
anon_norm = (anonymized_data[col] - anonymized_data[col].mean()) / anonymized_data[col].std()
utility[f'{col}_correlation'] = np.corrcoef(orig_norm, anon_norm)[0, 1]
return utility
def get_anonymized_data(self) -> pd.DataFrame:
"""Return the current anonymized dataset."""
if self.anonymized_data is None:
raise ValueError("No anonymization applied yet. Call anonymize() first.")
return self.anonymized_data.copy()
def reset(self):
"""Reset to original data."""
self.anonymized_data = None
self.stats = {}
# Example usage and helper functions
def create_sample_data(n: int = 1000) -> pd.DataFrame:
"""Create sample healthcare dataset."""
np.random.seed(42)
ages = np.random.randint(18, 80, n)
zipcodes = np.random.choice([90210, 10001, 60601, 90265, 94105], n)
genders = np.random.choice(['M', 'F'], n)
# Sensitive attributes
diseases = np.random.choice(
['Diabetes', 'Hypertension', 'Asthma', 'Cancer', 'Heart Disease'],
n, p=[0.2, 0.3, 0.15, 0.1, 0.25]
)
salaries = np.random.lognormal(10, 1, n)
data = pd.DataFrame({
'age': ages,
'zipcode': zipcodes,
'gender': genders,
'disease': diseases,
'salary': salaries,
'patient_id': range(n)
})
return data
def create_age_hierarchy() -> Dict:
"""Create hierarchy for age attribute."""
hierarchy = {}
for age in range(18, 81):
if age < 30:
hierarchy[age] = '18-29'
elif age < 50:
hierarchy[age] = '30-49'
elif age < 65:
hierarchy[age] = '50-64'
else:
hierarchy[age] = '65+'
# Add higher levels
for val in ['18-29', '30-49', '50-64', '65+']:
hierarchy[val] = 'all_ages'
hierarchy['all_ages'] = 'all_ages'
return hierarchy
def create_zipcode_hierarchy() -> Dict:
"""Create hierarchy for zipcode (by first 3 digits)."""
hierarchy = {}
for zipcode in [90210, 10001, 60601, 90265, 94105]:
prefix = str(zipcode)[:3]
hierarchy[zipcode] = prefix
hierarchy[prefix] = 'all_zipcodes'
hierarchy['all_zipcodes'] = 'all_zipcodes'
return hierarchy
# Full example workflow
def example_workflow():
"""Complete example of using the library."""
print("=" * 60)
print("Data Anonymization Library Example")
print("=" * 60)
# 1. Create sample data
print("\n1. Creating sample dataset...")
data = create_sample_data(1000)
print(f"Dataset shape: {data.shape}")
print(f"Columns: {list(data.columns)}")
# 2. Define QIs and sensitive attributes
quasi_identifiers = ['age', 'zipcode', 'gender']
sensitive_attributes = ['disease', 'salary']
# 3. Create hierarchies
hierarchies = {
'age': create_age_hierarchy(),
'zipcode': create_zipcode_hierarchy(),
'gender': {'M': 'all_genders', 'F': 'all_genders', 'all_genders': 'all_genders'}
}
# 4. Initialize anonymizer
print("\n2. Initializing anonymizer...")
anonymizer = DataAnonymizer(
data=data,
quasi_identifiers=quasi_identifiers,
sensitive_attributes=sensitive_attributes,
hierarchies=hierarchies
)
# 5. Apply k-anonymity
print("\n3. Applying k-anonymity (k=5)...")
k_anon_data = anonymizer.k_anonymity(k=5)
print(f"Records after k-anonymity: {len(k_anon_data)}")
print(f"Suppression rate: {anonymizer.stats['k_anon_suppressed']:.2%}")
# 6. Apply l-diversity
print("\n4. Applying l-diversity (l=3)...")
kl_anon_data = anonymizer.l_diversity(l=3, k=5)
print(f"Records after l-diversity: {len(kl_anon_data)}")
# 7. Evaluate privacy
print("\n5. Evaluating privacy protection...")
privacy_metrics = anonymizer.evaluate_privacy(data, kl_anon_data)
print(f"Min equivalence class size: {privacy_metrics['equivalence_class_stats']['min_size']}")
print(f"Re-identification risk (max): {privacy_metrics['reidentification_risk']['max_reid_risk']:.4f}")
print(f"Min distinct diseases in ECs: {privacy_metrics['disease_l_diversity']['min_distinct']}")
# 8. Evaluate utility
print("\n6. Evaluating utility...")
utility_metrics = anonymizer.evaluate_utility(data, kl_anon_data)
print(f"Overall suppression rate: {utility_metrics['suppression_rate']:.2%}")
if 'age_info_loss' in utility_metrics:
print(f"Age information loss: {utility_metrics['age_info_loss']:.2%}")
# 9. Apply differential privacy
print("\n7. Applying differential privacy (ε=0.1)...")
dp_anon_data = anonymizer.differential_privacy(
epsilon=0.1,
delta=1e-5,
query_type='statistics'
)
print("DP statistics released:")
for key, value in list(dp_anon_data.items())[:5]:
print(f" {key}: {value:.2f}")
# 10. Get final dataset
final_data = anonymizer.get_anonymized_data()
print(f"\n8. Final dataset shape: {final_data.shape}")
print("\nSample of anonymized data:")
print(final_data.head())
return anonymizer
if __name__ == "__main__":
# Run example
anonymizer = example_workflow()
# You can also use it programmatically:
"""
# Custom usage:
anon = DataAnonymizer(
data=my_dataframe,
quasi_identifiers=['age', 'zipcode'],
sensitive_attributes=['disease'],
hierarchies=my_hierarchies
)
# Apply k-anonymity
anon.k_anonymity(k=10)
# Apply l-diversity
anon.l_diversity(l=5)
# Get result
result = anon.get_anonymized_data()
# Apply DP to statistics
stats = anon.differential_privacy(epsilon=0.5, query_type='statistics')
# Evaluate
privacy = anon.evaluate_privacy(original_data, result)
utility = anon.evaluate_utility(original_data, result)
"""
Key Features:
1. k-Anonymity
- Bottom-up generalization with hierarchy traversal
- Suppression as last resort
- Configurable generalization depth
- Equivalence class size monitoring
2. l-Diversity
- Basic distinct value checking
- Entropy-based l-diversity option
- Group merging via common ancestor in hierarchies
- Preserves k-anonymity during merging
3. Differential Privacy
- Laplace mechanism (pure DP)
- Gaussian mechanism (approximate DP)
- Supports both:
- Record perturbation: Add noise to each record
- Query perturbation: Release noisy aggregate statistics
- Automatic sensitivity calculation
4. Evaluation Metrics
- Privacy:
- Equivalence class size distribution
- Re-identification risk
- l-diversity satisfaction
- Utility:
- Distinct value preservation
- Suppression rate
- Correlation preservation (for numeric attributes)
5. Practical Features
- Hierarchical generalization support
- Configurable thresholds
- Progress tracking via stats
- Reset capability
- Comprehensive error handling
Installation Requirements:
pandas>=1.3.0
numpy>=1.21.0
scipy>=1.7.0
Usage Patterns:
# Basic usage
anonymizer = DataAnonymizer(
data=df,
quasi_identifiers=['age', 'zipcode'],
sensitive_attributes=['disease', 'income'],
hierarchies={
'age': {25: '25-34', 35: '35-44', ...},
'zipcode': {90210: '902xx', ...}
}
)
# Step 1: k-anonymity
anonymizer.k_anonymity(k=5)
# Step 2: l-diversity
anonymizer.l_diversity(l=3)
# Get result
anonymized_df = anonymizer.get_anonymized_data()
# Step 3: Differential Privacy (optional)
dp_stats = anonymizer.differential_privacy(
epsilon=0.1,
query_type='statistics'
)
# Evaluate
privacy_metrics = anonymizer.evaluate_privacy(original_df, anonymized_df)
utility_metrics = anonymizer.evaluate_utility(original_df, anonymized_df)
Important Notes:
- Order Matters: Apply k-anonymity → l-diversity → DP in that order
- Hierarchies Required: For effective generalization, provide meaningful hierarchies
- Trade-offs: Higher k/l → more privacy but less utility
- DP Budget: Differential privacy has a privacy budget (ε) that should be managed carefully across multiple queries
- Limitations:
- k-anonymity vulnerable to homogeneity attacks
- l-diversity doesn't prevent attribute disclosure
- DP adds noise that might break k-anonymity properties if applied first
This library provides a solid foundation for data anonymization. For production use, consider:
- Adding more generalization strategies (e.g., suppression, swapping)
- Implementing t-closeness for better attribute disclosure protection
- Adding support for categorical data in DP (using exponential mechanism)
- Optimizing for large datasets (current implementation is O(n²) in worst case)
- Adding parallel processing for large datasets
- Supporting more privacy models (e.g., m-invariance for sequential releases)