Algorithm Search⌘K

Algorithmadvanced

PCA subspace method for traffic anomalies

Also called Lakhina subspace method.

Projects link traffic onto the residual subspace of its main principal components and flags times when the residual norm passes the Q-statistic.

Time
O(t m^2 + w m^3) worst
Space
O(t m + m^2) extra
Where
m = the number of links; r = the number of normal axes; t = the number of time bins; w = the number of Jacobi sweeps
Properties
deterministicnot exactofflineiterative
Origin
Anukool Lakhina, Mark Crovella, Christophe Diot, 2004

The PCA subspace method finds anomalies in the traffic of a whole network at once. The input is a table of link loads: one row for each time bin, one column for each link. The loads of the links are strongly correlated, because each traffic flow crosses several links, so most of the variation lies in a few directions, the top principal axes. The method calls the span of these axes the normal subspace and the rest the residual subspace. A time bin whose load vector has a large part in the residual subspace is flagged, even when no single link is unusual. Lakhina, Crovella and Diot (2004) proposed it for the anomaly detection problem in backbone networks.

In plain words

Several roads share a commuter flow, so on a busy morning all of them are busy together. A busy morning is normal. What is strange is one road busy while the roads that should be busy with it are quiet. Learn from history which roads move together. For each new hour, take away the part of the traffic that the usual patterns explain. If what is left is large, something unusual happened. A table from statistics tells how large is too large, for a chosen rate of false alarms.

The problem

The input is a matrix YY with tt rows, the time bins, and mm columns, the links, the number rr of normal axes with 0≤r≤m0 \le r \le m, and a false alarm rate α∈(0,1)\alpha \in (0, 1). Let μ\mu be the mean row and SS the sample covariance matrix, with eigenvalues λ1≥⋯≥λm\lambda_1 \ge \cdots \ge \lambda_m and orthonormal eigenvectors v1,…,vmv_1, \ldots, v_m. Let P=[v1⋯vr]P = [v_1 \cdots v_r]. For a row yy with z=y−μz = y - \mu, the squared prediction error is

SPE(y)=∥(I−PP⊤)z∥2=∑j>r(vj⊤z)2.\mathrm{SPE}(y) = \lVert (I - P P^\top) z \rVert^2 = \sum_{j > r} (v_j^\top z)^2 .

The output is the set of rows with SPE(y)>Qα\mathrm{SPE}(y) > Q_\alpha, where QαQ_\alpha is the threshold of Jackson and Mudholkar (1979) below.

The algorithm

  1. SUBSPACE-DETECT(Y[1..t][1..m], r, α)
  2. 1μ ← the mean of the rows of Y; subtract μ from each row
  3. 2S ← (1 / (t - 1)) Σ_s y_s y_sᵀ over the centered rows
  4. 3compute the eigenpairs of S with λ_1 ≥ … ≥ λ_m
  5. 4P ← [v_1 … v_r] ▷ the normal subspace
  6. 5φ_i ← Σ_{j>r} λ_j^i for i = 1, 2, 3; h_0 ← 1 - 2 φ_1 φ_3 / (3 φ_2²)
  7. 6Q ← φ_1 [c_α √(2 φ_2 h_0²) / φ_1 + 1 + φ_2 h_0 (h_0 - 1) / φ_1²]^(1 / h_0)
  8. 7for each row y do
  9. 8ỹ ← (y - μ) - P Pᵀ (y - μ) ▷ the residual part
  10. 9if ‖ỹ‖² > Q then flag y

Here cαc_\alpha is the 1−α1 - \alpha quantile of the standard normal distribution. Line L3 uses the Jacobi eigenvalue algorithm in the code, which is simple and accurate for the small symmetric matrices of one network. Line L8 subtracts the projection on each normal axis. Lines L5 and L6 use only the residual eigenvalues, so the threshold depends on how much variance the residual subspace normally holds.

Example

Take three links that carry one large shared flow, and eight time bins of load:

bin 1 2 3 4 5 6 7 8
link 1 8.2 12.2 9.8 9.8 9.1 11.1 9.9 9.9
link 2 7.8 11.8 10.2 10.2 9.1 11.1 9.9 9.9
link 3 8.0 12.0 10.0 10.0 8.8 10.8 10.2 10.2

The mean row is (10,10,10)(10, 10, 10). The eigenvalues of SS are 30/7≈4.285730/7 \approx 4.2857, 0.32/7≈0.04570.32/7 \approx 0.0457 and 0.24/7≈0.03430.24/7 \approx 0.0343. The top axis is (1,1,1)/3(1, 1, 1)/\sqrt{3}, the shared flow, and it holds 98.2% of the variance. With r=1r = 1 and α=0.01\alpha = 0.01, lines L5 and L6 give h0=0.3205h_0 = 0.3205 and Q=0.3759Q = 0.3759. The training rows have SPE 0.08 or 0.06. Now test four new bins:

