Skip to content

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.

Applied ~18 min10 steps

What runs in CodeSplash

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

Read first

01

A video as a table

Read

Flatten each grayscale frame into one long column of pixels and set the columns side by side: a video of TT frames with PP pixels each becomes a P×TP \times T table DD.

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 DD 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 DD 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?

11
How sure?

Picture

2
0.10
OriginalRank 2What's left

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 first; the figure appears when you commit.

Make your prediction to see the result.

02

Principal component pursuit

Read

Robust 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

min⁡L,S ∥L∥∗+λ∥S∥1subject toD=L+S,\min_{L, S}\ \lVert L \rVert_\ast + \lambda \lVert S \rVert_1 \quad \text{subject to}\quad D = L + S,

where ∥L∥∗\lVert L \rVert_\ast sums singular values (favoring low rank) and ∥S∥1\lVert S \rVert_1 sums the absolute values of all entries (favoring sparsity). The usual default is λ=1/max⁡(P,T)\lambda = 1/\sqrt{\max(P, T)}.

An ADMM solver repeats two thresholdings: shrink the singular values of D−S+UD - S + U to get LL, then shrink the entries of D−L+UD - L + U to get SS, and update the scaled dual UU by the leftover. The two are different operations; thresholding entries can't stand in for thresholding singular values.

03

The whole workflow in code

Explore

A 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.

Python
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)))
R
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.

  1. How simple is the background?

    Store the rank of L, counted as the number of its singular values above 0.1 times the largest, in rank_L.

    Show a solution
    Python
    s = np.linalg.svd(L, compute_uv=False)
    rank_L = int(np.sum(s > 0.1 * s[0]))
    R
    s <- svd(L)$d
    rank_L <- sum(s > 0.1 * s[1])
  2. 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 in recall.

    Show a solution
    Python
    recall = np.mean(np.abs(S[obj]) > 0.5)
    R
    recall <- mean(abs(S[obj]) > 0.5)
  3. What it flags by mistake

    Store the share of the background pixels (where obj is false) flagged as moving in false_rate.

    Show a solution
    Python
    false_rate = np.mean(np.abs(S[~obj]) > 0.5)
    R
    false_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.

04

The object stops

Predict

Predict first

In the second run, the bright patch sits in the same place in every frame. What does PCP do with it?

It is found as foreground, as beforeIt joins the background, and the foreground mask finds nothingThe solver fails to converge
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.

05

The same split in CodeSplash

Explore
Robust PCA (cell outliers)Recorded · Python and R agreeRecorded 2026-11-21 · 38 values compared
R

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

Plots

Low-rank part: variation by componentHow many components carry most of the variance?
View data
ComponentCumulativeShare of the low-rank part
10.64090.6409
20.99900.3581
310.0010
Flagged cells by variableHow often does each category occur?
View data
Variable
m7
m5
m6
m5
m3
m8
m1
m7
m4
m7
m5
m2
m2
m4
m7
Biplot of the low-rank part (LC1 × LC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range.

View data
KindLabelLC1LC2
point−0.7602−1.207
point−1.268−1.359
point−1.2211.296
point0.41320.6085
point−0.71910.1055
point0.07303.376
point1.419−1.365
point−1.0141.045
point−2.6970.5859
point−1.438−0.1922
point−0.37920.0315
point2.4990.4489
point2.816−1.192
point0.67841.071
point−3.345−1.156
point0.72331.959
point3.072−1.039
point0.22221.615
point0.57830.4367
point4.752−1.475
point0.85473.544
point1.7810.8524
point0.9886−0.5187
point0.3578−0.6322
point−0.1366−0.1460
point−0.56902.226
point−3.6802.066
point3.102−2.976
point−1.6201.076
point−0.9975−0.0467
point3.4303.129
point−1.301−0.4393
point1.566−1.441
point2.494−0.5314
point−1.282−1.388
point−0.0822−0.9451
point−0.7235−0.5301
point0.3745−0.2345
point3.858−2.766
point2.440−1.008
point1.806−1.423
point0.29460.7111
point0.1773−2.442
point−1.038−2.088
point−4.860−0.6180
point−0.1745−0.4724
point−2.805−2.993
point0.19341.160
point−1.2922.082
point2.6650.6096
point−0.93581.994
point−2.314−1.440
point0.8071−1.222
point−4.393−0.7417
point1.709−2.261
point1.1551.419
point−0.19522.301
point3.9661.389
point−1.903−0.8208
point2.0570.3706

First 60 of 128 rows.

Flagged cells (sparse part beyond 2 scaled units)

RowVariableValueLow-rank fitSparse part
75m47.5400.72696.813
111m46.8320.67366.158
103m26.827−0.75717.584
99m27.5550.02387.531
19m57.9740.54217.432
19m65.648−0.49706.145
98m5−7.087−0.1626−6.925
31m58.9972.2656.732
77m78.6750.58768.087
42m38.7070.19398.513
72m1−6.3940.0434−6.438
9m7−7.063−0.1119−6.951
72m7−7.084−0.5234−6.561
115m75.609−0.54666.155
51m8−11.312−2.556−8.756

Flagged cells by variable

VariableFlagged cellsShare of rowsCenterScale
m110.8%0.24711.345
m221.7%0.08020.8986
m310.8%0.16451.752
m421.7%−0.01510.4654
m532.5%0.23881.199
m610.8%−0.23091.011
m743.3%−0.06891.617
m810.8%−0.59643.408

Loadings of the low-rank part

VariableLC1LC2
m10.44910.1197
m2−0.28520.4072
m30.4501−0.2007
m4−0.18940.5481
m50.45930.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"))
))
Python

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)

RowVariableValueLow-rank fitSparse part
75m47.5400.72696.813
111m46.8320.67366.158
103m26.827−0.75717.584
99m27.5550.02387.531
19m57.9740.54217.432
19m65.648−0.49706.145
98m5−7.087−0.1626−6.925
31m58.9972.2656.732
77m78.6750.58768.087
42m38.7070.19398.513
72m1−6.3940.0434−6.438
9m7−7.063−0.1119−6.951
72m7−7.084−0.5234−6.561
115m75.609−0.54666.155
51m8−11.312−2.556−8.756

Flagged cells by variable

VariableFlagged cellsShare of rowsCenterScale
m110.8%0.24711.345
m221.7%0.08020.8986
m310.8%0.16451.752
m421.7%−0.01510.4654
m532.5%0.23881.199
m610.8%−0.23091.011
m743.3%−0.06891.617
m810.8%−0.59643.408

Loadings of the low-rank part

VariableLC1LC2
m10.44910.1197
m2−0.28520.4072
m30.4501−0.2007
m4−0.18940.5481
m50.45930.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.

06

Choosing the penalty honestly

Read

The decomposition uses only the video. Choosing λ\lambda 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.

07

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 D=L+S+ED = L + S + E.
  • 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.

08

What runs here

Read
EntryIn CodeSplash
REP005 · Robust PCA via principal component pursuitRuns in CodeSplash: Robust PCA (cell outliers), on any numeric table
09

Check: the RPCA workflow

Checkpoint

Check 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.

10

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