CDiscover · discover.cur
CUR decomposition (representative columns and rows)
Which real columns and rows can stand in for the whole table?
Approximates the table from a few of its own columns (C) and rows (R), joined by a small matrix U = C⁺ Z R⁺, so the summary is made of real variables and real records instead of abstract components. Columns and rows are chosen by their leverage on the top-k singular vectors (Mahoney and Drineas): the highest leverage, or sampled in proportion to it. The error is shown next to the best rank-k approximation (the SVD), and the map shows the rows as the CUR approximation rebuilds them.
A real result
Example “Usarrests top”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
CUR with 4 real columns and 8 real rows rebuilds the table with a relative error of 0.0%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 0.0%
- Rank-2 SVD error
- 36.4%
Plots
Leverage from the top 2 right singular vectors; the scores sum to 1.
View data
| Variable | Leverage |
|---|---|
| Murder | 0.2310 |
| Assault | 0.1877 |
| UrbanPop | 0.4196 |
| Rape | 0.1617 |
Column leverage (rank 2); the 4 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | Yes |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 5 | 0.0497 | 9 | 276 | 91 | 40.600 |
| 24 | 0.0619 | 16.100 | 259 | 44 | 17.100 |
| 28 | 0.0394 | 12.200 | 252 | 81 | 46 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
| 34 | 0.0397 | 0.8000 | 45 | 44 | 7.300 |
| 40 | 0.0448 | 14.400 | 279 | 48 | 22.500 |
| 45 | 0.0515 | 2.200 | 48 | 32 | 11.200 |
| 48 | 0.0384 | 5.700 | 81 | 39 | 9.300 |
CUR with 4 real columns and 8 real rows rebuilds the table with a relative error of 0.0%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 0.0%
- Rank-2 SVD error
- 36.4%
To keep this page light, the plots are shown once, under the R tab.
Column leverage (rank 2); the 4 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | Yes |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 5 | 0.0497 | 9 | 276 | 91 | 40.600 |
| 24 | 0.0619 | 16.100 | 259 | 44 | 17.100 |
| 28 | 0.0394 | 12.200 | 252 | 81 | 46 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
| 34 | 0.0397 | 0.8000 | 45 | 44 | 7.300 |
| 40 | 0.0448 | 14.400 | 279 | 48 | 22.500 |
| 45 | 0.0515 | 2.200 | 48 | 32 | 11.200 |
| 48 | 0.0384 | 5.700 | 81 | 39 | 9.300 |
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Usarrests topml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Usarrests sampleml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Usarrests all exactml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Lowrank unscaledrep1_lowrank · features: m1, m2, m3, m4, m5, m6, m7, m8
- Penguins imputeml_penguins · features: bill_len, bill_dep, flipper_len, body_mass
- Degenerate all naml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Degenerate empty after filterml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Degenerate infml_usarrests · features: Murder, Assault, UrbanPop, Rape
In the guides
Where it sits in the decision guides
- Dimensionality reduction (PCA, ICA, NMF) · DS & ML Decision Guide · Discover — find structure without labels
What you need
- Variablesnumeric · 2–2000 columns
- Numeric columns of the table; CUR picks some of them to represent all.
Choices you make
model
- Rank (k)default 2
Number of singular vectors that define leverage, and the rank of the SVD the error is compared with.
- Columns to keepdefault —
How many real columns form C; empty keeps twice the rank.
- Rows to keepdefault —
How many real rows form R; empty keeps four times the rank.
- Choose bydefault top
Take the highest-leverage columns and rows, or sample them in proportion to leverage.
- Highest leverage(default) — Deterministic: the columns and rows with the largest leverage (ties go to the earlier one).
- Sample by leverage — Draws without replacement with probability proportional to leverage, from the shared random stream (seeded).
preprocess
- Standardize variablesdefault on
Divide each variable by its SD first so units don't decide the leverage.
- Missing valuesdefault listwise
Leave out rows with a missing value, or replace it with the column median.
- Leave out rows with a missing value(default) — Leaves out rows with any missing value; the clean choice when few are missing.
- Replace with the column median — Replaces gaps with the column median; keeps every row.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_variables
- How many independent units the analysis used; it sets precision and power.
- rank
- Approximates a table from a few of its own columns and rows (C and R) joined by a small matrix U.
- n_columns
- Approximates a table from a few of its own columns and rows (C and R) joined by a small matrix U.
- n_rows
- Approximates a table from a few of its own columns and rows (C and R) joined by a small matrix U.
- rel_error_cur
- Frobenius norm of what the approximation misses, divided by the table's norm (0 = exact).
- rel_error_svd
- Frobenius norm of what the approximation misses, divided by the table's norm (0 = exact).
- error_ratio
- Frobenius norm of what the approximation misses, divided by the table's norm (0 = exact).
- n_components
- Approximates a table from a few of its own columns and rows (C and R) joined by a small matrix U.
Per group, level or term: leverage[<variable>], chosen[<variable>], chosen_row[<j>], score_check[<k>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-7). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Leverage scores, the chosen columns and rows and U come from the same SVD-based twin (pseudo-inverses cut singular values below max(dim)·ε·σ₁). Sampling uses the shared Wichmann–Hill stream, so both engines pick the same columns and rows.
The exact script CodeSplash ran for example “Usarrests top” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# CUR decomposition (representative columns and rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cur 1.0.0 · spec 16e79dc113e0ba61
# Dataset: ml_usarrests (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
# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
SEED = 42
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.parquet", columns=list(dict.fromkeys(FEATURES)))
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, "CUR decomposition")
X = csembed.numeric_matrix(df, FEATURES, rows)
if np.all(X.std(axis=0) == 0):
cs.cs_error("CS_E_CONSTANT", column=FEATURES[0])
# %% CUR: real columns C and rows R chosen by leverage, U = C⁺ Z R⁺
Z = rl.center_scale(X, True)
n, p = Z.shape
k = min(int(2), n - 1, p)
c = min(p, 2 * k) if None is None else min(int(None), p)
r = min(n, 4 * k) if None is None else min(int(None), n)
METHOD = "top"
res = rl.cur(Z, k, c, r, METHOD, SEED)
ratio = res["err_cur"] / res["err_svd"] if res["err_svd"] > 0 else float("nan")
U, sv, Vt = np.linalg.svd(res["approx"], full_matrices=False)
d = int(np.sum(sv[:k] > 1e-10 * max(sv[0], 1e-300)))
signs = csembed.canonical_signs(Vt[:d].T) if d else np.ones(0)
scores = U[:, :d] * sv[:d] * signs
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.cur/usarrests_top/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(d):
emb[f"dim_{j + 1}"] = scores[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
# %% Result
chosen = set(int(j) for j in res["cols"])
values = {
"n": n,
"n_variables": p,
"rank": k,
"n_columns": len(res["cols"]),
"n_rows": len(res["rows"]),
"rel_error_cur": res["err_cur"],
"rel_error_svd": res["err_svd"],
"error_ratio": ratio,
"n_components": d,
}
for i, f in enumerate(FEATURES):
values[f"leverage[{f}]"] = float(res["col_lev"][i])
values[f"chosen[{f}]"] = 1 if i in chosen else 0
for j, i in enumerate(res["rows"]):
values[f"chosen_row[{j + 1}]"] = int(rows[i]) + 1
for j in range(d):
values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
by_lev = np.argsort(-res["col_lev"], kind="stable")
tables = [
{
"key": "columns",
"title": f"Column leverage (rank {k}); the {len(res['cols'])} chosen columns represent the table",
"columns": [
{"key": "variable", "label": "Variable"},
{"key": "leverage", "label": "Leverage", "type": "number"},
{"key": "chosen", "label": "Chosen"},
],
"rows": [{"variable": FEATURES[i], "leverage": float(res["col_lev"][i]), "chosen": "Yes" if int(i) in chosen else "No"} for i in by_lev],
},
{
"key": "rows",
"title": "Representative rows (chosen by row leverage)",
"columns": [
{"key": "row", "label": "Row", "type": "integer"},
{"key": "leverage", "label": "Leverage", "type": "number"},
]
+ [{"key": f, "label": f, "type": "number"} for f in FEATURES],
"rows": [dict({"row": int(rows[i]) + 1, "leverage": float(res["row_lev"][i])}, **{f: float(X[i, j]) for j, f in enumerate(FEATURES)}) for i in res["rows"]],
},
]
charts = [
cs.chart(
"leverage",
"importance-bar",
"Column leverage scores",
{
"feature": cs.col("Variable", FEATURES, "categorical"),
"importance": cs.col("Leverage", res["col_lev"], "numeric"),
},
note=f"Leverage from the top {k} right singular vectors; the scores sum to 1.",
)
]
cs.publish(
{
"title": "CUR decomposition (representative columns and rows)",
"engine": cs.engine_info("numpy", "pandas"),
"n": n,
"summary": f"CUR with {len(res['cols'])} real columns and {len(res['rows'])} real rows rebuilds the table with a relative error of {res['err_cur']:.1%}, against {res['err_svd']:.1%} for the best rank-{k} approximation.",
"statistics": [
{"key": "rel_error_cur", "label": "CUR relative error", "value": res["err_cur"], "format": "percent"},
{"key": "rel_error_svd", "label": f"Rank-{k} SVD error", "value": res["err_svd"], "format": "percent"},
],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
}
)
The exact script CodeSplash ran for example “Usarrests top” · R version 4.5.1 (2025-06-13)
# CUR decomposition (representative columns and rows)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.cur 1.0.0 · spec 16e79dc113e0ba61
# Dataset: ml_usarrests (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
SEED <- 42
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.parquet", col_select = unique(FEATURES)))
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, "CUR decomposition")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (all(apply(X, 2, function(x) all(x == x[1])))) cs_error("CS_E_CONSTANT", column = FEATURES[1])
# %% CUR: real columns C and rows R chosen by leverage, U = C⁺ Z R⁺
Z <- cs_rep_center_scale(X, TRUE)
n <- nrow(Z); p <- ncol(Z)
k <- min(as.integer(2), n - 1L, p)
nc <- if (is.null(NULL)) min(p, 2L * k) else min(as.integer(NULL), p)
nr <- if (is.null(NULL)) min(n, 4L * k) else min(as.integer(NULL), n)
METHOD <- "top"
res <- cs_rep_cur(Z, k, nc, nr, METHOD, SEED)
ratio <- if (res$err_svd > 0) res$err_cur / res$err_svd else NaN
sv <- svd(res$approx)
d <- sum(sv$d[seq_len(k)] > 1e-10 * max(sv$d[1], 1e-300))
if (d > 0) {
signs <- cs_ml_canonical_signs(sv$v[, seq_len(d), drop = FALSE])
scores <- sweep(sv$u[, seq_len(d), drop = FALSE], 2, sv$d[seq_len(d)] * signs, "*")
} else {
scores <- matrix(0, n, 0)
}
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.cur/usarrests_top/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(d)) emb[[paste0("dim_", j)]] <- scores[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
# %% Result
values <- list(n = n, n_variables = p, rank = k, n_columns = length(res$cols), n_rows = length(res$rows),
rel_error_cur = res$err_cur, rel_error_svd = res$err_svd, error_ratio = ratio, n_components = d)
for (i in seq_along(FEATURES)) {
values[[sprintf("leverage[%s]", FEATURES[i])]] <- res$col_lev[i]
values[[sprintf("chosen[%s]", FEATURES[i])]] <- if (i %in% res$cols) 1L else 0L
}
for (j in seq_along(res$rows)) values[[sprintf("chosen_row[%d]", j)]] <- rows[res$rows[j]] + 1L
for (j in seq_len(d)) values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
by_lev <- order(-res$col_lev, method = "radix")
tables <- list(
list(key = "columns", title = sprintf("Column leverage (rank %d); the %d chosen columns represent the table", k, length(res$cols)),
columns = list(list(key = "variable", label = "Variable"),
list(key = "leverage", label = "Leverage", type = "number"),
list(key = "chosen", label = "Chosen")),
rows = lapply(by_lev, function(i) list(variable = FEATURES[i], leverage = res$col_lev[i], chosen = if (i %in% res$cols) "Yes" else "No"))),
list(key = "rows", title = "Representative rows (chosen by row leverage)",
columns = c(list(list(key = "row", label = "Row", type = "integer"),
list(key = "leverage", label = "Leverage", type = "number")),
lapply(FEATURES, function(f) list(key = f, label = f, type = "number"))),
rows = lapply(res$rows, function(i) {
r <- list(row = rows[i] + 1L, leverage = res$row_lev[i])
for (j in seq_along(FEATURES)) r[[FEATURES[j]]] <- X[i, j]
r
}))
)
charts <- list(cs_chart("leverage", "importance-bar", "Column leverage scores", list(
feature = cs_col("Variable", FEATURES, "categorical"),
importance = cs_col("Leverage", res$col_lev, "numeric")
), note = sprintf("Leverage from the top %d right singular vectors; the scores sum to 1.", k)))
cs_publish(list(
title = "CUR decomposition (representative columns and rows)",
engine = cs_engine_info("codesplashr", "nanoparquet"),
n = n,
summary = sprintf("CUR with %d real columns and %d real rows rebuilds the table with a relative error of %.1f%%, against %.1f%% for the best rank-%d approximation.",
length(res$cols), length(res$rows), 100 * res$err_cur, 100 * res$err_svd, k),
statistics = list(list(key = "rel_error_cur", label = "CUR relative error", value = res$err_cur, format = "percent"),
list(key = "rel_error_svd", label = sprintf("Rank-%d SVD error", k), value = res$err_svd, format = "percent")),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Sources
- Mahoney MW, Drineas P (2009). CUR matrix decompositions for improved data analysis. PNAS 106(3):697–702.
- Papailiopoulos D, Kyrillidis A, Boutsidis C (2014). Provable deterministic leverage score sampling. KDD '14.
From the CodeSplash method registry · discover.cur v1.0.0.