Skip to content

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.

Advanced ~13 min8 steps

What runs in CodeSplash

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

Read first

01

Random directions

Read

A 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, z=Rxz = Rx, with entries scaled so squared distances are kept on average. Nothing is learned from the data.

The Johnson–Lindenstrauss lemma promises that with about log⁡n/ϵ2\log n / \epsilon^2 output dimensions, every pairwise distance among nn rows stays within a factor 1±ϵ1 \pm \epsilon, 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 +s+s, 00, −s-s) and keep the same guarantee while multiplying faster.

02

Check the distortion, not the promise

Read

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

03

The same code, two different answers

Read

The reference's example projects 8 rows from 4 columns to 3 and prints the median ratio of new to old distances:

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

04

In CodeSplash

Read

Prepare'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.

05

CUR: keep real columns and rows

Read

CURCUR decompositionApproximates a table from a few of its own columns and rows (C and R) joined by a small matrix U. approximates X≈C U RX \approx C\,U\,R, where CC holds some of XX's actual columns, RR some actual rows and UU 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-kk singular vectors. High-leverage columns carry the dominant structure; selection keeps the top ones or samples in proportion to leverage.

06

CUR against the SVD

Read
CUR decomposition (representative columns and rows)Recorded · Python and R agreeRecorded 2026-11-25 · 25 values compared
R

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%

Plots

Column leverage scoresWhich features does the model rely on most?

Leverage from the top 2 right singular vectors; the scores sum to 1.

View data
VariableLeverage
Murder0.2310
Assault0.1877
UrbanPop0.4196
Rape0.1617

Column leverage (rank 2); the 3 chosen columns represent the table

VariableLeverageChosen
UrbanPop0.4196Yes
Murder0.2310Yes
Assault0.1877No
Rape0.1617Yes

Representative rows (chosen by row leverage)

RowLeverageMurderAssaultUrbanPopRape
30.01828.1002948031
70.01943.3001107711.100
190.02462.10083517.800
210.02294.4001498516.300
230.01562.700726614.900
330.0552133374516.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"))
))
Python

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

VariableLeverageChosen
UrbanPop0.4196Yes
Murder0.2310Yes
Assault0.1877No
Rape0.1617Yes

Representative rows (chosen by row leverage)

RowLeverageMurderAssaultUrbanPopRape
30.01828.1002948031
70.01943.3001107711.100
190.02462.10083517.800
210.02294.4001498516.300
230.01562.700726614.900
330.0552133374516.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).

07

Check: sketches

Checkpoint

Check 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

log⁡(2n)=log⁡n+log⁡2\log(2n) = \log n + \log 2: 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-kk 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-kk right singular vectors. Standardize first so units don't set it.

08

Recap

Recap
  • Random projection keeps pairwise distances with about log⁡n/ϵ2\log n/\epsilon^2 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