Units decide the answer: scaling and neighbors
A column measured in thousands drowns out one measured in tenths. See how standardizing changes nearest neighbors and principal components, and where the scaling must be fitted.
What runs in CodeSplash
- Principal component analysis Verified in Python and R
You will be able to
- Explain why a column's units change Euclidean distance and every method built on it
- Choose between raw units, standardizing and robust scaling for a given table
- Fit scaling on training rows only and apply it unchanged to new rows
Read first
A column in thousands
ReadRows A and B differ by 2 in age (years) and by 3,000 in income (dollars). Their Euclidean distance is : income decides almost everything, and age barely registers.
Change income to thousands of dollars and the gap becomes 3. Now age matters as much as income. Nothing about the people changed; only the units did.
Any method that adds squared gaps across columns (k-means, nearest neighbors, PCA, kernel methods, most maps) inherits this. The units you happened to record become a weighting you never chose.
Watch PCA swing
ExploreAExplorable · Rotate to the first principal component
What direction does the first principal component point in, and why?
With this correlation, what share of the total variance will the best single direction keep?
Solid: your direction, with each point's projection onto it. Dashed: the first principal component.
Commit your prediction above to see the result
Make your prediction to see the result.
Use the break-it toggle to measure in units twenty times smaller without standardizing. Its variance grows four hundred times, and the first component swings onto it. Then turn Standardize first on and watch the direction come back to the relationship between the columns.
Scale before you measure neighbors
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.
Two age groups, with income recorded in dollars. Unscaled, each person's neighbors are people with similar incomes, and a neighbor vote recovers the age groups about as often as a coin flip. Standardize, or use robust scaling, and the groups come back.
The same thing on real data
ReadPCA of 4 variables: the first component explains 96.6% of the variance.
- PC1 variance
- 96.6%
- PC1 + PC2
- 99.3%
Plots
View data
| Component | Cumulative | Proportion of variance |
|---|---|---|
| 1 | 0.9655 | 0.9655 |
| 2 | 0.9934 | 0.0278 |
| 3 | 0.9992 | 0.0058 |
| 4 | 1 | 0.0008 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | PC1 | PC2 |
|---|---|---|---|
| point | 64.802 | −11.448 | |
| point | 92.827 | −17.983 | |
| point | 124.07 | 8.830 | |
| point | 18.340 | −16.704 | |
| point | 107.42 | 22.520 | |
| point | 34.976 | 13.720 | |
| point | −60.887 | 12.933 | |
| point | 66.731 | 1.354 | |
| point | 165.24 | 6.275 | |
| point | 40.535 | −7.290 | |
| point | −123.54 | 24.291 | |
| point | −51.797 | −9.469 | |
| point | 78.992 | 12.897 | |
| point | −57.551 | 2.846 | |
| point | −115.59 | −3.342 | |
| point | −55.790 | 3.157 | |
| point | −62.383 | −10.673 | |
| point | 78.278 | −4.295 | |
| point | −89.261 | −11.488 | |
| point | 129.33 | −5.007 | |
| point | −21.266 | 19.450 | |
| point | 85.452 | 5.905 | |
| point | −98.955 | 5.210 | |
| point | 86.856 | −27.428 | |
| point | 7.986 | 5.276 | |
| point | −62.484 | −9.511 | |
| point | −69.097 | −0.2112 | |
| point | 83.614 | 15.102 | |
| point | −114.78 | −4.735 | |
| point | −10.816 | 23.137 | |
| point | 114.87 | −0.3365 | |
| point | 84.294 | 15.924 | |
| point | 164.33 | −31.097 | |
| point | −127.50 | −16.135 | |
| point | −50.087 | 12.279 | |
| point | −19.694 | 3.370 | |
| point | −11.150 | 3.866 | |
| point | −64.689 | 8.912 | |
| point | 3.064 | 18.374 | |
| point | 107.28 | −23.536 | |
| point | −86.107 | −16.598 | |
| point | 17.506 | −6.507 | |
| point | 31.291 | 12.985 | |
| point | −49.913 | 17.648 | |
| point | −124.71 | −27.314 | |
| point | −14.817 | −1.753 | |
| point | −25.076 | 9.968 | |
| point | −91.545 | −22.953 | |
| point | −118.18 | 5.508 | |
| point | −10.435 | −5.924 | |
| loading | Murder | 5.540 | −5.954 |
| loading | Assault | 132.20 | −7.805 |
| loading | UrbanPop | 6.155 | 129.76 |
| loading | Rape | 9.983 | 26.661 |
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 7011.11 | 96.6% | 96.6% |
| 2 | 201.99 | 2.8% | 99.3% |
| 3 | 42.113 | 0.6% | 99.9% |
| 4 | 6.164 | 0.1% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.0417 | −0.0448 | 0.0799 | 0.9949 |
| Assault | 0.9952 | −0.0588 | −0.0676 | −0.0389 |
| UrbanPop | 0.0463 | 0.9769 | −0.2005 | 0.0582 |
| Rape | 0.0752 | 0.2007 | 0.9741 | −0.0723 |
The exact R script · R R version 4.5.1 (2025-06-13)
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec 05e3bf3c506a81ec
# 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)
chart_rows <- function(n, cap = 2000) if (n <= cap) seq_len(n) else unique(round(seq(1, n, length.out = cap)))
# %% Data
FEATURES <- c("Murder", "Assault", "UrbanPop", "Rape")
LABEL <- NULL
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)
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))
}
cs_check_rows(length(rows), 2, "Principal component analysis")
X <- cs_ml_numeric_matrix(df, FEATURES, rows)
# %% Principal components
SCALE <- FALSE
Z <- sweep(X, 2, colMeans(X))
if (SCALE) {
s <- apply(X, 2, stats::sd)
s[s == 0] <- 1
Z <- sweep(Z, 2, s, "/")
}
k_max <- min(length(rows) - 1L, length(FEATURES))
p <- stats::prcomp(Z, center = FALSE, scale. = FALSE)
eig <- (p$sdev^2)[seq_len(k_max)]
prop <- eig / sum(eig)
cumulative <- cumsum(prop)
rot <- p$rotation[, seq_len(k_max), drop = FALSE]
signs <- cs_rep_canonical_signs(rot) # largest |loading| positive (near-ties: the first)
loadings <- sweep(rot, 2, signs, "*")
scores <- sweep(p$x[, seq_len(k_max), drop = FALSE], 2, signs, "*")
k <- if (is.null(NULL)) k_max else min(as.integer(NULL), k_max)
# %% Artifacts
out <- cs_ml_out_dir("target/academy-parity/run-95359/discover.pca/usarrests_unscaled/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_variables = length(FEATURES), n_components = k,
cum2 = if (k_max >= 2) cumulative[2] else NaN)
# Kaiser's "eigenvalue above 1" only means something on the correlation scale (scaled PCA).
if (SCALE) values$kaiser <- sum(eig > 1)
for (j in seq_len(k_max)) {
values[[sprintf("eigen[%d]", j)]] <- eig[j]
values[[sprintf("prop[%d]", j)]] <- prop[j]
values[[sprintf("cumulative[%d]", j)]] <- cumulative[j]
}
for (j in seq_len(k)) {
values[[sprintf("score_check[%d]", j)]] <- cs_ml_checksum(scores[, j], rows)
for (i in seq_along(FEATURES)) values[[sprintf("loading[%d:%s]", j, FEATURES[i])]] <- unname(loadings[i, j])
}
ppca_table <- NULL
show <- min(k, 5L)
tables <- list(
list(key = "variance", title = "Explained variance",
columns = list(list(key = "component", label = "Component", type = "integer"),
list(key = "eigenvalue", label = "Eigenvalue", type = "number"),
list(key = "proportion", label = "Proportion", type = "percent"),
list(key = "cumulative", label = "Cumulative", type = "percent")),
rows = lapply(seq_len(k_max), function(j) list(component = j, eigenvalue = eig[j], proportion = prop[j], cumulative = cumulative[j]))),
list(key = "loadings", title = "Loadings",
columns = c(list(list(key = "variable", label = "Variable")),
lapply(seq_len(show), function(j) list(key = paste0("pc", j), label = paste0("PC", j), type = "number"))),
rows = lapply(seq_along(FEATURES), function(i) {
r <- list(variable = FEATURES[i])
for (j in seq_len(show)) r[[paste0("pc", j)]] <- unname(loadings[i, j])
r
}))
)
if (!is.null(ppca_table)) tables[[length(tables) + 1L]] <- ppca_table
charts <- list(cs_chart("scree", "scree-plot", "Scree plot", list(
component = cs_col("Component", seq_len(k_max), "numeric"),
variance = cs_col("Proportion of variance", prop, "numeric"),
cumulative = cs_col("Cumulative", cumulative, "numeric")
)))
if (k_max >= 2) {
pick <- chart_rows(length(rows))
lab <- if (!is.null(LABEL)) as.character(df[[LABEL]][rows[pick] + 1L]) else rep("", length(pick))
lab[is.na(lab)] <- ""
reach <- max(abs(scores[pick, 1:2])) / max(max(abs(loadings[, 1:2])), 1e-12) * 0.8
charts[[2]] <- cs_chart("biplot", "biplot", "Biplot (PC1 × PC2)", list(
x = cs_col("PC1", c(scores[pick, 1], loadings[, 1] * reach), "numeric"),
y = cs_col("PC2", c(scores[pick, 2], loadings[, 2] * reach), "numeric"),
kind = cs_col("Kind", c(rep("point", length(pick)), rep("loading", length(FEATURES))), "categorical"),
label = cs_col(if (is.null(LABEL)) "Label" else LABEL, c(lab, FEATURES), "categorical")
), note = "Loading arrows are rescaled to the score range.")
}
cs_publish(list(
title = "Principal component analysis",
engine = cs_engine_info("stats", "nanoparquet"),
n = length(rows),
summary = sprintf("PCA of %d variables: the first component explains %.1f%% of the variance.", length(FEATURES), 100 * prop[1]),
statistics = list(list(key = "prop1", label = "PC1 variance", value = prop[1], format = "percent"),
list(key = "cum2", label = "PC1 + PC2", value = values$cum2, format = "percent")),
tables = tables,
charts = charts,
values = values,
warnings = warnings,
artifacts = list(list(key = "embedding", path = file.path(out, "embedding.parquet"), format = "parquet"))
))
PCA of 4 variables: the first component explains 96.6% of the variance.
- PC1 variance
- 96.6%
- PC1 + PC2
- 99.3%
To keep this page light, the plots are shown once, under the R tab.
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 7011.11 | 96.6% | 96.6% |
| 2 | 201.99 | 2.8% | 99.3% |
| 3 | 42.113 | 0.6% | 99.9% |
| 4 | 6.164 | 0.1% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.0417 | −0.0448 | 0.0799 | 0.9949 |
| Assault | 0.9952 | −0.0588 | −0.0676 | −0.0389 |
| UrbanPop | 0.0463 | 0.9769 | −0.2005 | 0.0582 |
| Rape | 0.0752 | 0.2007 | 0.9741 | −0.0723 |
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Principal component analysis
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method discover.pca 1.2.0 · spec 05e3bf3c506a81ec
# 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
from sklearn.decomposition import PCA
import codesplash as cs
from codesplash import ml as csml
from codesplash.ml import embed as csembed
from codesplash.ml import rep_linear as rl
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 = ["Murder", "Assault", "UrbanPop", "Rape"]
LABEL = None
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)
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.")
cs.check_rows(len(rows), 2, "Principal component analysis")
X = csembed.numeric_matrix(df, FEATURES, rows)
# %% Principal components
SCALE = False
Z = csembed.standardize(X, ddof=1) if SCALE else X - X.mean(axis=0) # SD with n − 1, like R's scale()
k_max = min(len(rows) - 1, len(FEATURES))
pca = PCA(n_components=k_max, svd_solver="full").fit(Z)
eig = pca.explained_variance_ # divisor n − 1 (= prcomp sdev²)
prop = eig / eig.sum()
cumulative = np.cumsum(prop)
signs = rl.canonical_signs(pca.components_.T) # largest |loading| positive (near-ties: the first)
loadings = pca.components_.T * signs
scores = pca.transform(Z) * signs
k = k_max if None is None else min(int(None), k_max)
# %% Artifacts
out = csml.out_dir("target/academy-parity/run-95359/discover.pca/usarrests_unscaled/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_variables": len(FEATURES),
"n_components": k,
"cum2": float(cumulative[1]) if k_max >= 2 else float("nan"),
}
if SCALE: # Kaiser's "eigenvalue above 1" only means something on the correlation scale
values["kaiser"] = int(np.sum(eig > 1))
for j in range(k_max):
values[f"eigen[{j + 1}]"] = float(eig[j])
values[f"prop[{j + 1}]"] = float(prop[j])
values[f"cumulative[{j + 1}]"] = float(cumulative[j])
for j in range(k):
values[f"score_check[{j + 1}]"] = csembed.checksum(scores[:, j], rows)
for i, f in enumerate(FEATURES):
values[f"loading[{j + 1}:{f}]"] = float(loadings[i, j])
ppca_table = None
show = min(k, 5)
tables = [
{
"key": "variance",
"title": "Explained variance",
"columns": [
{"key": "component", "label": "Component", "type": "integer"},
{"key": "eigenvalue", "label": "Eigenvalue", "type": "number"},
{"key": "proportion", "label": "Proportion", "type": "percent"},
{"key": "cumulative", "label": "Cumulative", "type": "percent"},
],
"rows": [{"component": j + 1, "eigenvalue": eig[j], "proportion": prop[j], "cumulative": cumulative[j]} for j in range(k_max)],
},
{
"key": "loadings",
"title": "Loadings",
"columns": [{"key": "variable", "label": "Variable"}] + [{"key": f"pc{j + 1}", "label": f"PC{j + 1}", "type": "number"} for j in range(show)],
"rows": [dict({"variable": f}, **{f"pc{j + 1}": loadings[i, j] for j in range(show)}) for i, f in enumerate(FEATURES)],
},
]
if ppca_table is not None:
tables.append(ppca_table)
charts = [
cs.chart(
"scree",
"scree-plot",
"Scree plot",
{
"component": cs.col("Component", list(range(1, k_max + 1)), "numeric"),
"variance": cs.col("Proportion of variance", prop, "numeric"),
"cumulative": cs.col("Cumulative", cumulative, "numeric"),
},
)
]
if k_max >= 2:
pick = chart_rows(len(rows))
lab = ["" if LABEL is None else str(v) for v in df.iloc[rows[pick]][LABEL]] if LABEL else [""] * len(pick)
reach = np.max(np.abs(scores[pick, :2])) / max(np.max(np.abs(loadings[:, :2])), 1e-12) * 0.8
charts.append(
cs.chart(
"biplot",
"biplot",
"Biplot (PC1 × PC2)",
{
"x": cs.col("PC1", np.concatenate([scores[pick, 0], loadings[:, 0] * reach]), "numeric"),
"y": cs.col("PC2", np.concatenate([scores[pick, 1], loadings[:, 1] * reach]), "numeric"),
"kind": cs.col("Kind", ["point"] * len(pick) + ["loading"] * len(FEATURES), "categorical"),
"label": cs.col(LABEL or "Label", lab + FEATURES, "categorical"),
},
note="Loading arrows are rescaled to the score range.",
)
)
cs.publish(
{
"title": "Principal component analysis",
"engine": cs.engine_info("scikit-learn", "numpy", "pandas"),
"n": len(rows),
"summary": f"PCA of {len(FEATURES)} variables: the first component explains {prop[0]:.1%} of the variance.",
"statistics": [
{"key": "prop1", "label": "PC1 variance", "value": float(prop[0]), "format": "percent"},
{"key": "cum2", "label": "PC1 + PC2", "value": values["cum2"], "format": "percent"},
],
"tables": tables,
"charts": charts,
"values": values,
"warnings": warnings,
"artifacts": [{"key": "embedding", "path": os.path.join(out, "embedding.parquet"), "format": "parquet"}],
}
)
US arrests records assaults per 100,000 people (values in the hundreds) beside murders per 100,000 (values near ten). Without scaling, the first component keeps 96.6% of the variance and its assault loading is 0.995. It is the assault column, renamed.
After standardizing, the first component keeps 62.0% and weighs the three crime rates about equally (murder 0.54, assault 0.58, rape 0.54).
Three choices
Read| Choice | What it does | Reach for it when |
|---|---|---|
| Raw units | Leaves columns as recorded | All columns share one unit that matters (centimeters, dollars) |
| StandardizeStandardizationRescales a column to mean 0 and standard deviation 1, by subtracting the mean and dividing by the SD. | Subtract the mean, divide by the SD | Columns in different units; the usual default |
| Robust scaling | Subtract the median, divide by the IQR | Heavy tails or outliers would inflate the SD |
Standardizing says "a one-SD change counts the same in every column". That is a choice too: a column of pure noise gets as much say as your best measurement.
Fit it where you fit the model
ReadThe mean and SD are learned from data. Learn them from the whole table and the test rows have quietly shaped your training features.
Fit the scaling on training rows, save the means and SDs, and apply those same numbers to validation, test and future rows. CodeSplash does this inside each cross-validation fold.
Predict
PredictPredict first
You find each row's nearest neighbor in a table of height (cm) and weight (kg), then convert height to meters. Does each row's nearest neighbor stay the same?
Reveal
It can change. Height gaps shrink a hundredfold, so weight now decides who is closest. Standardizing first makes the answer independent of the units you chose.
Check: scaling
CheckpointCheck yourself
In unscaled US arrests, the first principal component is almost exactly the assault column. Why?
Show the answer
Answer: a
PCA maximizes variance. Without scaling, the column with the biggest numbers has the biggest variance and claims the first component.
Check yourself
One column has a few enormous values that you believe are real. Which scaling keeps those values from setting the scale for everyone else?
Show the answer
Answer: b
The median and IQR ignore the extreme tail, so the bulk of the data sets the unit. The SD and the maximum are both pulled by the extremes.
Check yourself
Where should the means and SDs for standardizing come from in a model you'll test on held-out rows?
Show the answer
Answer: b
Learning the scale from held-out rows lets them leak into training. Save the training means and SDs and reuse them.
Recap
Recap- Euclidean methods weight columns by their units unless you scale.
- Standardize when units differ; scale robustly when tails are heavy; keep raw units only when they are shared and meaningful.
- Fit the scaling on training rows and replay it on new ones.
Concepts in this lesson