Lesson 03 · 40 minutes
Measure evasion and a privacy leak on your own model
- Describe the evasion, poisoning and privacy families of attack in plain words
- Measure how much a small change to the input lowers the accuracy of your model
- Measure the confidence gap that can reveal training examples
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
A vendor offers your bank a classifier that reads handwritten amounts on cheques, and its slide says "96 percent accuracy". Your lead asks you for two answers before the contract. What does the model do when someone changes an image a little on purpose? What can a stranger learn about the people in its training data by asking it questions? Accuracy on honest data answers neither question, so you build a small test for each on a model of your own.
Recall
Lesson 2: at which stage of the lifecycle does an attacker act who changes a picture at the moment a user sends it?
At the operate stage. The model is already in service, and the attacker needs only the right to send inputs.
Lesson 2: why did the per-class recall find an attack that the accuracy missed?
Accuracy averages over all classes, so a loss in one class is small. Recall for each class shows the loss in that class. Use the same habit here: look beyond one number.
The idea
NIST AI 100-2 is a report of the US National Institute of Standards and Technology, "Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations" (2025 edition). It gives the field one set of names. For predictive AI, the kind of model that you train in scikit-learn, it sorts attacks into three families. It also covers generative AI. It sorts attacks by what the attacker wants and by what the attacker knows: either the inside of the model, or only its answers.
| Family | When it acts | What the attacker does | Plain example |
|---|---|---|---|
| Evasion | Operate | Changes an input so that the model gets it wrong | A small change to a picture that flips the label |
| Poisoning | Collect, train | Changes the training data or the model | Flipped labels (lesson 2) |
| Privacy | Operate | Asks questions to learn about the training data or the model | Finding out that a person was in the training set |
Evasion changes the input, not the model. An adversarial example is an input that has been changed in a way that is small to a human and large to the model. A membership inference attack asks: was this record in the training data? If the model is more confident on examples that it saw during training, an attacker can use that gap as a clue.
Evasion and privacy attacks work through the same door: the questions that you send to the model and the answers that it gives. This is what an attacker at a model service sees and sends.
- Attacker → Application: an image with a small, chosen change
- Application → Model: the image
- Model → Application: a label and a confidence score
- Application → Attacker: the label and the score
Both tests in this lesson run on a model that you own, with full knowledge of its insides. That is the strongest attacker. Use it as the worst case when you assess a model.
Worked example
1. Train the model and set a baseline
Use the environment of the course "How AI works".
mkdir -p ~/krlab/ai-security-fundamentals/digits
cd ~/krlab/ai-security-fundamentals/digits
source ~/krlab/how-ai-works/.venv/bin/activateCreate evade.py. The pixel values of a digit run from 0 to 16. np.clip(images, 0, 16) cuts every value into that range, so the function accuracy never scores an impossible picture.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
model = LogisticRegression(max_iter=2000).fit(X_train, y_train)
print("clean test accuracy:", round(model.score(X_test, y_test), 4))
def accuracy(images):
"""Accuracy on changed images. Pixels stay in the range 0 to 16."""
return round(model.score(np.clip(images, 0, 16), y_test), 4)2. Compare random noise with a chosen-direction change
Random noise is the control. It changes each pixel by the same size, in a random direction. The chosen-direction change moves every pixel in the direction that makes the model more wrong. It is untargeted: it only makes the model wrong, not wrong in one chosen way. These terms are new.
- The loss is one number that says how wrong the model is on an image.
- The slope says how the loss changes when one pixel changes: a pixel with a positive slope makes the model more wrong when it gets brighter. The formula below is given, not derived: the probabilities minus the true row, multiplied by the weights.
model.predict_probagives the probability of each digit for each image.model.coef_holds the weights of the model.np.eye(10)[y_test]turns each true label into a row with a 1 at the right digit.rng.choice([-1, 1], size=X_test.shape)picks -1 or +1 at random for every pixel of every test image.@multiplies two tables of numbers (a matrix product).np.signkeeps only the direction of each slope: -1 or +1.
Add this and run the file.
# For each pixel, the slope of the loss: which way makes the model more wrong?
slope = (model.predict_proba(X_test) - np.eye(10)[y_test]) @ model.coef_
rng = np.random.default_rng(0)
print("\nsize random-noise chosen-direction")
for size in (0.5, 1, 2, 3):
noisy = X_test + size * rng.choice([-1, 1], size=X_test.shape)
chosen = X_test + size * np.sign(slope)
print(f"{size:<5} {accuracy(noisy):<13} {accuracy(chosen)}")python evade.pyclean test accuracy: 0.9622
size random-noise chosen-direction
0.5 0.9644 0.8667
1 0.9511 0.6733
2 0.9311 0.1867
3 0.8822 0.0111A size of 1 moves each pixel by one step of 16, about 6 percent of the range. Random noise of that size costs one point of accuracy. The chosen-direction change of the same size costs 29 points. At size 3 the model is wrong on about 99 images in 100, and that change is 3 steps of 16 on every pixel, about 19 percent of the range. That is a large change, so do not call it invisible. The size of the change is the same, and the direction is what hurts.
3. Measure the confidence gap
Create leak.py. confidence is the probability that the model gives to its top answer: .max(axis=1) takes the largest value in each row, and a row holds the probabilities of one picture. The script takes 450 training examples (members) and the 450 test examples (non-members), and guesses "member" when the confidence is above the mean of the non-members. It does this for two models: the logistic regression and a random forest, which is many decision trees that vote.
digits/leak.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
def confidence(model, X):
"""How sure the model is of its top answer, from 0 to 1."""
return model.predict_proba(X).max(axis=1)
rng = np.random.default_rng(0)
members = rng.choice(len(X_train), len(X_test), replace=False) # as many members as non-members
models = {
"logistic regression": LogisticRegression(max_iter=2000),
"random forest": RandomForestClassifier(random_state=0),
}
for name, model in models.items():
model.fit(X_train, y_train)
c_in = confidence(model, X_train[members])
c_out = confidence(model, X_test)
# The guess: "member" when the confidence is above the average of the non-members.
t = c_out.mean()
right = ((c_in > t).sum() + (c_out <= t).sum()) / (len(c_in) + len(c_out))
print(name)
print(" mean confidence members", round(c_in.mean(), 3), " non-members", round(c_out.mean(), 3))
print(" membership guess right:", round(right, 3), "(0.5 is a coin flip)")python leak.pylogistic regression
mean confidence members 0.997 non-members 0.977
membership guess right: 0.536 (0.5 is a coin flip)
random forest
mean confidence members 0.917 non-members 0.763
membership guess right: 0.69 (0.5 is a coin flip)For the logistic regression the gap is two points, and the guess is almost a coin flip. For the random forest the gap is 15 points, and the guess is right 69 times in 100. The rule uses the average confidence of known non-members, which a real attacker must estimate, so 0.69 is an estimate and not a limit. Even so, an attacker who sees only the confidence scores learns something real about who was in the training set. Digits are not personal data, but a model of medical notes or of customer records would have the same weakness.
4. Read the two results together
Evasion needs the attacker to send inputs to the model. The privacy test needs the attacker to see the confidence scores. Both are attacks in the operate stage, and both give you a control that costs little: return only the label, not the confidence; limit the number of queries for each user; and log the queries.
5. The finished file
This is the whole evade.py as it stands after the steps above (the start of step 1 and the part of step 2). The lab files of the course hold it.
The finished file: evade.py
digits/evade.py
import numpy as np
from sklearn.datasets import load_digits
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42, stratify=y
)
model = LogisticRegression(max_iter=2000).fit(X_train, y_train)
print("clean test accuracy:", round(model.score(X_test, y_test), 4))
def accuracy(images):
"""Accuracy on changed images. Pixels stay in the range 0 to 16."""
return round(model.score(np.clip(images, 0, 16), y_test), 4)
# For each pixel, the slope of the loss: which way makes the model more wrong?
slope = (model.predict_proba(X_test) - np.eye(10)[y_test]) @ model.coef_
rng = np.random.default_rng(0)
print("\nsize random-noise chosen-direction")
for size in (0.5, 1, 2, 3):
noisy = X_test + size * rng.choice([-1, 1], size=X_test.shape)
chosen = X_test + size * np.sign(slope)
print(f"{size:<5} {accuracy(noisy):<13} {accuracy(chosen)}")Your turn
The vendor trained its model on a different split of the data. Test your own version of its claim. Use the same data and the same logistic regression as in evade.py, but split with random_state=7. Measure the clean accuracy, and the accuracy under the chosen-direction change at size 1 and at size 1.5 (no random noise this time). Then run the membership test of leak.py on a random forest with only 10 trees (n_estimators=10, random_state=0), on the same split, with the same choice of members.
Last, write two lines for your lead: one control against the evasion result and one against the leak.
Check yourself
Random noise of size 1 cost one point and the chosen-direction change cost 29 points. What does that tell you about testing a model with random noise?
Random noise is a weak test. A model can look robust to it and still fail against a change that is chosen with knowledge of the model. Test with such changes, at least in the worst case where the attacker knows the model.
A membership guess is right 69 times in 100. Why is this not proof that the model leaks private data?
It is a clue, not a proof. The test uses one simple rule, and the model and the data are small. It does show the direction of the weakness. The rule borrows the average of known non-members, which a real attacker must estimate, so treat the number as an estimate.
Which of the three NIST families does a flipped label belong to, and which does a changed input belong to?
A flipped label is poisoning, because it changes the training data. A changed input at query time is evasion.
Why does a model that fits its training data too closely leak more?
It remembers its training examples, so it is much more confident on them than on new data. That gap is the signal that a membership attack reads. Lesson 7 of "How AI works" shows the same gap as overfitting.
Field notes
- White-box means that the attacker knows the model's parameters. Black-box means that the attacker sees only answers. Evasion examples often transfer from one model to another, so a black-box attacker can build them on a copy. Do not count on secrecy of the model as a defence.
- Defences have costs. Adversarial training (training on changed examples) improves robustness and often lowers clean accuracy. Input checks and ensembles help against weak attacks and fail against strong ones. Report robustness together with the attacker model you tested, never as a single number.
- Defences for privacy attacks include regularisation, early stopping, more data, rounding or hiding confidence scores, and differential privacy, which limits what any one record can change. The last gives a proven bound at a cost in accuracy.
- A model can also be copied: an attacker who may ask many questions can train a clone. Rate limits and monitoring of unusual query patterns apply here too.
- For generative AI, the 2025 edition of NIST AI 100-2 also covers prompt injection. Lesson 5 and the courses on LLM applications test it. In November 2026 NIST published a draft, SP 2400-102, on attacks on agentic systems (comments until 18 December 2026). The final edition of AI 100-2 is still the 2025 one. In a report, name the document and its state: final, or draft.