load vector SPE flagged
(12, 12, 12) 0 no
(10, 11, 10) 0.6667 yes
(10.3, 10, 9.7) 0.18 no
(13, 13, 13.4) 0.1067 no

The bin (12,12,12)(12, 12, 12) is a busy hour of the shared flow and has no residual part. The bin (10,11,10)(10, 11, 10) has a load of 11 on link 2, well inside the range 7.8 to 12.2 that link 2 shows in training, so a threshold on each link alone does not flag it. It breaks the pattern, though: link 2 went up while links 1 and 3 did not. Its residual is (−1/3,2/3,−1/3)(-1/3, 2/3, -1/3), with squared norm 2/3>Q2/3 > Q.

Correctness

The method has a part that is exact and a part that rests on a model of the data.

Theorem (the residual). If v1,…,vmv_1, \ldots, v_m are orthonormal, line L8 gives (I−PP⊤)z(I - PP^\top) z and SPE(y)=∑j>r(vj⊤z)2≤∥z∥2\mathrm{SPE}(y) = \sum_{j > r} (v_j^\top z)^2 \le \lVert z \rVert^2. On the training rows, 1t−1∑sSPE(ys)=∑j>rλj=φ1\frac{1}{t-1} \sum_s \mathrm{SPE}(y_s) = \sum_{j > r} \lambda_j = \varphi_1. So the threshold scales with the residual variance of the training data.

Theorem (the eigenpairs). Each Jacobi rotation is an orthogonal similarity, so the code returns an orthogonal VV and a matrix V⊤SVV^\top S V whose off-diagonal part has Frobenius norm at most tol times ∥S∥F\lVert S \rVert_F. By Weyl's inequality, the sorted diagonal is within that amount of the eigenvalues of SS. The code raises an error instead of returning when the rotations do not reach the tolerance.

Heuristic (the threshold). If the rows are independent Gaussian vectors and SS equals the true covariance, then SPE=∑j>rλjgj2\mathrm{SPE} = \sum_{j > r} \lambda_j g_j^2 with independent standard normal gjg_j. Jackson and Mudholkar approximate the quantile of this weighted sum of chi-square variables by a power transformation to near normality; line L6 is that approximation. For equal residual eigenvalues it reduces to the Wilson and Hilferty formula for the chi-square quantile. The rate of false alarms is then near α\alpha, but not exactly α\alpha. Real traffic is not Gaussian and not independent from bin to bin, so the rate on real data can differ much more.

Measurement. In the tests, with five links, two normal axes, 3000 training rows and 4000 fresh Gaussian rows, the false alarm rate at α=0.05\alpha = 0.05 is between 0.035 and 0.065. For two equal eigenvalues, line L6 is within 1% of the exact quantile at α=0.05\alpha = 0.05 and α=0.01\alpha = 0.01, and within 2.5% at α=0.001\alpha = 0.001.

The proofs section below proves the two theorems.

Proof: The subspace method computes the residual energy on the residual axes exactly, its eigenpairs are certified, and its threshold is well defined and monotonefull

Setting. YY has t≥2t \ge 2 rows y1,…,yt∈Rmy_1, \ldots, y_t \in \mathbb{R}^m, 0≤r≤m0 \le r \le m and 0<α<10 < \alpha < 1. Line L1 gives μ\mu and the centered rows zs=ys−μz_s = y_s - \mu, and line L2 gives S=1t−1∑szszs⊤S = \frac{1}{t-1} \sum_s z_s z_s^\top, which is symmetric and positive semidefinite. Write ∥⋅∥F\lVert \cdot \rVert_F for the Frobenius norm and off(A)2=∑i≠jAij2\mathrm{off}(A)^2 = \sum_{i \ne j} A_{ij}^2.

Lemma 1 (one Jacobi rotation). For a symmetric AA with Apq≠0A_{pq} \ne 0, let θ=(Aqq−App)/(2Apq)\theta = (A_{qq} - A_{pp}) / (2 A_{pq}), τ=sign⁡(θ)/(∣θ∣+θ2+1)\tau = \operatorname{sign}(\theta) / (|\theta| + \sqrt{\theta^2 + 1}), c=1/τ2+1c = 1/\sqrt{\tau^2 + 1} and s=τcs = \tau c. Let JJ be the identity except Jpp=Jqq=cJ_{pp} = J_{qq} = c, Jpq=sJ_{pq} = s and Jqp=−sJ_{qp} = -s. Then JJ is orthogonal, A′=J⊤AJA' = J^\top A J is symmetric with Apq′=0A'_{pq} = 0, ∥A′∥F=∥A∥F\lVert A' \rVert_F = \lVert A \rVert_F and off(A′)2=off(A)2−2Apq2\mathrm{off}(A')^2 = \mathrm{off}(A)^2 - 2 A_{pq}^2.

