Commit 2a5bd1cb authored by Katharine Jarmul's avatar Katharine Jarmul
Browse files

updating with more solutions

parent d512115c
Loading
Loading
Loading
Loading
+2 −2
Changes for notebooks/01 - Pseudonymization.ipynb: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

### 01. Pseudonymization

In this notebook, we'll explore pseudonymization methods such as hashing, masking and homomorphic pseudonymization.

For more reading on the topic, please see:

- [Medium (Alex Ewerlöf): Anonymization vs. Pseudonymization](https://medium.com/@alexewerlof/gdpr-pseudonymization-techniques-62f7b3b46a56)
- [KIProtect: GDPR for Data Science](https://kiprotect.com/blog/gdpr_for_data_science.html)
- [IAPP: Anonymization and Pseudonymization Compared in relation to GDPR compliance](https://iapp.org/media/pdf/resource_center/PA_WP2-Anonymous-pseudonymous-comparison.pdf)


To test out more [KIProtect](https://kiprotect.com) API calls, please [sign up](https://kiprotect.com/signup.html) on our site.

%% Cell type:code id: tags:

``` python
import base64
from hashlib import blake2b

import pandas as pd
import requests

from faker import Faker
```

%% Cell type:markdown id: tags:

#### Precheck: What is our data?
- What information is contained in our data?
- What privacy concerns are there?
- How should we proceed?

%% Cell type:code id: tags:

``` python
df = pd.read_csv('../data/iot_example.csv')
```

%% Cell type:code id: tags:

``` python
df.head()
```

%% Cell type:markdown id: tags:

#### Section One: Hashing

- Applying the blake2b hash
- Allowing for de-pseudonymization
- Creating a reusable method for hashing

%% Cell type:code id: tags:

``` python
username = df.iloc[0,1]
```

%% Cell type:code id: tags:

``` python
username
```

%% Cell type:code id: tags:

``` python
hasher = blake2b()
hasher.update(username)
hasher.hexdigest()
```

%% Cell type:markdown id: tags:

Oops. What went wrong? How can we fix?

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/proper_encoding.py

```

%% Cell type:markdown id: tags:

Great! Now we have a hash. Michael is safe! (or [is he?](https://nakedsecurity.sophos.com/2014/06/24/new-york-city-makes-a-hash-of-taxi-driver-data-disclosure/))

But... what if we need to later determine that michaelsmith is a2a858011c091715....

%% Cell type:code id: tags:

``` python
hasher.
```

%% Cell type:markdown id: tags:

Okay, let's try something that we can reverse...

%% Cell type:code id: tags:

``` python
# From https://stackoverflow.com/questions/2490334/simple-way-to-encode-a-string-according-to-a-password

def encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        #print(key_c)
        enc_c = (ord(clear[i]) + ord(key_c)) % 256
        #print(enc_c)
        enc.append(enc_c)
    return base64.urlsafe_b64encode(bytes(enc))

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc)
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + enc[i] - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)
```

%% Cell type:code id: tags:

``` python
encode('supa_secret', username)
```

%% Cell type:code id: tags:

``` python
decode('supa_secret', b'4N7TycDY0dbfzujb')
```

%% Cell type:markdown id: tags:

#### Challenge

- Can you come up with another string which will properly decode the secret which is *not* the same as the original key?
- Hint: Take a look at the encode method and use the print statements for a clue.

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/lockpick.py
```

%% Cell type:markdown id: tags:

Welp. That maybe is not so great...

%% Cell type:markdown id: tags:

#### Section Two: Data Masking and Tokenization

- What should we mask?
- How?
- What do we do if we need realistic values?

%% Cell type:code id: tags:

``` python
df.sample(2)
```

%% Cell type:code id: tags:

``` python
super_masked = df.applymap(lambda x: 'NOPE')
```

%% Cell type:code id: tags:

``` python
super_masked.head()
```

%% Cell type:markdown id: tags:

😜

Okay, no more jokes. But masking usually is just that. Replace your senstive data with some sort of represetation.

But instead, we could also tokenize the data. This means to replace it with random fictitious data. How do we tokenize this?

%% Cell type:code id: tags:

``` python
fakes = Faker()
```

%% Cell type:code id: tags:

``` python
fakes.name()
```

%% Cell type:code id: tags:

``` python
fakes.
```

%% Cell type:code id: tags:

``` python
fakes.user_name()
```

%% Cell type:markdown id: tags:

#### Challenge

Make a new column `pseudonym` which masks the data using the faker `user_name` method.

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/masked_pseudonym.py

```

%% Cell type:markdown id: tags:

Whaaaa!?!? Pretty cool, eh?

(In case you want to read up on [how it works](https://github.com/joke2k/faker/blob/06d323f6cff95103d4ccda03f5d4ab2c45334e46/faker/providers/internet/__init__.py#L162))

But.. we can't reverse it. It is tuned per locale (usually using probabilities based on names in locale). That said, works fabulous for test data!

%% Cell type:markdown id: tags:

#### Step Three: Homomorphic Pseudonymization

%% Cell type:code id: tags:

``` python
## This key is shared in trust (please do not abuse)!!
## We will leave it active for a few days.
## However, you can sign up for your own key on our site
## https://kiprotect.com

SHARED_KEY = '42a2d3fc1cc449e2a27ddd457e056012'
```

%% Cell type:markdown id: tags:

##### Finding Nulls

We need to create valid JSON, but Pandas and numpy don't make this easy if you have null values. How can we test for nulls?

%% Cell type:code id: tags:

``` python
df.isnull().any()
```

%% Cell type:code id: tags:

``` python
df.note.isnull().sum()
```

%% Cell type:code id: tags:

``` python
df.note.isnull().sum() / df.note.count()
```

%% Cell type:code id: tags:

``` python
df.note.dtype
```

%% Cell type:code id: tags:

``` python
df.note.value_counts()
```

%% Cell type:code id: tags:

``` python
jsonable_df = df.fillna('')
```

%% Cell type:markdown id: tags:

##### Creating a list of JSON items

%% Cell type:code id: tags:

``` python
items = jsonable_df.iloc[:10].T.to_dict()
```

%% Cell type:code id: tags:

``` python
items
```

%% Cell type:code id: tags:

``` python
item_list = list(items.values())
```

%% Cell type:code id: tags:

``` python
actions = [
    {
        "name": "pseudonymize-username",
        "transform-value" : {
            "key": "username",
            "pseudonymize" : {
                "method": "merengue",
                "key": "supa_secret",
            }
        }
    }
]
```

%% Cell type:code id: tags:

``` python
import json
data = requests.post(
    'https://api.kiprotect.com/v1/transform',
    data = json.dumps(
        {"actions": actions, "items": item_list},
        allow_nan=False),
    headers = {'Authorization': 'Bearer {}'.format(
        SHARED_KEY)}
        SHARED_KEY), 'Content-Type': 'application/json'}
)
```

%% Cell type:code id: tags:

``` python
data.json()
```

%% Cell type:code id: tags:

``` python
depseudonymize_actions = [
    {
        "name": "encode-username",
        "transform-value": {
        "key": "username",
        "decode": {
            "format": "base64"
        }}
    },
    {
        "name": "depseudonymize-username",
        "transform-value" : {
            "key": "username",
            "depseudonymize" : {
                "method": "merengue",
                "key": "supa_secret"
            }
        }
    },
    {
        "name": "encode-username",
        "transform-value": {
        "key": "username",
        "encode": {
            "format": "utf-8"
        }}
    }
]
```

%% Cell type:code id: tags:

``` python
depseudonymized_data = requests.post(
    'https://api.kiprotect.com/v1/transform',
    json = {'actions': depseudonymize_actions,
            'items': data.json()['items']},
    headers = {'Authorization': 'Bearer {}'.format(
        SHARED_KEY)}
        SHARED_KEY), 'Content-Type': 'application/json'}
)
```

%% Cell type:code id: tags:

``` python
depseudonymized_data.json()
```

%% Cell type:markdown id: tags:

#### Challenge

Create a function which takes a dataframe and uses the pseudonymization API to pseudonymize a selected subset of columns.

It returns a new dataframe of with pseudonymized data.

NOTE: Test using just 1k rows so you don't abuse the server please :)

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/pseudonymize_columns.py
```

