Skip to content

Other decompositions: ICA, NMF, kernel PCA, MDS and autoencoders

Each of these asks something PCA can't. Learn what question each one answers, so you reach for the right one.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Choose among ICA, NMF, kernel PCA, MDS and autoencoders by the question you are asking
  • Read stress and goodness of fit for MDS
  • Explain how a bottleneck turns reconstruction error into a map and an anomaly score

Read first

01

Five different questions

Read

PCA asks which directions hold the most variance. The other maps ask something else:

MethodThe question
ICAIndependent component analysisUnmixes variables into statistically independent, non-Gaussian sources and the matrix that mixed them.Which independent signals were mixed together?
NMFNon-negative matrix factorizationSplits non-negative data into a few additive parts so every row is a weighted sum of part profiles.Which additive parts build these non-negative values?
Kernel PCAKernel PCAPCA after mapping rows into a richer similarity space, so curved structure (rings, spirals) can unroll.Which curved directions hold the structure?
MDSWhere do rows sit, given only their distances?
AutoencoderAutoencoderA neural network that squeezes rows through a narrow layer and rebuilds them; the narrow layer works as a map.What can a network squeeze the rows through and rebuild?
02

Match a method

Predict

Predict first

Four microphones each record a different blend of three speakers. You want the separate voices back. Which method fits?

PCAICANMF
Reveal

ICA. PCA would give uncorrelated blends ordered by volume, and NMF needs non-negative parts. ICA looks for statistically independent, non-Gaussian sources: here it separates four channels into 3 components over 400 rows.

03

ICA: unmixing signals

Read

ICA first removes correlation, then rotates to make the components as non-Gaussian as possible. It relies on the fact that a blend of independent signals looks more normal than its parts.

So it needs non-Gaussian sources: two pure normal signals can't be unmixed. Component order and sign have no meaning, so name each one by what it looks like and how it loads onto the channels.

On your own data, a good reason to try ICA is that PCA's components look like blends of ideas you recognize separately.

04

NMF: parts, not contrasts

Reflect

Because NMF can only add, it builds rows out of parts, like ingredients in a recipe. PCA components mix plus and minus signs, so they read as contrasts.

NMF suits counts, amounts and intensities. US arrests factorizes into two parts with a relative error of 14%, and iris into three with 2%.

Don't feed it negative values. By default, the app scales each column by its maximum first, so large-unit columns don't take over.

Pick a table of counts or amounts you know. What parts would you expect it to break into?

05

Kernel PCA: curves

Read

Kernel PCA runs PCA on similarities instead of raw columns, so it can unroll rings and spirals that ordinary PCA flattens.

The price is interpretation: components no longer combine your columns, so there are no loadings to read. The bandwidth γ\gamma sets how local similarity is. Here the default for iris is 0.250. Try several values, as the map depends heavily on it.

Choose it when the structure is visibly curved, and you need a map more than an explanation.

06

MDS: only distances

In the app

MDS starts from a distance matrix. Use it when "how different are these two?" is what you really have.

Classical MDS on Euclidean distances gives the same answer as PCA on scaled data: both have a fit of 87% on US arrests (PCA: 87%). With other distances, negative eigenvalues show the distances aren't Euclidean: Bray–Curtis gives 26.

Non-metric MDSNon-metric MDSA map that keeps only the rank order of dissimilarities, fitted by minimizing Kruskal stress. keeps only the order of distances, and stress measures the misfit: iris gets 0.042. Low is good, and below 0.1 is commonly called a fair fit.

Multidimensional scaling (MDS / PCoA / NMDS)Recorded · Python and R agreeRecorded 2026-11-25 · 12 values compared
R

Classical scaling (euclidean) placed 50 rows in 2 dimensions reproducing 86.8% of the positive variance.

Goodness of fit
86.8%
Stress
—

Plots