Proof. c2+s2=1c^2 + s^2 = 1, so JJ is orthogonal. The code updates the columns pp and qq of AA, which is AJAJ, then the rows, which is J⊤(AJ)J^\top (AJ). The entry is Apq′=(c2−s2)Apq+cs(App−Aqq)A'_{pq} = (c^2 - s^2) A_{pq} + cs (A_{pp} - A_{qq}). It is zero if and only if (1−τ2)/τ=2θ(1 - \tau^2)/\tau = 2\theta, that is τ2+2θτ−1=0\tau^2 + 2\theta\tau - 1 = 0, and τ\tau is the root sign⁡(θ)(θ2+1−∣θ∣)\operatorname{sign}(\theta)(\sqrt{\theta^2 + 1} - |\theta|) of this equation. An orthogonal similarity keeps the Frobenius norm. Only the rows and columns pp and qq change. For k∉{p,q}k \notin \{p, q\} the pair (Akp′,Akq′)(A'_{kp}, A'_{kq}) is a rotation of (Akp,Akq)(A_{kp}, A_{kq}), so its squared norm is the same. The 2×22 \times 2 block on p,qp, q is an orthogonal similarity of the old block, so its Frobenius norm is the same too, and its off-diagonal entries become 0. So the diagonal gains 2Apq22 A_{pq}^2, and the off-diagonal part loses it. □\square

Lemma 2 (the eigenpairs are certified). If jacobi_eigen returns, then VV is orthogonal, D=V⊤SVD = V^\top S V has off(D)≤tol⋅∥S∥F\mathrm{off}(D) \le \mathrm{tol} \cdot \lVert S \rVert_F, and the sorted diagonal values d1≥⋯≥dmd_1 \ge \cdots \ge d_m satisfy ∣di−λi(S)∣≤tol⋅∥S∥F|d_i - \lambda_i(S)| \le \mathrm{tol} \cdot \lVert S \rVert_F for each ii.

Proof. VV is a product of the matrices JJ of Lemma 1, so it is orthogonal, and the working matrix is always V⊤SVV^\top S V. The loop returns only after the test off≤tol⋅∥S∥F\mathrm{off} \le \mathrm{tol} \cdot \lVert S \rVert_F. Write D=Δ+FD = \Delta + F with Δ\Delta the diagonal part. DD is similar to SS, so it has the same eigenvalues. By Weyl's inequality, ∣λi(D)−λi(Δ)∣≤∥F∥2≤∥F∥F=off(D)|\lambda_i(D) - \lambda_i(\Delta)| \le \lVert F \rVert_2 \le \lVert F \rVert_F = \mathrm{off}(D), and the eigenvalues of Δ\Delta are the sorted diagonal values. Permuting the columns of VV to sort them keeps VV orthogonal. □\square

Termination. The Jacobi loop runs at most max_sweeps sweeps and raises an error if the test fails after them, so it never returns an uncertified result. By Lemma 1 the off-diagonal mass never goes up. All other loops run over a finite range.

Theorem 1 (the residual). Let v1,…,vmv_1, \ldots, v_m be orthonormal and P=[v1⋯vr]P = [v_1 \cdots v_r]. For z=y−μz = y - \mu, line L8 gives (I−PP⊤)z(I - PP^\top) z, and

SPE(y)=∑j>r(vj⊤z)2=∥z∥2−∑j≤r(vj⊤z)2≤∥z∥2.\mathrm{SPE}(y) = \sum_{j > r} (v_j^\top z)^2 = \lVert z \rVert^2 - \sum_{j \le r} (v_j^\top z)^2 \le \lVert z \rVert^2 .

Proof. The code subtracts (vi⊤z)vi(v_i^\top z) v_i for i=1,…,ri = 1, \ldots, r from zz, which gives z−∑i≤r(vi⊤z)vi=z−PP⊤zz - \sum_{i \le r} (v_i^\top z) v_i = z - PP^\top z. Write z=∑j(vj⊤z)vjz = \sum_j (v_j^\top z) v_j in the orthonormal basis. Then (I−PP⊤)z=∑j>r(vj⊤z)vj(I - PP^\top) z = \sum_{j > r} (v_j^\top z) v_j, and by Parseval its squared norm is ∑j>r(vj⊤z)2\sum_{j > r} (v_j^\top z)^2. Also by Parseval, ∥z∥2=∑j(vj⊤z)2\lVert z \rVert^2 = \sum_j (v_j^\top z)^2. □\square

