Adversarial testing
Why This Matters
A few stickers on a stop sign, invisible to most drivers, can make an image classifier read “speed limit 45”. A word swapped for a synonym can flip a spam filter. These adversarial examples are not random bugs; they are found on purpose, by people who want the model to fail, and often at almost no cost. If you don’t look for them, someone else will.
What you will learn
- What adversarial examples are, and why ML models are vulnerable to them
- White-box and black-box attacks, surrogate models and transferability
- How to run a black-box attack on the practice loan model, in code
Syllabus: AI-6.1.4.
Adversarial examples
An adversarial example is an input with a small, often imperceptible change that makes the model give a wrong answer. The change looks irrelevant to a person, but it pushes the input across one of the model’s decision boundaries (lesson 21: those boundaries are complicated, and inputs can sit very close to them).
They matter in two ways:
- Malicious: an attacker crafts them on purpose: a fraudster who tweaks a transaction until it passes, a spammer who rewrites a message until it is not flagged.
- Accidental: real-world noise does the same thing by chance: dirt on a camera, an unusual phrasing, a rounding difference.
Adversarial testing looks for these inputs so that safeguards can be added: retraining with adversarial examples (augmentation, lesson 15), input checks, smoothing the decision boundary, or human review near the boundary. It is an arms race: new attack techniques keep appearing, and keeping up is part of the job.
How attacks work
- White-box: the attacker knows the model: architecture, parameters, training data. With the internals, crafting an example is relatively easy: you can calculate in which direction to change the input to change the output fastest.
- Black-box: the attacker can only send inputs and see outputs. Two strategies:
- Brute force: try many random variations and hope one works.
- Surrogate model: query the model many times, train your own model (the surrogate) on its answers, craft adversarial examples on the surrogate (which you can inspect), and try them on the real model. This works because of transferability: models trained for the same task tend to have similar decision boundaries, so an example that fools one often fools the other.
Examples are crafted manually or with automated tools that generate many variations.
Hands-on: a black-box attack on the loan model
You have only the API. The plan: query the model, train a surrogate, read its boundaries, and use them to craft the smallest change that flips a decision. You continue in the practice project; create module-7/test_adversarial.py:
"""Lesson "Adversarial testing": find the smallest change that flips the model's decision."""
import numpy as np
import pandas as pd
import pytest
from sklearn.tree import DecisionTreeClassifier, export_text
BASE = {"name": "Sam Taylor", "gender": "Male", "age": 40, "income": 30000,
"creditScore": 700, "employmentYears": 4, "zipCode": "60601"}
RUNS = 20
def predict(api, applicants, model="v1"):
"""Predictions for any number of applicants, 100 per batch call."""
predictions = []
for start in range(0, len(applicants), 100):
response = api.post(f"{api.base}/predict/batch", timeout=10,
json={"applicants": applicants[start:start + 100], "model": model, "seed": 1})
response.raise_for_status()
predictions += response.json()["predictions"]
return predictions
def average(api, applicant):
"""Mean score and approval rate over RUNS runs, so the model's noise does not hide the effect."""
predictions = predict(api, [applicant] * RUNS)
return np.mean([p["score"] for p in predictions]), np.mean([p["approved"] for p in predictions])
@pytest.fixture(scope="module")
def surrogate(api):
"""Black-box attack, step 1: query the model 300 times and train our own model on its answers."""
rng = np.random.default_rng(0)
queries = [{**BASE, "income": int(rng.integers(20000, 120000)), "creditScore": int(rng.integers(500, 800))}
for _ in range(300)]
answers = [p["approved"] for p in predict(api, queries)]
features = pd.DataFrame(queries)[["income", "creditScore"]]
model = DecisionTreeClassifier(max_depth=3, random_state=0).fit(features, answers)
print("\n" + export_text(model, feature_names=["income", "creditScore"]))
return model
def thresholds(model, feature_index):
tree = model.tree_
return sorted({round(t, 1) for f, t in zip(tree.feature, tree.threshold) if f == feature_index})
Three tests. The first checks what the surrogate learned; the second uses it to attack the real model; the third is a robustness requirement the model should meet:
def test_the_surrogate_finds_the_credit_score_boundaries(surrogate):
credit_thresholds = thresholds(surrogate, 1)
assert any(abs(t - 600) <= 5 for t in credit_thresholds)
assert any(abs(t - 700) <= 5 for t in credit_thresholds)
def test_one_credit_point_flips_the_decision(api, surrogate):
"""Black-box attack, step 2: craft an input just across a boundary the surrogate found, and try it on the real model."""
boundary = next(t for t in thresholds(surrogate, 1) if abs(t - 700) <= 5)
below, above = {**BASE, "creditScore": int(np.floor(boundary))}, {**BASE, "creditScore": int(np.ceil(boundary))}
(score_below, approved_below), (score_above, approved_above) = average(api, below), average(api, above)
print(f"\n credit {below['creditScore']}: score {score_below:.1f}, approved {approved_below:.0%}"
f"\n credit {above['creditScore']}: score {score_above:.1f}, approved {approved_above:.0%}")
assert approved_below == 0 and approved_above == 1
@pytest.mark.xfail(strict=True, reason="defect: a cliff edge at an income of $50,000")
def test_one_dollar_does_not_change_the_score_much(api):
score_low, _ = average(api, {**BASE, "income": 50000, "creditScore": 650})
score_high, _ = average(api, {**BASE, "income": 50001, "creditScore": 650})
print(f"\n income 50000: {score_low:.1f} income 50001: {score_high:.1f}")
assert abs(score_high - score_low) <= 3
Run it
pytest module-7/test_adversarial.py -v -s
|--- creditScore <= 600.50
| |--- income <= 88164.00
| | |--- class: False
| |--- income > 88164.00
| | |--- creditScore <= 568.00
| | | |--- class: False
| | |--- creditScore > 568.00
| | | |--- class: True
|--- creditScore > 600.50
| |--- income <= 47558.50
| | |--- creditScore <= 700.50
| | | |--- class: False
| | |--- creditScore > 700.50
| | | |--- class: True
| |--- income > 47558.50
| | |--- class: True
PASSED
module-7/test_adversarial.py::test_one_credit_point_flips_the_decision
credit 700: score 54.0, approved 0%
credit 701: score 70.5, approved 100%
PASSED
module-7/test_adversarial.py::test_one_dollar_does_not_change_the_score_much
income 50000: 54.5 income 50001: 74.9
XFAIL
What the attack found
From 300 queries and no knowledge of the model, the surrogate recovered its structure: boundaries at a credit score of 600.5 and 700.5, and an income boundary near $47,500 (the real one is $50,000; the surrogate is close but not exact, as surrogates are).
Using the 700.5 boundary, the attack crafted two applicants that differ by one credit point: 700 is rejected every time (score 54.0), 701 is approved every time (70.5). An applicant with an income of $30,000 who is rejected only needs to nudge their credit score by one point. The same cliff exists for income: one dollar, from $50,000 to $50,001, adds 20 points.
These are cliff edges: the model’s score jumps at hard thresholds. A real attacker would use them to game the decision; an honest applicant just across the line gets a different answer for no meaningful reason. The robustness test states what should be true (a tiny change, a tiny effect) and documents that it is not.
Note the role of the noise: a single prediction can be approved or rejected by chance near the threshold (lesson 26). Averaging 20 runs separates the real effect from the noise, so the attack result is reliable.
Exercise
- The surrogate put the income boundary at $47,558.50. Craft an applicant with a credit score of 650 and an income of $48,000, which the surrogate approves. What does the real model do, and what does that say about transferability?
- Name two safeguards the bank could add against the cliff edges you found.
Show suggested answer
Add
average(api, {**BASE, "income": 48000, "creditScore": 650})to a test. The real model rejects it (the real boundary is $50,000; score around 55). The surrogate’s boundary was close but not exact, so this example did not transfer. Transferability is a tendency, not a guarantee: an attacker uses the surrogate to know where to look, then probes the real model around that point. That is what the credit-score attack did.For example: replace the hard thresholds with a smooth function of income and credit score, so a small change gives a small effect; send applicants within a band around the threshold to a human reviewer; limit the number of times one person can query the model (making a black-box attack expensive); and monitor for many near-identical applications in a short time.
Exam-style questions
1. What is an adversarial example?
- A. A test case that the model always gets right
- B. An input with a small, often imperceptible change that makes the model produce a wrong result
- C. A mislabelled training example
- D. An example from a competitor’s dataset
Show answer
2. An attacker has no access to the model’s internals. They query it many times, train their own model on the answers, craft adversarial examples on it, and use them on the original. Which property makes this work?
- A. Explainability
- B. Transferability
- C. Overfitting
- D. Determinism
Show answer
3. Why is white-box adversarial testing usually easier than black-box?
- A. The tester knows the architecture, parameters and training, and can use them to craft examples
- B. White-box testing does not need any test inputs
- C. White-box models have no decision boundaries
- D. Black-box testing is not allowed
Show answer
Your project so far
ai-testing-practice/
├── ...
└── module-7/
├── test_functional_performance.py
├── test_adversarial.py new in this lesson
└── test_metamorphic.py
The finished version is in the example repository: module-7/test_adversarial.py.