%% Cell type:code id: tags:

``` python
ps_df = pseudonymize_columns(jsonable_df[:1000],
                             ['username', 'note'])
ps_df.head()
```

%% Cell type:code id: tags:

``` python
```
+14 −7
Changes for notebooks/02 - Introduction to Anonymization with K-Anonymity.ipynb: 14 added lines, 7 removed lines.
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

### A Brief Introduction to Anonymization with K-Anonymity

Anonymization of data usually requires a knowledge of what potential attacks the data will face, and an understanding of possible linked data which may be available to the attacker. It is difficult to anticipate, when releasing data, what future linkage or attacks might be possible -- so it is indeed quite difficult to release useful information and determine it has been "fully" anonymized and will remain so in the future.

That said, in this notebook, we will explore several concepts related to K-Anonymity. For further review, please see the in-depth notebooks, which also contain definitions and code for exploring anonymization via K-Anonymity and measuring privacy loss with differential privacy.

%% Cell type:code id: tags:

``` python
import pandas as pd
from matplotlib import pylab as pl

# this is a list of the column names in our dataset (as the file doesn't contain any headers)
names = (
    'age',
    'workclass', #Private, Self-emp-not-inc, Self-emp-inc, Federal-gov, Local-gov, State-gov, Without-pay, Never-worked.
    'fnlwgt', # "weight" of that person in the dataset (i.e. how many people does that person represent) -> https://www.kansascityfed.org/research/datamuseum/cps/coreinfo/keyconcepts/weights
    'education',
    'education-num',
    'marital-status',
    'occupation',
    'relationship',
    'race',
    'sex',
    'capital-gain',
    'capital-loss',
    'hours-per-week',
    'native-country',
    'income',
)

# some fields are categorical and will require special treatment
categorical = set((
    'workclass',
    'education',
    'marital-status',
    'occupation',
    'relationship',
    'sex',
    'native-country',
    'race',
    'income',
))

df = pd.read_csv("../data/k-anonymity/adult.all.txt",
                 sep=", ", header=None,
                 names=names, index_col=False, engine='python')
```