Theorem 2 (the training mean). With vjv_j the eigenvectors of SS for λj\lambda_j, 1t−1∑sSPE(ys)=∑j>rλj=φ1\frac{1}{t-1} \sum_s \mathrm{SPE}(y_s) = \sum_{j > r} \lambda_j = \varphi_1.

Proof. By Theorem 1, ∑sSPE(ys)=∑j>r∑s(vj⊤zs)2=∑j>rvj⊤(∑szszs⊤)vj=(t−1)∑j>rvj⊤Svj=(t−1)∑j>rλj\sum_s \mathrm{SPE}(y_s) = \sum_{j > r} \sum_s (v_j^\top z_s)^2 = \sum_{j > r} v_j^\top \big(\sum_s z_s z_s^\top\big) v_j = (t - 1) \sum_{j > r} v_j^\top S v_j = (t - 1) \sum_{j > r} \lambda_j. □\square

Lemma 3 (the threshold is well defined). Let λr+1,…,λm≥0\lambda_{r+1}, \ldots, \lambda_m \ge 0 with φ2>0\varphi_2 > 0. Then h0≤1/3h_0 \le 1/3. If h0>0h_0 > 0 and the base BB in line L6 is positive, Q=φ1B1/h0Q = \varphi_1 B^{1/h_0} is positive, and it increases strictly as α\alpha decreases. If φ2=0\varphi_2 = 0, all residual eigenvalues are 0, every training row has SPE 0 by Theorem 2, and the code returns Q=0Q = 0.

Proof. By the Cauchy and Schwarz inequality, φ22=(∑λj1/2λj3/2)2≤φ1φ3\varphi_2^2 = \big(\sum \lambda_j^{1/2} \lambda_j^{3/2}\big)^2 \le \varphi_1 \varphi_3, so 2φ1φ3/(3φ22)≥2/32 \varphi_1 \varphi_3 / (3 \varphi_2^2) \ge 2/3 and h0≤1/3h_0 \le 1/3. As α\alpha decreases, cαc_\alpha increases strictly. The coefficient of cαc_\alpha in BB is 2φ2h02/φ1>0\sqrt{2 \varphi_2 h_0^2} / \varphi_1 > 0, so BB increases strictly, and B↦B1/h0B \mapsto B^{1/h_0} is strictly increasing for B>0B > 0 and h0>0h_0 > 0. □\square

When h0≤0h_0 \le 0 the power 1/h01/h_0 is not a valid transformation, and the code raises an error.

Lemma 4 (equal eigenvalues). If the k=m−rk = m - r residual eigenvalues all equal λ>0\lambda > 0, then Q=kλ(1−29k+cα29k)3Q = k\lambda \big(1 - \frac{2}{9k} + c_\alpha \sqrt{\frac{2}{9k}}\big)^3, which is λ\lambda times the Wilson and Hilferty approximation of the 1−α1 - \alpha quantile of the chi-square distribution with kk degrees of freedom.

Proof. φi=kλi\varphi_i = k \lambda^i, so h0=1−2k2λ4/(3k2λ4)=1/3h_0 = 1 - 2 k^2 \lambda^4 / (3 k^2 \lambda^4) = 1/3. Then cα2φ2h02/φ1=cα2k λ/(3kλ)=cα2/(9k)c_\alpha \sqrt{2 \varphi_2 h_0^2} / \varphi_1 = c_\alpha \sqrt{2 k}\, \lambda / (3 k \lambda) = c_\alpha \sqrt{2/(9k)}, and φ2h0(h0−1)/φ12=kλ2⋅13⋅(−23)/(k2λ2)=−2/(9k)\varphi_2 h_0 (h_0 - 1) / \varphi_1^2 = k \lambda^2 \cdot \frac13 \cdot (-\frac23) / (k^2 \lambda^2) = -2/(9k). The power is 1/h0=31/h_0 = 3. □\square

By Lemma 2 the axes are orthonormal eigenvectors of SS up to the tolerance, by Theorems 1 and 2 line L8 computes the energy of each row on the residual axes and its training mean is φ1\varphi_1, and by Lemmas 3 and 4 line L6 returns a positive threshold that grows as α\alpha shrinks and agrees with the classical chi-square approximation in the case of equal eigenvalues. That this threshold gives a false alarm rate near α\alpha is the approximation of Jackson and Mudholkar for Gaussian data, which this proof does not claim. ■\blacksquare

Complexity

The cost is in the real-RAM model.

  • Mean and covariance. Lines L1 and L2 take Θ(tm2)\Theta(t m^2) time and O(tm+m2)O(t m + m^2) space for the centered copy and SS.
  • Eigenpairs. One Jacobi sweep takes O(m3)O(m^3) time, so ww sweeps take O(wm3)O(w m^3). For a symmetric matrix the number of sweeps is small in practice.
  • Threshold. Lines L5 and L6 take O(m)O(m) time.
  • Test. Line L8 takes O(rm)O(r m) time for each row.

