Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 06 · 45 minutes

Add privacy defences and price them

After this lesson you can
  • Apply four defences against the membership attack and read the price of each in accuracy
  • Release a count with a stated epsilon, and clip what one person can add
  • Say plainly which of your defences give a guarantee and which only give a measured gain
Lab files of this lesson (9)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

The data protection officer has read your numbers from lesson 5: the forest leaks, and the answer in the review is "we need privacy". Your lead wants a table that a manager can read. For each defence: what it does to the leak, what it costs in accuracy, and whether anyone can promise anything about it. You build that table, and you add a count query with a real privacy parameter.

Recall

Lesson 5: which model leaked most, and what made it leak?

The random forest with unlimited depth, with a membership attack right 78 times in 100. Its trees fitted the 300 training images so closely that members got a much higher confidence than other images.

Lesson 5: what did the inversion need from the service?

Scores that change when the input changes, and many queries. The defences below act on the first, and lesson 7 on the second.

The idea

There are four places to act. You can make the model memorise less (regularisation), show less (hide the scores), blur the data that it learns from (noise on training), and blur the answers that you publish about the data (a noisy count). Each place has a price, and only the last one can have a proof.

Differential privacy is a promise about a result. A result has epsilon privacy when adding or removing any one person changes the chance of every possible result by a factor of at most e to the power epsilon (about 1 plus epsilon, for a small epsilon). A small epsilon means a strong promise. The Laplace mechanism keeps that promise for a count: add noise from the Laplace distribution with scale 1 divided by epsilon. One person changes a count by at most 1, which is called the sensitivity. If a person can add many records, clip them first: count at most cap for each person, and the sensitivity is cap.

Where the four defences act
LearningAnsweringDataTrainingModelPublished countService1234LearningAnsweringDataTrainingModelPublished countService1234
  1. Data → Training: noise on training blurs the data
  2. Training → Model: regularising: memorises less
  3. Model → Service: show less: labels, not scores
  4. Data → Published count: a noisy count has a proof

Worked example

1. Write the defences

New words in the code: class Name: defines a new kind of object. __init__ runs when you make one, and self is the object itself, so self.sigma = sigma keeps a setting inside it, and a, b = x, y sets two names in one line. NoisyTraining(model, 3) makes one. A class that has fit, predict_proba and score can stand in for a scikit-learn model. LabelsOnly is such a class: it makes the service show the label and nothing else, probability 1 for the label and 0 for all others. NoisyTraining adds random noise to every training image before the model learns from it, so the model never sees the exact images. forest(**settings) collects the named options that you give it, such as min_samples_leaf=5, and passes them on to RandomForestClassifier. min_samples_leaf=5 forbids a tree leaf with fewer than 5 images, so a tree cannot remember a single image. np.eye(10)[labels] makes, for each label, a row with a 1 at that label and 0 elsewhere. np.round(p, 1) rounds to one decimal. In clipped_count, np.unique(..., return_counts=True) counts the records of each user and np.minimum(counts, cap) cuts each count at cap. rng.laplace(0, scale) draws noise from the Laplace distribution. The label-only attack guesses "member" when the label is right: members are right more often.

privacy.py

"""privacy.py: four defences against the membership attack, with their price, and a count with a stated epsilon."""
import numpy as np
from sklearn.ensemble import RandomForestClassifier

from common import digits, record, train
from leak import attack_accuracy, confidence, groups, invert, looks_like


class NoisyTraining:
    """Wrap a model so that it trains on noisy copies of the images, never on the exact ones."""

    def __init__(self, model, sigma, seed=0):
        self.model, self.sigma, self.rng = model, sigma, np.random.default_rng(seed)

    def fit(self, X, y):
        self.model.fit(np.clip(X + self.rng.normal(0, self.sigma, X.shape), 0, 16), y)
        return self

    def predict_proba(self, X):
        return self.model.predict_proba(X)

    def score(self, X, y):
        return self.model.score(X, y)


class LabelsOnly:
    """Wrap a model so that the service shows the label only: probability 1 for the label, 0 for the rest."""

    def __init__(self, model):
        self.model = model

    def predict_proba(self, X):
        return np.eye(10)[self.model.predict(X)]


def forest(**settings):
    return lambda: RandomForestClassifier(random_state=0, **settings)


