Skip to content

The PCA family: plain, probabilistic and kernel PCA

Three versions of one idea. PCA keeps variance, probabilistic PCA adds a noise model and a likelihood, and kernel PCA runs PCA on similarities so curved structure can show. Know what each assumes and where each breaks.

Applied ~14 min9 steps

What runs in CodeSplash

You will be able to

  • State the objective, assumptions and main pitfalls of PCA as a representation
  • Explain what probabilistic PCA assumes about noise and what its likelihood buys
  • Describe kernel PCA's centered kernel matrix, the effect of the kernel width, and the pre-image problem

Read first

01

PCA as a representation

Read

PCAPrincipal component analysisRotates correlated variables into uncorrelated components ordered by how much variance they capture. keeps the qq orthogonal directions of largest variance; a row's representation is its qq scores. It is the baseline every other map should beat.

Assumes: Euclidean variation is meaningful, so scaling matters. Gives: a linear, parametric map that embeds new rows with the saved mean and loadings. Watch for: high-variance nuisance columns and outliers capturing components, and the temptation to read a component as a real-world factor.

On standardized US arrests, two components keep 86.8% of the variance. Choose the rank with held-out reconstruction, not only the scree plot: explained variance on the fitted rows always grows with more components.

02

A noise model: probabilistic PCA

Read

Probabilistic PCAProbabilistic PCAPCA as a model: data = loadings × latent scores + equal-variance noise, so it has a likelihood and a BIC. says each row is x=μ+Wz+εx = \mu + Wz + \varepsilon with latent z∼N(0,Iq)z \sim N(0, I_q) and noise ε∼N(0,σ2I)\varepsilon \sim N(0, \sigma^2 I), so x∼N(μ,WW⊤+σ2I)x \sim N(\mu, WW^\top + \sigma^2 I).

It keeps PCA's directions and adds a likelihood: compare ranks with BIC or held-out log-likelihood, fill gaps by EM, and score how surprising a new row is.

Principal component analysisRecorded · Python and R agreeRecorded 2026-11-21 · 45 values compared
R

PCA of 4 variables: the first component explains 62.0% of the variance.

PC1 variance
62.0%
PC1 + PC2
86.8%

Plots

Scree plotHow many components carry most of the variance?
View data
ComponentCumulativeProportion of variance
10.62010.6201
20.86750.2474
30.95660.0891
410.0434
Biplot (PC1 × PC2)How do rows spread on the main components, and which variables drive each direction?

Loading arrows are rescaled to the score range.

View data
KindLabelPC1PC2
point0.9757−1.122
point1.931−1.062
point1.7450.7385
point−0.1400−1.109
point2.4991.527
point1.4990.9776
point−1.3451.078
point0.04720.3221
point2.983−0.0388
point1.623−1.266
point−0.90351.555
point−1.623−0.2089
point1.3650.6750
point−0.50040.1500
point−2.2310.1030
point−0.78890.2674
point−0.7433−0.9488
point1.549−0.8623
point−2.373−0.3726
point1.746−0.4234
point−0.48131.460
point2.0870.1538
point−1.6760.6259
point0.9865−2.370
point0.68980.2607
point−1.174−0.5315
point−1.2530.1920
point2.8460.7678
point−2.3600.0179
point0.17971.435
point1.960−0.1414
point1.6660.8149
point1.112−2.206
point−2.962−0.5931
point−0.22370.7348
point−0.30860.2850
point0.05850.5360
point−0.87950.5654
point−0.85511.477
point1.307−1.914
point−1.968−0.8151
point0.9897−0.8516
point1.3420.4083
point−0.54501.457
point−2.773−1.388
point−0.0954−0.1977
point−0.21470.9604
point−2.087−1.411
point−2.0590.6051
point−0.6231−0.3178
loadingMurder1.465−1.143
loadingAssault1.594−0.5139
loadingUrbanPop0.76062.386
loadingRape1.4860.4574

Explained variance

ComponentEigenvalueProportionCumulative
12.48062.0%62.0%
20.989824.7%86.8%
30.35668.9%95.7%
40.17344.3%100.0%

Loadings