For a network the number of links mm is in the hundreds at most, so the fit is cheap and the test of each new bin is fast.

Properties

  • Network-wide. The method sees all links at once, so it can find an anomaly that is small on each link but breaks the correlation between them.
  • Batch. The axes come from a training window. To follow slow changes, refit on a sliding window.
  • Invariant to the mean. Line L1 removes the mean, so a constant offset on all bins does not change the result.
  • Not invariant to scale. A link with a large load and a large variance dominates the top axes. To give each link the same weight, scale it to unit variance first.
  • Detection only. The SPE says that a bin is unusual. Lakhina et al. also identify the flow that caused it and estimate its size, from the direction of the residual and the routing matrix.

Variants and improvements

  • Hotelling's T2T^2 on the normal subspace. The statistic ∑j≤r(vj⊤z)2/λj\sum_{j \le r} (v_j^\top z)^2 / \lambda_j flags bins that are extreme along the usual patterns, a complement to the SPE.
  • Robust PCA. Robust PCA and robust covariance estimates stop a large anomaly in the training window from pulling an axis toward itself.
  • SVD. The axes can be computed from the singular value decomposition of the centered matrix YY without forming SS, which is more accurate when the eigenvalues span many orders of magnitude.
  • Nonlinear subspaces. Kernel PCA and the autoencoder replace the linear subspace by a curved one, and the reconstruction error plays the role of the SPE.
  • Many features. Later work by Lakhina and coauthors applied the same test to the entropy of packet header fields instead of byte counts.

When to use it

Use it when the features are many correlated measurements of one system, such as the link loads or the flow counts of a network, and the normal behavior lies close to a low-dimensional subspace. It needs a training window that is mostly free of anomalies, and enough rows to estimate an m×mm \times m covariance, so tt should be well above mm. For data with no strong linear correlation, a distance or density method such as the k-NN outlier score is a better fit.

Pitfalls

  • No centering. If line L1 does not subtract the mean, the first axis of line L3 points to the mean, not to the main variation, and the residual subspace is wrong.
  • The wrong number of axes. If rr in line L4 is too small, normal variation stays in the residual and gives false alarms. If it is too large, the anomalies fall into the normal subspace and the SPE misses them. Ringberg et al. (2007) showed that the results are very sensitive to this choice.
  • Polluted training data. A large anomaly in the window of line L2 adds variance in its own direction, so line L3 may give it a normal axis and the method stops seeing anomalies of that kind.
  • A negative h0h_0. When the residual eigenvalues are very spread, for example one large value and many tiny ones, line L5 gives h0≤0h_0 \le 0 and line L6 is not defined. The code raises an error. Use fewer residual axes or a different threshold.
  • Gaussian assumption. Line L6 assumes Gaussian rows. Traffic is heavy-tailed and has daily cycles, so on real data the threshold is a heuristic, and the false alarm rate should be measured on held-out data.
  • Eigenvectors that are not orthonormal. Line L8 subtracts one projection per axis, which is correct only for orthonormal axes. Use a symmetric eigensolver at line L3.

Implementations

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.

pca_subspace_anomaly_detection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pca-subspace-anomaly-detection/. The authors are listed in prov/WTXAPY.jsonl.

import math
from dataclasses import dataclass
from statistics import NormalDist
from typing import Sequence

Matrix = list[list[float]]


def jacobi_eigen(s: Sequence[Sequence[float]], tol: float = 1e-13, max_sweeps: int = 100) -> tuple[list[float], Matrix]:
    """Eigenvalues (in decreasing order) and unit eigenvectors (as columns) of a symmetric matrix.

    Cyclic Jacobi rotations until the off-diagonal mass is below tol times the
    Frobenius norm. Precondition: s is symmetric. Cost: O(m^3) per sweep, and
    a small number of sweeps in practice for m <= 8.
    """
    m = len(s)
    a = [list(map(float, row)) for row in s]
    v = [[1.0 if i == j else 0.0 for j in range(m)] for i in range(m)]
    norm = math.sqrt(sum(x * x for row in a for x in row)) or 1.0
    for _ in range(max_sweeps):
        off = math.sqrt(sum(a[i][j] ** 2 for i in range(m) for j in range(m) if i != j))
        if off <= tol * norm:
            break
        for p in range(m - 1):
            for q in range(p + 1, m):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(m):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(m):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
                for k in range(m):
                    vkp, vkq = v[k][p], v[k][q]
                    v[k][p] = c * vkp - sn * vkq
                    v[k][q] = sn * vkp + c * vkq
    else:
        raise RuntimeError("Jacobi iteration did not converge")
    order = sorted(range(m), key=lambda i: -a[i][i])
    vals = [a[i][i] for i in order]
    vecs = [[v[k][i] for i in order] for k in range(m)]
    return vals, vecs


