Algorithmadvanced
Poisoning attack on support vector machines
Also called Biggio poisoning attack.
Finds a training point that most increases an SVM's validation error by gradient ascent through the incremental SVM solution.
- Time
- O(p (n^2 d + k n + d s^3 + v d^2)) worst
- Space
- O(n^2 + v) extra
- Where
- d = the dimension; k = the number of SMO iterations per training; n = the number of training points; p = the number of ascent steps; s = the number of margin support vectors; v = the number of validation points
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Battista Biggio, Blaine Nelson, Pavel Laskov, 2012
The poisoning attack of Biggio, Nelson and Laskov (2012) is the first optimization attack on the training data of a support vector machine. The attacker adds one point to the training set and chooses to maximize the hinge loss of the trained SVM on a validation set, by gradient ascent. The gradient goes through the training: when moves a little and no training point changes its role (margin support vector, error vector, or neither), the dual solution changes smoothly, and the KKT conditions give its derivative by a linear solve. On this page the kernel is linear, so the SVM solution is an affine function of on each region where the roles stay fixed. The attack is a local search with no guarantee of a global maximum; its effect is a measurement.
In plain words
An SVM learns a line that separates two classes. An attacker who can add one training point wants to put it where it hurts the line the most.
Start with a copy of a point of one class and give it the other label. Train the SVM, check how badly it does on some held out points, and work out which way to move the bad point to make that worse. Move it a step that way and repeat.
The hard part is the "which way". Moving the point changes the training, and the line moves in turn. While the same points stay on the margin, the line moves in a simple, predictable way, so the direction comes from one small system of equations. When the points on the margin change, the attack retrains and starts again from there.
The problem
The threat model, in the three parts of Biggio and Roli:
- Goal of the attacker. Raise the error of the SVM on clean test data. The attack is not targeted at one test point.
- Knowledge. Full: the training set, the learning algorithm, the parameter and the kernel, and a validation set from the same distribution. This is a worst case for the defender.
- Capability. Add one point with a label of the attacker's choice (in Algorithm 1, the flipped label of a cloned point), inside a box of feasible values; several points are added one at a time.
Input. Training points with , a validation set , the SVM parameter , a label , a start , a step , a box , a step limit and a tolerance .
Output. A point in the box with a large value of
where is the SVM trained on the training set plus .
The SVM. The dual is subject to and , with and . The solution splits the points into the margin support vectors (, ), the error vectors (, ) and the rest (, ).
The algorithm
SVM-POISON(training set, V, C, y_c, x_c0, t, box, steps, epsilon)- 1
x_c <- x_c0 - 2
for p = 1 to steps do - 3
train the SVM on the training set plus (x_c, y_c); this gives alpha, b, S, E, R - 4
u <- gradient of L at x_c, from the KKT system on S with S, E, R held fixed - 5
x_c <- the projection onto the box of x_c + t u / ||u|| - 6
stop if L rose by less than epsilon since the last step - 7
return x_c
Line L4. Write . If the attack point is not in , its is or and does not move, and only the column , with entries , depends on . The derivative of the KKT equations gives, for each coordinate ,
and then . This is the linear kernel case of equation (10) of Biggio et al. In the code, line L3 runs SMO and then solves the KKT equations exactly on the sets it found, by Gaussian elimination.
Example
Two classes in the plane, : training points with label and with label , and validation points with the sign of the first coordinate as label. The clean SVM is , : every validation point has margin , so and the error is .
The attacker adds with label , starting at . The solution has , the two points with label in and the other three in . The constraint and the two margin equations give
so the gradient is : move left. With in the box the losses are , and the attack stops at , where no longer rises. The clean points with label at first coordinate have margin , which is negative for , so from the third step on, half of the validation set is misclassified.
Correctness
Theorem (the gradient, proved on this page). Fix a solution with sets , the attack point not in , , and nonsingular. On the region of where these sets give a solution of the KKT conditions, and are affine functions of ; where also no validation point has , is differentiable and its gradient is the formula of line L4. The proof differentiates the KKT equations; the KKT conditions are sufficient for the convex dual, so the solution of the equations is the SVM.
Theorem (flat regions, proved on this page). With a linear kernel, if and the points of are affinely independent, the equations fix and , so the gradient of is on the region. Algorithm 1 then stops.
What is not proved. is not concave in , so gradient ascent finds a local maximum at best, and a fixed step may overshoot. Biggio et al. report that the attack finds good local maxima in their experiments; this is a measurement.
Proof: The gradient of the validation hinge loss of a linear SVM in one training point, with the active sets held fixedfull
Setting. Training points with labels , of which the last, , is the attack point. . The dual is over , ; it is a convex quadratic program, so the KKT conditions are necessary and sufficient. With and they read: , and for each , either and (set ), or and (set ), or and (set ). The primal is unique, and is unique when .
Claim 1 (an affine solution on a region). Fix a partition of the points into , , and , with , and fix ; so is an error vector or a rest point, but it is listed apart from and . Let and assume is nonsingular. For define as the solution of
with , , and . Let be the set of where these values satisfy the KKT inequalities ( on , on , on , including ). Then on the SVM solution is , and , and are affine in .
Proof. The rows of (1) for say , which is ; the last row is . So on all KKT conditions hold, and by sufficiency the point is optimal; since is unique and is unique when , it is the SVM solution. The matrix uses only and , which do not involve because . On the right side, only depends on , and its entries are linear in . So is affine in . Finally , a sum of affine functions.
Claim 2 (the derivative). On , for each coordinate ,
Proof. Differentiate (1) in . is constant, and the derivative of the row of the right side is ; the last row is constant. Multiply by . For , the terms of are constant, the term has derivative , and has derivative because is constant.
Claim 3 (the gradient of ). Let and assume no validation point has . Then near such an in the interior of , with fixed, and
which is what poison_gradient computes.
Proof. Each is a continuous (affine) function of by Claim 1, so a strict inequality holds near , and the set does not change there. On that neighborhood is a finite sum of affine functions, and the chain rule with Claim 2 gives the formula. Since is affine on the neighborhood, central finite differences inside it equal the gradient up to rounding, which the tests use.
Claim 4 (flat regions). If moreover and the vectors , , are linearly independent, then and are constant on , and .
Proof. On , the equations for hold, and they form a linear system in whose matrix has the rows , which is nonsingular by the hypothesis. Its right side is , which does not depend on , and no point of is the attack point, so the unique solution does not depend on . Then is constant near .
The algorithm. Line L5 moves along , which is the direction of fastest increase of the affine function on the current region, and projects onto the box. Nothing more is claimed: when the step leaves the region the sets change, may fall, and line L6 stops; is not concave, so the result is not a global maximum.
Complexity
- Time per step. Training costs for and for SMO iterations; the exact solve on costs . The gradient solves for right sides, (or with one factorization), and the validation sum costs . The incremental SVM of Cauwenberghs and Poggio updates the solution in place of a full retraining.
- Total. steps, so .
- Space. for and for the validation set.
Properties
- One point at a time. Several attack points are found one after another, each with the previous ones in the training set.
- Needs full knowledge. The gradient needs the training set and the validation set. An attacker with less knowledge must estimate them, for example from a substitute data set.
- Kernels. Equation (10) of Biggio et al. holds for any differentiable kernel, so the attack works in input space with a nonlinear kernel. The code covers the linear kernel only.
Variants and improvements
- Bilevel poisoning. Mei and Zhu (2015) wrote optimal training set attacks as a bilevel program, with the learner as the inner problem, and solved it through its KKT conditions for several convex learners.
- Back-gradient poisoning. Munoz-Gonzalez et al. (2017) replaced the KKT solve by differentiation through the steps of gradient descent, which reaches neural networks.
- Certified bounds. Steinhardt, Koh and Liang (2017) bound the loss that any poisoning of a fixed fraction can cause against an outlier removal defense, for linear models.
- Targeted poisoning. Clean-label poisoning aims at one test point, and a backdoor at inputs with a trigger.
When to use it
Use it to measure the worst case robustness of an SVM, or of another convex learner, to a few added points, in a setting where the attacker could know the training data. It is a tool for evaluation on synthetic or owned data, not a defense. For deep networks use back-gradient methods; for a guarantee in place of a measurement use certified bounds. Defenses that remove outliers, such as spectral signatures for a group of poisoned points, do not target this attack.
Pitfalls
- Flat regions with a linear kernel. In low dimension the margin set often has points, the gradient is , and the attack does not move. The example of the tests in shows this; in with 15 points per class the attack moves.
- The attack point on the margin. If is a margin support vector, moves too, and the formula of line L4 does not apply. Start from a point deep in the other class, where .
- Sets that change. The gradient holds only while , and stay fixed. A large step crosses into another region, and may fall; line L6 stops there.
- An inexact solver. SMO stops at a tolerance, so is close but not exact, and amplifies the error. The code solves the KKT equations exactly on the sets that SMO finds and checks them.
Implementations
The code runs only on a linear SVM and on data that the tests build from a fixed seed, two Gaussian blobs in at most 8 dimensions; it never reads a real data set or a deployed model. The tests check the SVM on 500 random problems by a duality certificate (a feasible whose dual value equals the primal value of is optimal, by weak duality), check the gradient against central finite differences where the sets do not change, check the example and the flat region, and measure the attack: on four seeds with the means and covariance of Biggio et al. but and 15 points per class, one point raises the validation error from 5.0, 5.75, 4.5 and 7.0 percent to 21.0, 12.0, 11.5 and 7.75 percent.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svm-poisoning-attack/. The authors are listed in prov/VZRNHS.jsonl.
"""The poisoning attack of Biggio, Nelson and Laskov (2012) on a linear soft-margin SVM, as an abstract model.
The tests build every training set and validation set from a fixed seed (two Gaussian
blobs in a few dimensions). Nothing here reads a real data set or a deployed model.
Labels are +1 and -1. The SVM is the dual problem
min_a 1/2 a^T Q a - 1^T a subject to 0 <= a_i <= C and sum_i y_i a_i = 0,
with Q_ij = y_i y_j <x_i, x_j>, solved by SMO and then made exact on its active set.
"""
import math
from dataclasses import dataclass
from typing import Sequence
Vector = list[float]
Matrix = list[list[float]]
def dot(u: Sequence[float], v: Sequence[float]) -> float:
"""Inner product. Cost O(d)."""
return math.fsum(a * b for a, b in zip(u, v, strict=True))
def solve(a: Matrix, rhs: Vector) -> Vector:
"""Solve a x = rhs by Gaussian elimination with partial pivoting. Raises ValueError if a is singular. Cost O(m^3)."""
m = len(a)
aug = [list(a[i]) + [rhs[i]] for i in range(m)]
scale = max((abs(x) for row in a for x in row), default=0.0)
for col in range(m):
piv = max(range(col, m), key=lambda r: abs(aug[r][col]))
if abs(aug[piv][col]) <= 1e-12 * max(scale, 1.0):
raise ValueError("singular system")
aug[col], aug[piv] = aug[piv], aug[col]
for r in range(m):
if r != col and aug[r][col] != 0.0:
f = aug[r][col] / aug[col][col]
for c in range(col, m + 1):
aug[r][c] -= f * aug[col][c]
return [aug[i][m] / aug[i][i] for i in range(m)]
@dataclass
class Svm:
"""A trained linear SVM: dual variables, weights w, bias b, and the index sets of the solution."""
alpha: Vector
w: Vector
b: float
margin: list[int] # S: 0 < alpha < C, so y f(x) = 1
error: list[int] # E: alpha = C, so y f(x) <= 1
rest: list[int] # R: alpha = 0, so y f(x) >= 1
def _sets(alpha: Sequence[float], c: float, eps: float) -> tuple[list[int], list[int], list[int]]:
s, e, r = [], [], []
for i, a in enumerate(alpha):
(r if a <= eps else e if a >= c - eps else s).append(i)
return s, e, r
def _finish(xs: Sequence[Sequence[float]], ys: Sequence[int], alpha: Vector, b: float, c: float) -> Svm:
d = len(xs[0])
w = [math.fsum(alpha[i] * ys[i] * xs[i][j] for i in range(len(xs))) for j in range(d)]
s, e, r = _sets(alpha, c, 1e-9 * c)
return Svm(alpha, w, b, s, e, r)
def kkt_violation(xs: Sequence[Sequence[float]], ys: Sequence[int], m: Svm, c: float) -> float:
"""The largest violation of the KKT conditions of m, in units of the margin. Cost O(n d)."""
worst = abs(math.fsum(a * y for a, y in zip(m.alpha, ys)))
for i, (x, y) in enumerate(zip(xs, ys)):
g = y * (dot(m.w, x) + m.b)
a = m.alpha[i]
worst = max(worst, -a, a - c)
if i in m.margin:
worst = max(worst, abs(g - 1.0))
elif i in m.error:
worst = max(worst, g - 1.0)
else:
worst = max(worst, 1.0 - g)
return worst
def _polish(xs: Sequence[Sequence[float]], ys: Sequence[int], alpha: Vector, c: float) -> tuple[Vector, float] | None:
"""Solve the KKT equations exactly on the active sets that alpha suggests; None if they do not hold."""
n = len(xs)
s, e, _ = _sets(alpha, c, 1e-6 * c)
if not s:
return None
fixed = [c if i in e else 0.0 for i in range(n)]
k = len(s)
a = [[ys[p] * ys[q] * dot(xs[p], xs[q]) for q in s] + [float(ys[p])] for p in s]
a.append([float(ys[q]) for q in s] + [0.0])
rhs = [1.0 - math.fsum(ys[p] * ys[j] * dot(xs[p], xs[j]) * fixed[j] for j in e) for p in s]
rhs.append(-math.fsum(ys[j] * fixed[j] for j in e))
try:
sol = solve(a, rhs)
except ValueError:
return None
new = fixed[:]
for t, p in enumerate(s):
new[p] = sol[t]
b = sol[k]
m = _finish(xs, ys, new, b, c)
m.margin, m.error = s, e
m.rest = [i for i in range(n) if i not in s and i not in e]
if kkt_violation(xs, ys, m, c) > 1e-9:
return None
return new, b
def train_svm(xs: Sequence[Sequence[float]], ys: Sequence[int], c: float, tol: float = 1e-10, max_iter: int = 200000) -> Svm:
"""Train a linear soft-margin SVM by SMO with the maximal violating pair, then solve its active set exactly.
Precondition: both labels occur and c > 0. Cost O(max_iter n + n^2 d) for SMO, and O(n^3) for the exact solve.
"""
n = len(xs)
q = [[ys[i] * ys[j] * dot(xs[i], xs[j]) for j in range(n)] for i in range(n)]
alpha = [0.0] * n
grad = [-1.0] * n # Q alpha - 1
for _ in range(max_iter):
up = [t for t in range(n) if (ys[t] > 0 and alpha[t] < c) or (ys[t] < 0 and alpha[t] > 0)]
low = [t for t in range(n) if (ys[t] > 0 and alpha[t] > 0) or (ys[t] < 0 and alpha[t] < c)]
i = max(up, key=lambda t: -ys[t] * grad[t])
j = min(low, key=lambda t: -ys[t] * grad[t])
if -ys[i] * grad[i] + ys[j] * grad[j] < tol:
break
ai, aj = alpha[i], alpha[j]
if ys[i] != ys[j]:
quad = max(q[i][i] + q[j][j] + 2 * q[i][j], 1e-12)
delta = (-grad[i] - grad[j]) / quad
diff = ai - aj
ni, nj = ai + delta, aj + delta
if diff > 0:
if nj < 0:
nj, ni = 0.0, diff
elif ni < 0:
ni, nj = 0.0, -diff
if diff > 0:
if ni > c:
ni, nj = c, c - diff
elif nj > c:
nj, ni = c, c + diff
else:
quad = max(q[i][i] + q[j][j] - 2 * q[i][j], 1e-12)
delta = (grad[i] - grad[j]) / quad
total = ai + aj
ni, nj = ai - delta, aj + delta
if total > c:
if ni > c:
ni, nj = c, total - c
elif nj < 0:
nj, ni = 0.0, total
if total > c:
if nj > c:
nj, ni = c, total - c
elif ni < 0:
ni, nj = 0.0, total
di, dj = ni - ai, nj - aj
alpha[i], alpha[j] = ni, nj
for t in range(n):
grad[t] += q[t][i] * di + q[t][j] * dj
polished = _polish(xs, ys, alpha, c)
if polished is not None:
new, b = polished
m = _finish(xs, ys, new, b, c)
s, e, _ = _sets(alpha, c, 1e-6 * c)
m.margin, m.error = s, e
m.rest = [i for i in range(n) if i not in s and i not in e]
return m
free = [t for t in range(n) if 0 < alpha[t] < c]
if free:
b = -math.fsum(ys[t] * grad[t] for t in free) / len(free)
else:
up = [t for t in range(n) if (ys[t] > 0 and alpha[t] < c) or (ys[t] < 0 and alpha[t] > 0)]
low = [t for t in range(n) if (ys[t] > 0 and alpha[t] > 0) or (ys[t] < 0 and alpha[t] < c)]
b = (max(-ys[t] * grad[t] for t in up) + min(-ys[t] * grad[t] for t in low)) / 2
return _finish(xs, ys, alpha, b, c)
def hinge_total(m: Svm, val: Sequence[tuple[Sequence[float], int]]) -> float:
"""The attacker objective L = sum over the validation set of max(0, 1 - y f(x)). Cost O(v d)."""
return math.fsum(max(0.0, 1.0 - y * (dot(m.w, x) + m.b)) for x, y in val)
def error_rate(m: Svm, val: Sequence[tuple[Sequence[float], int]]) -> float:
"""Fraction of validation points with y f(x) <= 0. Cost O(v d)."""
return sum(1 for x, y in val if y * (dot(m.w, x) + m.b) <= 0) / len(val)
def poison_gradient(xs: Sequence[Sequence[float]], ys: Sequence[int], m: Svm, c: float, val: Sequence[tuple[Sequence[float], int]]) -> Vector:
"""Gradient of hinge_total in the last training point x_c, with the sets S, E, R of m held fixed.
The last point (xs[-1], ys[-1]) is the attack point. Precondition: it is not in S
(its alpha is 0 or C), S is not empty, and the KKT matrix on S is nonsingular; the
gradient then exists wherever no point changes set and no validation point sits on
its margin. Cost O(s^3 + s d^2 + v d) for s = |S| and v validation points.
"""
cidx = len(xs) - 1
d = len(xs[0])
if cidx in m.margin:
raise ValueError("the attack point is a margin support vector")
s = m.margin
if not s:
raise ValueError("no margin support vector")
yc, ac = ys[cidx], m.alpha[cidx]
k = len(s)
a = [[ys[p] * ys[q] * dot(xs[p], xs[q]) for q in s] + [float(ys[p])] for p in s]
a.append([float(ys[q]) for q in s] + [0.0])
# Columns j = 1..d: d(alpha_S, b) / d(x_c)_j = -K^{-1} [a_c y_c y_s (x_s)_j ; 0]
dalpha = [[0.0] * d for _ in range(k)]
db = [0.0] * d
for j in range(d):
rhs = [-ac * yc * ys[p] * xs[p][j] for p in s] + [0.0]
sol = solve(a, rhs)
for t in range(k):
dalpha[t][j] = sol[t]
db[j] = sol[k]
# dw / d(x_c) = sum_s y_s x_s (d alpha_s)^T + a_c y_c I
dw = [[math.fsum(ys[p] * xs[p][r] * dalpha[t][j] for t, p in enumerate(s)) + (ac * yc if r == j else 0.0) for j in range(d)] for r in range(d)]
g = [0.0] * d
for x, y in val:
if 1.0 - y * (dot(m.w, x) + m.b) > 0.0:
for j in range(d):
g[j] -= y * (math.fsum(x[r] * dw[r][j] for r in range(d)) + db[j])
return g
def poison(
xs: Sequence[Sequence[float]],
ys: Sequence[int],
val: Sequence[tuple[Sequence[float], int]],
c: float,
x0: Sequence[float],
yc: int,
step: float,
lo: float,
hi: float,
iters: int,
eps: float,
) -> tuple[Vector, list[float]]:
"""Gradient ascent on the validation hinge loss over one attack point (x_c, yc) in the box [lo, hi]^d.
Stops when the loss rises by less than eps, after iters steps, or where the gradient
does not exist or is zero. Returns the final x_c and the loss after each training.
Precondition: the conditions of poison_gradient at each step. Cost O(iters) SVM trainings.
"""
xc = list(x0) # @line L1
losses: list[float] = []
for _ in range(iters): # @line L2
m = train_svm(list(xs) + [xc], list(ys) + [yc], c) # @line L3
losses.append(hinge_total(m, val))
if len(losses) >= 2 and losses[-1] - losses[-2] < eps: # @line L6
break
try:
u = poison_gradient(list(xs) + [xc], list(ys) + [yc], m, c, val) # @line L4
except ValueError:
break
norm = math.sqrt(math.fsum(a * a for a in u))
if norm <= 1e-9 * max(len(val), 1): # a flat region, for example |S| = d + 1
break
xc = [min(max(a + step * g / norm, lo), hi) for a, g in zip(xc, u)] # @line L5
return xc, losses # @line L7
test_svm_poisoning_attack.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/svm-poisoning-attack/. The authors are listed in prov/VZRNHS.jsonl.
"""Tests of the SVM poisoning attack on seeded synthetic blobs: a duality certificate, finite differences, a measurement."""
import math
import random
from svm_poisoning_attack import dot, error_rate, hinge_total, kkt_violation, poison, poison_gradient, train_svm
def blobs(rng: random.Random, per_class: int, d: int, shift: float, sigma: float) -> tuple[list[list[float]], list[int]]:
xs, ys = [], []
for i in range(2 * per_class):
y = 1 if i % 2 == 0 else -1
xs.append([(y * shift if j == 0 else 0.0) + rng.gauss(0.0, sigma) for j in range(d)])
ys.append(y)
return xs, ys
def primal(xs, ys, w, b, c) -> float:
return 0.5 * dot(w, w) + c * math.fsum(max(0.0, 1.0 - y * (dot(w, x) + b)) for x, y in zip(xs, ys))
def dual(alpha, w) -> float:
return math.fsum(alpha) - 0.5 * dot(w, w)
def test_svm_solution_has_zero_duality_gap() -> None:
"""Weak duality: D(alpha) <= P* <= P(w, b) for feasible alpha, so a zero gap certifies the optimum."""
rng = random.Random(6201)
for _ in range(500):
n, d = rng.randint(2, 10), rng.randint(1, 3)
xs = [[rng.uniform(-2.0, 2.0) for _ in range(d)] for _ in range(n)]
ys = [1, -1] + [rng.choice([1, -1]) for _ in range(n - 2)]
c = rng.choice([0.1, 1.0, 10.0])
m = train_svm(xs, ys, c)
assert all(-1e-12 <= a <= c + 1e-12 for a in m.alpha)
assert abs(math.fsum(a * y for a, y in zip(m.alpha, ys))) < 1e-9
w = [math.fsum(m.alpha[i] * ys[i] * xs[i][j] for i in range(n)) for j in range(d)]
assert all(abs(a - b) < 1e-12 for a, b in zip(w, m.w))
p, q = primal(xs, ys, m.w, m.b, c), dual(m.alpha, m.w)
assert p - q <= 1e-7 * (1.0 + abs(p)), (p, q)
assert kkt_violation(xs, ys, m, c) < 1e-6
def test_gradient_matches_finite_differences() -> None:
rng = random.Random(6202)
checked = nonzero = 0
for _ in range(60):
d = rng.randint(2, 5)
xs, ys = blobs(rng, 6, d, 1.5, math.sqrt(0.6))
val = list(zip(*blobs(rng, 10, d, 1.5, math.sqrt(0.6))))
k = rng.randrange(len(xs) // 2) * 2 + 1 # a point of class -1
xc = [a + rng.gauss(0.0, 0.3) for a in xs[k]]
allx, ally = xs + [xc], ys + [1]
m = train_svm(allx, ally, 1.0)
if len(allx) - 1 in m.margin or not m.margin:
continue
try:
g = poison_gradient(allx, ally, m, 1.0, val)
except ValueError:
continue
h = 1e-5
ok = True
fd = []
for j in range(d):
vals = []
for sgn in (1.0, -1.0):
moved = list(xc)
moved[j] += sgn * h
mm = train_svm(xs + [moved], ally, 1.0)
same_sets = mm.margin == m.margin and mm.error == m.error
same_val = all((1 - y * (dot(mm.w, x) + mm.b) > 0) == (1 - y * (dot(m.w, x) + m.b) > 0) for x, y in val)
ok = ok and same_sets and same_val
vals.append(hinge_total(mm, val))
fd.append((vals[0] - vals[1]) / (2 * h))
if not ok:
continue
checked += 1
nonzero += max(abs(a) for a in g) > 1e-6
assert all(abs(a - b) <= 1e-5 * (1.0 + abs(b)) for a, b in zip(g, fd)), (g, fd)
assert checked >= 30 and nonzero >= 15, (checked, nonzero)
EX_X = [[-2.0, 0.0], [2.0, 0.0], [-2.0, 1.0], [2.0, 1.0]]
EX_Y = [-1, 1, -1, 1]
EX_VAL = [([-1.0, 0.0], -1), ([1.0, 0.0], 1), ([-1.0, 1.0], -1), ([1.0, 1.0], 1)]
def test_example_of_the_page() -> None:
clean = train_svm(EX_X, EX_Y, 0.1)
assert abs(clean.w[0] - 0.5) < 1e-12 and abs(clean.w[1]) < 1e-12 and abs(clean.b) < 1e-12
assert abs(hinge_total(clean, EX_VAL) - 2.0) < 1e-12 and error_rate(clean, EX_VAL) == 0.0
for a in (-2.0, -2.5, -3.0, -5.0):
m = train_svm(EX_X + [[a, 0.5]], EX_Y + [1], 0.1)
assert m.margin == [1, 3] and m.error == [0, 2, 4]
assert abs(m.w[0] - (0.6 + 0.1 * a)) < 1e-12 and abs(m.w[1]) < 1e-12 and abs(m.b - (-0.2 - 0.2 * a)) < 1e-12
assert abs(hinge_total(m, EX_VAL) - (2.4 - 0.4 * (a + 2.0))) < 1e-12
g = poison_gradient(EX_X + [[a, 0.5]], EX_Y + [1], m, 0.1, EX_VAL)
assert abs(g[0] + 0.4) < 1e-12 and abs(g[1]) < 1e-12
assert error_rate(m, EX_VAL) == (0.5 if a < -8.0 / 3.0 else 0.0)
xc, losses = poison(EX_X, EX_Y, EX_VAL, 0.1, [-2.0, 0.5], 1, 0.5, -5.0, 5.0, 20, 1e-9)
assert xc == [-5.0, 0.5] and [round(t, 9) for t in losses] == [2.4, 2.6, 2.8, 3.0, 3.2, 3.4, 3.6, 3.6]
def test_flat_region_when_the_margin_set_has_d_plus_one_points() -> None:
"""With a linear kernel and |S| = d + 1, the margin equations fix w and b, so the gradient is zero."""
rng = random.Random(6203)
xs, ys = blobs(rng, 25, 2, 1.5, math.sqrt(0.6))
val = list(zip(*blobs(rng, 250, 2, 1.5, math.sqrt(0.6))))
m = train_svm(xs + [xs[1]], ys + [1], 1.0)
assert len(m.margin) == 3
g = poison_gradient(xs + [xs[1]], ys + [1], m, 1.0, val)
assert max(abs(a) for a in g) < 1e-10
def test_one_point_raises_the_validation_error() -> None:
"""A measurement: the means (+-1.5, 0, ...) and covariance 0.6 I of Biggio et al., but d = 8 and 15 points per class, C = 1."""
gains = []
for seed in (6204, 6205, 6206, 6207):
rng = random.Random(seed)
xs, ys = blobs(rng, 15, 8, 1.5, math.sqrt(0.6))
val = list(zip(*blobs(rng, 200, 8, 1.5, math.sqrt(0.6))))
clean = train_svm(xs, ys, 1.0)
# Clone a point of class -1 and flip its label.
xc, losses = poison(xs, ys, val, 1.0, xs[1], 1, 0.5, -5.0, 5.0, 60, 1e-6)
attacked = train_svm(xs + [xc], ys + [1], 1.0)
assert losses[-1] > losses[0]
assert all(-5.0 <= a <= 5.0 for a in xc)
gains.append(error_rate(attacked, val) - error_rate(clean, val))
assert min(gains) > 0.0 and sum(gains) / len(gains) >= 0.05
History
Barreno et al. (2006, 2010) named causative attacks on the training data. Biggio, Nelson and Laskov (2012) gave the first gradient attack on SVM training, using the incremental SVM of Cauwenberghs and Poggio (2000) and experiments on artificial data and MNIST. Mei and Zhu (2015) generalized it to bilevel optimization, Steinhardt, Koh and Liang (2017) gave certified bounds, and Munoz-Gonzalez et al. (2017) extended gradient poisoning to deep networks.
References
- Battista Biggio, Blaine Nelson and Pavel Laskov, Poisoning attacks against support vector machines, Proceedings of the 29th International Conference on Machine Learning (ICML) 2012, arXiv:1206.6389, the attack objective (the hinge loss on a validation set), Algorithm 1 (gradient ascent with a fixed step), equation (10) (the gradient through the KKT conditions of the incremental SVM), and the experiments on artificial data (means (+-1.5, 0), covariance 0.6 I, 25 points per class, 500 validation points) and on MNIST
- Shike Mei and Xiaojin Zhu, Using machine teaching to identify optimal training-set attacks on machine learners, Proceedings of the 29th AAAI Conference on Artificial Intelligence (AAAI) 2015, optimal training set attacks as a bilevel program, solved through the KKT conditions of the learner
- Luis Munoz-Gonzalez, Battista Biggio, Ambra Demontis, Andrea Paudice, Vasin Wongrassamee, Emil C. Lupu and Fabio Roli, Towards poisoning of deep learning algorithms with back-gradient optimization, Proceedings of the 10th ACM Workshop on Artificial Intelligence and Security (AISec) 2017, the poisoning gradient by differentiation through the steps of the learning algorithm
- Gert Cauwenberghs and Tomaso Poggio, Incremental and decremental support vector machine learning, Advances in Neural Information Processing Systems 13 (NIPS) 2000, the update of the dual solution that keeps the KKT conditions while one point is added or changed, with the sets S, E and R
- Marco Barreno, Blaine Nelson, Anthony D. Joseph and J. D. Tygar, The security of machine learning, Machine Learning 81, 2010, the taxonomy of attacks, with causative attacks that change the training data
- Battista Biggio and Fabio Roli, Wild patterns, ten years after the rise of adversarial machine learning, Pattern Recognition 84, 2018, the threat model in three parts, goal, knowledge and capability
- Jacob Steinhardt, Pang Wei Koh and Percy Liang, Certified defenses for data poisoning attacks, Advances in Neural Information Processing Systems 30 (NeurIPS) 2017, upper bounds on the loss that a poisoning attacker can cause against defenses that remove outliers, for linear models such as the SVM
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag VZRNHS Edit this page History Report an error Markdown