%% Cell type:code id: tags:

``` python
df.head()
```

%% Cell type:markdown id: tags:

### Your Turn

- What potential sensitive data do we have?
- How might different attacks be used on this data?
- How might we go about anonymization when thinking of K-Anonymity?

%% Cell type:code id: tags:

``` python
df.dtypes
```

%% Cell type:markdown id: tags:

### Your Turn

- We need to turn each categorical column into a Pandas Categorical column

%% Cell type:code id: tags:

``` python
for column in categorical:
    df[column] = pd.Categorical(df[column])
```

%% Cell type:code id: tags:

``` python
from utils import split, get_spans
```

%% Cell type:code id: tags:

``` python
split?
```

%% Cell type:code id: tags:

``` python
get_spans?
```

%% Cell type:code id: tags:

``` python
get_spans(df, df.index)
```

%% Cell type:markdown id: tags:

### Your Turn

- Now we need to write a function `is_k_anonymous` which allows us to test whether a partition (in this case, a set of rows) is valid.

%% Cell type:code id: tags:

``` python
def is_k_anonymous(df, partition, sensitive_column, k=3):
    """
    :param               df: The dataframe on which to check the partition.
    :param        partition: The partition of the dataframe to check.
    :param sensitive_column: The name of the sensitive column
    :param                k: The desired k
    :returns               : True if the partition is valid according to our k-anonymity criteria, False otherwise.
    """
    if len(partition) < k:
        # we cannot split this partition further...
        return False
    return True
    pass
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/k-anonymity/k-anonymous.py
```

