Rows as points: vectors and distances
Treat each row of a table as a point in space, measure how far apart two rows are in four different ways, and see why the choice of distance changes every method built on it.
What runs in CodeSplash
- Multidimensional scaling (MDS / PCoA / NMDS) Verified in Python and R
You will be able to
- Describe a row of numeric columns as a vector in p-dimensional space
- Compute Euclidean, Manhattan and cosine comparisons by hand on a small example
- Explain what Mahalanobis distance adds and when a distance is not Euclidean
Read first
A row is a point
ReadA table with numeric columns turns each row into a list of numbers: a vector. Picture it as a point, or an arrow from the origin, in -dimensional space.
Two columns give a flat scatter plot. Four columns give a space you can't draw, but the arithmetic is the same.
Almost every method in this Academy asks one question first: how far apart are two rows? Clustering groups close rows, nearest-neighbor learners copy close rows, and maps try to keep close rows close. The answer depends on how you measure.
Four ways to measure
ReadFor rows and :
| Measure | Formula | It cares about |
|---|---|---|
| EuclideanEuclidean distanceThe straight-line distance between two rows: square the differences column by column, add them up, take the square root. | straight-line gaps; big gaps count extra | |
| ManhattanManhattan distanceThe sum of the absolute differences, column by column: the distance walked along a street grid. | total gap, no squaring | |
| CosineCosine similarityThe cosine of the angle between two vectors: 1 for the same direction, 0 for unrelated, −1 for opposite. | direction only, not length | |
| MahalanobisMahalanobis distanceDistance between points or means measured in standard deviations, allowing for the variables' correlations. | gaps measured against the data's own spread and correlation |
The dot productDot productMultiply two vectors entry by entry and add: large when they point the same way, zero when they are at right angles. sits inside cosine: it is large when two arrows point the same way.
Distances change with units
ExploreAExplorable · Distance depends on units
Who counts as a neighbor when one column is in years and another in dollars?
The two groups differ only in age. With these units and this scaling, which column decides who is whose neighbor?
Income recorded in
Scaling
Distance
Odd, so a vote can't tie.
- Younger group
- Older group
Both axes use the same unit length, so a column with a huge range stretches the picture along its axis. Distances are measured in this picture.
Commit your prediction above to see the result
Make your prediction to see the result.
Switch the distance between Euclidean, Manhattan, cosine and Mahalanobis, and watch who counts as person one's nearest neighbors. Then record income in dollars: the column with the bigger numbers takes over every distance except Mahalanobis, which rescales by the data's own covariance.
Work one by hand
PredictPredict first
Row A is and row B is . What are the Euclidean and Manhattan distances?
Reveal
The gaps are 3 and 4. Euclidean is ; Manhattan is . Manhattan is never smaller, because a grid walk can't beat a straight line.
Length versus direction
ReadTwo shoppers bought the same mix of products, but one spent ten times more. Their vectors point the same way and differ only in length.
- Euclidean and Manhattan call them far apart.
- Cosine similarity is 1: identical direction.
That is why text and embedding methods often use cosine. Word counts grow with document length, and what matters is the mix, not the total. When length is the signal (spend, dose, size), cosine throws it away.
Not every dissimilarity is a distance in space
ReadClassical scaling (bray–curtis) placed 50 rows in 3 dimensions reproducing 90.8% of the positive variance.
- Goodness of fit
- 90.8%
- Stress
- —
Plots
View data
| Group | Dimension 1 | Dimension 2 |
|---|---|---|
| All rows | −0.1488 | 0.0495 |
| All rows | −0.2110 | 0.1078 |
| All rows | −0.2248 | −0.0173 |
| All rows | −0.0712 | 0.0601 |
| All rows | −0.2263 | −0.0294 |
| All rows | −0.1253 | −0.0580 |
| All rows | 0.1184 | −0.0805 |
| All rows | −0.1422 | −0.0016 |
| All rows | −0.2626 | −0.0016 |
| All rows | −0.1228 | 0.0224 |
| All rows | 0.2410 | −0.1573 |
| All rows | 0.1120 | 0.0252 |
| All rows | −0.1780 | −0.0349 |
| All rows | 0.0940 | −0.0375 |
| All rows | 0.3025 | 0.0221 |
| All rows | 0.0966 | −0.0380 |
| All rows | 0.1220 | 0.0392 |
| All rows | −0.1695 | 0.0159 |
| All rows | 0.2394 | 0.0598 |
| All rows | −0.2226 | 0.0279 |
| All rows | 0.0045 | −0.0870 |
| All rows | −0.1919 | −0.0130 |
| All rows | 0.2277 | −0.0410 |
| All rows | −0.1900 | 0.1362 |
| All rows | −0.0669 | −0.0424 |
| All rows | 0.1304 | 0.0285 |
| All rows | 0.1427 | −0.0163 |
| All rows | −0.2026 | −0.0323 |
| All rows | 0.3070 | 0.0307 |
| All rows | −0.0287 | −0.0895 |
| All rows | −0.2157 | 0.0117 |
| All rows | −0.1896 | −0.0350 |
| All rows | −0.2531 | 0.1709 |
| All rows | 0.3764 | 0.1287 |
| All rows | 0.0645 | −0.0770 |
| All rows | 0.0046 | −0.0411 |
| All rows | −0.0220 | −0.0451 |
| All rows | 0.1183 | −0.0605 |
| All rows | −0.0435 | −0.0693 |
| All rows | −0.2102 | 0.1176 |
| All rows | 0.2235 | 0.0824 |
| All rows | −0.0824 | 0.0139 |
| All rows | −0.1151 | −0.0550 |
| All rows | 0.0658 | −0.0989 |
| All rows | 0.3844 | 0.1420 |
| All rows | −0.0065 | −0.0183 |
| All rows | 0.0071 | −0.0702 |
| All rows | 0.2527 | 0.1006 |
| All rows | 0.2921 | −0.0520 |
| All rows | −0.0040 | 0.0069 |
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.697 |
| 2 | 0.2433 |
| 3 | 0.1514 |
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 5ab97efab4dd6ef2
# 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 <- "bray_curtis"
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(3, 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_bray_curtis/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
))
Classical scaling (bray–curtis) placed 50 rows in 3 dimensions reproducing 90.8% of the positive variance.
- Goodness of fit
- 90.8%
- Stress
- —
To keep this page light, the plots are shown once, under the R tab.
Principal coordinates
| Dimension | Eigenvalue |
|---|---|
| 1 | 1.697 |
| 2 | 0.2433 |
| 3 | 0.1514 |
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 5ab97efab4dd6ef2
# 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 = "bray_curtis"
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(3, 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_bray_curtis/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,
})
Classical scaling tries to place rows so map distances equal your dissimilarities. With Euclidean distances on the standardized US arrests columns it works exactly, with 0 negative eigenvalues. With Bray–Curtis, a dissimilarity built for counts, it found 26 negative eigenvalues.
A negative eigenvalue means no arrangement of points in ordinary space reproduces those dissimilarities. Methods that assume Euclidean geometry (means, variances, PCA) then rest on an approximation.
Check: distances
CheckpointCheck yourself
Two documents use the same words in the same proportions, but one is three times as long. Which comparison calls them identical?
Show the answer
Answer: c
Cosine looks only at the angle between the count vectors. Scaling a vector changes its length, not its direction.
Check yourself
Row A is and row B is . What is the Manhattan distance?
Show the answer
Answer: 9
.
Check yourself
Height and weight are strongly correlated. A person who is tall and heavy, compared with someone short and light, is far apart in Euclidean distance. What does Mahalanobis distance do with that gap?
Show the answer
Answer: a
Mahalanobis divides by the covariance matrix, so steps along the data's main direction of variation are cheap and steps against it are expensive.
Check yourself
Classical scaling on your dissimilarities reports many negative eigenvalues. What does that tell you?
Show the answer
Answer: b
Euclidean distances always give non-negative eigenvalues. Negative ones flag a dissimilarity that isn't a distance in space, so map distances can only approximate it.
Recap
Recap- A row of numbers is a vector, a point in -dimensional space.
- Euclidean squares gaps, Manhattan adds them, cosine compares directions, Mahalanobis measures gaps against the data's own spread.
- The distance is a modeling choice: every method downstream inherits it.
Concepts in this lesson