Score anomalies with a tied-weight autoencoder's reconstruction error

Why it matters Reconstruction-error anomaly detection is used for fraud, machine sensor faults and log monitoring.

An autoencoder trained on normal data rebuilds normal inputs well and odd inputs badly, so reconstruction error is an anomaly score.

Write ae_scores(X, W, b_enc, b_dec, threshold). X is (n, d), W is (d, k) and is shared by encoder and decoder (tied weights). Encode h = relu(X @ W + b_enc), decode X_hat = h @ W.T + b_dec. The score of each row is the mean squared error over its d features. Return (scores (n,) float array, flags (n,) boolean array of scores > threshold).

Signaturedef ae_scores(X, W, b_enc, b_dec, threshold)

Example

X = [[1, 1], [3, -3]], W = [[0.7071], [0.7071]], b_enc = [0], b_dec = [0, 0], threshold = 1 gives scores about [0, 9] and flags [False, True].

Understand the idea

An autoencoder squeezes each input into a short code and then tries to rebuild it. Trained on normal data, it learns the usual patterns, so it rebuilds normal inputs well. A strange input does not fit those patterns and comes back distorted, like a photocopier tuned for text that smears a photo.

Tiny example: the code is the projection onto the direction [1, 1] / sqrt(2). The point [1, 1] lies on that direction: code 1.414, rebuilt as [1, 1], error 0. The point [3, -3] is at right angles to it: code 0, rebuilt as [0, 0], error (9 + 9) / 2 = 9. It gets flagged.

Rules: h = relu(X W + b_enc); X_hat = h W^T + b_dec; score = mean((X - X_hat)^2) per row.

Anomaly detectors on sensor data and card transactions often start from this score.

Shapes and data flow

X (n,d) @ W (d,k) -> h (n,k) @ W^T (k,d) -> X_hat (n,d) -> scores (n,)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: exampleae_scores([[1.0, 1.0], [3.0, -3.0]], [[0.7071], [0.7071]], [0.0], [0.0, 0.0], 1.0)
  • Sample 2: three rowsae_scores([[1.0, 0.0, 1.0], [0.5, 0.5, 0.0], [-2.0, 4.0, 1.0]], [[0.5, 0.0], [0.0, 1.0], [0.5, 0.0]], [0.0,...
  • Test 3: bias onlyae_scores([[2.0, 2.0]], [[1.0], [0.0]], [-5.0], [2.0, 1.0], 0.1)