Principal coordinatesWhich rows group together, and how well separated are the groups?
View data
GroupDimension 1Dimension 2
All rows0.97571.122
All rows1.9311.062
All rows1.745−0.7385
All rows−0.14001.109
All rows2.499−1.527
All rows1.499−0.9776
All rows−1.345−1.078
All rows0.0472−0.3221
All rows2.9830.0388
All rows1.6231.266
All rows−0.9035−1.555
All rows−1.6230.2089
All rows1.365−0.6750
All rows−0.5004−0.1500
All rows−2.231−0.1030
All rows−0.7889−0.2674
All rows−0.74330.9488
All rows1.5490.8623
All rows−2.3730.3726
All rows1.7460.4234
All rows−0.4813−1.460
All rows2.087−0.1538
All rows−1.676−0.6259
All rows0.98652.370
All rows0.6898−0.2607
All rows−1.1740.5315
All rows−1.253−0.1920
All rows2.846−0.7678
All rows−2.360−0.0179
All rows0.1797−1.435
All rows1.9600.1414
All rows1.666−0.8149
All rows1.1122.206
All rows−2.9620.5931
All rows−0.2237−0.7348
All rows−0.3086−0.2850
All rows0.0585−0.5360
All rows−0.8795−0.5654
All rows−0.8551−1.477
All rows1.3071.914
All rows−1.9680.8151
All rows0.98970.8516
All rows1.342−0.4083
All rows−0.5450−1.457
All rows−2.7731.388
All rows−0.09540.1977
All rows−0.2147−0.9604
All rows−2.0871.411
All rows−2.059−0.6051
All rows−0.62310.3178

Principal coordinates

DimensionEigenvalue
1121.53
248.498
The exact R script · R R version 4.5.1 (2025-06-13)
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec 54a6e6c2f89c6a53
# 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")
LABEL <- NULL
DISTANCE <- "euclidean"
METHOD <- "classical"
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)  # infinite values stop the run (registry/errors.yaml)
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))
}
keep <- cs_ml_even_sample(length(rows), 1000)
if (length(keep) < length(rows)) {
  warnings <- c(warnings, sprintf("MDS maps %s evenly spaced rows of %s (pairwise distances grow with the square of the rows).",
                                  format(length(keep), big.mark = ","), format(length(rows), big.mark = ",")))
  rows <- rows[keep + 1L]
}
cs_check_rows(length(rows), 3, "MDS")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
if (DISTANCE %in% c("euclidean", "manhattan")) {
  s <- apply(X, 2, stats::sd)
  s[s == 0] <- 1
  X <- sweep(sweep(X, 2, colMeans(X)), 2, s, "/")
}
D <- cs_ml_dissimilarity(X, DISTANCE)

# %% Scaling
K <- min(2, length(rows) - 1L)
classical <- cs_ml_pcoa(D, K)
coords <- classical$coords
K <- ncol(coords)
values <- list(n = length(rows), n_variables = length(FEATURES), n_components = K,
               gof_abs = classical$gof_abs, gof_pos = classical$gof_pos, n_negative = classical$n_negative,
               stress = NaN, iterations = 0L)
for (j in seq_len(K)) values[[sprintf("eigen[%d]", j)]] <- classical$eigen[j]
charts <- list()
if (METHOD == "nmds") {
  fit <- cs_ml_nmds(D, coords, max_iter = 200)
  coords <- fit$coords
  values$stress <- fit$stress
  values$iterations <- fit$iterations
  show <- cs_ml_even_sample(length(fit$delta), 2000) + 1L
  note <- sprintf("Kruskal stress-1 = %.3f", fit$stress)
  if (length(show) < length(fit$delta)) note <- paste0(note, sprintf("; %s of %s pairs shown", format(length(show), big.mark = ","), format(length(fit$delta), big.mark = ",")))
  charts[[1]] <- cs_chart("shepard", "shepard-diagram", "Shepard diagram", list(
    dissimilarity = cs_col("Dissimilarity", fit$delta[show], "numeric"),
    distance = cs_col("Map distance", fit$distance[show], "numeric"),
    fitted = cs_col("Monotone fit", fit$disparity[show], "numeric")
  ), note = note)
  if (fit$stress > 0.2) warnings <- c(warnings, sprintf("Stress %.2f is high (above 0.2): the map distorts many distances — try more dimensions.", fit$stress))
}
for (j in seq_len(K)) values[[sprintf("coord_check[%d]", j)]] <- cs_ml_checksum(coords[, j], rows)

# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-8142/discover.mds/usarrests_classical/out-r")
emb <- data.frame(row = as.integer(rows))
for (j in seq_len(K)) emb[[paste0("dim_", j)]] <- coords[, j]
nanoparquet::write_parquet(emb, file.path(out, "embedding.parquet"))
ARTIFACTS <- list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))

# %% Result
MAP_TITLE <- switch(METHOD, nmds = "NMDS map", sammon = "Sammon map", "Principal coordinates")
if (K >= 2) {
  groups <- if (is.null(LABEL)) rep("All rows", length(rows)) else {
    g <- as.character(df[[LABEL]][rows + 1L]); g[is.na(g)] <- "(missing)"; g
  }
  charts <- c(list(cs_chart("map", "cluster-scatter", if (METHOD == "nmds") "NMDS map" else "Principal coordinates", list(
    x = cs_col("Dimension 1", coords[, 1], "numeric"),
    y = cs_col("Dimension 2", coords[, 2], "numeric"),
    cluster = cs_col(if (is.null(LABEL)) "Group" else LABEL, groups, "categorical")
  ))), charts)
}
SOURCE <- switch("features", features = gsub("_", "–", DISTANCE), matrix = "distance matrix", pairs = "pair list")
WHAT <- if ("features" == "pairs") "items" else "rows"
summary <- if (METHOD == "nmds") {
  sprintf("Non-metric MDS (%s) placed %d %s in %d dimensions with stress %.3f.", SOURCE, length(rows), WHAT, K, values$stress)
} else if (METHOD == "sammon") {
  sprintf("Sammon mapping (%s) placed %d %s in %d dimensions with stress %.4f.", SOURCE, length(rows), WHAT, K, values$stress)
} else {
  sprintf("Classical scaling (%s) placed %d %s in %d dimensions reproducing %.1f%% of the positive variance.", SOURCE, length(rows), WHAT, K, 100 * classical$gof_pos)
}
cs_publish(list(
  title = "Multidimensional scaling (MDS / PCoA / NMDS)",
  engine = cs_engine_info("codesplashr", "nanoparquet"),
  n = length(rows),
  summary = summary,
  statistics = list(list(key = "gof_pos", label = "Goodness of fit", value = classical$gof_pos, format = "percent"),
                    list(key = "stress", label = "Stress", value = values$stress)),
  tables = list(list(key = "eigen", title = "Principal coordinates",
                     columns = list(list(key = "dimension", label = "Dimension", type = "integer"),
                                    list(key = "eigen", label = "Eigenvalue", type = "number")),
                     rows = lapply(seq_len(K), function(j) list(dimension = j, eigen = classical$eigen[j])))),
  charts = charts,
  values = values,
  warnings = warnings,
  artifacts = ARTIFACTS
))
Python

Classical scaling (euclidean) placed 50 rows in 2 dimensions reproducing 86.8% of the positive variance.

Goodness of fit
86.8%
Stress
—

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

Principal coordinates

DimensionEigenvalue
1121.53
248.498
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Multidimensional scaling (MDS / PCoA / NMDS)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.mds 1.1.0 · spec 54a6e6c2f89c6a53
# 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 cluster as csc
from codesplash.ml import discover_ext as dx
from codesplash.ml import embed as csembed

# %% Data
FEATURES = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None
DISTANCE = "euclidean"
METHOD = "classical"
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)  # infinite values stop the run (registry/errors.yaml)
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.")
keep = csc.even_sample(len(rows), 1000)
if len(keep) < len(rows):
    warnings.append(f"MDS maps {len(keep):,} evenly spaced rows of {len(rows):,} (pairwise distances grow with the square of the rows).")
    rows = rows[keep]
cs.check_rows(len(rows), 3, "MDS")
X = csembed.numeric_matrix(df, FEATURES, rows)
if DISTANCE in ("euclidean", "manhattan"):
    X = csembed.standardize(X, ddof=1)
D = dx.dissimilarity(X, DISTANCE)

# %% Scaling
K = min(2, len(rows) - 1)
classical = dx.pcoa(D, K)
coords = classical["coords"]
K = coords.shape[1]
values = {
    "n": len(rows), "n_variables": len(FEATURES), "n_components": K,
    "gof_abs": classical["gof_abs"], "gof_pos": classical["gof_pos"], "n_negative": classical["n_negative"],
    "stress": float("nan"), "iterations": 0,
}
for j in range(K):
    values[f"eigen[{j + 1}]"] = float(classical["eigen"][j])