def q_threshold(residual_eigenvalues: Sequence[float], alpha: float) -> float:
    """Jackson and Mudholkar limit for the squared prediction error at false alarm rate alpha.

    phi_i = sum of lambda_j^i over the residual eigenvalues, h0 = 1 - 2 phi1 phi3 / (3 phi2^2),
    Q = phi1 [c sqrt(2 phi2 h0^2) / phi1 + 1 + phi2 h0 (h0 - 1) / phi1^2]^(1 / h0),
    with c the 1 - alpha quantile of the standard normal. Precondition: 0 < alpha < 1.
    Raises ValueError when h0 <= 0, where the approximation does not apply. Cost: O(m).
    """
    lam = [max(0.0, x) for x in residual_eigenvalues]
    phi1, phi2, phi3 = (sum(x**i for x in lam) for i in (1, 2, 3))
    if phi2 == 0.0:
        return 0.0
    h0 = 1.0 - 2.0 * phi1 * phi3 / (3.0 * phi2 * phi2)  # @line L5
    if h0 <= 0.0:
        raise ValueError("h0 <= 0: the residual eigenvalues are too spread for this approximation")
    c = NormalDist().inv_cdf(1.0 - alpha)
    base = c * math.sqrt(2.0 * phi2 * h0 * h0) / phi1 + 1.0 + phi2 * h0 * (h0 - 1.0) / (phi1 * phi1)
    if base <= 0.0:
        return 0.0
    return phi1 * base ** (1.0 / h0)  # @line L6


@dataclass(frozen=True)
class SubspaceModel:
    mean: tuple[float, ...]
    eigenvalues: tuple[float, ...]
    normal_axes: tuple[tuple[float, ...], ...]
    threshold: float


def fit_subspace(y: Sequence[Sequence[float]], r: int, alpha: float) -> SubspaceModel:
    """Fit the subspace method of Lakhina, Crovella and Diot on the rows of y (time bins by links).

    The normal subspace is spanned by the top r principal axes of the sample
    covariance; the threshold is the Q-statistic at false alarm rate alpha.
    Precondition: t = len(y) >= 2 rows of equal length m >= 1, 0 <= r <= m,
    0 < alpha < 1. Cost: O(t m^2) for the covariance and O(m^3) per Jacobi sweep.
    """
    t = len(y)
    if t < 2 or not 0 <= r <= len(y[0]) or not 0.0 < alpha < 1.0:
        raise ValueError("need t >= 2, 0 <= r <= m and 0 < alpha < 1")
    m = len(y[0])
    mu = [sum(row[j] for row in y) / t for j in range(m)]  # @line L1
    z = [[row[j] - mu[j] for j in range(m)] for row in y]
    s = [[sum(row[i] * row[j] for row in z) / (t - 1) for j in range(m)] for i in range(m)]  # @line L2
    vals, vecs = jacobi_eigen(s)  # @line L3
    axes = tuple(tuple(vecs[k][i] for k in range(m)) for i in range(r))  # @line L4
    q = q_threshold(vals[r:], alpha)
    return SubspaceModel(tuple(mu), tuple(vals), axes, q)


def spe(model: SubspaceModel, row: Sequence[float]) -> float:
    """Squared prediction error |(I - P P^T)(y - mean)|^2 of one row. Cost: O(m r)."""
    z = [v - mu for v, mu in zip(row, model.mean)]
    resid = z[:]
    for axis in model.normal_axes:  # @line L8
        dot = sum(a * b for a, b in zip(axis, z))
        resid = [e - dot * a for e, a in zip(resid, axis)]
    return sum(e * e for e in resid)


def detect(model: SubspaceModel, rows: Sequence[Sequence[float]]) -> list[int]:
    """Indices of the rows whose squared prediction error exceeds the threshold. Cost: O(n m r)."""
    flagged = []
    for idx, row in enumerate(rows):  # @line L7
        if spe(model, row) > model.threshold:  # @line L9
            flagged.append(idx)
    return flagged
test_pca_subspace_anomaly_detection.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/pca-subspace-anomaly-detection/. The authors are listed in prov/WTXAPY.jsonl.

import math
import random
from statistics import NormalDist

import pytest

from pca_subspace_anomaly_detection import detect, fit_subspace, jacobi_eigen, q_threshold, spe

EXAMPLE = [
    (8.2, 7.8, 8.0),
    (12.2, 11.8, 12.0),
    (9.8, 10.2, 10.0),
    (9.8, 10.2, 10.0),
    (9.1, 9.1, 8.8),
    (11.1, 11.1, 10.8),
    (9.9, 9.9, 10.2),
    (9.9, 9.9, 10.2),
]