VariablePC1PC2PC3PC4
Murder0.5359−0.4182−0.3412−0.6492
Assault0.5832−0.1880−0.26810.7434
UrbanPop0.27820.8728−0.3780−0.1339
Rape0.54340.16730.8178−0.0890

Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)

Rankσ²Log-likelihoodParametersBIC
10.4965−253.479542.15
20.2597−237.8212522.58
30.1700−234.6414524.05
The exact R script · R R version 4.5.1 (2025-06-13)
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec f98441aa79b6edf2
# 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)

chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))

# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_usarrests.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), 2, "Principal component analysis")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)

# %% Principal components
SCALE <- TRUE
Z <- sweep(X, 2, colMeans(X))
if (SCALE) {
  s <- apply(X, 2, stats::sd)
  s[s == 0] <- 1
  Z <- sweep(Z, 2, s, "/")
}
k_max <- min(length(rows) - 1L, length(FEATURES))
p <- stats::prcomp(Z, center = FALSE, scale. = FALSE)
eig <- (p$sdev^2)[seq_len(k_max)]
prop <- eig / sum(eig)
cumulative <- cumsum(prop)
rot <- p$rotation[, seq_len(k_max), drop = FALSE]
signs <- cs_rep_canonical_signs(rot)  # largest |loading| positive (near-ties: the first)
loadings <- sweep(rot, 2, signs, "*")
scores <- sweep(p$x[, seq_len(k_max), drop = FALSE], 2, signs, "*")
k <- if (is.null(NULL)) k_max else min(as.integer(NULL), k_max)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-95359/discover.pca/usarrests_probabilistic/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"))

# %% Result
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = k,
               cum2 = if (k_max >= 2) cumulative[2] else NaN)
