Principal Component Analysis: Dimensionality Reduction
How PCA turns many correlated features into a few uncorrelated ones: the math, scaling, choosing components, anomaly detection and PCA in the cloud.
Monitoring data has a habit of saying the same thing several times. CPU, request rate, network in, network out and load average all rise when traffic rises. Five columns, one underlying fact. Feed all five to a model and it spends effort untangling the overlap; plot them and you need five axes to show one idea.
Principal component analysis (PCA) finds that overlap and removes it. It rotates your data onto a new set of axes, ordered so the first explains as much of the spread as possible, the second as much of what is left, and so on. Keep the first few, drop the rest, and you have fewer columns that still carry most of the information.
This article follows k-means clustering in the series. Like k-means, PCA is unsupervised: it looks only at the features, never at a label. It also shares k-means’ sensitivity to feature scale, which turns out to matter even more here. If the terms feature, label and variance are unfamiliar, key concepts and terminologies in ML covers them.
What PCA does
PCA works on the variance of the data: how spread out each feature is, and how pairs of features move together (their covariance). It looks for directions through the data, each a weighted combination of the original features, along which the rows are most spread out.
The steps are:
- Center each feature by subtracting its mean, so the data sits around the origin.
- Scale each feature, usually to standard deviation 1, if the features use different units.
- Find the direction of greatest variance. This is the first principal component (PC1).
- Find the next direction, at right angles to every component already found, with the greatest remaining variance. Repeat until you have as many components as features.
- Project each row onto the components you keep. The coordinates along them are the row’s scores, the new features.
flowchart LR
R["Raw features"] --> C["Center: subtract means"]
C --> S["Scale: divide by std dev"]
S --> E["Eigenvectors of the covariance matrix"]
E --> O["Order by eigenvalue"]
O --> K["Keep the top k"]
K --> P["Project rows: k scores per row"]
Mathematically, the components are the eigenvectors of the covariance matrix, and each one’s eigenvalue is the variance of the data along it. Libraries usually compute them with a singular value decomposition (SVD) of the centered data, which gives the same answer with better numerical behavior.
Because the components are at right angles, the scores are uncorrelated with each other. That is the property that makes PCA useful: the redundancy between the original columns is gone, and each new column carries information the others don’t.
A worked example by hand
Take five web servers and two features: requests per second, in hundreds, and CPU percent.
| Server | Requests (hundreds/s) | CPU % |
|---|---|---|
| a | 2 | 20 |
| b | 4 | 34 |
| c | 6 | 46 |
| d | 8 | 64 |
| e | 10 | 76 |
The means are 6 and 48. After centering, requests run -4, -2, 0, 2, 4 and CPU runs -28, -14, -2, 16, 28. Dividing the sums of squares and cross-products by n - 1 = 4 gives the covariance matrix:
requests cpu
requests 10 71
cpu 71 506
The eigenvalues solve λ² - 516λ + (10 × 506 - 71²) = 0, which is λ² - 516λ + 19 = 0. The roots are 515.96 and 0.037. The first component carries 515.96 / 516 of the total variance, or 99.99 percent. Its direction is (0.139, 0.990): almost entirely CPU.
scikit-learn agrees:
import numpy as np
from sklearn.decomposition import PCA
X = np.array([[2, 20], [4, 34], [6, 46], [8, 64], [10, 76]], dtype=float)
pca = PCA(n_components=2).fit(X)
print("components:", pca.components_.round(3).tolist())
print("eigenvalues:", pca.explained_variance_.round(3))
print("ratio:", pca.explained_variance_ratio_.round(4))
components: [[0.139, 0.99], [0.99, -0.139]]
eigenvalues: [5.15963e+02 3.70000e-02]
ratio: [9.999e-01 1.000e-04]
Two things stand out. First, the sign of a component is arbitrary: (0.99, -0.139) and (-0.99, 0.139) describe the same axis, and different libraries or versions may flip it. Don’t write code that depends on a sign.
Second, PC1 is mostly CPU only because CPU is measured in larger numbers. Requests and CPU here are almost perfectly correlated (r = 0.998), so the honest summary is “both rise together”, not “CPU”. Standardize both columns first and PC1 becomes (0.707, 0.707), an equal blend of the two, still explaining 99.9 percent of the variance. That is the subject of the next section.
A component's eigenvalue is 4.8 and the eigenvalues of all components sum to 12. What does that tell you?
Correct! Explained variance ratio is the eigenvalue divided by the sum of all eigenvalues: 4.8 / 12 = 0.4.
Reducing twelve VM metrics to three
A more realistic case: 2,000 VMs, each with twelve averaged metrics from your monitoring system. The synthetic data below is generated from three hidden drivers, request traffic, memory working set and storage activity, with noise on every metric. PCA never sees the drivers; the point is to check whether it finds them. Save it as metrics.py:
import numpy as np
rng = np.random.default_rng(7)
n = 2000
# Three hidden drivers per VM: request traffic, memory working set, storage activity
traffic = rng.gamma(2.0, 1.0, n)
memory = rng.normal(0, 1, n)
storage = rng.gamma(1.5, 1.0, n)
def noisy(base, scale):
return base + rng.normal(0, scale, n)
X = np.column_stack([
noisy(10 + 12 * traffic, 4), # cpu_pct
noisy(200 * traffic, 60), # requests_per_s
noisy(8 * traffic, 2.5), # net_in_mbps
noisy(15 * traffic, 4), # net_out_mbps
noisy(1.5 * traffic, 0.6), # load_avg
noisy(55 + 12 * memory, 4), # mem_pct
noisy(2.0 + 0.4 * memory, 0.25), # page_cache_gb
noisy(5 + 1.5 * memory, 0.8), # swap_mb_s
noisy(400 * storage, 120), # disk_read_iops
noisy(250 * storage, 90), # disk_write_iops
noisy(30 * storage, 10), # disk_mbps
noisy(4 + 2 * storage, 1.2), # disk_latency_ms
])
feature_names = [
"cpu_pct", "requests_per_s", "net_in_mbps", "net_out_mbps", "load_avg",
"mem_pct", "page_cache_gb", "swap_mb_s",
"disk_read_iops", "disk_write_iops", "disk_mbps", "disk_latency_ms",
]
Scale first
Here is PCA on the raw metrics, showing the two features with the largest weight in each of the first three components:
import numpy as np
from sklearn.decomposition import PCA
from metrics import X, feature_names
pca = PCA(n_components=3).fit(X)
print("variance ratio:", pca.explained_variance_ratio_.round(3))
for i, comp in enumerate(pca.components_, 1):
top = np.argsort(-np.abs(comp))[:2]
print(f"PC{i}: " + ", ".join(f"{feature_names[j]} {comp[j]:+.2f}" for j in top))
variance ratio: [0.784 0.192 0.023]
PC1: disk_read_iops +0.85, disk_write_iops +0.52
PC2: requests_per_s +1.00, net_out_mbps +0.07
PC3: disk_write_iops +0.86, disk_read_iops -0.52
Three components explain 99.9 percent of the variance, which sounds excellent and is nearly useless. Disk IOPS has a standard deviation around 500 and requests per second around 290, while page cache varies by half a gigabyte. Variance in raw units is mostly a measure of which columns use big numbers. PC1 and PC3 split the two IOPS columns, PC2 is requests alone, and memory doesn’t appear at all.
Standardizing gives every metric a variance of 1, so the components reflect correlation rather than units. PCA centers the data itself but doesn’t scale it, so put a StandardScaler in front:
import numpy as np
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from metrics import X
pca = make_pipeline(StandardScaler(), PCA()).fit(X)[-1]
cum = np.cumsum(pca.explained_variance_ratio_)
for i, (v, r, c) in enumerate(zip(pca.explained_variance_, pca.explained_variance_ratio_, cum), 1):
print(f"PC{i:<2} eigenvalue={v:5.2f} ratio={r:.3f} cumulative={c:.3f}")
PC1 eigenvalue= 4.81 ratio=0.400 cumulative=0.400
PC2 eigenvalue= 3.69 ratio=0.307 cumulative=0.708
PC3 eigenvalue= 2.62 ratio=0.218 cumulative=0.925
PC4 eigenvalue= 0.24 ratio=0.020 cumulative=0.945
PC5 eigenvalue= 0.17 ratio=0.014 cumulative=0.960
PC6 eigenvalue= 0.15 ratio=0.012 cumulative=0.972
PC7 eigenvalue= 0.08 ratio=0.006 cumulative=0.978
PC8 eigenvalue= 0.07 ratio=0.006 cumulative=0.984
PC9 eigenvalue= 0.06 ratio=0.005 cumulative=0.989
PC10 eigenvalue= 0.05 ratio=0.004 cumulative=0.994
PC11 eigenvalue= 0.04 ratio=0.003 cumulative=0.997
PC12 eigenvalue= 0.04 ratio=0.003 cumulative=1.000
The first three eigenvalues are large and then the values fall off a cliff, from 2.62 to 0.24. Three components explain 92.5 percent of the variance in twelve standardized metrics. The other nine hold the measurement noise.
There are cases where you should not standardize: when all features share a unit and their differences in spread are meaningful, such as pixel intensities or a set of temperatures from identical sensors. For mixed units, standardize.
Read the loadings
Each component is a list of weights over the original features, called loadings. Reading them tells you what a component means:
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from metrics import X, feature_names
model = make_pipeline(StandardScaler(), PCA(n_components=0.90)).fit(X)
pca = model[-1]
print("components kept:", pca.n_components_)
loadings = pd.DataFrame(pca.components_.T, index=feature_names,
columns=[f"PC{i + 1}" for i in range(pca.n_components_)])
print(loadings.round(2))
components kept: 3
PC1 PC2 PC3
cpu_pct 0.45 -0.00 0.01
requests_per_s 0.45 -0.01 0.01
net_in_mbps 0.45 -0.01 0.01
net_out_mbps 0.45 -0.01 0.01
load_avg 0.44 -0.01 0.01
mem_pct -0.01 -0.01 0.59
page_cache_gb -0.01 -0.01 0.57
swap_mb_s -0.01 0.00 0.58
disk_read_iops 0.01 0.51 -0.00
disk_write_iops 0.01 0.50 0.00
disk_mbps 0.01 0.50 0.00
disk_latency_ms 0.00 0.49 0.02
Passing a fraction between 0 and 1 as n_components keeps the fewest components that explain at least that share of the variance; here 0.90 kept three. Each component loads on one group of metrics and ignores the rest: PC1 is traffic, PC2 is storage and PC3 is memory. PCA recovered the three drivers without being told they existed.
Real loadings are rarely this clean. Usually the first component is a broad “everything is busy” axis, and later ones are contrasts, positive on some features and negative on others. A component is a direction that explains variance; it is not guaranteed to match a concept you have a name for.
Choosing how many components
Every component you drop loses some information, so the choice is a trade between size and fidelity. Common approaches:
- Cumulative variance threshold. Keep enough components for 90, 95 or 99 percent of the variance. Simple and the most common default, but the right threshold depends on the noise level of your data.
- Scree plot. Plot eigenvalues in order and look for the elbow, the point where they flatten. On the VM metrics, the elbow after PC3 is unmistakable.
- Kaiser rule. On standardized data, keep components with an eigenvalue above 1, meaning each explains more than one original feature’s worth of variance. It also picks three here, but tends to keep too many when there are lots of features.
- Downstream performance. If PCA feeds a model, treat the number of components as a hyperparameter and pick it with cross-validation.
flowchart TD
Q["What is PCA for?"] --> V{"Visualization?"}
V -- "yes" --> T["Keep 2 or 3"]
V -- "no" --> M{"Input to a model?"}
M -- "yes" --> CV["Tune k with cross-validation"]
M -- "no" --> CMP["Compression or anomaly detection"]
CMP --> TH["Cumulative variance threshold, check the scree plot"]
The last approach matters because the variance threshold and model accuracy don’t always agree. The digits dataset bundled with scikit-learn has 1,797 handwritten digits as 8 by 8 images, 64 pixel features. On standardized pixels, 95 percent of the variance needs 40 components. Here is a logistic regression classifier with different numbers of components:
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_digits(return_X_y=True) # 1,797 images, 8x8 = 64 pixel features
for n in [None, 40, 20, 10, 5]:
steps = [StandardScaler()] + ([PCA(n_components=n, random_state=0)] if n else [])
pipe = make_pipeline(*steps, LogisticRegression(max_iter=5000))
acc = cross_val_score(pipe, X, y, cv=5).mean()
print(f"{'all 64 pixels' if n is None else f'{n} components':<14} accuracy={acc:.3f}")
all 64 pixels accuracy=0.920
40 components accuracy=0.914
20 components accuracy=0.899
10 components accuracy=0.840
5 components accuracy=0.771
Twenty components, under a third of the inputs, cost about two points of accuracy. Below that the loss grows quickly. Whether 20 is a good trade depends on what you gain from the smaller input: faster training, a smaller model, or a model such as k-nearest neighbors that degrades as the number of dimensions grows.
Keep the scaler and PCA inside the pipeline, as above. Fitting PCA on all the data before splitting into training and validation sets leaks information about the validation rows into the components, which makes the scores look slightly better than they will be in production.
You run PCA on unscaled VM metrics and PC1 explains 78 percent of the variance. Why might that be misleading?
Correct! Without scaling, high-magnitude columns such as IOPS dominate the components regardless of how informative they are.
Variance is not the same as relevance
PCA ranks directions by how spread out the data is along them. It has no idea what you want to predict. If the signal lives in a low-variance direction, PCA will discard it first.
A deliberately bad case: one feature with a wide spread that has nothing to do with the label, and one narrow feature that decides it.
import numpy as np
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
n = 1000
y = rng.integers(0, 2, n)
X = np.column_stack([
rng.normal(0, 10, n), # wide spread, unrelated to y
y * 2.0 + rng.normal(0, 0.5, n), # narrow spread, decides y
])
for name, pipe in [
("both features", make_pipeline(LogisticRegression())),
("PCA, 1 component", make_pipeline(PCA(n_components=1), LogisticRegression())),
]:
print(f"{name:<18} accuracy={cross_val_score(pipe, X, y, cv=5).mean():.3f}")
both features accuracy=0.981
PCA, 1 component accuracy=0.553
The single component is the noisy feature, and accuracy falls to barely better than a coin toss. Standardizing doesn’t fix this in general: after scaling, both features have the same variance and PCA has no reason to prefer the useful one. PCA is a compression method, not a feature selector for a target. When you have labels and care only about predicting them, compare PCA against no reduction at all, and against methods that use the label, such as regularization in linear and logistic regression or the feature importances of a random forest.
Reconstruction error as an anomaly score
PCA can run backwards. inverse_transform maps scores back to the original feature space, giving the closest point that the kept components can describe. The squared distance between a row and its reconstruction is the reconstruction error.
A row that follows the usual correlations reconstructs well, even if its values are large. A row that breaks them can’t be described by the kept components, and its error is high. That makes reconstruction error a useful anomaly score for monitoring data:
import numpy as np
from sklearn.decomposition import PCA
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from metrics import X
model = make_pipeline(StandardScaler(), PCA(n_components=3)).fit(X)
def recon_error(rows):
Z = model[0].transform(rows) # standardized
Z_hat = model[1].inverse_transform(model[1].transform(Z)) # back from 3 scores
return ((Z - Z_hat) ** 2).sum(axis=1)
train_err = recon_error(X)
print("training error: median={:.2f} p99={:.2f} max={:.2f}".format(
np.median(train_err), np.percentile(train_err, 99), train_err.max()))
new_vms = np.array([
# cpu req/s net_in net_out load mem cache swap read write MB/s lat
[36, 380, 16, 29, 3.2, 58, 2.1, 5.3, 620, 360, 44, 7], # typical
[95, 1600, 64, 120, 12.0, 60, 2.1, 5.5, 500, 320, 38, 6], # very busy
[95, 150, 6, 11, 12.0, 55, 2.0, 5.0, 600, 375, 45, 7], # CPU pegged, little traffic
])
for name, err in zip(["typical", "busy", "cpu-no-traffic"], recon_error(new_vms)):
print(f"{name:<15} error={err:6.2f}")
training error: median=0.79 p99=2.51 max=5.56
typical error= 0.03
busy error= 0.34
cpu-no-traffic error= 26.63
The busy VM has CPU at 95 percent and four times the typical request rate, but every traffic metric rose together, so PC1 describes it and the error is small. The third VM has the same CPU and load with almost no requests or network traffic. No combination of the three components produces that, and its error is about five times the largest seen in training. A runaway process, a stuck job or unexpected software would all look like this.
A simple threshold check would flag both of the last two machines for high CPU. Reconstruction error flags only the one whose behavior is unusual, which is what you want from an alert. In production, set the threshold from a high percentile of the training errors and refit the model periodically as normal behavior drifts.
sequenceDiagram
participant M as Monitoring
participant P as Scaler + PCA
participant A as Alerting
M->>P: Hourly metrics per VM
P->>P: Project to 3 scores, reconstruct
P->>P: Error = distance to reconstruction
P->>A: Rows with error above p99 of training
A->>A: Open a ticket with the metrics attached
Two VMs both run at 95 percent CPU. One serves heavy traffic, the other serves almost none. Which has the higher PCA reconstruction error?
Correct! Reconstruction error measures how far a row is from the patterns the kept components describe, not how large its values are.
Large data and other variants
The default PCA in scikit-learn picks a solver from the data’s shape. With fewer than 1,000 features and more than ten times as many rows, it eigendecomposes the covariance matrix, which is fast for tall, narrow tables. For larger, wider data where you keep a small fraction of the components, it uses a randomized SVD that approximates the top components without computing the rest.
When the data doesn’t fit in memory, IncrementalPCA learns from batches with partial_fit:
from sklearn.decomposition import PCA, IncrementalPCA
from sklearn.preprocessing import StandardScaler
from metrics import X
Xs = StandardScaler().fit_transform(X)
ipca = IncrementalPCA(n_components=3)
for start in range(0, len(Xs), 250):
ipca.partial_fit(Xs[start:start + 250])
print("incremental:", ipca.explained_variance_ratio_.round(3))
print("full: ", PCA(n_components=3).fit(Xs).explained_variance_ratio_.round(3))
incremental: [0.4 0.307 0.218]
full: [0.4 0.307 0.218]
On this data the batched version matches the full one to three decimals. In a real streaming setup you also need the scaler’s means and deviations from somewhere other than the full table, such as a sample or running statistics.
Other relatives cover cases plain PCA doesn’t:
| Method | What it finds | Use it when | Watch out for |
|---|---|---|---|
| PCA | Linear directions of greatest variance | Dense numeric data with correlated features | Needs scaling; linear only |
| IncrementalPCA | Same, learned in batches | Data doesn’t fit in memory | Scaling must also be done without the full table |
| TruncatedSVD | Top singular vectors without centering | Sparse data such as text term counts | Not centered, so not exactly PCA |
| Kernel PCA | Nonlinear components via a kernel | Curved structure in modest data sizes | Memory grows with rows squared; harder to interpret |
| t-SNE, UMAP | 2D or 3D maps that keep local neighbors | Visualizing clusters | Distances and axes between clusters mean little; not for model inputs |
| Feature selection | A subset of the original columns | You need to keep original, named features | Doesn’t combine redundant features |
PCA in the cloud
BigQuery ML trains PCA with SQL, so you can reduce a table where it lives. You set either NUM_PRINCIPAL_COMPONENTS or PCA_EXPLAINED_VARIANCE_RATIO, not both, and PCA_SOLVER accepts FULL, RANDOMIZED or AUTO:
CREATE OR REPLACE MODEL ops.vm_metrics_pca
OPTIONS (
model_type = 'PCA',
pca_explained_variance_ratio = 0.9,
scale_features = TRUE
) AS
SELECT cpu_pct, requests_per_s, net_in_mbps, net_out_mbps, load_avg,
mem_pct, page_cache_gb, swap_mb_s,
disk_read_iops, disk_write_iops, disk_mbps, disk_latency_ms
FROM ops.vm_hourly_metrics;
SELECT * FROM ML.PRINCIPAL_COMPONENT_INFO(MODEL ops.vm_metrics_pca);
ML.PRINCIPAL_COMPONENT_INFO returns each component’s eigenvalue, explained variance ratio and cumulative ratio, the same table as the scikit-learn output above. ML.PRINCIPAL_COMPONENTS returns the loadings, ML.PREDICT returns the scores for new rows, and ML.DETECT_ANOMALIES works with PCA models, using the reconstruction idea from the previous section.
Amazon SageMaker AI has PCA as a built-in algorithm. feature_dim and num_components are required; algorithm_mode is regular by default or randomized for many features; and subtract_mean defaults to true. It fits the case where the data sits in S3 and you want a managed training job, for example to reduce features before training another built-in algorithm.
Apache Spark provides pyspark.ml.feature.PCA for data on Amazon EMR, Google Cloud Dataproc, Azure Databricks or any other Spark service. Put a StandardScaler with withMean=True in front, so the projected scores are centered and the components don’t depend on units:
from pyspark.ml import Pipeline
from pyspark.ml.feature import PCA, StandardScaler, VectorAssembler
metrics = ["cpu_pct", "requests_per_s", "net_in_mbps", "net_out_mbps", "load_avg",
"mem_pct", "page_cache_gb", "swap_mb_s",
"disk_read_iops", "disk_write_iops", "disk_mbps", "disk_latency_ms"]
pipeline = Pipeline(stages=[
VectorAssembler(inputCols=metrics, outputCol="raw"),
StandardScaler(inputCol="raw", outputCol="scaled", withMean=True, withStd=True),
PCA(k=3, inputCol="scaled", outputCol="pcs"),
])
model = pipeline.fit(vm_df)
print(model.stages[-1].explainedVariance) # share of variance per component
reduced = model.transform(vm_df) # adds a "pcs" vector column
For a table of a few thousand rows, none of this is necessary; the scikit-learn code runs in under a second in the simple ML project setup.
For further reading, see the scikit-learn decomposition guide, the BigQuery ML PCA CREATE MODEL reference, the SageMaker AI PCA hyperparameters and the Spark feature extraction guide.
When to use PCA
PCA is a good choice when:
- many numeric features are correlated and you want fewer, uncorrelated ones
- you want a 2D or 3D view of high-dimensional data to look for structure, for example before running k-means
- a distance-based model such as KNN or k-means suffers from many noisy dimensions
- you want an anomaly score that flags rows breaking the usual relationships between metrics
- you need to compress features for storage or faster training and can accept some loss
Look elsewhere when you need to keep original, named features for explanation (feature selection), when the structure is strongly nonlinear (kernel PCA or an autoencoder), when the data is sparse text counts (TruncatedSVD), or when the only goal is predicting a label and the model already handles many features well.
Key takeaways
- PCA rotates the data onto uncorrelated axes ordered by variance. The components are eigenvectors of the covariance matrix, and each eigenvalue is the variance along its component.
- Standardize features with different units first. On the VM metrics, raw PCA described which columns had the largest numbers; scaled PCA recovered the three real drivers.
- Read the loadings to see what each component means, and don’t rely on their signs.
- Choose the number of components from cumulative variance and the scree plot, or with cross-validation when PCA feeds a model. On the digits data, 20 of 64 inputs cost about two points of accuracy.
- PCA keeps variance, not predictive signal. A low-variance feature that decides the label can be the first thing it drops.
- Reconstruction error flags rows that break the usual correlations, and BigQuery ML, SageMaker AI and Spark run the same method where your data already lives.
Part 9 of 9 · Machine Learning Algorithms
- 01Linear Regression: Predicting Outcomes
- 02Logistic Regression: Understanding Probabilities
- 03Decision Trees: Making Decisions Using Data
- 04Random Forest: An Ensemble Learning Method
- 05Support Vector Machines: Classifying Data
- 06K-Nearest Neighbors: Finding Similar Data Points
- 07Naive Bayes: Applying Probability in ML
- 08K-Means Clustering: Grouping Similar Data
- 09Principal Component Analysis: Dimensionality Reduction


