CDiscover · discover.kpca
Kernel PCA
Which curved, non-linear directions capture the structure in these numeric variables?
Principal components in a kernel feature space (RBF, polynomial, cosine or sigmoid): finds non-linear structure such as rings and spirals that ordinary PCA flattens. The kernel is fitted on up to 2,000 evenly spaced rows and every row is projected with the training centering, so large tables stay fast. Eigenvector signs are canonical, so Python and R agree.
A real result
Example “Iris rbf”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Kernel PCA (rbf, γ = 0.25) of 4 variables: component 1 carries 40.1% of the kernel variance.
- kPC1 share
- 40.1%
- γ
- 0.2500
Plots
View data
| species | kPC1 | kPC2 |
|---|---|---|
| setosa | 0.8020 | −0.0944 |
| setosa | 0.6659 | 0.1099 |
| setosa | 0.7587 | 0.0127 |
| setosa | 0.7064 | 0.0573 |
| setosa | 0.7937 | −0.1270 |
| setosa | 0.6286 | −0.1806 |
| setosa | 0.7802 | −0.0527 |
| setosa | 0.8041 | −0.0518 |
| setosa | 0.5829 | 0.0969 |
| setosa | 0.7187 | 0.0611 |
| setosa | 0.7231 | −0.1535 |
| setosa | 0.8003 | −0.0499 |
| setosa | 0.6704 | 0.0867 |
| setosa | 0.6177 | 0.0322 |
| setosa | 0.5239 | −0.1870 |
| setosa | 0.3453 | −0.1664 |
| setosa | 0.6363 | −0.1851 |
| setosa | 0.7961 | −0.0873 |
| setosa | 0.6127 | −0.1650 |
| setosa | 0.7179 | −0.1699 |
| setosa | 0.7352 | −0.0393 |
| setosa | 0.7462 | −0.1435 |
| setosa | 0.7570 | −0.1279 |
| setosa | 0.7224 | 0.0422 |
| setosa | 0.7831 | −0.0366 |
| setosa | 0.6508 | 0.1330 |
| setosa | 0.7797 | −0.0278 |
| setosa | 0.7886 | −0.0906 |
| setosa | 0.7871 | −0.0546 |
| setosa | 0.7513 | 0.0296 |
| setosa | 0.7135 | 0.0777 |
| setosa | 0.7222 | −0.0296 |
| setosa | 0.5499 | −0.1933 |
| setosa | 0.4719 | −0.1892 |
| setosa | 0.7163 | 0.0766 |
| setosa | 0.7609 | 0.0174 |
| setosa | 0.7327 | −0.0966 |
| setosa | 0.7913 | −0.1302 |
| setosa | 0.6365 | 0.0626 |
| setosa | 0.7966 | −0.0509 |
| setosa | 0.8035 | −0.0910 |
| setosa | 0.2587 | 0.1666 |
| setosa | 0.7155 | −0.0011 |
| setosa | 0.7404 | −0.0546 |
| setosa | 0.6925 | −0.1576 |
| setosa | 0.6601 | 0.1192 |
| setosa | 0.7189 | −0.1711 |
| setosa | 0.7476 | 0.0135 |
| setosa | 0.7399 | −0.1537 |
| setosa | 0.7897 | −0.0142 |
| versicolor | −0.3733 | −0.3334 |
| versicolor | −0.4119 | −0.1479 |
| versicolor | −0.4472 | −0.3221 |
| versicolor | −0.1828 | 0.6313 |
| versicolor | −0.5004 | 0.0732 |
| versicolor | −0.3431 | 0.4789 |
| versicolor | −0.3885 | −0.2168 |
| versicolor | 0.0370 | 0.5692 |
| versicolor | −0.4543 | 0.0206 |
| versicolor | −0.1629 | 0.5964 |
First 60 of 150 rows.
View data
| Component | Cumulative | Share of kernel variance |
|---|---|---|
| 1 | 0.4013 | 0.4013 |
| 2 | 0.5829 | 0.1816 |
Kernel variance
| Component | Eigenvalue | Share |
|---|---|---|
| 1 | 39.306 | 40.1% |
| 2 | 17.791 | 18.2% |
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
| Component | Eigenvalue | Share |
|---|---|---|
| 1 | 39.306 | 40.1% |
| 2 | 17.791 | 18.2% |
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
- Iris rbfml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Usarrests polyml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Pdna nullable labelpdna_penguins · features: bill_len, bill_dep, flipper_len, body_mass · label: sex
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–500 columns
- Numbers to map (standardized; rows with a missing value are left out).
- Color points bycategorical / boolean · 0–1 column
- Optional: colors the map only.
Choices you make
model
- Kerneldefault rbf
How similarity between two rows is measured before the PCA.
- Radial basis (Gaussian)(default) — exp(−γ‖x − y‖²): local, flexible; the usual choice.
- Polynomial — (γ x·y + c)^d: interactions up to degree d.
- Cosine — Angle between rows; ignores their length.
- Sigmoid — tanh(γ x·y + c): neural-network-like similarity.
- Kernel width (γ)default —
Larger γ = more local similarity (RBF) or steeper response.
- Degreedefault 3
Polynomial degree.
- Constant (c)default 1
The constant added inside the polynomial or sigmoid kernel.
- Components to keepdefault 2
Kernel principal components to return.
What it reports
- n
- How many independent units the analysis used; it sets precision and power.
- n_fit
- 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.
- n_components
- How many independent units the analysis used; it sets precision and power.
- gamma
- Half the average squared difference between pairs of sites, by distance. Low at short range when nearby sites resemble each other.
- n_positive
- How many independent units the analysis used; it sets precision and power.
Per group, level or term: eigen[<k>], share[<k>], score_check[<k>]
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-8). Python uses numpy; R uses codesplashr.
Default traps between the two languages
- Both engines compute the kernel column by column and center it the same way; scikit-learn's KernelPCA and kernlab::kpca use different eigen solvers, scalings and sign conventions. Here scores = centered kernel × eigenvectors / √eigenvalue (scikit-learn's convention) with each eigenvector's largest entry positive.
The exact script CodeSplash ran for example “Iris rbf” · 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"}],
})
The exact script CodeSplash ran for example “Iris rbf” · 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"))
))
Sources
- Schölkopf B, Smola A, Müller KR (1998). Nonlinear component analysis as a kernel eigenvalue problem. Neural Computation 10(5):1299–1319.
From the CodeSplash method registry · discover.kpca v1.0.0.