%% Cell type:markdown id: tags:

### Creating a K Anonymous Dataset

Next, we need to implement the partitioning of the dataset and visualize it, to get a better understanding of the chosen partitions.

%% Cell type:code id: tags:

``` python
def partition_dataset(df, feature_columns, sensitive_column,
                      scale, is_valid):
    """
    :param               df: The dataframe to be partitioned.
    :param  feature_columns: A list of column names along which to partition the dataset.
    :param sensitive_column: The name of the sensitive column (to be passed on to the `is_valid` function)
    :param            scale: The column spans as generated before.
    :param         is_valid: A function that takes a dataframe and a partition and returns True if the partition is valid.
    :returns               : A list of valid partitions that cover the entire dataframe.
    """
    finished_partitions = []
    partitions = [df.index]
    while partitions:
        partition = partitions.pop(0)
        spans = get_spans(df[feature_columns], partition, scale)
        for column, span in sorted(spans.items(), key=lambda x:-x[1]):
            #we try to split this partition along a given column
            lp, rp = split(df, partition, column)
            if not is_valid(df, lp, sensitive_column) or not is_valid(df, rp, sensitive_column):
                continue
            # the split is valid, we put the new partitions on the list and continue
            partitions.extend((lp, rp))
            break
        else:
            # no split was possible, we add the partition to the finished partitions
            finished_partitions.append(partition)
    return finished_partitions
```

%% Cell type:code id: tags:

``` python
feature_columns = ['age', 'education-num']
sensitive_column = 'income'
finished_partitions = partition_dataset(df, feature_columns,
                                        sensitive_column,
                                        get_spans(df, df.index),
                                        is_k_anonymous)
```

%% Cell type:code id: tags:

``` python
len(finished_partitions)
```

%% Cell type:code id: tags:

``` python
from utils import build_indexes, get_partition_rects, plot_rects, is_categorical
```

%% Cell type:code id: tags:

``` python
indexes = build_indexes(df)
column_x, column_y = feature_columns[:2] # age,
rects = get_partition_rects(df, finished_partitions,
                            column_x, column_y, indexes,
                            offsets=[0.0, 0.0])
```

%% Cell type:code id: tags:

``` python
rects[:10]
```

%% Cell type:code id: tags:

``` python
pl.figure(figsize=(20,20))
ax = pl.subplot(111)
plot_rects(df, ax, rects, indexes,
           column_x, column_y, facecolor='r')
# we can also plot the datapoints themselves
pl.scatter(df[column_x], df[column_y])
```

%% Cell type:markdown id: tags:

### Your Turn: Building a K Anonymous Dataset

First, we need to figure out a way to combine columns. How can we define the new values?

%% Cell type:code id: tags:

``` python
def aggregate_column(series):
    if is_categorical(series):
        return [','.join(set(series))]
    return [series.mean()]
    pass
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/k-anonymity/agg_column.py
```

%% Cell type:code id: tags:

``` python
def build_anonymized_dataset(df, partitions,
                             feature_columns,
                             sensitive_column,
                             max_partitions=None):
    rows = []
    aggregations = {col: aggregate_column for col in feature_columns}
    for i, partition in enumerate(partitions):
        if i % 100 == 1:
            print("Finished {} partitions...".format(i))
        if max_partitions is not None and i > max_partitions:
            break
        grouped_columns = df.loc[partition].agg(
            aggregations)
        sensitive_counts = df.loc[partition].groupby(
            sensitive_column).agg({sensitive_column : 'count'})
        values = grouped_columns.iloc[0].to_dict()
        for sensitive_value, count in sensitive_counts[sensitive_column].items():
            if count == 0:
                continue
            values.update({
                sensitive_column : sensitive_value,
                'count' : count,
            })
            rows.append(values.copy())
    return pd.DataFrame(rows)
```

%% Cell type:code id: tags:

