Workflow: background and foreground with robust PCA
Put a video in a table, one column per frame: still background is low rank, a moving object sparse. Split them with principal component pursuit, choose the penalty honestly and break the model on purpose.
What runs in CodeSplash
- REP005Robust PCA via principal component pursuit Runs in CodeSplash
- Robust PCA (cell outliers) Verified in Python and R
You will be able to
- Arrange a video as a pixel-by-frame matrix and say why background is low rank
- Write principal component pursuit and its two thresholding steps
- Choose the penalty without tuning on the test video, and say when the pipeline uses labels
- Show where the model fails (a stationary object, a moving camera) and why that isn't a bug
- Run the same low-rank-plus-sparse split on a table in CodeSplash
A video as a table
ReadFlatten each grayscale frame into one long column of pixels and set the columns side by side: a video of frames with pixels each becomes a table .
If the camera is still and the light changes slowly, every background column is nearly a multiple of one background image: the background part of is low rank. A small moving object touches a few pixels per frame, different ones each time: it is sparse. Background subtractionBackground subtractionSeparate what stays (background) from what changes (foreground), for example as low-rank plus sparse parts of a pixel-by-frame table. by robust PCA splits into those two parts.
See how few singular values a low-rank table needs:
AExplorable · Low-rank pictures
How few rank-one layers does it take to rebuild a matrix?
How many rank-one layers will it take to keep 90% of this picture's squared size?
Picture
Each singular value measures one rank-one layer. Keeping the largest k layers gives the best rank-k picture there is (Eckart–Young); the error is the size of the layers you drop.
Commit your prediction above to see the result
Make your prediction to see the result.
Principal component pursuit
ReadRobust PCARobust PCA (principal component pursuit)Splits a table into a low-rank pattern plus a sparse part holding the few cells that break it. by principal component pursuit solves
where sums singular values (favoring low rank) and sums the absolute values of all entries (favoring sparsity). The usual default is .
An ADMM solver repeats two thresholdings: shrink the singular values of to get , then shrink the entries of to get , and update the scaled dual by the leftover. The two are different operations; thresholding entries can't stand in for thresholding singular values.
The whole workflow in code
ExploreA 40-frame, 16 × 20 video: a textured background under slowly changing light (rank one) plus a bright 3 × 3 patch that moves. The code fits PCP, marks pixels whose sparse part is above a fixed threshold, scores them against the known patch by IoU, and repeats with the patch standing still.
import numpy as np
def make_video(moving=True, T=40, H=16, W=20):
yy, xx = np.mgrid[0:H, 0:W]
texture = 0.5 + 0.2 * np.sin(xx / 2.0) * np.cos(yy / 3.0) # still background
D = np.outer(texture.ravel(), 1 + 0.1 * np.sin(np.arange(T) / 6.0)) # pixels x frames
truth = np.zeros_like(D, dtype=bool)
for t in range(T):
r, c = (2 + t % 11, 1 + (t * 2) % 16) if moving else (6, 8)
m = np.zeros((H, W), bool); m[r:r + 3, c:c + 3] = True
D[m.ravel(), t] += 0.5; truth[m.ravel(), t] = True # bright 3x3 patch
return D, truth
def pcp(D, rho=1.0, iters=500):
lam = 1 / np.sqrt(max(D.shape)); S = np.zeros_like(D); U = np.zeros_like(D)
for _ in range(iters):
P, s, Qt = np.linalg.svd(D - S + U, full_matrices=False)
L = (P * np.maximum(s - 1 / rho, 0)) @ Qt # shrink singular values
A = D - L + U
S = np.sign(A) * np.maximum(np.abs(A) - lam / rho, 0) # shrink entries
U = U + D - L - S
return L, S
for moving in (True, False):
D, truth = make_video(moving)
L, S = pcp(D)
pred = np.abs(S) > 0.12 # fixed in advance
print("moving" if moving else "stationary",
"IoU", round((pred & truth).sum() / (pred | truth).sum(), 3),
"rank of L", int(np.sum(np.linalg.svd(L, compute_uv=False) > 1e-4)))make_video <- function(moving = TRUE, Tn = 40, H = 16, W = 20) {
texture <- outer(0:(H - 1), 0:(W - 1), function(y, x) 0.5 + 0.2 * sin(x / 2) * cos(y / 3))
D <- outer(as.vector(t(texture)), 1 + 0.1 * sin((0:(Tn - 1)) / 6)) # pixels x frames
truth <- matrix(FALSE, nrow(D), Tn)
for (t in 0:(Tn - 1)) {
rc <- if (moving) c(2 + t %% 11, 1 + (t * 2) %% 16) else c(6, 8)
m <- matrix(FALSE, H, W); m[rc[1] + 1:3, rc[2] + 1:3] <- TRUE
idx <- which(as.vector(t(m))) # row-major, as numpy
D[idx, t + 1] <- D[idx, t + 1] + 0.5; truth[idx, t + 1] <- TRUE
}
list(D = D, truth = truth)
}
pcp <- function(D, rho = 1, iters = 500) {
lam <- 1 / sqrt(max(dim(D))); S <- U <- matrix(0, nrow(D), ncol(D))
for (i in 1:iters) {
s <- svd(D - S + U)
L <- s$u %*% (pmax(s$d - 1 / rho, 0) * t(s$v)) # shrink singular values
A <- D - L + U
S <- sign(A) * pmax(abs(A) - lam / rho, 0) # shrink entries
U <- U + D - L - S
}
list(L = L, S = S)
}
for (moving in c(TRUE, FALSE)) {
v <- make_video(moving); f <- pcp(v$D)
pred <- abs(f$S) > 0.12 # fixed in advance
cat(if (moving) "moving" else "stationary",
"IoU", round(sum(pred & v$truth) / sum(pred | v$truth), 3),
"rank of L", sum(svd(f$L)$d > 1e-4), "\n")
}Notebook exercise · ~15 min
Split a scene into background and motion
Separate a synthetic clip into a low-rank background and a sparse moving object with robust PCA, then count what it finds and what it wrongly flags.
- How simple is the background?
Store the rank of
L, counted as the number of its singular values above 0.1 times the largest, inrank_L.Show a solution
Pythons = np.linalg.svd(L, compute_uv=False) rank_L = int(np.sum(s > 0.1 * s[0]))Rs <- svd(L)$d rank_L <- sum(s > 0.1 * s[1]) - Does it find the moving square?
Call a pixel "moving" when |S| > 0.5. Store the share of the true object pixels (
obj) that are flagged as moving inrecall.Show a solution
Pythonrecall = np.mean(np.abs(S[obj]) > 0.5)Rrecall <- mean(abs(S[obj]) > 0.5) - What it flags by mistake
Store the share of the background pixels (where
objis false) flagged as moving infalse_rate.Show a solution
Pythonfalse_rate = np.mean(np.abs(S[~obj]) > 0.5)Rfalse_rate <- mean(abs(S[!obj]) > 0.5)
In the app this opens as a Python or R notebook with the sample data, and its checks mark your progress.
The object stops
PredictPredict first
In the second run, the bright patch sits in the same place in every frame. What does PCP do with it?
Reveal
It joins the background. A patch that never moves is the same in every column, so it is low rank, and the background grows by one rank to hold it. The sparse part, and so the foreground mask, finds nothing. The solver did its job; the model can't tell a parked car from the road.
The same split in CodeSplash
ExploreRobust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.
- Low-rank part: rank
- 3
- Flagged cells
- 15
- Rows with a flagged cell
- 13
Plots
View data
| Component | Cumulative | Share of the low-rank part |
|---|---|---|
| 1 | 0.6409 | 0.6409 |
| 2 | 0.9990 | 0.3581 |
| 3 | 1 | 0.0010 |
View data
| Variable |
|---|
| m7 |
| m5 |
| m6 |
| m5 |
| m3 |
| m8 |
| m1 |
| m7 |
| m4 |
| m7 |
| m5 |
| m2 |
| m2 |
| m4 |
| m7 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | LC1 | LC2 |
|---|---|---|---|
| point | −0.7602 | −1.207 | |
| point | −1.268 | −1.359 | |
| point | −1.221 | 1.296 | |
| point | 0.4132 | 0.6085 | |
| point | −0.7191 | 0.1055 | |
| point | 0.0730 | 3.376 | |
| point | 1.419 | −1.365 | |
| point | −1.014 | 1.045 | |
| point | −2.697 | 0.5859 | |
| point | −1.438 | −0.1922 | |
| point | −0.3792 | 0.0315 | |
| point | 2.499 | 0.4489 | |
| point | 2.816 | −1.192 | |
| point | 0.6784 | 1.071 | |
| point | −3.345 | −1.156 | |
| point | 0.7233 | 1.959 | |
| point | 3.072 | −1.039 | |
| point | 0.2222 | 1.615 | |
| point | 0.5783 | 0.4367 | |
| point | 4.752 | −1.475 | |
| point | 0.8547 | 3.544 | |
| point | 1.781 | 0.8524 | |
| point | 0.9886 | −0.5187 | |
| point | 0.3578 | −0.6322 | |
| point | −0.1366 | −0.1460 | |
| point | −0.5690 | 2.226 | |
| point | −3.680 | 2.066 | |
| point | 3.102 | −2.976 | |
| point | −1.620 | 1.076 | |
| point | −0.9975 | −0.0467 | |
| point | 3.430 | 3.129 | |
| point | −1.301 | −0.4393 | |
| point | 1.566 | −1.441 | |
| point | 2.494 | −0.5314 | |
| point | −1.282 | −1.388 | |
| point | −0.0822 | −0.9451 | |
| point | −0.7235 | −0.5301 | |
| point | 0.3745 | −0.2345 | |
| point | 3.858 | −2.766 | |
| point | 2.440 | −1.008 | |
| point | 1.806 | −1.423 | |
| point | 0.2946 | 0.7111 | |
| point | 0.1773 | −2.442 | |
| point | −1.038 | −2.088 | |
| point | −4.860 | −0.6180 | |
| point | −0.1745 | −0.4724 | |
| point | −2.805 | −2.993 | |
| point | 0.1934 | 1.160 | |
| point | −1.292 | 2.082 | |
| point | 2.665 | 0.6096 | |
| point | −0.9358 | 1.994 | |
| point | −2.314 | −1.440 | |
| point | 0.8071 | −1.222 | |
| point | −4.393 | −0.7417 | |
| point | 1.709 | −2.261 | |
| point | 1.155 | 1.419 | |
| point | −0.1952 | 2.301 | |
| point | 3.966 | 1.389 | |
| point | −1.903 | −0.8208 | |
| point | 2.057 | 0.3706 |
First 60 of 128 rows.
Flagged cells (sparse part beyond 2 scaled units)
| Row | Variable | Value | Low-rank fit | Sparse part |
|---|---|---|---|---|
| 75 | m4 | 7.540 | 0.7269 | 6.813 |
| 111 | m4 | 6.832 | 0.6736 | 6.158 |
| 103 | m2 | 6.827 | −0.7571 | 7.584 |
| 99 | m2 | 7.555 | 0.0238 | 7.531 |
| 19 | m5 | 7.974 | 0.5421 | 7.432 |
| 19 | m6 | 5.648 | −0.4970 | 6.145 |
| 98 | m5 | −7.087 | −0.1626 | −6.925 |
| 31 | m5 | 8.997 | 2.265 | 6.732 |
| 77 | m7 | 8.675 | 0.5876 | 8.087 |
| 42 | m3 | 8.707 | 0.1939 | 8.513 |
| 72 | m1 | −6.394 | 0.0434 | −6.438 |
| 9 | m7 | −7.063 | −0.1119 | −6.951 |
| 72 | m7 | −7.084 | −0.5234 | −6.561 |
| 115 | m7 | 5.609 | −0.5466 | 6.155 |
| 51 | m8 | −11.312 | −2.556 | −8.756 |
Flagged cells by variable
| Variable | Flagged cells | Share of rows | Center | Scale |
|---|---|---|---|---|
| m1 | 1 | 0.8% | 0.2471 | 1.345 |
| m2 | 2 | 1.7% | 0.0802 | 0.8986 |
| m3 | 1 | 0.8% | 0.1645 | 1.752 |
| m4 | 2 | 1.7% | −0.0151 | 0.4654 |
| m5 | 3 | 2.5% | 0.2388 | 1.199 |
| m6 | 1 | 0.8% | −0.2309 | 1.011 |
| m7 | 4 | 3.3% | −0.0689 | 1.617 |
| m8 | 1 | 0.8% | −0.5964 | 3.408 |
Loadings of the low-rank part
| Variable | LC1 | LC2 |
|---|---|---|
| m1 | 0.4491 | 0.1197 |
| m2 | −0.2852 | 0.4072 |
| m3 | 0.4501 | −0.2007 |
| m4 | −0.1894 | 0.5481 |
| m5 | 0.4593 | 0.0342 |
| m6 | −0.4223 | −0.1572 |
| m7 | −0.1095 | −0.5254 |
| m8 | −0.2779 | −0.4210 |
- Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.
The exact R script · R R version 4.5.1 (2025-06-13)
# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))
# %% Data
FEATURES <- c("m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8")
LABEL <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
cs_check_finite_columns(df, FEATURES)
rows <- cs_ml_complete_rows(df, FEATURES)
if (length(rows) < n_input) {
warnings <- c(warnings, sprintf("%d of %d rows were left out because a value was missing.", n_input - length(rows), n_input))
}
cs_check_rows(length(rows), 3, "Robust PCA")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
rc <- cs_rep_robust_center_scale(X, "robust")
Zs <- rc$Z; center <- rc$center; scale <- rc$scale
if (!any(Zs != 0)) cs_error("CS_E_CONSTANT", column = FEATURES[1])
n <- nrow(Zs); p <- ncol(Zs)
LAM <- NULL
lam <- if (is.null(LAM)) 1 / sqrt(max(n, p)) else as.numeric(LAM)
fit <- cs_rep_robust_pca(Zs, lam)
L <- fit$L; S <- fit$S; rank <- fit$rank
if (!fit$converged) warnings <- c(warnings, "Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG <- as.numeric(2)
flagged <- abs(S) > FLAG
n_flagged <- sum(flagged)
rows_flagged <- sum(rowSums(flagged) > 0)
total_ss <- sum(Zs * Zs)
sparse_share <- sum(S * S) / total_ss
# low-rank part: its own principal axes give the map
sv <- svd(L)
k <- min(as.integer(2), rank)
if (k > 0) {
signs <- cs_ml_canonical_signs(sv$v[, seq_len(k), drop = FALSE])
loadings <- sweep(sv$v[, seq_len(k), drop = FALSE], 2, signs, "*")
scores <- sweep(sv$u[, seq_len(k), drop = FALSE], 2, sv$d[seq_len(k)] * signs, "*")
} else {
loadings <- matrix(0, p, 0); scores <- matrix(0, n, 0)
}
lr_ss <- sum(sv$d[seq_len(rank)]^2)
lr_prop <- if (rank > 0) sv$d[seq_len(rank)]^2 / lr_ss else numeric(0)
if (rank == 0) warnings <- c(warnings, "The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(k)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
w <- which(flagged, arr.ind = TRUE)
fi <- unname(w[, 1]); fj <- unname(w[, 2])
ord <- order(-abs(S[cbind(fi, fj)]), fi, fj) # largest sparse part first; ties by row, then column
fi <- fi[ord]; fj <- fj[ord]
cells <- data.frame(row = as.integer(rows[fi]), column = FEATURES[fj], value = X[cbind(fi, fj)],
fitted = L[cbind(fi, fj)] * scale[fj] + center[fj], sparse = S[cbind(fi, fj)] * scale[fj],
stringsAsFactors = FALSE)
nanoparquet::write_parquet(cells, file.path(out, "cells.parquet"))
# %% Result
values <- list(n = n, n_variables = p, rank = rank, lambda = lam, n_flagged = n_flagged,
flagged_share = n_flagged / (n * p), rows_flagged = rows_flagged, sparse_share = sparse_share,
n_components = k)
per_var <- colSums(flagged)
for (i in seq_along(FEATURES)) values[[sprintf("flagged[%s]", FEATURES[i])]] <- per_var[i]
for (j in seq_len(rank)) values[[sprintf("lowrank_prop[%d]", j)]] <- lr_prop[j]
for (j in seq_len(k)) {
values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- loadings[i, j]
}
top <- min(nrow(cells), 50L)
tables <- list(
list(key = "cells",
title = sprintf("Flagged cells (sparse part beyond %s scaled units)%s", format(FLAG), if (top == nrow(cells)) "" else sprintf(", largest %d of %d", top, nrow(cells))),
columns = list(list(key = "row", label = "Row", type = "integer"),
list(key = "variable", label = "Variable"),
list(key = "value", label = "Value", type = "number"),
list(key = "fitted", label = "Low-rank fit", type = "number"),
list(key = "sparse", label = "Sparse part", type = "number")),
rows = lapply(seq_len(top), function(i) list(row = cells$row[i] + 1L, variable = cells$column[i], value = cells$value[i],
fitted = cells$fitted[i], sparse = cells$sparse[i]))),
list(key = "variables", title = "Flagged cells by variable",
columns = list(list(key = "variable", label = "Variable"),
list(key = "flagged", label = "Flagged cells", type = "integer"),
list(key = "share", label = "Share of rows", type = "percent"),
list(key = "center", label = "Center", type = "number"),
list(key = "scale", label = "Scale", type = "number")),
rows = lapply(seq_along(FEATURES), function(i) list(variable = FEATURES[i], flagged = per_var[[i]], share = per_var[[i]] / n,
center = center[i], scale = scale[i])))
)
if (k > 0) {
tables[[3]] <- list(key = "loadings", title = "Loadings of the low-rank part",
columns = c(list(list(key = "variable", label = "Variable")),
lapply(seq_len(k), function(j) list(key = paste0("lc", j), label = paste0("LC", j), type = "number"))),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(k)) r[[paste0("lc", j)]] <- loadings[i, j]
r
}))
}
charts <- list()
if (rank > 0) {
charts[[length(charts) + 1L]] <- cs_chart("scree", "scree-plot", "Low-rank part: variation by component", list(
component = cs_col("Component", seq_len(rank), "numeric"),
variance = cs_col("Share of the low-rank part", lr_prop, "numeric"),
cumulative = cs_col("Cumulative", cumsum(lr_prop), "numeric")
))
}
if (n_flagged > 0) {
wr <- which(flagged, arr.ind = TRUE)
wr <- wr[order(wr[, 1], wr[, 2]), , drop = FALSE] # row by row, like numpy's nonzero
charts[[length(charts) + 1L]] <- cs_chart("flagged", "bar", "Flagged cells by variable", list(
x = cs_col("Variable", FEATURES[wr[, 2]], "categorical", levels = FEATURES)
))
}
if (k >= 2) {
pick <- chart_rows(n)
lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
lab[is.na(lab)] <- ""
reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
charts[[length(charts) + 1L]] <- cs_chart("biplot", "biplot", "Biplot of the low-rank part (LC1 × LC2)", list(
x = cs_col("LC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
y = cs_col("LC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", p)), "categorical"),
label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
title = "Robust PCA (cell outliers)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("Robust PCA split the data into a rank-%d part and a sparse part; %d of %d cells (%.1f%%) are flagged.",
rank, n_flagged, n * p, 100 * n_flagged / (n * p)),
statistics = list(list(key = "rank", label = "Low-rank part: rank", value = rank, format = "integer"),
list(key = "n_flagged", label = "Flagged cells", value = n_flagged, format = "integer"),
list(key = "rows_flagged", label = "Rows with a flagged cell", value = rows_flagged, format = "integer")),
notes = list("Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"),
list(key = "cells", path = file.path(out, "cells.parquet"), format = "parquet"))
))
Robust PCA split the data into a rank-3 part and a sparse part; 15 of 960 cells (1.6%) are flagged.
- Low-rank part: rank
- 3
- Flagged cells
- 15
- Rows with a flagged cell
- 13
To keep this page light, the plots are shown once, under the R tab.
Flagged cells (sparse part beyond 2 scaled units)
| Row | Variable | Value | Low-rank fit | Sparse part |
|---|---|---|---|---|
| 75 | m4 | 7.540 | 0.7269 | 6.813 |
| 111 | m4 | 6.832 | 0.6736 | 6.158 |
| 103 | m2 | 6.827 | −0.7571 | 7.584 |
| 99 | m2 | 7.555 | 0.0238 | 7.531 |
| 19 | m5 | 7.974 | 0.5421 | 7.432 |
| 19 | m6 | 5.648 | −0.4970 | 6.145 |
| 98 | m5 | −7.087 | −0.1626 | −6.925 |
| 31 | m5 | 8.997 | 2.265 | 6.732 |
| 77 | m7 | 8.675 | 0.5876 | 8.087 |
| 42 | m3 | 8.707 | 0.1939 | 8.513 |
| 72 | m1 | −6.394 | 0.0434 | −6.438 |
| 9 | m7 | −7.063 | −0.1119 | −6.951 |
| 72 | m7 | −7.084 | −0.5234 | −6.561 |
| 115 | m7 | 5.609 | −0.5466 | 6.155 |
| 51 | m8 | −11.312 | −2.556 | −8.756 |
Flagged cells by variable
| Variable | Flagged cells | Share of rows | Center | Scale |
|---|---|---|---|---|
| m1 | 1 | 0.8% | 0.2471 | 1.345 |
| m2 | 2 | 1.7% | 0.0802 | 0.8986 |
| m3 | 1 | 0.8% | 0.1645 | 1.752 |
| m4 | 2 | 1.7% | −0.0151 | 0.4654 |
| m5 | 3 | 2.5% | 0.2388 | 1.199 |
| m6 | 1 | 0.8% | −0.2309 | 1.011 |
| m7 | 4 | 3.3% | −0.0689 | 1.617 |
| m8 | 1 | 0.8% | −0.5964 | 3.408 |
Loadings of the low-rank part
| Variable | LC1 | LC2 |
|---|---|---|
| m1 | 0.4491 | 0.1197 |
| m2 | −0.2852 | 0.4072 |
| m3 | 0.4501 | −0.2007 |
| m4 | −0.1894 | 0.5481 |
| m5 | 0.4593 | 0.0342 |
| m6 | −0.4223 | −0.1572 |
| m7 | −0.1095 | −0.5254 |
| m8 | −0.2779 | −0.4210 |
- Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Robust PCA (cell outliers)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.robust_pca 1.0.0 · spec 63c7f51a131dcaad
# Dataset: rep1_lowrank (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import os
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl
def chart_rows(n, cap=2000):
return np.arange(n) if n <= cap else np.unique(np.linspace(0, n - 1, cap).round().astype(int))
# %% Data
FEATURES = ["m1", "m2", "m3", "m4", "m5", "m6", "m7", "m8"]
LABEL = None
df = pd.read_parquet("tests/parity/fixtures/rep1_lowrank.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
cs.check_finite_columns(df, FEATURES)
rows = csembed.complete_rows(df, FEATURES)
if len(rows) < n_input:
warnings.append(f"{n_input - len(rows)} of {n_input} rows were left out because a value was missing.")
cs.check_rows(len(rows), 3, "Robust PCA")
X = csembed.numeric_matrix(df, FEATURES, rows)
# %% Principal component pursuit (ADMM to primal and dual tolerance): low-rank part L + sparse part S = scaled data
Zs, center, scale = rl.robust_center_scale(X, "robust")
if not np.any(Zs != 0):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
n, p = Zs.shape
LAM = None
lam = 1.0 / np.sqrt(max(n, p)) if LAM is None else float(LAM)
L, S, rank, iterations, converged = rl.robust_pca(Zs, lam)
if not converged:
warnings.append("Principal component pursuit stopped after 10,000 iterations before reaching its tolerance; treat the split as approximate.")
FLAG = float(2)
flagged = np.abs(S) > FLAG
n_flagged = int(np.sum(flagged))
rows_flagged = int(np.sum(flagged.any(axis=1)))
total_ss = float(np.sum(Zs * Zs))
sparse_share = float(np.sum(S * S)) / total_ss
# low-rank part: its own principal axes give the map
U, sv, Vt = np.linalg.svd(L, full_matrices=False)
k = min(int(2), rank)
signs = csembed.canonical_signs(Vt[:k].T) if k else np.ones(0)
loadings = Vt[:k].T * signs
scores = U[:, :k] * sv[:k] * signs
lr_ss = float(np.sum(sv[:rank] ** 2))
lr_prop = sv[:rank] ** 2 / lr_ss if rank else np.zeros(0)
if rank == 0:
warnings.append("The low-rank part is empty: λ is so small that the sparse part takes everything. Raise λ.")
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-93840/discover.robust_pca/planted_cells/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(k):
emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
fi, fj = np.nonzero(flagged)
size = np.abs(S[fi, fj])
order = np.lexsort((fj, fi, -size)) # largest sparse part first; ties by row, then column
fi, fj = fi[order], fj[order]
cells = pd.DataFrame({
"row": rows[fi].astype(np.int64),
"column": [FEATURES[j] for j in fj],
"value": X[fi, fj],
"fitted": L[fi, fj] * scale[fj] + center[fj],
"sparse": S[fi, fj] * scale[fj],
})
cells.to_parquet(os.path.join(out, "cells.parquet"), index=False)
# %% Result
values = {
"n": n,
"n_variables": p,
"rank": int(rank),
"lambda": lam,
"n_flagged": n_flagged,
"flagged_share": n_flagged / (n * p),
"rows_flagged": rows_flagged,
"sparse_share": sparse_share,
"n_components": k,
}
per_var = flagged.sum(axis=0)
for i, f in enumerate(FEATURES):
values[f"flagged[{f}]"] = int(per_var[i])
for j in range(rank):
values[f"lowrank_prop[{j + 1}]"] = float(lr_prop[j])
for j in range(k):
values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
for i, f in enumerate(FEATURES):
values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
top = min(len(cells), 50)
tables = [
{
"key": "cells",
"title": f"Flagged cells (sparse part beyond {FLAG:g} scaled units){'' if top == len(cells) else f', largest {top} of {len(cells)}'}",
"columns": [
{"key": "row", "label": "Row", "type": "integer"},
{"key": "variable", "label": "Variable"},
{"key": "value", "label": "Value", "type": "number"},
{"key": "fitted", "label": "Low-rank fit", "type": "number"},
{"key": "sparse", "label": "Sparse part", "type": "number"},
],
"rows": [
{"row": int(cells["row"].iloc[i]) + 1, "variable": cells["column"].iloc[i], "value": float(cells["value"].iloc[i]),
"fitted": float(cells["fitted"].iloc[i]), "sparse": float(cells["sparse"].iloc[i])}
for i in range(top)
],
},
{
"key": "variables",
"title": "Flagged cells by variable",
"columns": [
{"key": "variable", "label": "Variable"},
{"key": "flagged", "label": "Flagged cells", "type": "integer"},
{"key": "share", "label": "Share of rows", "type": "percent"},
{"key": "center", "label": "Center", "type": "number"},
{"key": "scale", "label": "Scale", "type": "number"},
],
"rows": [{"variable": f, "flagged": int(per_var[i]), "share": float(per_var[i]) / n, "center": float(center[i]), "scale": float(scale[i])} for i, f in enumerate(FEATURES)],
},
]
if k:
tables.append({
"key": "loadings",
"title": "Loadings of the low-rank part",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"lc{j + 1}", "label": f"LC{j + 1}", "type": "number"} for j in range(k)],
"rows": [dict({"variable": f}, **{f"lc{j + 1}": loadings[i, j] for j in range(k)}) for i, f in enumerate(FEATURES)],
})
charts = []
if rank:
charts.append(cs.chart(
"scree",
"scree-plot",
"Low-rank part: variation by component",
{
"component": cs.col("Component", list(range(1, rank + 1)), "numeric"),
"variance": cs.col("Share of the low-rank part", lr_prop, "numeric"),
"cumulative": cs.col("Cumulative", np.cumsum(lr_prop), "numeric"),
},
))
if n_flagged:
charts.append(cs.chart(
"flagged",
"bar",
"Flagged cells by variable",
{"x": cs.col("Variable", [FEATURES[j] for j in np.nonzero(flagged)[1]], "categorical", levels=FEATURES)},
))
if k >= 2:
pick = chart_rows(n)
lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
charts.append(cs.chart(
"biplot",
"biplot",
"Biplot of the low-rank part (LC1 × LC2)",
{
"x": cs.col("LC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
"y": cs.col("LC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
"kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * p, "categorical"),
"label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
},
note="Loading arrows are rescaled to the score range.",
))
cs.publish(
{
"title": "Robust PCA (cell outliers)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": f"Robust PCA split the data into a rank-{rank} part and a sparse part; {n_flagged} of {n * p} cells ({n_flagged / (n * p):.1%}) are flagged.",
"statistics": [
{"key": "rank", "label": "Low-rank part: rank", "value": int(rank), "format": "integer"},
{"key": "n_flagged", "label": "Flagged cells", "value": n_flagged, "format": "integer"},
{"key": "rows_flagged", "label": "Rows with a flagged cell", "value": rows_flagged, "format": "integer"},
],
"notes": ["Robust PCA flags single cells, not whole rows: a row is unusual only when many of its cells are flagged."],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [
{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"},
{"key": "cells", "path": os.path.join(out, "cells.parquet"), "format": "parquet"},
],
}
)
Robust PCA (cell outliers) runs this same convex problem on any numeric table, in Python and R. Here a table of 120 rows and 8 columns splits into a rank-3 pattern and a sparse part, with the default penalty 0.0913. It flagged 15 cells, 1.6% of the table.
A pixel-by-frame table is the same shape of problem: rows are pixels, columns are frames.
Choosing the penalty honestly
ReadThe decomposition uses only the video. Choosing or the mask threshold by checking IoU against labeled frames does use labels, so the pipeline isn't label-free. That's fine if you say so and keep it clean:
- tune on a development video, never on the test video;
- lock the penalty and the threshold before touching the test and stress videos;
- if several penalties tie on development data, the data can't tell them apart; that's not evidence the default is best everywhere.
Compare against a baseline: plain rank-one SVD, whose leftover holds both the object and any background it missed.
Ways it breaks
Read- A stationary object becomes background (the run above).
- A moving camera shifts every pixel, so the "background" is no longer low rank: its rank climbs and background leaks into the foreground.
- Dense noise in every pixel isn't sparse; stable PCP adds a separate noise term .
- Large objects stop being sparse.
- Per-frame contrast normalization changes the model; don't slip it into preprocessing without testing.
Synthetic success here is a demonstration of the method, not evidence about real surveillance footage.
What runs here
Read| Entry | In CodeSplash |
|---|---|
| REP005 · Robust PCA via principal component pursuit | Runs in CodeSplash: Robust PCA (cell outliers), on any numeric table |
Check: the RPCA workflow
CheckpointCheck yourself
Why is a still camera's background low rank in a pixel-by-frame table?
Show the answer
Answer: a
Columns that are scaled copies of one image span a one-dimensional space; slow lighting changes only scale them.
Check yourself
In the ADMM solver, which step produces the low-rank part?
Show the answer
Answer: b
Singular-value thresholding handles the nuclear norm; entry-wise soft thresholding handles the sparse part.
Check yourself
You pick λ by maximizing foreground IoU on labeled frames of the test video. What's wrong?
Show the answer
Answer: b
The decomposition is label-free; your selection step isn't. Keep it off the test data.
Check yourself
The camera pans slowly during the video. What happens to the low-rank picture?
Show the answer
Answer: b
Camera motion breaks the still-background assumption; align frames first or use a model that allows motion.
Check yourself
Rank-one SVD rebuilds the video exactly as low-rank part plus residual. Does that make it a good separator?
Show the answer
Answer: b
Exact reconstruction holds by construction. Separation quality is about what lands in each part.
Recap
Recap- A video as a pixel-by-frame table: still background is low rank, a moving object is sparse.
- PCP minimizes nuclear norm plus λ times the entry-wise sparse norm; ADMM alternates two thresholdings.
- Tune λ and the mask threshold on a development video; the pipeline then uses labels.
- Stationary objects, camera motion, dense noise and large objects break the model.
- The same split runs on tables in CodeSplash as Robust PCA (cell outliers).
Concepts in this lesson