When working with data in machine learning and statistics, we often encounter observations scattered across high-dimensional coordinate spaces. Real-world features — such as age, salary, height, or pixel intensity — rarely sit neatly around zero, nor do they share the same units of measurement.
To make datasets geometrically comparable and well-behaved for optimization and dimensionality reduction, we rely on two foundational preprocessing steps:
- Step 1: Mean Centering (Coordinate Translation): Subtracting the feature means so the centroid moves to the origin .
- Step 2: Variance Normalization (Axis Rescaling): Dividing by each feature's standard deviation so every dimension has unit variance ().
Together, these two operations form Z-score Standardization. This master guide explores the geometric intuition, mathematical proofs, matrix formulations, PCA connections, and raw Python code behind both steps.
Part I: Mean Centering — Moving Data to the Origin
1. Introduction: The Core Geometric Question
Imagine collecting height and weight data for several individuals:
- The horizontal axis represents height ().
- The vertical axis represents weight ().
Plotted on a Cartesian plane, these measurements cluster somewhere high up in the first quadrant:
Weight (x₂)
▲
12 ┼
10 ┼ ● D (8, 10)
8 ┼ ● C (6, 8)
6 ┼ ● B (4, 6)
4 ┼ ● A (2, 4)
2 ┼
0 ┼───┼───┼───┼───┼───┼───┼───┼───► Height (x₁)
0 2 4 6 8 10 12
This raises a fundamental question:
lightbulbHow can we move the center of an entire collection of points to the origin without altering the shape, distances, or relative arrangement of those points?
The answer is mean centering: subtracting the arithmetic mean of each feature from every observation of that feature:
Where:
- represents an original observation.
- represents the mean of that feature.
- represents the centered observation.
The true insight lies in understanding why this simple subtraction is an exact geometric translation that guarantees a zero centroid.
2. Understanding a Dataset as a Collection of Points
Consider four observations, each with two numerical features:
| Observation | Feature (Height) | Feature (Weight) |
|---|---|---|
| A | ||
| B | ||
| C | ||
| D |
Each observation is a coordinate vector:
All points reside in the positive quadrant. Where is the "center of gravity" of this data cloud?
3. What Is the Arithmetic Mean & Centroid?
The arithmetic mean is the sum of all observations divided by the total count :
For multidimensional data, we calculate the mean independently for each feature:
-
Feature 1:
-
Feature 2:
Representing these means as a vector yields the centroid:
The point is the geometric center of mass of the four points. Our objective is to translate this center to .
4. Geometric Intuition: Coordinate Translation
In coordinate geometry, translation means shifting every point of an object by the exact same displacement vector. Translation is an isometry: it preserves distances, angles, orientation, and shape.
Consider four people standing along a 1D line:
Their average position is:
Now shift every person units to the left:
Calculate the new mean:
Original: ──[10]────[20]────[μ=25]────[30]────[40]──►
│ Shift -25
▼
Centered: ──[-15]───[-5]────[μ'=0]────[+5]────[+15]──►
Because every point moved by the exact same displacement (), the distances between people did not change (, and ). The center simply moved from to .
lightbulbFundamental Principle: Translating every point by the negative of the dataset's centroid translates the centroid itself directly to the origin.
5. Why We Subtract the Mean (2D Step-by-Step)
For our 2D dataset with centroid , we subtract from every observation vector :
Subtracting from Each Point
-
Observation A:
-
Observation B:
-
Observation C:
-
Observation D:
The transformed points are:
Before Centering: After Centering:
x₂ x₂
▲ ▲
10 ┼ ● D (8,10) 3 ┼ ● D' (3,3)
8 ┼ ● C (6,8) 2 ┼
7 ┼─── ⊕ μ (5,7) 1 ┼ ● C' (1,1)
6 ┼ ● B (4,6) 0 ┼─── ⊕ (0,0) ──────► x₁
4 ┼● A (2,4) -1 ┼ ● B' (-1,-1)
0 ┼───────┼───────► x₁ -2 ┼
0 5 -3 ┼● A' (-3,-3)
The new centroid is:
6. The Mathematical Proof: Why the New Mean is Always Zero
Let be observations of a feature with mean:
Define the centered observations as . The mean of the transformed data is:
Using the distributive linearity of summation:
Because is a constant across all observations, summing it times gives :
Substituting :
This identity holds identically for every dimension in any -dimensional space.
7. Mean Centering Using Matrix Notation
In machine learning and linear algebra, data is represented as an design matrix :
For our running example ():
The feature means form a row vector :
Using an column vector of ones , we express mean centering in compact matrix notation:
In code, modern numerical libraries like NumPy achieve this automatically through broadcasting.
8. Invariants: What Changes and What Remains the Same?
| Property | Original Dataset | Centered Dataset | Status |
|---|---|---|---|
| Centroid | Changed (Shifted to origin) | ||
| Distance | Preserved (Unchanged) | ||
| Relative Vectors | Preserved (Identical) | ||
| Angles & Correlations | Collinear along | Collinear along | Preserved (Slope unchanged) |
| Shape & Spread | Same bounding dimensions | Same bounding dimensions | Preserved (No distortion) |
Because coordinate translation is a rigid body transformation, pairwise Euclidean distances and geometric shapes are completely invariant.
9. Why Mean Centering is Essential for PCA
Principal Component Analysis (PCA) is an unsupervised technique that finds orthogonal directions (eigenvectors) maximizing data variance.
Variance measures deviation around the mean:
When data is centered (), the sample covariance matrix takes a particularly elegant form:
Here is why centering is non-negotiable for PCA:
- If you forget to center: The uncentered product measures the second moment around the arbitrary origin , not around the data's center of mass. The first principal component would simply point from toward the cluster centroid, wasting a dimension on the dataset's offset rather than its internal variance.
- When centered: The origin coincides with the data's center of mass. The eigenvectors of capture the true axes of maximum spread.
Part II: Step 2: Variance Normalization (Feature Scaling)
10. Why Mean Centering Alone is Not Enough
In Step 1, mean centering moved the center of data to . However, features can still have dramatically different spreads.
Consider two centered 1D features:
Both have a mean of zero:
Yet their spreads are wildly different:
- ranges from to (span of ).
- ranges from to (span of ).
If you feed both features into gradient descent, KNN, or PCA, the feature with the larger numerical scale () will overpower the other purely because of its measurement units!
Step 2 solves this problem by scaling each feature so its variance becomes 1.
11. What is Variance? (And Why Centering Simplifies It)
Variance measures the average squared deviation of observations from their mean. The population variance formula is:
Because we already mean-centered the data in Step 1 (), the formula simplifies dramatically:
(Variance of centered data is simply the average of its squared values.)
Step-by-Step Variance Calculation
-
For :
- Square every observation:
- Sum squares:
- Divide by :
-
For :
- Square every observation:
- Sum squares:
- Divide by :
| Feature | Mean | Variance () | Spread Comparison |
|---|---|---|---|
| Base variance | |||
| larger variance |
12. What is Standard Deviation and Why Do We Divide by It?
Standard deviation is the square root of variance:
Why take the square root?
Variance is measured in squared units (e.g., or ). Taking the square root brings the scale back to the original units ( or ), matching the units of the data values themselves.
13. The Normalization Transformation: Dividing by
To give every feature unit variance (), divide every observation of feature by its standard deviation :
Normalizing Feature 1
Normalizing Feature 2
Both features now have identical numerical spread! We compressed the feature with large variance and expanded the feature with small variance.
14. Mathematical Proof: Why Dividing by Produces Unit Variance
Let be a centered random variable with variance .
Define the normalized variable . Calculate its variance:
Distributing the square:
Since is a constant scalar for this feature, factor it outside the summation:
The bracketed expression is by definition the original variance :
lightbulbKey Rule of Variance: Scaling a variable by a constant scales its variance by : . Setting yields , canceling the original variance to exactly .
15. Geometric Effect: Coordinate Axis Rescaling
Geometrically, variance normalization performs anisotropic scaling:
- Mean centering translates the entire cloud.
- Variance normalization stretches or compresses each coordinate axis independently.
Centered Data (Unequal Variance): Variance Normalized (Unit Variance):
x₂ x₂
▲ ▲
10 ┼ ● 2 ┼ ●
5 ┼ ● 1 ┼ ●
0 ┼──●───⊕───●──► x₁ 0 ┼──●────⊕────●──► x₁
-5 ┼ ● -1 ┼ ●
-10 ┼ ● -2 ┼ ●
(Tall, narrow ellipse) (Equalized axis spread)
16. Crucial Nuance: Does Unit Variance Make Data Spherical?
A common textbook misconception states that after variance normalization, the point cloud becomes a circular or spherical ball around .
This is mathematically incorrect when features are correlated.
Making each feature have unit variance guarantees:
However, the diagonal elements of the covariance matrix are , while the off-diagonal elements (covariances) remain nonzero!
Consider our 4-point centered dataset:
Both columns are identical (). Each column has variance:
Dividing each column by :
Both features now have variance , yet all points still lie strictly along the line . The distribution is not a circular disk — it is a -dimensional line!
Operation Effect on Center Effect on Variance Effect on Correlation
────────────────────────────────────────────────────────────────────────────────────────
Mean Centering Moves to (0, 0) Unchanged Unchanged
Variance Scaling At (0, 0) All diagonal = 1 Unchanged (still correlated)
Whitening (PCA) At (0, 0) Identity matrix (I) Correlations eliminated (Spherical)
To achieve a truly spherical distribution, you need Whitening (decorrelating via PCA eigenvectors, then scaling).
17. The Complete Process in Matrix Notation
For a design matrix :
- Compute the mean vector:
- Mean-center:
- Compute the standard deviation vector:
- Normalize variance: (where is element-wise square and is element-wise division).
18. Python Implementation with NumPy
Here is the complete, self-contained implementation demonstrating both steps:
import numpy as np
# 1. Original 4-sample, 2-feature dataset
X = np.array([
[2.0, 4.0],
[4.0, 6.0],
[6.0, 8.0],
[8.0, 10.0]
])
print("--- Original Data ---")
print(X)
# 2. Step 1: Mean Centering
means = np.mean(X, axis=0) # Mean of each column: [5.0, 7.0]
X_centered = X - means # Broadcasting (4x2 - 1x2 -> 4x2)
print("\n--- Step 1: Centered Data ---")
print(X_centered)
print("New Column Means:", np.round(np.mean(X_centered, axis=0), 4)) # [0., 0.]
# 3. Step 2: Variance Normalization
# ddof=0 calculates population variance (matches formula with denominator m)
std_devs = np.std(X_centered, axis=0, ddof=0) # [sqrt(5), sqrt(5)]
X_normalized = X_centered / std_devs
print("\n--- Step 2: Standardized Data (Mean 0, Var 1) ---")
print(np.round(X_normalized, 4))
print("\nVerification:")
print("Final Means: ", np.round(np.mean(X_normalized, axis=0), 4)) # [0., 0.]
print("Final Variances:", np.round(np.var(X_normalized, axis=0), 4)) # [1., 1.]
Script Output:
--- Original Data ---
[[ 2. 4.]
[ 4. 6.]
[ 6. 8.]
[ 8. 10.]]
--- Step 1: Centered Data ---
[[-3. -3.]
[-1. -1.]
[ 1. 1.]
[ 3. 3.]]
New Column Means: [0. 0.]
--- Step 2: Standardized Data (Mean 0, Var 1) ---
[[-1.3416 -1.3416]
[-0.4472 -0.4472]
[ 0.4472 0.4472]
[ 1.3416 1.3416]]
Verification:
Final Means: [0. 0.]
Final Variances: [1. 1.]
19. Final Comparison: Step 1 vs. Step 2
| Property | Step 1: Mean Centering | Step 2: Variance Normalization | Combined: Z-Score Standardization |
|---|---|---|---|
| Mathematical Operation | Subtract mean () | Divide by std dev () | |
| New Mean | |||
| New Variance | Original variance () | ||
| Geometric Effect | Rigid translation | Non-uniform coordinate scaling | Translation + Rescaling |
| Preserves Pairwise Distances? | Yes (Isometry) | No (Distances rescaled) | No |
| Preserves Point Cloud Shape? | Yes (Rigid shift) | No (Aspect ratio changes) | No |
| Impact on PCA | Required (aligns center of mass) | Optional (changes covariance to correlation) | PCA on correlation matrix |
20. Common Misconceptions
schoolMisconception 1: Mean centering moves every point to the origin.expand_more
Correction: Mean centering moves the average position (centroid) of the dataset to . Individual data points remain scattered around the origin according to their natural variance.
schoolMisconception 2: Mean centering makes all values positive.expand_more
Correction: Mean centering produces both positive and negative values. Any observation that was originally below the mean becomes negative (), while observations above the mean become positive.
schoolMisconception 3: Mean centering changes the shape of the data distribution.expand_more
Correction: Mean centering is a pure translation (adding/subtracting a constant vector). It does not rotate, shear, or stretch the data. The pairwise distances between all points remain 100% identical.
schoolMisconception 4: Unit variance makes the point cloud circular/spherical.expand_more
Correction: Giving each feature unit variance only standardizes spread along the standard coordinate axes. If features have high mutual correlation, the point cloud will still be an elongated diagonal ellipse. Only whitening (which decorrelates the features) produces a spherical distribution.
schoolMisconception 5: PCA always requires both mean centering and variance scaling.expand_more
Correction: PCA strictly requires mean centering so that eigenvectors capture variance around the centroid. However, variance scaling is optional:
- If all features share the same units (e.g. image pixel intensities from 0 to 255), we usually keep the original variances so higher-energy patterns dominate.
- If features have different units (e.g. age in years vs income in dollars), variance scaling is required to prevent income from dominating the principal components.
21. Key Takeaways
- Mean Centering Shifts the Centroid: Subtracting the mean vector translates the center of gravity to the origin without altering pairwise distances or cluster geometry.
- The Sum of Mean Deviations is Identically Zero: guarantees that the new mean is always 0.
- Variance Normalization Scales Spread: Dividing by standard deviation divides the variance by , forcing the new variance to equal exactly .
- Standardization Combines Both: Z-score standardization () produces zero-mean, unit-variance features, equalizing the influence of disparate measurement units across machine learning algorithms.
22. Test Your Understanding
schoolQuestion 1: Calculate the mean of X = [4, 8, 12, 16].expand_more
Answer:
schoolQuestion 2: Subtract the mean from every observation in X = [4, 8, 12, 16].expand_more
Answer: The centered dataset is .
schoolQuestion 3: Verify that the mean of X_c = [-6, -2, 2, 6] is zero.expand_more
Answer:
schoolQuestion 4: If every observation is translated by subtracting 10, does the distance between any two observations change? Explain why.expand_more
Answer: No. Let two points be and . The original distance is . The new distance is: Translations are isometries that cancel out when taking differences.
schoolQuestion 5: A dataset has two features with means μ₁ = 5 and μ₂ = 8. What vector must be subtracted from every observation?expand_more
Answer: Subtract the centroid vector:
schoolQuestion 6: Explain the difference between mean centering and standardization.expand_more
Answer:
- Mean Centering: . Result has mean , but retains its original measurement units and variance.
- Standardization: . Result has mean and variance (dimensionless Z-scores).
23. Recommended Next Explorations
- Principal Component Analysis (PCA) — How covariance matrices, eigenvalues, and eigenvectors project high-dimensional centered data onto maximal variance axes.
- Loss Functions & Gradient Descent — How feature scaling transforms elongated, poorly conditioned loss contours into symmetric circular bowls, speeding up gradient descent convergence.
- Batch & Layer Normalization — How deep neural networks dynamically center and scale intermediate activations across mini-batches during training.