def random_symmetric(rng, m):
    a = [[0.0] * m for _ in range(m)]
    for i in range(m):
        for j in range(i, m):
            a[i][j] = a[j][i] = rng.choice([rng.uniform(-3, 3), float(rng.randint(-2, 2))])
    return a


def eigen_3x3(a):
    """Closed form eigenvalues of a symmetric 3 x 3 matrix (trigonometric method), decreasing."""
    p1 = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
    q = (a[0][0] + a[1][1] + a[2][2]) / 3
    p2 = sum((a[i][i] - q) ** 2 for i in range(3)) + 2 * p1
    if p2 == 0.0:
        return [q, q, q]
    p = math.sqrt(p2 / 6)
    b = [[(a[i][j] - (q if i == j else 0.0)) / p for j in range(3)] for i in range(3)]
    det = (
        b[0][0] * (b[1][1] * b[2][2] - b[1][2] * b[2][1])
        - b[0][1] * (b[1][0] * b[2][2] - b[1][2] * b[2][0])
        + b[0][2] * (b[1][0] * b[2][1] - b[1][1] * b[2][0])
    )
    phi = math.acos(max(-1.0, min(1.0, det / 2))) / 3
    e1 = q + 2 * p * math.cos(phi)
    e3 = q + 2 * p * math.cos(phi + 2 * math.pi / 3)
    return sorted([e1, 3 * q - e1 - e3, e3], reverse=True)


def test_example() -> None:
    model = fit_subspace(EXAMPLE, 1, 0.01)
    assert model.eigenvalues == pytest.approx([30 / 7, 0.32 / 7, 0.24 / 7], abs=1e-12)
    axis = model.normal_axes[0]
    assert [abs(v) for v in axis] == pytest.approx([1 / math.sqrt(3)] * 3, abs=1e-12)
    assert model.threshold == pytest.approx(0.375936, abs=1e-6)
    assert [round(spe(model, row), 9) for row in EXAMPLE] == [0.08] * 4 + [0.06] * 4
    tests = [(12.0, 12.0, 12.0), (10.0, 11.0, 10.0), (10.3, 10.0, 9.7), (13.0, 13.0, 13.4)]
    assert [spe(model, row) for row in tests] == pytest.approx([0.0, 2 / 3, 0.18, 0.32 / 3], abs=1e-12)
    assert detect(model, tests) == [1]


def test_jacobi_against_independent_checks() -> None:
    rng = random.Random(3)
    for trial in range(600):
        m = rng.randint(1, 6)
        s = random_symmetric(rng, m)
        vals, vecs = jacobi_eigen(s)
        scale = max(1.0, max(abs(x) for row in s for x in row))
        assert all(vals[i] >= vals[i + 1] for i in range(m - 1))
        for i in range(m):
            v = [vecs[k][i] for k in range(m)]
            sv = [sum(s[k][l] * v[l] for l in range(m)) for k in range(m)]
            assert max(abs(sv[k] - vals[i] * v[k]) for k in range(m)) <= 1e-9 * scale
            for j in range(m):
                dot = sum(vecs[k][i] * vecs[k][j] for k in range(m))
                assert abs(dot - (1.0 if i == j else 0.0)) <= 1e-12
        assert math.isclose(sum(vals), sum(s[i][i] for i in range(m)), abs_tol=1e-9 * scale)
        frob = sum(x * x for row in s for x in row)
        assert math.isclose(sum(x * x for x in vals), frob, rel_tol=1e-9, abs_tol=1e-9)
        if m == 3:
            assert vals == pytest.approx(eigen_3x3(s), abs=1e-7 * scale)
        if m == 2:
            mid = (s[0][0] + s[1][1]) / 2
            rad = math.hypot((s[0][0] - s[1][1]) / 2, s[0][1])
            assert vals == pytest.approx([mid + rad, mid - rad], abs=1e-12 * scale)


def test_spe_identities_on_random_data() -> None:
    rng = random.Random(8)
    for _ in range(500):
        m = rng.randint(1, 5)
        t = rng.randint(2, 12)
        y = [[rng.gauss(0, 1) * (j + 1) for j in range(m)] for _ in range(t)]
        r = rng.randint(0, m)
        model = fit_subspace(y, r, 0.05)
        vals, vecs = jacobi_eigen(
            [[sum((row[i] - model.mean[i]) * (row[j] - model.mean[j]) for row in y) / (t - 1) for j in range(m)] for i in range(m)]
        )
        total = 0.0
        for row in y:
            z = [row[j] - model.mean[j] for j in range(m)]
            got = spe(model, row)
            parts = [sum(vecs[k][i] * z[k] for k in range(m)) ** 2 for i in range(m)]
            # Parseval: the error is the energy on the residual axes, and it is at most the full energy.
            assert math.isclose(got, sum(parts[r:]), rel_tol=1e-9, abs_tol=1e-9)
            assert got <= sum(v * v for v in z) + 1e-9
            total += got
        # The mean squared error on the training rows (with t - 1) is the sum of the residual eigenvalues.
        assert math.isclose(total / (t - 1), sum(model.eigenvalues[r:]), rel_tol=1e-9, abs_tol=1e-9)
        if r == m:
            assert model.threshold == 0.0


