Eigenvectors: the directions a matrix only stretches
Find the directions a covariance matrix stretches without turning, see that they are the principal components, and compute the first one with nothing but repeated multiplication.
What runs in CodeSplash
- REP001Principal component analysis (PCA) Runs in CodeSplash
- Principal component analysis Verified in Python and R
You will be able to
- State the eigenvector equation and what an eigenvalue measures
- Explain why the eigenvectors of a covariance matrix are the principal components
- Use eigenvalues to read the share of variance, and power iteration to find the top direction
Read first
Most directions turn, a few don't
ReadFeed a vector to a matrix and it usually comes out pointing somewhere new. A few special directions come out pointing the same way, only longer or shorter:
is an eigenvector and the number is its eigenvalue: how much stretches that direction.
A covariance matrix is symmetric, which guarantees three things: its eigenvalues are real and never negative, its eigenvectors are at right angles to each other, and together they describe the whole matrix. That is the eigendecompositionEigendecompositionDirections a square matrix only stretches (eigenvectors) and how much it stretches each (eigenvalues). .
Variance along a direction
ExploreThe variance of the data projected onto a unit direction is . Rotate and that number rises and falls.
AExplorable · 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.
Find the peak. The best direction is the top eigenvector of , and the variance there is the top eigenvalue. The next best direction at right angles is the second eigenvector, and so on. That is all PCA is.
PCA as the reference states it
ReadPCAPrincipal component analysisRotates correlated variables into uncorrelated components ordered by how much variance they capture. looks for orthonormal directions () that rebuild the centered data best:
The answer is the top eigenvectors of the covariance matrix. Keeping the most variance and making the smallest squared reconstruction error are the same goal, because the two always add up to the total.
Eigenvalues are variances
ReadPCA of 4 variables: the first component explains 62.0% of the variance.
- PC1 variance
- 62.0%
- PC1 + PC2
- 86.8%
Plots
View data
| Component | Cumulative | Proportion of variance |
|---|---|---|
| 1 | 0.6201 | 0.6201 |
| 2 | 0.8675 | 0.2474 |
| 3 | 0.9566 | 0.0891 |
| 4 | 1 | 0.0434 |
Loading arrows are rescaled to the score range.
View data
| Kind | Label | PC1 | PC2 |
|---|---|---|---|
| point | 0.9757 | −1.122 | |
| point | 1.931 | −1.062 | |
| point | 1.745 | 0.7385 | |
| point | −0.1400 | −1.109 | |
| point | 2.499 | 1.527 | |
| point | 1.499 | 0.9776 | |
| point | −1.345 | 1.078 | |
| point | 0.0472 | 0.3221 | |
| point | 2.983 | −0.0388 | |
| point | 1.623 | −1.266 | |
| point | −0.9035 | 1.555 | |
| point | −1.623 | −0.2089 | |
| point | 1.365 | 0.6750 | |
| point | −0.5004 | 0.1500 | |
| point | −2.231 | 0.1030 | |
| point | −0.7889 | 0.2674 | |
| point | −0.7433 | −0.9488 | |
| point | 1.549 | −0.8623 | |
| point | −2.373 | −0.3726 | |
| point | 1.746 | −0.4234 | |
| point | −0.4813 | 1.460 | |
| point | 2.087 | 0.1538 | |
| point | −1.676 | 0.6259 | |
| point | 0.9865 | −2.370 | |
| point | 0.6898 | 0.2607 | |
| point | −1.174 | −0.5315 | |
| point | −1.253 | 0.1920 | |
| point | 2.846 | 0.7678 | |
| point | −2.360 | 0.0179 | |
| point | 0.1797 | 1.435 | |
| point | 1.960 | −0.1414 | |
| point | 1.666 | 0.8149 | |
| point | 1.112 | −2.206 | |
| point | −2.962 | −0.5931 | |
| point | −0.2237 | 0.7348 | |
| point | −0.3086 | 0.2850 | |
| point | 0.0585 | 0.5360 | |
| point | −0.8795 | 0.5654 | |
| point | −0.8551 | 1.477 | |
| point | 1.307 | −1.914 | |
| point | −1.968 | −0.8151 | |
| point | 0.9897 | −0.8516 | |
| point | 1.342 | 0.4083 | |
| point | −0.5450 | 1.457 | |
| point | −2.773 | −1.388 | |
| point | −0.0954 | −0.1977 | |
| point | −0.2147 | 0.9604 | |
| point | −2.087 | −1.411 | |
| point | −2.059 | 0.6051 | |
| point | −0.6231 | −0.3178 | |
| loading | Murder | 1.465 | −1.143 |
| loading | Assault | 1.594 | −0.5139 |
| loading | UrbanPop | 0.7606 | 2.386 |
| loading | Rape | 1.486 | 0.4574 |
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.480 | 62.0% | 62.0% |
| 2 | 0.9898 | 24.7% | 86.8% |
| 3 | 0.3566 | 8.9% | 95.7% |
| 4 | 0.1734 | 4.3% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.5359 | −0.4182 | −0.3412 | −0.6492 |
| Assault | 0.5832 | −0.1880 | −0.2681 | 0.7434 |
| UrbanPop | 0.2782 | 0.8728 | −0.3780 | −0.1339 |
| Rape | 0.5434 | 0.1673 | 0.8178 | −0.0890 |
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 ebb02e3a46ffe368
# 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 <- TRUE
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_scaled/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 62.0% of the variance.
- PC1 variance
- 62.0%
- PC1 + PC2
- 86.8%
To keep this page light, the plots are shown once, under the R tab.
Explained variance
| Component | Eigenvalue | Proportion | Cumulative |
|---|---|---|---|
| 1 | 2.480 | 62.0% | 62.0% |
| 2 | 0.9898 | 24.7% | 86.8% |
| 3 | 0.3566 | 8.9% | 95.7% |
| 4 | 0.1734 | 4.3% | 100.0% |
Loadings
| Variable | PC1 | PC2 | PC3 | PC4 |
|---|---|---|---|---|
| Murder | 0.5359 | −0.4182 | −0.3412 | −0.6492 |
| Assault | 0.5832 | −0.1880 | −0.2681 | 0.7434 |
| UrbanPop | 0.2782 | 0.8728 | −0.3780 | −0.1339 |
| Rape | 0.5434 | 0.1673 | 0.8178 | −0.0890 |
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 ebb02e3a46ffe368
# 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 = True
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_scaled/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"}],
}
)
The eigenvalues of the standardized US arrests data are 2.48, 0.99, 0.36 and 0.17. They add up to 4, the number of columns, because each standardized column contributes variance 1.
Divide each by the total for its share: the first holds 62.0%. On iris without scaling, the first eigenvalue is 4.23, a share of 92.5%, mostly petal length.
Power iteration
ReadYou can find the top eigenvector with multiplication alone: start from any vector, multiply by , rescale to length 1, repeat.
Each multiplication stretches the top direction by and the second by , so the second shrinks relative to the first by every round. A big gapEigengapThe drop between consecutive eigenvalues of the normalized similarity matrix; a large drop after the k-th suggests k clusters. between the top two eigenvalues means fast, stable convergence. Nearly equal eigenvalues mean the two directions are almost interchangeable, and small changes to the data can swap them.
import numpy as np
S = np.array([[2.0, 0.8], [0.8, 1.0]])
w = np.array([1.0, 0.0])
for _ in range(50):
w = S @ w
w = w / np.linalg.norm(w)
print(w, w @ S @ w) # top eigenvector and eigenvalue
print(np.linalg.eigh(S)) # checkS <- matrix(c(2, 0.8, 0.8, 1), 2)
w <- c(1, 0)
for (i in 1:50) {
w <- S %*% w
w <- w / sqrt(sum(w^2))
}
print(c(w, t(w) %*% S %*% w)) # top eigenvector and eigenvalue
print(eigen(S)) # checkWhat PCA is not
Read- Not a clustering method. Separated groups on a score plot are a hint to check, not evidence that groups exist.
- Not a test. It has no null hypothesis or p-value.
- Explained variance is not usefulness. A high-variance nuisance column can own the first component.
- Outliers pull it. One extreme row can rotate a direction toward itself.
- Descriptive PCA doesn't need normal data; models built on top of it may.
Check: eigenvectors and PCA
CheckpointCheck yourself
. What does the 3 tell you?
Show the answer
Answer: a
An eigenvalue is the stretch factor along its eigenvector. The direction stays put.
Check yourself
You run PCA on six standardized columns and keep all components. What do the eigenvalues add up to?
Show the answer
Answer: 6
Each standardized column has variance 1, and PCA only rotates, so the total variance stays at 6.
Check yourself
A PCA score plot shows two well-separated islands. What can you conclude?
Show the answer
Answer: c
PCA is a summary, not a clustering method or a test. Check the islands in the original columns, with stability checks and outside information.
Check yourself
Which statement about PCA's two goals is right?
Show the answer
Answer: a
Variance kept plus squared reconstruction error equals the total variance, so maximizing one minimizes the other, for any data.
Check yourself
The top two eigenvalues are almost equal. What should you expect?
Show the answer
Answer: b
With near 1, nothing strongly prefers one direction over the other in that plane, so the split between them is fragile.
Recap
Recap- An eigenvector keeps its direction under the matrix; its eigenvalue is the stretch.
- The covariance matrix's eigenvectors are the principal components, its eigenvalues their variances.
- Power iteration finds the top direction; a small eigengap means fragile components.
Concepts in this lesson