# Kaiser's "eigenvalue above 1" only means something on the correlation scale (scaled PCA).
if (SCALE) values$kaiser <- sum(eig > 1)
for (j in seq_len(k_max)) {
  values[[sprintf("eigen[%d]", j)]] <- eig[j]
  values[[sprintf("prop[%d]", j)]] <- prop[j]
  values[[sprintf("cumulative[%d]", j)]] <- cumulative[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])]] <- unname(loadings[i, j])
}
ppca_table <- NULL
# Probabilistic PCA (Tipping & Bishop): closed-form ML noise variance, log-likelihood and BIC by rank
profile <- cs_rep_ppca_profile(eig, length(rows), length(FEATURES))
if (length(profile)) {
  want <- min(as.integer(2), length(FEATURES) - 1L)
  qs <- vapply(profile, function(d) d$q, numeric(1))
  bics <- vapply(profile, function(d) d$bic, numeric(1))
  chosen <- profile[[if (any(qs <= want)) max(which(qs <= want)) else 1L]]
  values$latent <- chosen$q
  values$sigma2 <- chosen$sigma2
  values$loglik <- chosen$loglik
  values$bic <- chosen$bic
  values$bic_rank <- qs[order(bics, qs)[1]]
  for (d in profile) values[[sprintf("bic[%d]", d$q)]] <- d$bic
  ppca_table <- list(key = "ppca", title = "Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)",
                     columns = list(list(key = "q", label = "Rank", type = "integer"),
                                    list(key = "sigma2", label = "σ²", type = "number"),
                                    list(key = "loglik", label = "Log-likelihood", type = "number"),
                                    list(key = "df", label = "Parameters", type = "number"),
                                    list(key = "bic", label = "BIC", type = "number")),
                     rows = lapply(profile, function(d) list(q = d$q, sigma2 = d$sigma2, loglik = d$loglik, df = d$df, bic = d$bic)))
}
show <- min(k, 5L)
tables <- list(
  list(key = "variance", title = "Explained variance",
       columns = list(list(key = "component", label = "Component", type = "integer"),
                      list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
                      list(key = "proportion", label = "Proportion", type = "percent"),
                      list(key = "cumulative", label = "Cumulative", type = "percent")),
       rows = lapply(seq_len(k_max), function(j) list(component = j, eigenvalue = eig[j], proportion = prop[j], cumulative = cumulative[j]))),
  list(key = "loadings", title = "Loadings",
       columns = c(list(list(key = "variable", label = "Variable")),
                   lapply(seq_len(show), function(j) list(key = paste0("pc", j), label = paste0("PC", j), type = "number"))),
       rows = lapply(seq_along(FEATURES), function(i) {
         r <- list(variable = FEATURES[i])
         for (j in seq_len(show)) r[[paste0("pc", j)]] <- unname(loadings[i, j])
         r
       }))
)
if (!is.null(ppca_table)) tables[[length(tables) + 1L]] <- ppca_table
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
  component = cs_col("Component", seq_len(k_max), "numeric"),
  variance = cs_col("Proportion of variance", prop, "numeric"),
  cumulative = cs_col("Cumulative", cumulative, "numeric")
)))
if (k_max >= 2) {
  pick <- chart_rows(length(rows))
  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[[2]] <- cs_chart("biplot", "biplot", "Biplot (PC1 × PC2)", list(
    x = cs_col("PC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
    y = cs_col("PC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
    kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(FEATURES))), "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 = "Principal component analysis",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = length(rows),
  summary = sprintf("PCA of %d variables: the first component explains %.1f%% of the variance.", length(FEATURES), 100 * prop[1]),
  statistics = list(list(key = "prop1", label = "PC1 variance", value = prop[1], format = "percent"),
                    list(key = "cum2", label = "PC1 + PC2", value = values$cum2, format = "percent")),
  tables = tables,
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

PCA of 4 variables: the first component explains 62.0% of the variance.

PC1 variance
62.0%
PC1 + PC2
86.8%

To keep this page light, the plots are shown once, under the R tab.

Explained variance

ComponentEigenvalueProportionCumulative
12.48062.0%62.0%
20.989824.7%86.8%
30.35668.9%95.7%
40.17344.3%100.0%

Loadings

VariablePC1PC2PC3PC4
Murder0.5359−0.4182−0.3412−0.6492
Assault0.5832−0.1880−0.26810.7434
UrbanPop0.27820.8728−0.3780−0.1339
Rape0.54340.16730.8178−0.0890

Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)

Rankσ²Log-likelihoodParametersBIC
10.4965−253.479542.15
20.2597−237.8212522.58
30.1700−234.6414524.05
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec f98441aa79b6edf2
# 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
from sklearn.decomposition import PCA

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 = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None
df = pd.read_parquet("tests/parity/fixtures/ml_usarrests.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), 2, "Principal component analysis")
X = csembed.numeric_matrix(df, FEATURES, rows)

# %% Principal components
SCALE = True
Z = csembed.standardize(X, ddof=1) if SCALE else X - X.mean(axis=0)  # SD with n − 1, like R's scale()
k_max = min(len(rows) - 1, len(FEATURES))
pca = PCA(n_components=k_max, svd_solver="full").fit(Z)
eig = pca.explained_variance_  # divisor n − 1 (= prcomp sdev²)
prop = eig / eig.sum()
cumulative = np.cumsum(prop)
signs = rl.canonical_signs(pca.components_.T)  # largest |loading| positive (near-ties: the first)
loadings = pca.components_.T * signs
scores = pca.transform(Z) * signs
k = k_max if None is None else min(int(None), k_max)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-95359/discover.pca/usarrests_probabilistic/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)

# %% Result
values = {
    "n": len(rows),
    "n_variables": len(FEATURES),
    "n_components": k,
    "cum2": float(cumulative[1]) if k_max >= 2 else float("nan"),
}
if SCALE:  # Kaiser's "eigenvalue above 1" only means something on the correlation scale
    values["kaiser"] = int(np.sum(eig > 1))
for j in range(k_max):
    values[f"eigen[{j + 1}]"] = float(eig[j])
    values[f"prop[{j + 1}]"] = float(prop[j])
    values[f"cumulative[{j + 1}]"] = float(cumulative[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])
ppca_table = None
# Probabilistic PCA (Tipping & Bishop): closed-form ML noise variance, log-likelihood and BIC by rank
profile = rl.ppca_profile(eig, len(rows), len(FEATURES))
if profile:
    want = min(int(2), len(FEATURES) - 1)
    pick_q = [d for d in profile if d["q"] <= want] or profile[:1]
    chosen = pick_q[-1]
    values["latent"] = chosen["q"]
    values["sigma2"] = chosen["sigma2"]
    values["loglik"] = chosen["loglik"]
    values["bic"] = chosen["bic"]
    values["bic_rank"] = min(profile, key=lambda d: (d["bic"], d["q"]))["q"]
    for d in profile:
        values[f"bic[{d['q']}]"] = d["bic"]
    ppca_table = {
        "key": "ppca",
        "title": "Probabilistic PCA by rank (σ² = noise variance; lowest BIC is the best rank)",
        "columns": [
            {"key": "q", "label": "Rank", "type": "integer"},
            {"key": "sigma2", "label": "σ²", "type": "number"},
            {"key": "loglik", "label": "Log-likelihood", "type": "number"},
            {"key": "df", "label": "Parameters", "type": "number"},
            {"key": "bic", "label": "BIC", "type": "number"},
        ],
        "rows": [{"q": d["q"], "sigma2": d["sigma2"], "loglik": d["loglik"], "df": d["df"], "bic": d["bic"]} for d in profile],
    }
show = min(k, 5)
tables = [
    {
        "key": "variance",
        "title": "Explained variance",
        "columns": [
            {"key": "component", "label": "Component", "type": "integer"},
            {"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
            {"key": "proportion", "label": "Proportion", "type": "percent"},
            {"key": "cumulative", "label": "Cumulative", "type": "percent"},
        ],
        "rows": [{"component": j + 1, "eigenvalue": eig[j], "proportion": prop[j], "cumulative": cumulative[j]} for j in range(k_max)],
    },
    {
        "key": "loadings",
        "title": "Loadings",
        "columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"PC{j + 1}", "type": "number"} for j in range(show)],
        "rows": [dict({"variable": f}, **{f"pc{j + 1}": loadings[i, j] for j in range(show)}) for i, f in enumerate(FEATURES)],
    },
]
if ppca_table is not None:
    tables.append(ppca_table)
charts = [
    cs.chart(
        "scree",
        "scree-plot",
        "Scree plot",
        {
            "component": cs.col("Component", list(range(1, k_max + 1)), "numeric"),
            "variance": cs.col("Proportion of variance", prop, "numeric"),
            "cumulative": cs.col("Cumulative", cumulative, "numeric"),
        },
    )
]
if k_max >= 2:
    pick = chart_rows(len(rows))
    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 (PC1 × PC2)",
            {
                "x": cs.col("PC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
                "y": cs.col("PC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
                "kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(FEATURES), "categorical"),
                "label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
            },
            note="Loading arrows are rescaled to the score range.",
        )
    )
cs.publish(
    {
        "title": "Principal component analysis",
        "engine": cs.engine_info("scikit-learn", "numpy", "pandas"),
        "n": len(rows),
        "summary": f"PCA of {len(FEATURES)} variables: the first component explains {prop[0]:.1%} of the variance.",
        "statistics": [
            {"key": "prop1", "label": "PC1 variance", "value": float(prop[0]), "format": "percent"},
            {"key": "cum2", "label": "PC1 + PC2", "value": values["cum2"], "format": "percent"},
        ],
        "tables": tables,
        "charts": charts,
        "values": values,
        "warnings": warnings,
        "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
    }
)

Here BIC picks 2 components, with noise variance 0.260.

03

What PPCA assumes

Read
  • One noise level for every column. Isotropic noise is restrictive. Factor analysis (lesson 4) lets each column have its own.
  • One linear subspace. Data on several separate subspaces need a mixture of PPCAs, which is a different model.
  • Rotations aren't identified. Any rotation of zz fits equally well, so read the subspace, not the individual latent axes.
  • A noise variance near zero makes the likelihood unstable.
04

Kernel PCA: PCA on similarities

Read

Kernel PCAKernel PCAPCA after mapping rows into a richer similarity space, so curved structure (rings, spirals) can unroll. replaces covariances between columns with similarities between rows. Build the n×nn \times n kernel matrix Kij=k(xi,xj)K_{ij} = k(x_i, x_j), center it,

Kc=HKH,H=I−1n11⊤,K_c = HKH, \qquad H = I - \tfrac{1}{n}\mathbf{1}\mathbf{1}^\top,

and keep its leading eigenvectors. With a radial basis kernel k(x,y)=e−γ∥x−y∥2k(x, y) = e^{-\gamma\lVert x - y\rVert^2} this is PCA in an implicit, very high-dimensional feature space, the kernel trickKernelA similarity between rows that lets a linear method draw curves without building new columns., so curved structure can unfold.

05

Kernel PCA in a run

Read
Kernel PCARecorded · Python and R agreeRecorded 2026-11-25 · 12 values compared
R

Kernel PCA (rbf, γ = 0.25) of 4 variables: component 1 carries 40.1% of the kernel variance.

kPC1 share
40.1%
γ
0.2500

Plots

Kernel PCA mapWhich rows group together, and how well separated are the groups?
View data
specieskPC1kPC2
setosa0.8020−0.0944
setosa0.66590.1099
setosa0.75870.0127
setosa0.70640.0573
setosa0.7937−0.1270
setosa0.6286−0.1806
setosa0.7802−0.0527
setosa0.8041−0.0518
setosa0.58290.0969
setosa0.71870.0611
setosa0.7231−0.1535
setosa0.8003−0.0499
setosa0.67040.0867
setosa0.61770.0322
setosa0.5239−0.1870
setosa0.3453−0.1664
setosa0.6363−0.1851
setosa0.7961−0.0873
setosa0.6127−0.1650
setosa0.7179−0.1699
setosa0.7352−0.0393
setosa0.7462−0.1435
setosa0.7570−0.1279
setosa0.72240.0422
setosa0.7831−0.0366
setosa0.65080.1330
setosa0.7797−0.0278
setosa0.7886−0.0906
setosa0.7871−0.0546
setosa0.75130.0296
setosa0.71350.0777
setosa0.7222−0.0296
setosa0.5499−0.1933
setosa0.4719−0.1892
setosa0.71630.0766
setosa0.76090.0174
setosa0.7327−0.0966
setosa0.7913−0.1302
setosa0.63650.0626
setosa0.7966−0.0509
setosa0.8035−0.0910
setosa0.25870.1666
setosa0.7155−0.0011
setosa0.7404−0.0546
setosa0.6925−0.1576
setosa0.66010.1192
setosa0.7189−0.1711
setosa0.74760.0135
setosa0.7399−0.1537
setosa0.7897−0.0142
versicolor−0.3733−0.3334
versicolor−0.4119−0.1479
versicolor−0.4472−0.3221
versicolor−0.18280.6313
versicolor−0.50040.0732
versicolor−0.34310.4789
versicolor−0.3885−0.2168
versicolor0.03700.5692
versicolor−0.45430.0206
versicolor−0.16290.5964

First 60 of 150 rows.

Kernel variance by componentHow many components carry most of the variance?
View data
ComponentCumulativeShare of kernel variance
10.40130.4013
20.58290.1816

Kernel variance

ComponentEigenvalueShare
139.30640.1%
217.79118.2%
The exact R script · R R version 4.5.1 (2025-06-13)
# Kernel PCA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kpca 1.0.0 · spec 57468126ac6203a8
# Dataset: ml_iris (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("sepal_length", "sepal_width", "petal_length", "petal_width")
LABEL <- "species"
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ml_iris.parquet", col_select = unique(c(FEATURES, LABEL))))
n_input <- nrow(df)
warnings <- list()
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))
}
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
s <- apply(X, 2, stats::sd)
s[s == 0] <- 1  # constant columns are only centered
X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")

