Maps from distances: classical, non-metric and Sammon
When all you have is how far apart things are, MDS places them on a map. Classical scaling needs one eigendecomposition, non-metric scaling keeps only the order of distances, and Sammon mapping protects small ones.
What runs in CodeSplash
- REP026Classical multidimensional scaling Partly runs in CodeSplash
- REP027Nonmetric multidimensional scaling Runs in CodeSplash
- REP039Sammon mapping Partly runs in CodeSplash
- Multidimensional scaling (MDS / PCoA / NMDS) Verified in Python and R
You will be able to
- Double-center a squared distance matrix and explain why classical MDS on Euclidean distances equals PCA
- Read negative eigenvalues and the two goodness-of-fit numbers for non-Euclidean distances
- Contrast non-metric MDS's stress with Sammon's weighting, and read a Shepard diagram
From distances back to points
ReadRoad distances between cities, dissimilarities between species, disagreement between voters: sometimes you have only a dissimilarityDissimilarityA number for how unlike two rows are; distance-based tests ask their question of this matrix of all pairs. matrix and no columns. Multidimensional scaling (MDS) asks for points whose map distances reproduce as closely as possible.
The answer is never unique: any rotation, reflection or shift of the map keeps every distance. Read neighbors and spacing, not axes.
Classical scaling in one eigendecomposition
ReadSquare the distances and double-center them:
If came from points in Euclidean space, is their inner-product (Gram) matrix. Its top eigenvectors, scaled by , are the coordinates: .
For Euclidean distances on standardized columns, this is PCA exactly: on US arrests the classical map keeps 86.8%, the same share as two principal components.
Predict
PredictPredict first
You give classical MDS the road distances between European cities. How many negative eigenvalues do you expect?
Reveal
Many. Roads detour around mountains, seas and borders, so road distances break the geometry of a flat map. The run below counts them.
Distances that don't fit in a plane
ReadClassical scaling (distance matrix) placed 21 rows in 2 dimensions reproducing 86.8% of the positive variance.
- Goodness of fit
- 86.8%
- Stress
- —
Plots
View data
| city | Item | Dimension 1 | Dimension 2 |
|---|---|---|---|
| Athens | Athens | 2290.27 | −1798.80 |
| Barcelona | Barcelona | −825.38 | −546.81 |
| Brussels | Brussels | 59.183 | 367.08 |
| Calais | Calais | −82.846 | 429.91 |
| Cherbourg | Cherbourg | −352.50 | 290.91 |
| Cologne | Cologne | 293.69 | 405.31 |
| Copenhagen | Copenhagen | 681.93 | 1108.64 |
| Geneva | Geneva | −9.423 | −240.41 |
| Gibraltar | Gibraltar | −2048.45 | −642.46 |
| Hamburg | Hamburg | 561.11 | 773.37 |
| Hook of Holland | Hook of Holland | 164.92 | 549.37 |
| Lisbon | Lisbon | −1935.04 | −49.125 |
| Lyons | Lyons | −226.42 | −187.09 |
| Madrid | Madrid | −1423.35 | −305.88 |
| Marseilles | Marseilles | −299.50 | −388.81 |
| Milan | Milan | 260.88 | −416.67 |
| Munich | Munich | 587.68 | −81.182 |
| Paris | Paris | −156.84 | 211.14 |
| Rome | Rome | 709.41 | −1109.37 |
| Stockholm | Stockholm | 839.45 | 1836.79 |
| Vienna | Vienna | 911.23 | −205.93 |
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.954e+7 |
| 2 | 1.186e+7 |
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 a455379895bba44c
# Dataset: rep2_eurodist (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("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"
DISTANCE <- "euclidean"
METHOD <- "classical"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", col_select = unique(c(FEATURES, LABEL))), check.names = FALSE)
n_input <- nrow(df)
warnings <- list()
n_missing <- sum(is.na(df[FEATURES]))
if (n_missing > 0) cs_error("CS_E_INVALID_VALUES", column = "The distance matrix", requirement = "complete (no missing distances)", count = n_missing)
mx <- cs_ml_mds_matrix(df[FEATURES], FEATURES)
D <- mx$D
warnings <- c(warnings, as.list(mx$notes))
rows <- seq_len(nrow(df)) - 1L
point_labels <- if (is.null(LABEL)) NULL else { g <- as.character(df[[LABEL]]); g[is.na(g)] <- "(missing)"; g }
if (length(rows) < 3) cs_error("CS_E_TOO_FEW_ROWS", what = "MDS", min = 3, n = length(rows))
# %% 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/eurodist_matrix_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(point_labels) || length(unique(point_labels)) > 30) rep("All items", length(rows)) else point_labels
data <- 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")
)
if (!is.null(point_labels)) data$label <- cs_col("Item", point_labels, "categorical")
charts <- c(list(cs_chart("map", "cluster-scatter", MAP_TITLE, data)), charts)
}
SOURCE <- switch("matrix", features = gsub("_", "–", DISTANCE), matrix = "distance matrix", pairs = "pair list")
WHAT <- if ("matrix" == "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
))
Classical scaling (distance matrix) placed 21 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 | 1.954e+7 |
| 2 | 1.186e+7 |
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 a455379895bba44c
# Dataset: rep2_eurodist (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
from codesplash.ml import mds_ext as mdsx
# %% Data
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"
DISTANCE = "euclidean"
METHOD = "classical"
# A square dissimilarity matrix: the chosen variables are its columns, one dataset row per object.
df = pd.read_parquet("tests/parity/fixtures/rep2_eurodist.parquet", columns=list(dict.fromkeys(FEATURES + ([LABEL] if LABEL else []))))
n_input = len(df)
warnings = []
n_missing = int(df[FEATURES].isna().to_numpy().sum())
if n_missing:
cs.cs_error("CS_E_INVALID_VALUES", column="The distance matrix", requirement="complete (no missing distances)", count=n_missing)
D, notes = mdsx.matrix_input(df[FEATURES].to_numpy(dtype=float), FEATURES)
warnings += notes
rows = np.arange(len(df))
point_labels = None if LABEL is None else [("(missing)" if pd.isna(v) else str(v)) for v in df[LABEL]]
if len(rows) < 3:
cs.cs_error("CS_E_TOO_FEW_ROWS", what="MDS", min=3, n=len(rows))
# %% 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/eurodist_matrix_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 items"] * len(rows) if point_labels is None or len(set(point_labels)) > 30 else point_labels
data = {
"x": cs.col("Dimension 1", coords[:, 0], "numeric"),
"y": cs.col("Dimension 2", coords[:, 1], "numeric"),
"cluster": cs.col(LABEL or "Group", groups, "categorical"),
}
if point_labels is not None:
data["label"] = cs.col("Item", point_labels, "categorical")
charts.insert(0, cs.chart("map", "cluster-scatter", MAP_TITLE, data))
SOURCE = {"features": DISTANCE.replace("_", "–"), "matrix": "distance matrix", "pairs": "pair list"}["matrix"]
WHAT = "items" if "matrix" == "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,
})
Road distances among 21 European cities give 9 negative eigenvalues: roads bend around mountains and seas, so no flat map matches them exactly.
Two fit numbers follow. Measured against positive eigenvalues only, two dimensions keep 86.8%; against the absolute values of all of them, 75.4%. A large gap means much of the dissimilarity structure isn't Euclidean.
Non-metric: keep the order
ReadOften only the order of dissimilarities is trustworthy: "A is more like B than like C". Non-metric MDSNon-metric MDSA map that keeps only the rank order of dissimilarities, fitted by minimizing Kruskal stress. fits a monotone transformation of the dissimilarities (the disparities) and minimizes Kruskal's stress:
It is fitted iteratively, so it can stop in a local minimum; CodeSplash starts from the classical solution. On iris, stress-1 is 0.042.
Sammon: protect small distances
ReadSammon mappingSammon mappingMDS that weights each pair by one over its distance, so small distances — local neighborhoods — are kept best. divides each squared error by the original distance:
An error of 10 km between two neighboring towns costs far more than the same error between Lisbon and Stockholm, so local neighborhoods are kept best. Duplicate rows (distance 0) make the weights infinite, so remove them first. On the city distances Sammon's error is 0.0094.
Read the Shepard diagram
ReadA Shepard diagramShepard diagramMap distance plotted against original dissimilarity, with the monotone fit NMDS works to. plots original dissimilarities against map distances, one dot per pair. A tight band means the map is faithful. A wide fan at the small end means local neighborhoods are scrambled; at the large end, the global layout is.
Low stress doesn't prove a mechanism. It says the map reproduces the dissimilarities you chose, nothing more.
Check: MDS
CheckpointCheck yourself
You run classical MDS on Euclidean distances computed from standardized columns. How does the map compare with PCA scores?
Show the answer
Answer: a
Double-centering squared Euclidean distances recovers the Gram matrix of the centered data, whose eigenvectors give the principal component scores.
Check yourself
Classical MDS reports many large negative eigenvalues. What does that tell you?
Show the answer
Answer: a
Dropping the negative directions changes the distances you represent. Consider non-metric MDS, or a different dissimilarity.
Check yourself
When should you prefer non-metric MDS over classical MDS?
Show the answer
Answer: a
Non-metric MDS fits any monotone transformation of the dissimilarities, so only their order matters.
Check yourself
Two non-metric MDS runs from different random starts give stress 0.08 and 0.15. What should you conclude?
Show the answer
Answer: a
Non-metric MDS is optimized iteratively and can get stuck. Keep the lowest-stress solution and check that it's stable.
Check yourself
Which errors does Sammon mapping punish most?
Show the answer
Answer: a
Each squared error is divided by the original distance, so small distances carry large weights.
Check yourself
Sammon mapping stops with an error on a table containing duplicate rows. Why?
Show the answer
Answer: a
Remove exact duplicates (or merge them) before a Sammon map; CodeSplash stops with a clear message.
Recap
Recap- Classical MDS double-centers squared distances and takes eigenvectors; on Euclidean distances it is PCA.
- Negative eigenvalues flag non-Euclidean dissimilarities; report both fit measures.
- Non-metric MDS keeps order via stress; Sammon weights small distances; read either with a Shepard diagram.
Concepts in this lesson