def test_q_threshold() -> None:
    for k in (1, 2, 5, 10):
        for alpha in (0.1, 0.05, 0.01, 0.001):
            c = NormalDist().inv_cdf(1 - alpha)
            wilson_hilferty = k * 2.0 * (1 - 2 / (9 * k) + c * math.sqrt(2 / (9 * k))) ** 3
            assert math.isclose(q_threshold([2.0] * k, alpha), wilson_hilferty, rel_tol=1e-12)
    # For two equal eigenvalues the exact quantile of lambda times chi square with 2 degrees is -2 lambda ln(alpha).
    # The approximation is within 1% at alpha = 0.05 and 0.01 and within 2.5% at alpha = 0.001.
    for alpha, tol in ((0.05, 0.01), (0.01, 0.01), (0.001, 0.025)):
        assert math.isclose(q_threshold([1.0, 1.0], alpha), -2 * math.log(alpha), rel_tol=tol)
    lam = [1.0, 0.5, 0.2, 0.1]
    qs = [q_threshold(lam, a) for a in (0.2, 0.1, 0.05, 0.01, 0.001)]
    assert all(qs[i] < qs[i + 1] for i in range(len(qs) - 1))
    assert q_threshold([], 0.05) == 0.0 and q_threshold([0.0, 0.0], 0.05) == 0.0
    with pytest.raises(ValueError):
        q_threshold([1.0] + [0.01] * 100, 0.05)


def test_false_alarm_rate_and_injected_anomaly() -> None:
    rng = random.Random(21)
    m = 5
    w = [1.0, -2.0, 0.5, 1.5, -1.0]
    nw = sum(x * x for x in w)
    house = [[(1.0 if i == j else 0.0) - 2 * w[i] * w[j] / nw for j in range(m)] for i in range(m)]
    scales = [5.0, 3.0, 1.0, 0.8, 0.6]

    def sample():
        g = [rng.gauss(0, s) for s in scales]
        return [100.0 + sum(house[i][j] * g[j] for j in range(m)) for i in range(m)]

    model = fit_subspace([sample() for _ in range(3000)], 2, 0.05)
    fresh = [sample() for _ in range(4000)]
    rate = len(detect(model, fresh)) / len(fresh)
    assert 0.035 <= rate <= 0.065
    big_normal = [100.0 + 20 * house[i][0] for i in range(m)]
    residual_spike = [100.0 + 4 * house[i][2] for i in range(m)]
    assert detect(model, [big_normal, residual_spike]) == [1]


def test_bad_input() -> None:
    with pytest.raises(ValueError):
        fit_subspace([(1.0, 2.0)], 1, 0.05)
    with pytest.raises(ValueError):
        fit_subspace(EXAMPLE, 4, 0.05)
    with pytest.raises(ValueError):
        fit_subspace(EXAMPLE, 1, 1.0)
    one_axis = fit_subspace(EXAMPLE, 3, 0.05)
    assert one_axis.threshold == 0.0 and detect(one_axis, [(10.0, 11.0, 10.0)]) == [0]

History

Jackson and Mudholkar (1979) gave the residual test for principal components in statistical process control, where many correlated sensors watch one plant. Lakhina, Crovella and Diot (2004) applied it to the link loads of backbone networks and called it the subspace method. It found volume anomalies that per-link tests missed and could point to the flow that caused them. Ringberg, Soule, Rexford and Diot (2007) showed that the method needs careful tuning of the number of axes and is easily polluted by anomalies in the training data, which led to work on robust versions.

References

  1. Anukool Lakhina, Mark Crovella and Christophe Diot, Diagnosing network-wide traffic anomalies, SIGCOMM 2004, pages 219 to 230, the subspace method, the split into a normal and an anomalous subspace, the squared prediction error and the Q-statistic as the detection threshold
  2. J. Edward Jackson and Govind S. Mudholkar, Control procedures for residuals associated with principal component analysis, Technometrics 21(3), pages 341 to 349, 1979, the approximate distribution of the residual sum of squares and its upper control limit
  3. Haakon Ringberg, Augustin Soule, Jennifer Rexford and Christophe Diot, Sensitivity of PCA for traffic anomaly detection, SIGMETRICS 2007, pages 109 to 120, the sensitivity of the method to the number of normal axes and to anomalies in the training data

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example