# %% Kernel PCA (fit on <= 2,000 evenly spaced rows, every row projected)
fit_rows <- cs_ml_even_sample(length(rows), 2000)
if (length(fit_rows) < length(rows)) {
  warnings <- c(warnings, sprintf("The kernel was fitted on %s evenly spaced rows; all %s rows are projected.",
                                  format(length(fit_rows), big.mark = ","), format(length(rows), big.mark = ",")))
}
KERNEL <- "rbf"
GAMMA <- NULL
GAMMA <- if (is.null(GAMMA)) 1 / length(FEATURES) else as.numeric(GAMMA)
fit <- cs_ml_kpca(X, fit_rows, 2, KERNEL, GAMMA, 3, 1)
scores <- fit$scores; eig <- fit$eigen; share <- fit$share
k <- ncol(scores)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.kpca/iris_rbf/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"))

# %% Result
values <- list(n = length(rows), n_fit = length(fit_rows), n_variables = length(FEATURES), n_components = k, gamma = GAMMA, n_positive = fit$n_positive)
for (j in seq_len(k)) {
  values[[sprintf("eigen[%d]", j)]] <- eig[j]
  values[[sprintf("share[%d]", j)]] <- share[j]
  values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
}
charts <- list(cs_chart("scree", "scree-plot", "Kernel variance by component", list(
  component = cs_col("Component", seq_len(k), "numeric"),
  variance = cs_col("Share of kernel variance", share, "numeric"),
  cumulative = cs_col("Cumulative", cumsum(share), "numeric")
)))
if (k >= 2) {
  pick <- chart_rows(length(rows))
  groups <- if (is.null(LABEL)) rep("All rows", length(pick)) else {
    g <- as.character(df[[LABEL]][rows[pick] + 1L]); g[is.na(g)] <- "(missing)"; g
  }
  charts <- c(list(cs_chart("map", "cluster-scatter", "Kernel PCA map", list(
    x = cs_col("kPC1", scores[pick, 1], "numeric"),
    y = cs_col("kPC2", scores[pick, 2], "numeric"),
    cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ))), charts)
}
cs_publish(list(
  title = "Kernel PCA",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = sprintf("Kernel PCA (%s, γ = %s) of %d variables: component 1 carries %.1f%% of the kernel variance.",
                    KERNEL, format(signif(GAMMA, 3)), length(FEATURES), 100 * share[1]),
  statistics = list(list(key = "share1", label = "kPC1 share", value = share[1], format = "percent"),
                    list(key = "gamma", label = "γ", value = GAMMA)),
  tables = list(list(key = "variance", title = "Kernel variance",
                     columns = list(list(key = "component", label = "Component", type = "integer"),
                                    list(key = "eigen", label = "Eigenvalue", type = "number"),
                                    list(key = "share", label = "Share", type = "percent")),
                     rows = lapply(seq_len(k), function(j) list(component = j, eigen = eig[j], share = share[j])))),
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
Python

Kernel PCA (rbf, γ = 0.25) of 4 variables: component 1 carries 40.1% of the kernel variance.

kPC1 share
40.1%
γ
0.2500

To keep this page light, the plots are shown once, under the R tab.

Kernel variance

ComponentEigenvalueShare
139.30640.1%
217.79118.2%
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Kernel PCA
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.kpca 1.0.0 · spec 57468126ac6203a8
# Dataset: ml_iris (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 cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed

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 = ["sepal_length", "sepal_width", "petal_length", "petal_width"]
LABEL = "species"
df = pd.read_parquet("tests/parity/fixtures/ml_iris.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
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.")
X = csembed.standardize(csembed.numeric_matrix(df, FEATURES, rows), ddof=1)

# %% Kernel PCA (fit on ≤ 2,000 evenly spaced rows, every row projected)
fit_rows = csc.even_sample(len(rows), 2000)
if len(fit_rows) < len(rows):
    warnings.append(f"The kernel was fitted on {len(fit_rows):,} evenly spaced rows; all {len(rows):,} rows are projected.")
KERNEL = "rbf"
GAMMA = None
GAMMA = 1.0 / len(FEATURES) if GAMMA is None else float(GAMMA)
fit = dx.kpca(X, fit_rows, 2, KERNEL, GAMMA, 3, 1)
scores, eig, share = fit["scores"], fit["eigen"], fit["share"]
k = scores.shape[1]

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.kpca/iris_rbf/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)

# %% Result
values = {"n": len(rows), "n_fit": len(fit_rows), "n_variables": len(FEATURES), "n_components": k, "gamma": GAMMA, "n_positive": fit["n_positive"]}
for j in range(k):
    values[f"eigen[{j + 1}]"] = float(eig[j])
    values[f"share[{j + 1}]"] = float(share[j])
    values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
charts = [cs.chart("scree", "scree-plot", "Kernel variance by component", {
    "component": cs.col("Component", list(range(1, k + 1)), "numeric"),
    "variance": cs.col("Share of kernel variance", share, "numeric"),
    "cumulative": cs.col("Cumulative", np.cumsum(share), "numeric"),
})]
if k >= 2:
    pick = chart_rows(len(rows))
    groups = ["All rows"] * len(pick) if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL].iloc[rows[pick]]]
    charts.insert(0, cs.chart("map", "cluster-scatter", "Kernel PCA map", {
        "x": cs.col("kPC1", scores[pick, 0], "numeric"),
        "y": cs.col("kPC2", scores[pick, 1], "numeric"),
        "cluster": cs.col(LABEL or "Group", groups, "categorical"),
    }))