``` python
dfn = build_anonymized_dataset(df, finished_partitions,
                               feature_columns, sensitive_column)
```

%% Cell type:code id: tags:

``` python
# we sort the resulting dataframe using the feature columns and the sensitive attribute
dfn.sort_values(feature_columns+[sensitive_column])
```

%% Cell type:markdown id: tags:

### Hmmm... Why do some rows only have a count of 1???

%% Cell type:code id: tags:

``` python
dfn.sort_values(['age', 'education-num'])
```

%% Cell type:markdown id: tags:

### Building on K-Anonymity

- l-diversity: Does the group contain more than `l` variations of the sensitive variable?
- t-closeness: Does the group distribution represent the overall distribution of the sensitive variable?

%% Cell type:code id: tags:

``` python
```
+10 −7
Changes for notebooks/03 - Introduction to Differential Privacy with Randomized Response.ipynb: 10 added lines, 7 removed lines.
Original line number Diff line number Diff line
%% Cell type:markdown id: tags:

### Introduction to Differential Privacy with Randomized Response

In this notebook, we'll take a *very simple* view of differential privacy to try and implement a basic boolean (yes, no) randomized response. We will then investigate the measurement of epsilon for our response and evaluate the aggregate statistics of our implementation on several distributions.

For further investigation into differential privacy guarantees and implmentations, please see the in-depth notebook included in this repository.

%% Cell type:markdown id: tags:

## Defining Differential Privacy