def label_only_attack():
    """The attacker sees labels only and guesses 'member' when the label is right. Return (test accuracy, right)."""
    t_in, t_out = groups()[:2]
    target = forest()().fit(*t_in)
    right_in, right_out = target.predict(t_in[0]) == t_in[1], target.predict(t_out[0]) == t_out[1]
    return target.score(*t_out), (right_in.sum() + (~right_out).sum()) / (len(right_in) + len(right_out))


def laplace_count(true_count, epsilon, rng):
    """A count released with epsilon-differential privacy. It needs a count in which each person adds at most 1,
    so the noise has scale 1 / epsilon (the Laplace distribution)."""
    return true_count + rng.laplace(0, 1 / epsilon)


def clipped_count(user_ids, wanted, cap=1):
    """Count the records that are `wanted`, but let each user add at most `cap`. Then one user changes the
    count by at most `cap`, however many records that user has."""
    users, counts = np.unique(user_ids[wanted], return_counts=True)
    return int(np.minimum(counts, cap).sum())


if __name__ == "__main__":
    print("1. defences against the membership attack (random forest, 300 training images)")
    print("defence                      test acc  attack right")
    rows = [
        ("none", forest(), confidence),
        ("min 5 samples in a leaf", forest(min_samples_leaf=5), confidence),
        ("scores rounded to 0.1", forest(), lambda m, X: np.round(m.predict_proba(X), 1).max(axis=1)),
        ("noisy training, sigma 3", lambda: NoisyTraining(forest()(), 3), confidence),
    ]
    for name, make, score in rows:
        _, test, guess = attack_accuracy(make, score)
        print(f"{name:<29}{test:>6.2f}{guess:>14.2f}")
    test, guess = label_only_attack()
    print(f"{'labels only':<29}{test:>6.2f}{guess:>14.2f}")

    X_train, X_test, y_train, y_test = digits()
    model = train(X_train, y_train)
    means = np.array([X_train[y_train == c].mean(axis=0) for c in range(10)])
    print("2. inversion with 500 queries for each digit: digits recognised out of 10")
    for name, served in (("scores shown", model), ("labels only", LabelsOnly(model))):
        print(f"{name:<14}{sum(looks_like(invert(served, d), means) == d for d in range(10))}")

    X, y = groups()[0]
    users = np.arange(len(y)) // 3          # 100 users with 3 images each
    raw = int((y == 8).sum())
    count = clipped_count(users, y == 8)      # each user counted once: one user changes this count by at most 1
    print("3. a count query: how many of the 300 members have digit 8")
    print("raw count", raw, " users with a digit 8, one record each:", count)
    rng = np.random.default_rng(0)
    print("epsilon  noise scale  chance the error is at most 3")
    for eps in (0.1, 0.5, 1, 5):
        print(f"{eps:<9}{1 / eps:>10.1f}{1 - np.exp(-3 * eps):>22.2f}")
    answers = [laplace_count(count, 0.5, rng) for _ in range(1000)]
    print("1000 answers at epsilon 0.5, average:", round(float(np.mean(answers)), 1), "-> total epsilon spent: 500")
    record("privacy.raw_count_digit8", raw)

2. Run it

python3 privacy.py
1. defences against the membership attack (random forest, 300 training images)
defence                      test acc  attack right
none                           0.93          0.78
min 5 samples in a leaf        0.90          0.62
scores rounded to 0.1          0.93          0.77
noisy training, sigma 3        0.91          0.56
labels only                    0.93          0.54
2. inversion with 500 queries for each digit: digits recognised out of 10
scores shown  10
labels only   0
3. a count query: how many of the 300 members have digit 8
raw count 35  users with a digit 8, one record each: 32
epsilon  noise scale  chance the error is at most 3
0.1            10.0                  0.26
0.5             2.0                  0.78
1               1.0                  0.95
5               0.2                  1.00
1000 answers at epsilon 0.5, average: 32.1 -> total epsilon spent: 500

3. Read the price table

Membership attack, share of right guesses
No defence0.78Min 5 samples in a leaf0.62Scores rounded to 0.10.77Noisy training, sigma 30.56Labels only0.54No defence0.78Min 5 samples in a leaf0.62Scores rounded to 0.10.77Noisy training, sigma 30.56Labels only0.54
DefenceTest accuracyPrice and remark
none0.93the baseline
min 5 samples in a leaf0.903 points of accuracy
scores rounded to 0.10.93free, and nearly useless here
noisy training, sigma 30.912 points of accuracy
labels only0.93free in accuracy, but callers lose the scores

