CDiscover · discover.mds
Multidimensional scaling (MDS / PCoA / NMDS)
How do rows sit relative to each other when only their distances matter?
Places rows on a map so that map distances reproduce chosen dissimilarities. Classical scaling (principal coordinates, PCoA) is exact for Euclidean distances and reports goodness of fit and negative eigenvalues for non-Euclidean ones (Bray–Curtis, Jaccard, Manhattan); non-metric MDS (Kruskal stress-1, SMACOF from the classical start) only keeps the rank order of the distances. Both engines run the same algorithm, so maps and stress agree. Sammon mapping weights small distances more, so local neighborhoods are kept. Distances can also come straight from the data: a square distance matrix (one row per object) or a long list of pairs (from, to, distance), for when there are no features.
A real result
Example “Usarrests classical”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Classical scaling (euclidean) placed 50 rows in 2 dimensions reproducing 86.8% of the positive variance.
- Goodness of fit
- 86.8%
- Stress
- —
Plots
View data
| Group | Dimension 1 | Dimension 2 |
|---|---|---|
| All rows | 0.9757 | 1.122 |
| All rows | 1.931 | 1.062 |
| All rows | 1.745 | −0.7385 |
| All rows | −0.1400 | 1.109 |
| All rows | 2.499 | −1.527 |
| All rows | 1.499 | −0.9776 |
| All rows | −1.345 | −1.078 |
| All rows | 0.0472 | −0.3221 |
| All rows | 2.983 | 0.0388 |
| All rows | 1.623 | 1.266 |
| All rows | −0.9035 | −1.555 |
| All rows | −1.623 | 0.2089 |
| All rows | 1.365 | −0.6750 |
| All rows | −0.5004 | −0.1500 |
| All rows | −2.231 | −0.1030 |
| All rows | −0.7889 | −0.2674 |
| All rows | −0.7433 | 0.9488 |
| All rows | 1.549 | 0.8623 |
| All rows | −2.373 | 0.3726 |
| All rows | 1.746 | 0.4234 |
| All rows | −0.4813 | −1.460 |
| All rows | 2.087 | −0.1538 |
| All rows | −1.676 | −0.6259 |
| All rows | 0.9865 | 2.370 |
| All rows | 0.6898 | −0.2607 |
| All rows | −1.174 | 0.5315 |
| All rows | −1.253 | −0.1920 |
| All rows | 2.846 | −0.7678 |
| All rows | −2.360 | −0.0179 |
| All rows | 0.1797 | −1.435 |
| All rows | 1.960 | 0.1414 |
| All rows | 1.666 | −0.8149 |
| All rows | 1.112 | 2.206 |
| All rows | −2.962 | 0.5931 |
| All rows | −0.2237 | −0.7348 |
| All rows | −0.3086 | −0.2850 |
| All rows | 0.0585 | −0.5360 |
| All rows | −0.8795 | −0.5654 |
| All rows | −0.8551 | −1.477 |
| All rows | 1.307 | 1.914 |
| All rows | −1.968 | 0.8151 |
| All rows | 0.9897 | 0.8516 |
| All rows | 1.342 | −0.4083 |
| All rows | −0.5450 | −1.457 |
| All rows | −2.773 | 1.388 |
| All rows | −0.0954 | 0.1977 |
| All rows | −0.2147 | −0.9604 |
| All rows | −2.087 | 1.411 |
| All rows | −2.059 | −0.6051 |
| All rows | −0.6231 | 0.3178 |
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 121.53 |
| 2 | 48.498 |
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
| Dimension | Eigenvalue |
|---|---|
| 1 | 121.53 |
| 2 | 48.498 |
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
- Usarrests classicalml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Usarrests bray curtisml_usarrests · features: Murder, Assault, UrbanPop, Rape
- Iris nmdsml_iris · features: sepal_length, sepal_width, petal_length, petal_width · label: species
- Eurodist matrix classicalrep2_eurodist · features: Athens, Barcelona, Brussels, Calais, Cherbourg, Cologne, Copenhagen, Geneva, Gibraltar, Hamburg, Hook of Holland, Lisbon, Lyons, Madrid, Marseilles, Milan, Munich, Paris, Rome, Stockholm, Vienna · label: city
- Eurodist matrix sammonrep2_eurodist · features: Athens, Barcelona, Brussels, Calais, Cherbourg, Cologne, Copenhagen, Geneva, Gibraltar, Hamburg, Hook of Holland, Lisbon, Lyons, Madrid, Marseilles, Milan, Munich, Paris, Rome, Stockholm, Vienna · label: city
- Europairs nmdsrep2_europairs · features: km · item_from: from · item_to: to
- Europairs classicalrep2_europairs · features: km · item_from: from · item_to: to
- Iris sammonrep2_iris_unique · features: sepal_length, sepal_width, petal_length, petal_width · label: species
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 · 1–2000 columns
- Numbers that define how different two rows are (rows with a missing value are left out). For a distance matrix, its columns in the same order as the rows; for a pair list, the one distance column.
- Color points bycategorical / boolean · 0–1 column
- Optional: colors the map only (and names the points of a distance matrix).
- From item (pair list)categorical · 0–1 column
- For a pair list: the first object of each pair.
- To item (pair list)categorical · 0–1 column
- For a pair list: the second object of each pair.
Choices you make
model
- Scalingdefault classical
Classical scaling keeps distances as numbers; non-metric scaling keeps only their order.
- Classical (PCoA)(default) — Exact eigen solution; also called Torgerson–Gower scaling or principal coordinates.
- Non-metric (NMDS) — Kruskal stress-1: only the rank order of dissimilarities matters; robust to odd distance scales.
- Sammon mapping — Weights each pair by 1/distance, so small distances (local neighborhoods) are kept best; from the classical start.
- Distances fromdefault features
Compute distances from variables, or use distances you already have.
- Variables(default) — Compute a dissimilarity between rows from the chosen variables.
- Distance matrix — The chosen variables are the columns of a square distance matrix: one row per object, columns in the same order as the rows.
- Pair list — One row per pair: From item, To item and the distance (the one chosen variable). Every pair must appear.
- Dissimilaritydefault euclidean
How different two rows are.
- Euclidean(default) — Straight-line distance on standardized variables.
- Manhattan — Sum of absolute differences on standardized variables.
- Bray–Curtis — Compositional dissimilarity for counts or abundances (raw, non-negative values).
- Jaccard (presence/absence) — Share of non-shared presences; a value above 0 counts as present.
- Dimensionsdefault 2
Map dimensions to return.
Advanced
- Maximum iterationsdefault 200
SMACOF iterations for non-metric MDS, or Sammon sweeps.
What it reports
- n
- 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.
- gof_abs
- Kept dimensions' eigenvalues over the sum of all absolute eigenvalues. Nearer 1 means the map keeps more of the distances.
- gof_pos
- A map whose distances reproduce a chosen dissimilarity as closely as possible, solved exactly by eigen decomposition.
- n_negative
- A map whose distances reproduce a chosen dissimilarity as closely as possible, solved exactly by eigen decomposition.
- stress
- A map that keeps only the rank order of dissimilarities, fitted by minimizing Kruskal stress.
- iterations
- Whether an iterative fit found a stable solution; warnings mean estimates may be unreliable.
Per group, level or term: eigen[<k>], coord_check[<k>]
Python and R
Python and R agree to 6 decimals (relative tolerance 1e-6). Python uses numpy, scikit-learn; R uses codesplashr, MASS.
Default traps between the two languages
- Classical scaling equals stats::cmdscale (coordinates up to sign; signs here are canonical) and agrees to rounding (P0 in practice). Non-metric MDS runs the codesplash SMACOF twin from the classical start with monotone regression (scikit-learn isotonic_regression ↔ stats::isoreg, which solve the same unique problem); vegan::metaMDS and MASS::isoMDS use random or different starts and stress definitions, so their maps differ.
- Rows beyond 1,000 are mapped on an evenly spaced sample of 1,000 rows (pairwise distances grow with the square of the rows). A distance matrix is never sampled (one row per object, up to 2,000); a pair list maps up to 1,000 items.
- Sammon mapping: the R engine calls MASS::sammon; the Python engine is a line-for-line port of MASS's C routine (VR_sammon) from the same classical start, so points and stress agree to rounding. MASS does not report the sweeps it used, so `iterations` is empty for Sammon in both engines.
- A pair list's items are ordered by code point in both engines (Python sorted(), R sort with method radix); duplicate pairs are averaged and a missing pair stops the run.
The exact script CodeSplash ran for example “Usarrests classical” · 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,
})
The exact script CodeSplash ran for example “Usarrests classical” · 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
))
Sources
- Gower JC (1966). Some distance properties of latent root and vector methods used in multivariate analysis. Biometrika 53:325–338.
- Kruskal JB (1964). Nonmetric multidimensional scaling: a numerical method. Psychometrika 29:115–129.
- De Leeuw J (1977). Applications of convex analysis to multidimensional scaling. In Recent Developments in Statistics, 133–145.
- Sammon JW (1969). A nonlinear mapping for data structure analysis. IEEE Transactions on Computers C-18:401–409.
- Venables WN, Ripley BD (2002). Modern Applied Statistics with S, 4th ed., §11.1 (MASS::sammon). Springer.
From the CodeSplash method registry · discover.mds v1.1.0.