[Differential privacy](https://www.microsoft.com/en-us/research/publication/differential-privacy/) is a popular mechanism to quantitatively assess the privacy loss of a given probabilistic query schema or data transformation method. The fundamental equation of differntial privacy is given as

$$
\begin{equation}
    \mathrm{Pr}[\mathcal{K}(D_1) \in S] \le exp(\epsilon) \times \mathrm{Pr}[\mathcal{K}(D_2) \in S] \label{eq:dp}
\end{equation}
$$

Here, $\mathrm{Pr}[\mathcal{K}(D_1) \in S]$ is the probability of a
randomized function $\mathcal{K}$ to yield one of values in the $S$ when evaluating
it on a given dataset $D_1$. The right side is identical to the left except
that the function is now evaluated on a dataset $D_2$ that differs from $D_1$
in at most one element. And finally, $\epsilon$ is a parameter that describes
how much information is leaked (or generated) by the function.

But how might this work in practice? We can think of one simple implementation, which is randomized response. With randomized response we are able to return the true value with some probability. We can think of this like a coin-flip. Let's say we want to ask something where only one response might be seen as sensitive, such as: Have you ever stolen something?

We might say to the respondents, flip a coin. If the flip turns up heads, say yes no matter what. Otherwise, say the true answer. This gives each individual respondent some guarantee of individual privacy (and plausable deniability).

%% Cell type:code id: tags:

``` python
from random import random, choice
from matplotlib import pylab as pl

def simple_randomized_response(prob, value):
    """With probability `prob` return the true value,
       val -- otherwise return 1.
    """
    if random() <= prob:
        return value
    return 1
```

%% Cell type:code id: tags:

``` python
simulated, real = [], []

while len(simulated) < 1000:
    real_val = choice([0,1, 0, 0])
    real_val = choice([0, 1, 0, 0])
    real.append(real_val)
    simulated.append(simple_randomized_response(.5, real_val))
```

%% Cell type:markdown id: tags:

## Your Turn: How many from our simulated runs answered truthfully?

%% Cell type:code id: tags:

``` python
```

%% Cell type:code id: tags:

``` python
import pandas as pd
pd.DataFrame({'real': real, 'simulated': simulated}).hist()
# %load ../solutions/differential-privacy/view_runs.py

```

%% Cell type:markdown id: tags:

### How might we estimate the true distribution when given only the randomized response?

%% Cell type:code id: tags:

``` python
prob = .5

estimate = []
for sim in simulated:
    if sim == 1 and random() <= prob:
        estimate.append(0)
    else:
        estimate.append(1)
    pass
```

%% Cell type:code id: tags:

``` python
# %load ../solutions/differential-privacy/estimate-val.py
```

%% Cell type:code id: tags:

``` python
import pandas as pd
pd.DataFrame({'real': real, 'simulated': simulated,
              'estimated': estimate}).hist()
```

%% Cell type:markdown id: tags:

### Your Turn: How would this change if we had a different real distribution?

- Can you run an experiment by modifying the outcome above?
- How might your estimate change if you have knowledge of the population distribution?

%% Cell type:markdown id: tags:

#### Calculating $\epsilon$

In our differentially private scheme, the probability of adding the true attribute value to the database is $1-p$. The probability of adding a random value is therefore $p$ and the probability of that value being $0$ is $k$. So how can we relate this to our initial definition of differential privacy? Well, we can set $D_1$ and $D_2$ as the versions of our database **before** and **after** adding the person's data to it. Let's say that before adding the person's data there are $n$ $1$'s in the database. We can then use a query $\mathcal{K}$ that returns the number of 1's in the database and choose our result set as $S = \{n\}$. Before adding the person to the database, $\mathcal{K}(D_1)=n$ with certainty, hence $\mathrm{Pr}(\mathcal{K}(D_1))=1$. After adding the person's data, the probability that the query result is still $n$ can be calculated as follows, depending on the person's attribute value:

* If a persons's attribute value is $0$, the probability that $\mathcal{K}$ is unchanged after adding the data to the database is given as $1-p+p\cdot k$.
* If a person's attribute value is $1$, the probability that $\mathcal{K}$ is unchanged after adding the data to the database is given as $p\cdot k$.

We therefore have the two equations

$$
\begin{eqnarray}
\mathrm{Pr}[\mathcal{K}(D_1) \in S | x_i=1] & = & 1 \le \exp{\epsilon}\cdot \mathrm{Pr}[\mathcal{K}(D_2) \in S | x_i=1] = \exp{\epsilon}\cdot p \cdot k \\
\mathrm{Pr}[\mathcal{K}(D_1) \in S | x_i=0] & = & 1 \le \exp{\epsilon}\cdot \mathrm{Pr}[\mathcal{K}(D_2) \in S | x_i=0] = \exp{\epsilon}\cdot (1-p+p \cdot k) \\
\end{eqnarray}
$$

This yields

$$
\begin{eqnarray}
 \epsilon & \ge & -\ln{\left(p \cdot k\right)} \\
 \epsilon & \ge & -\ln{\left(1-p+p\cdot k\right)} \\
\end{eqnarray}
$$

Since we're interested in an upper bound for $\epsilon$ and since $-\ln{\left(1-p+p\cdot k\right)} \le -\ln{p\cdot k}$, we obtain

$$
\begin{equation}
\epsilon = -\ln{\left(p\cdot k\right)}
\end{equation}
$$

%% Cell type:code id: tags:

``` python
# %load "../solutions/differential-privacy/epsilon.py"
```

%% Cell type:code id: tags:

``` python
# so in our case...

epsilon(.5, 1)
```

%% Cell type:code id: tags:

``` python
np.exp(epsilon(.5, 1))
```

%% Cell type:markdown id: tags:

### Protecting both responses

- What about if either response was sensitive, and we needed to protect both yes and no?
- How about if our response was not a simple yes or no; but instead multidimensional data?
- What if we want to query a person over a longer period of time?

%% Cell type:code id: tags:

``` python
```
+1 −1

File changed.

Contains only whitespace changes.

+1 −1
Changes for solutions/case-study/possible-solution.py: 1 added line, 1 removed line.
Original line number Diff line number Diff line
@@ -59,7 +59,7 @@ pseudonymized_data = requests.post(
        {"actions": actions, "items": item_list}, 
        allow_nan=False),
    headers = {'Authorization': 'Bearer {}'.format(
        SHARED_KEY)}
        SHARED_KEY), 'Content-Type': 'application/json'}
)


Loading