Rounding the scores to one decimal changes nothing, because the forest's gap is wide. Showing the label only is the best defence in this table, against this one simple attacker. It has a limit: the attacker can still check whether the label is right, and attacks that measure how far an image lies from the decision boundary can do better. The guess is right when the model is right on its training images and wrong more often elsewhere, so the gap between train and test accuracy is a floor that no output rule removes. Only less memorising removes it. The second block shows the same for inversion: with scores the attacker recognises 10 of 10 digits, and with labels only 0, since a label gives nothing to climb on.

4. Read the count query

The 300 members hold 35 images of the digit 8, which belong to 32 users when each user may count once. The count that is published is the clipped one, 32: one user changes it by at most 1, and only then does the noise of scale 2 give epsilon 0.5. The raw count of 35 can change by 3 for one user. The table of epsilon follows from the formula. With epsilon 0.5, the noise has scale 2, and a published count is within 3 of the true one with chance 0.78. With epsilon 0.1 the chance falls to 0.26. A small epsilon is a strong promise and a noisy answer.

Chance that a noisy count is within 3
Epsilon 0.10.26Epsilon 0.50.78Epsilon 10.95Epsilon 51.00Epsilon 0.10.26Epsilon 0.50.78Epsilon 10.95Epsilon 51.00

The last line is the cost that people forget. Asking the same question 1,000 times with fresh noise gives 1,000 answers whose average is 32.1, which is nearly the true count. The privacy loss adds up: 1,000 answers at 0.5 spend a total epsilon of 500, and that is no protection. A real system keeps a budget and refuses queries when it is used up.

5. Say what is and is not a guarantee

The noisy count has a proof: epsilon 0.5 for this one result, because its input is the clipped count, where one user changes the answer by at most 1. The four model defences have none. Noise on training lowered the measured attack, but nobody can say what epsilon it gives. A true privacy guarantee for training needs an algorithm that clips the effect of each training example and adds noise inside training, with an accountant that adds up epsilon (DP-SGD is the best known). That is a job for a well-tested library, not for a few lines of your own code. Until then, report your table as "measured against this attack", and never as "private".

Your turn

Use the 300 members of groups()[0], and think of the images as belonging to users in sets of four: user number is index // 4. Count the images of digit 3, and count again with clipped_count(users, y == 3), where each user counts once. Then work out the noise scale of a Laplace count at epsilon 0.25, and the chance that its error is at most 6 (the chance is 1 minus the exponential of minus the error times epsilon).

Last, write two sentences for the data protection officer: which defence you would pick first, and what you would not promise.

Check yourself

The label-only service still leaks 0.54. Where does that come from?

The attacker guesses "member" when the label is right. A model that is right on all its training images and on 93 percent of other images makes this guess right a little more than half of the time. The gap between training and test accuracy is the leak that remains.

Why is "we added noise" not a privacy guarantee?

Noise lowers a measured attack, but a stronger attack may exist, and there is no proof about any record. A guarantee needs a definition (such as epsilon privacy) and a method that provably meets it, with the noise tied to the sensitivity.

Why must a person be clipped before the count is noised?

The noise is scaled to what one person can change. If one person can add 50 records, the count changes by 50, and noise made for a change of 1 hides nothing. Clipping gives every person the same small, known effect.

What is wrong with answering the same noisy query 1,000 times?

The average of the answers approaches the true value, so the noise cancels. The privacy loss of every answer adds up. A system needs a budget for each question and each person.

Field notes

  • NIST SP 800-226, "Guidelines for Evaluating Differential Privacy Guarantees" (final, March 2025), helps you ask the right questions about a claim of differential privacy. Read the current text at NIST. It also advises well-tested library code over your own mechanisms.
  • A claim of epsilon is only meaningful with its unit: epsilon for what (one record, one person), over which queries, and with which delta if the form is approximate. A single large epsilon with no context is a marketing number.
  • Combine controls. A smaller model, fewer details in the answer, a query limit (lesson 7) and a smaller, cleaner dataset together work better than one strong control.
  • Data minimisation is the cheapest privacy defence: the model cannot leak what it never saw. Remove fields that the task does not need before training.