Sketches: random projection and CUR
Two cheap ways to shrink a wide table without learning directions the PCA way. Random projection multiplies by a random matrix and keeps distances; CUR keeps a few real columns and rows, so the summary is made of things you can name.
What runs in CodeSplash
- REP012Johnson–Lindenstrauss random projection Runs in CodeSplash (Prepare)
- REP020CUR decomposition Runs in CodeSplash
- CUR decomposition (representative columns and rows) Verified in Python and R
You will be able to
- Apply the Johnson–Lindenstrauss rule and check distortion across several random maps
- Explain why the same seed doesn't give the same projection in Python and R unless the random stream is shared
- Describe CUR's leverage-based choice of columns and rows and compare its error fairly with the SVD
Random directions
ReadA random projectionRandom projectionMaps many numeric columns to fewer by fixed random weights; distances between rows are kept up to a small distortion. maps each row with a fixed random matrix, , with entries scaled so squared distances are kept on average. Nothing is learned from the data.
The Johnson–Lindenstrauss lemma promises that with about output dimensions, every pairwise distance among rows stays within a factor , with high probability. The original width doesn't matter, which makes it a strong, cheap baseline for very wide or sparse data.
Sparse versions use mostly-zero matrices (entries of , , ) and keep the same guarantee while multiplying faster.
Check the distortion, not the promise
ReadThe guarantee is about probability, so measure what you got: the distribution of compressed-to-original distance ratios, over several random maps. Report quantiles, not only the average.
Small output dimensions hurt rare, close neighbors first: their distances are small, so a little distortion can reorder them.
Reuse the same matrix for training and new data. A fresh random matrix for the test rows puts them in a different space.
The same code, two different answers
ReadThe reference's example projects 8 rows from 4 columns to 3 and prints the median ratio of new to old distances:
target_dim = 3
projection = rng.normal(size=(X.shape[1], target_dim)) / np.sqrt(target_dim)
embedding = X @ projection
print(np.median(pdist(embedding) / pdist(X)))target_dim <- 3
projection <- matrix(rnorm(ncol(X) * target_dim), ncol(X), target_dim) / sqrt(target_dim)
embedding <- X %*% projection
print(median(as.vector(dist(embedding)) / as.vector(dist(X))))CodeSplash's runs printed 1.165 in Python and 1.079 in R. Both are correct: NumPy and R draw different random numbers, so they built different matrices. With 3 dimensions and 8 rows, single maps vary a lot.
In CodeSplash
ReadPrepare's Random projection step adds projected columns with a matrix drawn once from CodeSplash's shared random stream and frozen into the recipe. Python, R and SQL replay the same matrix, so the columns match in every engine, unlike the snippet above.
Standardize the inputs first when their units differ, or the widest column dominates the projection.
CUR: keep real columns and rows
ReadCURCUR decompositionApproximates a table from a few of its own columns and rows (C and R) joined by a small matrix U. approximates , where holds some of 's actual columns, some actual rows and is a small linking matrix. The summary is made of real variables and records, which PCA's mixtures aren't.
Columns are chosen by leverage: how strongly each column loads on the top- singular vectors. High-leverage columns carry the dominant structure; selection keeps the top ones or samples in proportion to leverage.
CUR against the SVD
ReadCUR with 3 real columns and 6 real rows rebuilds the table with a relative error of 26.5%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 26.5%
- 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 3 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | No |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 3 | 0.0182 | 8.100 | 294 | 80 | 31 |
| 7 | 0.0194 | 3.300 | 110 | 77 | 11.100 |
| 19 | 0.0246 | 2.100 | 83 | 51 | 7.800 |
| 21 | 0.0229 | 4.400 | 149 | 85 | 16.300 |
| 23 | 0.0156 | 2.700 | 72 | 66 | 14.900 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
The exact R script · R 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 95488b570ee6ace3
# 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(3)) min(p, 2L * k) else min(as.integer(3), p)
nr <- if (is.null(6)) min(n, 4L * k) else min(as.integer(6), n)
METHOD <- "sample"
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_sample/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"))
))
CUR with 3 real columns and 6 real rows rebuilds the table with a relative error of 26.5%, against 36.4% for the best rank-2 approximation.
- CUR relative error
- 26.5%
- 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 3 chosen columns represent the table
| Variable | Leverage | Chosen |
|---|---|---|
| UrbanPop | 0.4196 | Yes |
| Murder | 0.2310 | Yes |
| Assault | 0.1877 | No |
| Rape | 0.1617 | Yes |
Representative rows (chosen by row leverage)
| Row | Leverage | Murder | Assault | UrbanPop | Rape |
|---|---|---|---|---|---|
| 3 | 0.0182 | 8.100 | 294 | 80 | 31 |
| 7 | 0.0194 | 3.300 | 110 | 77 | 11.100 |
| 19 | 0.0246 | 2.100 | 83 | 51 | 7.800 |
| 21 | 0.0229 | 4.400 | 149 | 85 | 16.300 |
| 23 | 0.0156 | 2.700 | 72 | 66 | 14.900 |
| 33 | 0.0552 | 13 | 337 | 45 | 16.100 |
The exact Python script · Python 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 95488b570ee6ace3
# 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 3 is None else min(int(3), p)
r = min(n, 4 * k) if 6 is None else min(int(6), n)
METHOD = "sample"
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_sample/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"}],
}
)
Sampling three of US arrests' four columns and six rows gives relative error 0.265. The best rank-2 SVD has 0.364. CUR looks better here only because three columns span more than two dimensions; compare at equal sizes before claiming a win.
Urban population had the highest leverage, 0.42: it is the column least like the others. Keep all four columns and the error is essentially zero (5.77e-16).
Check: sketches
CheckpointCheck yourself
You double the number of rows from 1 million to 2 million. Roughly how does the Johnson–Lindenstrauss dimension change?
Show the answer
Answer: a
: a small additive increase.
Check yourself
Python and R run the same random-projection code with the same seed and print different distortions. Why?
Show the answer
Answer: a
Same seed number, different algorithms. CodeSplash's Prepare step uses one shared stream so both engines get the same matrix.
Check yourself
You project training rows with one random matrix and test rows with a newly drawn one. What goes wrong?
Show the answer
Answer: a
Distances within each set are kept, but coordinates aren't comparable across matrices. Freeze and reuse one matrix.
Check yourself
Why choose CUR over PCA for a summary of 300 lab measurements?
Show the answer
Answer: a
The best rank- error belongs to the SVD. CUR trades a little error for a summary made of real columns and rows.
Check yourself
What makes a column's leverage high?
Show the answer
Answer: a
Leverage is the squared length of the column's row in the top- right singular vectors. Standardize first so units don't set it.
Recap
Recap- Random projection keeps pairwise distances with about dimensions; measure distortion and freeze the matrix.
- Different languages draw different random numbers; a shared stream makes engines agree.
- CUR keeps real columns and rows chosen by leverage; compare its error with the SVD at equal size.
Concepts in this lesson