charts = []
if METHOD == "nmds":
    fit = dx.nmds(D, coords, max_iter=200)
    coords = fit["coords"]
    values["stress"] = fit["stress"]
    values["iterations"] = fit["iterations"]
    show = csc.even_sample(len(fit["delta"]), 2000)
    charts.append(cs.chart("shepard", "shepard-diagram", "Shepard diagram", {
        "dissimilarity": cs.col("Dissimilarity", fit["delta"][show], "numeric"),
        "distance": cs.col("Map distance", fit["distance"][show], "numeric"),
        "fitted": cs.col("Monotone fit", fit["disparity"][show], "numeric"),
    }, note=f"Kruskal stress-1 = {fit['stress']:.3f}" + ("" if len(show) == len(fit["delta"]) else f"; {len(show):,} of {len(fit['delta']):,} pairs shown")))
    if fit["stress"] > 0.2:
        warnings.append(f"Stress {fit['stress']:.2f} is high (above 0.2): the map distorts many distances — try more dimensions.")
for j in range(K):
    values[f"coord_check[{j + 1}]"] = csembed.checksum(coords[:, j], rows)

# %% Artifacts
out = csml.out_dir("target/academy-parity/run-8142/discover.mds/usarrests_classical/out-python")
emb = pd.DataFrame({"row": rows.astype(np.int64)})
for j in range(K):
    emb[f"dim_{j + 1}"] = coords[:, j]
emb.to_parquet(os.path.join(out, "embedding.parquet"), index=False)
ARTIFACTS = [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}]

# %% Result
MAP_TITLE = {"nmds": "NMDS map", "sammon": "Sammon map"}.get(METHOD, "Principal coordinates")
if K >= 2:
    groups = ["All rows"] * len(rows) if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL].iloc[rows]]
    charts.insert(0, cs.chart("map", "cluster-scatter", "NMDS map" if METHOD == "nmds" else "Principal coordinates", {
        "x": cs.col("Dimension 1", coords[:, 0], "numeric"),
        "y": cs.col("Dimension 2", coords[:, 1], "numeric"),
        "cluster": cs.col(LABEL or "Group", groups, "categorical"),
    }))
SOURCE = {"features": DISTANCE.replace("_", "–"), "matrix": "distance matrix", "pairs": "pair list"}["features"]
WHAT = "items" if "features" == "pairs" else "rows"
if METHOD == "nmds":
    summary = f"Non-metric MDS ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.3f}."
elif METHOD == "sammon":
    summary = f"Sammon mapping ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions with stress {values['stress']:.4f}."
else:
    summary = f"Classical scaling ({SOURCE}) placed {len(rows)} {WHAT} in {K} dimensions reproducing {classical['gof_pos']:.1%} of the positive variance."
cs.publish({
    "title": "Multidimensional scaling (MDS / PCoA / NMDS)",
    "engine": cs.engine_info("numpy", "scikit-learn", "pandas"),
    "n": len(rows),
    "summary": summary,
    "statistics": [
        {"key": "gof_pos", "label": "Goodness of fit", "value": classical["gof_pos"], "format": "percent"},
        {"key": "stress", "label": "Stress", "value": values["stress"]},
    ],
    "tables": [{
        "key": "eigen",
        "title": "Principal coordinates",
        "columns": [{"key": "dimension", "label": "Dimension", "type": "integer"}, {"key": "eigen", "label": "Eigenvalue", "type": "number"}],
        "rows": [{"dimension": j + 1, "eigen": float(classical["eigen"][j])} for j in range(K)],
    }],
    "charts": charts,
    "values": values,
    "warnings": warnings,
    "artifacts": ARTIFACTS,
})
07

Check the fit

Explore

A Shepard diagram plots original distances against map distances. Points close to a rising curve mean a faithful map. Wide scatter means the map misstates some pairs.