cs.publish({
    "title": "Kernel PCA",
    "engine": cs.engine_info("numpy", "pandas"),
    "n": len(rows),
    "summary": f"Kernel PCA ({KERNEL}, γ = {GAMMA:.3g}) of {len(FEATURES)} variables: component 1 carries {share[0]:.1%} of the kernel variance.",
    "statistics": [
        {"key": "share1", "label": "kPC1 share", "value": float(share[0]), "format": "percent"},
        {"key": "gamma", "label": "γ", "value": GAMMA},
    ],
    "tables": [{
        "key": "variance",
        "title": "Kernel variance",
        "columns": [{"key": "component", "label": "Component", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"},
                    {"key": "share", "label": "Share", "type": "percent"}],
        "rows": [{"component": j + 1, "eigen": float(eig[j]), "share": float(share[j])} for j in range(k)],
    }],
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
})

With γ\gamma = 0.25, the first kernel component holds 40.1% of the centered kernel's total and 148 of 150 eigenvalues are positive.

A degree-2 polynomial kernel on US arrests has only 14 positive eigenvalues: its feature space holds only the 4 columns, their 4 squares and their 6 pairwise products, 14 directions in all, so it can't be richer than that.

06

Where kernel PCA breaks

Read
  • The width decides everything. A tiny γ\gamma makes every row look alike and the map collapses toward linear PCA; a huge γ\gamma makes every row unlike every other and the map shatters.
  • No way back. A point in kernel space usually has no exact pre-image in the original columns, so "reconstruction" needs an extra estimator.
  • It costs n2n^2. The kernel matrix grows with the square of the rows.
  • New rows need the training centering, not a fresh one.
07

Readiness

Read

PCA and kernel PCA run in CodeSplash under Discover (Principal component analysis, Kernel PCA). Probabilistic PCA partly runs, as the Model choice inside PCA.

08

Check: the PCA family

Checkpoint

Check yourself

Why isn't "explained variance on the fitted rows" enough to choose PCA's rank?

Show the answer

Answer: a

On the rows you fitted, every extra component explains a little more. Reconstruction error on held-out rows stops improving when the extra components are fitting noise.

Check yourself

A sensor's drift column has the largest variance in your table, and PCA's first component is mostly that column. What is the honest reading?

Show the answer

Answer: a

PCA ranks directions by variance only. Remove or scale down nuisance columns, or judge components by downstream use.

Check yourself

Your columns have very different noise levels: one precise lab assay, several rough survey items. Which assumption of probabilistic PCA does that break?

Show the answer

Answer: a

PPCA's noise is isotropic. Factor analysis gives each column its own residual variance.

Check yourself

Two PPCA fits on the same data give latent axes rotated 30° from each other, with identical likelihoods. What does that mean?

Show the answer

Answer: a

WW and WRWR for any rotation RR give the same covariance WW⊤+σ2IWW^\top + \sigma^2 I, so the likelihood can't prefer one.

Check yourself

You raise the RBF kernel width γ\gamma to a huge value. What happens to the kernel PCA map?

Show the answer

Answer: a

With huge γ\gamma, e−γ∥x−y∥2e^{-\gamma\lVert x-y\rVert^2} is about 0 for any two different rows. Tiny γ\gamma has the opposite problem: rows look alike and the map drifts toward linear PCA.

Check yourself

Why can't kernel PCA reconstruct a row in its original columns the way PCA does?

Show the answer

Answer: a

PCA's map is linear and invertible on its subspace. The kernel feature map isn't, so going back is an extra, approximate step.

09

Recap

Recap
  • PCA keeps variance; pick its rank with held-out reconstruction and distrust high-variance nuisance.
  • Probabilistic PCA adds isotropic noise and a likelihood; it identifies a subspace, not axes.
  • Kernel PCA runs PCA on a centered kernel matrix; the width rules it, it costs n2n^2, and pre-images are approximate.

Concepts in this lesson