Lesson 05 · 40 minutes
Measure privacy leaks with membership inference and inversion
- Run a membership attack with a shadow model and read its accuracy against a coin flip
- Show how the leak grows with the size of the trees, and why the accuracy gap alone does not measure it
- Rebuild what a class looks like from the scores of a linear model
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
Imagine that the digit images are scans of customers' handwriting, kept for a signature service. The data protection officer of Northgate Parcels asks two questions. Can a stranger who only uses the service tell whether a given sample was in the training data? Can a stranger rebuild what a class looks like from the answers? You attack your own models to find out, and you measure how much the answer depends on the kind of model.
Recall
Lesson 4: what did the black-box attacker see, and what did it need?
The probabilities that the service returned, and enough queries. The same two things matter in this lesson: what the service returns, and how often it may be asked.
Lesson 2: why is one average number a poor way to see harm?
An average hides a loss in one part. This lesson has the same problem: an accuracy gap does not tell how much a model leaks. You measure the leak directly.
The idea
Membership inference asks: was this record used to train the model? A model is usually more confident on records that it has seen. The attacker turns that gap into a guess: a confidence above a threshold means "member". "AI security fundamentals" (lesson 3) measured the gap with a threshold taken from the non-members. A real attacker does not have the labels of members, so this lesson uses a shadow model: the attacker trains a model of the same kind on data of their own, learns the best threshold there, and then applies it to the target. The result is the share of right guesses. 0.50 is a coin flip, and 1.00 is a full leak.
Model inversion goes the other way. The attacker starts with a blank image and keeps every small change that raises the model's score for one class. The result shows what the model has learned about that class. The training images are never seen, only the scores.
- Attacker → Shadow model: train on images of their own
- Shadow model → Attacker: confidence on members and others
- Attacker: choose the best threshold
- Attacker → Target model: one record to test
- Target model → Attacker: above the threshold means member
Worked example
1. Write the attacks
New words in the code:
groupscuts the data into four separate groups of 300: the target's members and non-members, and the attacker's own shadow members and shadow non-members.confidenceis the probability of the model's top answer..max(axis=1)takes the largest value of each row, andnp.uniquelists each different value once.np.corrcoef(a, b)gives the correlation of two lists: 1 means that they move together.looks_likefinds the digit whose average training image correlates most with an image.RandomForestClassifieris many decision trees that vote ("AI security fundamentals", lesson 3), andmax_depthlimits how deep each tree may grow.lambda: ...is a small function without a name and without arguments. Inattack_accuracy(lambda: RandomForestClassifier(...))it means "build a new model each time you are called", so the attacker and the target get two separate models.logisticfromcommon.pyis already such a function, so it needs nolambda.
leak.py
"""leak.py: a membership attack with a shadow model, and the inversion of a linear model."""
import numpy as np
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from common import digits, logistic, record, train
def groups(n=300):
"""Four disjoint groups of n digit images: the target's members and non-members, and the attacker's own
shadow members and shadow non-members."""
X, y = load_digits(return_X_y=True)
order = np.random.default_rng(0).permutation(len(X))
return [(X[order[i * n:(i + 1) * n]], y[order[i * n:(i + 1) * n]]) for i in range(4)]
def confidence(model, X):
"""How sure the model is of its top answer."""
return model.predict_proba(X).max(axis=1)
def best_threshold(c_in, c_out):
"""The confidence level that best separates members from non-members, found on the attacker's own data."""
levels = np.unique(np.concatenate([c_in, c_out]))
hits = [((c_in > t).sum() + (c_out <= t).sum()) for t in levels]
return levels[int(np.argmax(hits))]
def attack_accuracy(make, score=confidence):
"""Train a target and a shadow model in the same way. Learn the threshold on the shadow model and apply it to
the target. Return (target train accuracy, target test accuracy, share of guesses that are right)."""
t_in, t_out, s_in, s_out = groups()
target, shadow = make().fit(*t_in), make().fit(*s_in)
level = best_threshold(score(shadow, s_in[0]), score(shadow, s_out[0]))
c_in, c_out = score(target, t_in[0]), score(target, t_out[0])
guessed = ((c_in > level).sum() + (c_out <= level).sum()) / (len(c_in) + len(c_out))
return target.score(*t_in), target.score(*t_out), guessed
def mean_confidence(make):
"""The mean confidence of a target model on its own members, and on non-members."""
t_in, t_out = groups()[:2]
target = make().fit(*t_in)
return confidence(target, t_in[0]).mean(), confidence(target, t_out[0]).mean()
def invert(model, digit, queries=500, step=4, seed=0):
"""Model inversion with scores only: start from a blank image and keep each change of one pixel that raises
the model's probability for `digit`."""
rng = np.random.default_rng(seed)
x = np.zeros(64)
best = model.predict_proba(x[None])[0][digit]
for _ in range(queries):
cand = x.copy()
cand[rng.integers(0, 64)] += rng.choice([-step, step])
cand = np.clip(cand, 0, 16)
p = model.predict_proba(cand[None])[0][digit]
if p > best:
x, best = cand, p
return x
def looks_like(x, means):
"""The digit whose average training image correlates most with x (-1 when x is blank)."""
if x.std() == 0:
return -1
return int(np.argmax([np.corrcoef(x, m)[0, 1] for m in means]))
def show(x):
"""Print an 8 by 8 image, dark to bright as ' .:-=+*#%@'."""
for line in x.reshape(8, 8):
print(" " + "".join(" .:-=+*#%@"[min(int(v / 16 * 10), 9)] * 2 for v in line))
if __name__ == "__main__":
print("1. membership attack: the leak grows with the depth of the trees")
print("model train acc test acc attack right")
for depth in (2, 4, 6, 8, None):
tr, te, guess = attack_accuracy(lambda: RandomForestClassifier(max_depth=depth, random_state=0))
print(f"forest depth {str(depth):<5}{tr:>7.2f}{te:>10.2f}{guess:>14.2f}")
if depth is None:
record("leak.forest_attack", round(guess, 2))
tr, te, guess = attack_accuracy(logistic)
print(f"logistic {tr:>7.2f}{te:>10.2f}{guess:>14.2f}")
for name, make in (("forest, any depth", lambda: RandomForestClassifier(random_state=0)),
("logistic", logistic)):
c_in, c_out = mean_confidence(make)
print(f"mean confidence, {name}: members {c_in:.2f}, non-members {c_out:.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: 500 queries for each digit, scores only")
found = [looks_like(invert(model, d), means) for d in range(10)]
print("the image built for each digit looks most like:", found)
print("recognised:", sum(f == d for d, f in enumerate(found)), "of 10")
x3 = invert(model, 3)
corr = [np.corrcoef(x3, m)[0, 1] for m in means]
print(f"the image built for digit 3 correlates {corr[3]:.2f} with the average 3, and at most {max(corr[:3] + corr[4:]):.2f} with any other digit:")
show(x3)
shuffled = train(X_train, np.random.default_rng(0).permutation(y_train)) # a model that learned nothing true
print("a model trained on shuffled labels:", sum(looks_like(invert(shuffled, d), means) == d for d in range(10)), "of 10 recognised")
record("leak.inversion_recognised", sum(f == d for d, f in enumerate(found)))2. Run it
The run takes less than a minute.
python3 leak.py1. membership attack: the leak grows with the depth of the trees
model train acc test acc attack right
forest depth 2 0.90 0.83 0.56
forest depth 4 0.98 0.91 0.59
forest depth 6 1.00 0.91 0.67
forest depth 8 1.00 0.92 0.74
forest depth None 1.00 0.93 0.78
logistic 1.00 0.93 0.59
mean confidence, forest, any depth: members 0.86, non-members 0.63
mean confidence, logistic: members 1.00, non-members 0.96
2. inversion: 500 queries for each digit, scores only
the image built for each digit looks most like: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
recognised: 10 of 10
the image built for digit 3 correlates 0.27 with the average 3, and at most 0.12 with any other digit:
@@ @@++@@::@@
:: @@####++
:: ::##
:: ++ @@
## ::
@@ @@@@##
++ ::@@@@
@@::++## ++
a model trained on shuffled labels: 1 of 10 recognised3. Read the membership table
Look at the forests. Trees of depth 2 give an attack that is right 56 times in 100. Unlimited depth gives 78: the model has learned its training images by heart, so that it is much more confident on them. The leak grows with the size of the trees, and so does the gap between the training accuracy (1.00) and the test accuracy (0.93).
Now compare the last two rows. The logistic regression has the same accuracies as the unlimited forest (1.00 and 0.93) and a leak of only 0.59. The accuracy gap is a hint, not a measure. What counts is how the confidence differs between members and non-members, and the two lines under the table give it. The forest has a mean confidence of 0.86 on members and 0.63 on non-members: a gap of 0.23. The logistic regression is very sure of both (1.00 and 0.96): a gap of only 0.04, so no threshold separates them well. Measure the attack. Do not infer it from the gap.
4. Read the inversion
The attacker asked 500 questions for each digit and kept the changes that raised the score. For all 10 digits, the image that came out correlates most with the average image of the right digit. A model that learned nothing true (trained on shuffled labels) gives 1 right digit in 10, which is chance, so 10 of 10 is a real signal. The printed picture of digit 3 correlates 0.27 with the average 3 and at most 0.12 with any other digit. It does not look like a clean 3 to a person: it is a set of scattered bright pixels that the model scores as a 3 with a probability near 1. Yet the statistics are right. A linear model has one weight image for each class, and the scores lead the attacker to it. With a model trained on faces, the same method gives a blurred average of the faces of one person. The attacker needs only scores and queries, so the defence is again in the output (lesson 6) and in the query limit (lesson 7).
Your turn
Measure two more models with attack_accuracy: a random forest with min_samples_leaf=2 and random_state=0, and a logistic regression made with logistic(0.01) (a small C means strong regularisation: the weights are kept small). Then run the inversion with queries=100 instead of 500 for all 10 digits on the course model, and count the digits that looks_like recognises.
Then write one sentence on which of your two new models you would deploy for private data, and why.
Check yourself
The attack is right 0.56 of the time on the shallow forest. Is that "no leak"?
It is near a coin flip, so the attack as written gets little. It is not proof of no leak. A stronger attack, more shadow data or a test on the most unusual records can do better. The number is a floor for what an attacker can do.
Why does the attacker train a shadow model?
The attacker needs a threshold, and for that they need confidences of known members and non-members. They have neither for the target, but they can train a model of the same kind on their own data and learn the threshold there.
Which condition made the forest leak, and which would reduce it?
The trees fitted the training data so closely that members got a far higher confidence than other images. A smaller tree (lower max_depth, a larger min_samples_leaf), more data, or an output that hides the confidence reduces it. Lesson 6 measures a larger min_samples_leaf, noisy training and a hidden output, each with its cost.
What does inversion need from the service?
A score that changes when the input changes, and many queries. A service that returns only a label gives much less to climb on, and a limit on queries stops the climb. Lesson 6 tests the first and lesson 7 the second.
Field notes
- The OWASP Machine Learning Security Top Ten lists these as ML04 Membership Inference Attack and ML03 Model Inversion Attack. NIST AI 100-2 puts them in the privacy family of attacks.
- Accuracy of a membership attack over all records is a weak report. A leak that finds a few records with great certainty can matter more than a small gain on all of them. Report also the guesses that the attack makes with the highest confidence.
- The risk rises with overfitting, with small training sets, with rare records (outliers are remembered) and with sensitive data such as health, money or text with names. Rank your models by that risk before you test all of them.
- Data that leaks from the context of a language model is the subject of "Securing LLM applications" (lesson 4). This site does not teach leaks of memorised training text.