Shepard diagramHow faithfully does an MDS map keep the original distances?
View data
dissimilaritymap distancemonotone fit
2.7281.8211.799
1.7371.5221.492
3.0421.7021.910
2.6281.9821.799
2.5071.7091.799
2.1111.4001.602
0.44800.92800.7559
0.57801.0760.8525
2.5271.7911.799
1.2561.4681.212
3.4852.1321.997
0.80501.0351.032
3.8602.1142.115
3.5492.2572.115
0.20300.57000.5580
3.4931.9741.997
0.68501.0390.9494
1.4341.2121.341
0.95901.0561.109
1.3451.2341.236
1.0161.0431.109
2.5961.9701.799
1.2631.2101.212
2.8261.8611.813
1.2121.1981.206
1.8841.8331.559
2.3631.8291.738
1.8511.5141.520
2.4031.7401.738
0.79801.0101.032
2.8951.8041.813
3.5022.0072.017
3.6572.0442.115
0.59901.0730.8529
0.66401.2340.9494
2.5911.7491.799
2.3401.6621.729
2.8511.8921.813
3.9122.1462.208
0.53600.94600.7722
0.24900.66400.5612
1.4971.4991.363
1.8261.5311.520
3.4991.7361.997
2.1581.5331.607
2.0151.6441.559
0.59300.92600.8529
2.5931.8381.799
0.26800.67700.5612
1.3901.5231.341
1.5381.3071.363
0.58800.70800.8525
0.43500.82100.6828
3.6402.1532.115
2.5172.0221.799
2.7561.8561.799
3.4312.0631.997
2.6001.7051.799
0.77001.1721.032
3.3322.0661.997

First 60 of 400 rows.

Find the region of the chart with the widest scatter. Small distances and large distances often behave differently, and that tells you which comparisons to trust on the map.

08

Autoencoders: a learned bottleneck

Read

An autoencoder is a neural network that squeezes each row through a narrow layer and rebuilds it. The bottleneck is your map, and it can bend. With no hidden layer, it's about the same as PCA.

On iris: reconstruction error of 0.0395 per standardized feature, trustworthiness 0.978. Rows it rebuilds worst become anomaly candidates: 8 here, since the default rule flags a fixed share.

It has more settings to get wrong than PCA does, so start with PCA and move on only if the fit improves meaningfully.

09

Check your understanding

Checkpoint

Check yourself

You have word counts per document and want topics that read as "ingredients" of each document. Which method fits best?

Show the answer

Answer: b

Non-negative counts and additive parts are what NMF is for. It's also one of the two engines behind the topic models you'll meet later in this track.

Check yourself

You have only a table of perceived differences between 20 products, gathered from a survey. Which method can use that directly?

Show the answer

Answer: b

MDS only needs dissimilarities. Non-metric MDS is a natural choice here, because survey differences are more trustworthy as an order than as exact amounts.

Check yourself

Why can't ICA separate two independent, purely Gaussian signals?

Show the answer

Answer: a

Non-Gaussian shape is ICA's only foothold. With normal sources there's nothing to distinguish one rotation from another.

10

Do it on your own data

In the app

Each of these runs under Map the data. Start from PCA as your baseline, and try one of them only when your question needs it.

Python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.decomposition import NMF, FastICA, KernelPCA
from sklearn.preprocessing import MinMaxScaler, StandardScaler

X = load_iris().data
Z = StandardScaler().fit_transform(X)
print(FastICA(n_components=2, random_state=1).fit_transform(Z)[:2].round(3))
nmf = NMF(n_components=3, init="nndsvda", max_iter=500, random_state=1).fit(MinMaxScaler().fit_transform(X))
print(round(nmf.reconstruction_err_, 3))
print(KernelPCA(n_components=2, kernel="rbf", gamma=0.25).fit_transform(Z)[:2].round(3))
R
X <- as.matrix(iris[, 1:4])
d <- dist(scale(X))
mds <- cmdscale(d, k = 2, eig = TRUE)
round(mds$GOF, 3)
nmds <- MASS::isoMDS(d + 1e-6, k = 2, trace = FALSE)
round(nmds$stress / 100, 3)

isoMDS reports stress as a percentage, and needs no zero distances, hence the small constant added.

11

Recap

Recap
  • Choose by the question: unmixing, parts, curves, distances or a learned squeeze.
  • Check fit before you read a map: stress, goodness of fit or reconstruction error.
  • PCA is the baseline. Each alternative has to earn its added complexity.

Concepts in this lesson