Theory ofIntelligence
Index
Data Preprocessing & FoundationsBook Index: Letter M

Mean Centering & Variance Normalization: The Geometry of Feature Scaling

Understand why subtracting the mean moves the centroid to the origin and why dividing by standard deviation scales variance to 1. Complete geometric intuition, algebraic proofs, 2D matrix mechanics, PCA connections, and raw NumPy implementations.

functionsMathematical Representation
x~=x−μσ\tilde{\mathbf{x}} = \frac{\mathbf{x} - \boldsymbol{\mu}}{\boldsymbol{\sigma}}

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:

  1. Step 1: Mean Centering (Coordinate Translation): Subtracting the feature means so the centroid moves to the origin (0,0)(0, 0).
  2. Step 2: Variance Normalization (Axis Rescaling): Dividing by each feature's standard deviation so every dimension has unit variance (σ2=1\sigma^2 = 1).

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 (x1x_1).
  • The vertical axis represents weight (x2x_2).

Plotted on a Cartesian plane, these measurements cluster somewhere high up in the first quadrant:

TEXT
    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:

lightbulb

How can we move the center of an entire collection of points to the origin (0,0)(0, 0) 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:

xi′=xi−μ\boxed{x_i' = x_i - \mu}

Where:

  • xix_i represents an original observation.
  • μ\mu represents the mean of that feature.
  • xi′x_i' 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:

ObservationFeature x1x_1 (Height)Feature x2x_2 (Weight)
A2244
B4466
C6688
D881010

Each observation is a coordinate vector: A=(2,4),B=(4,6),C=(6,8),D=(8,10)A = (2, 4), \quad B = (4, 6), \quad C = (6, 8), \quad D = (8, 10)

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 nn:

μ=1n∑i=1nxi\boxed{\mu = \frac{1}{n}\sum_{i=1}^{n} x_i}

For multidimensional data, we calculate the mean independently for each feature:

  • Feature 1: μ1=2+4+6+84=204=5\mu_1 = \frac{2 + 4 + 6 + 8}{4} = \frac{20}{4} = \mathbf{5}

  • Feature 2: μ2=4+6+8+104=284=7\mu_2 = \frac{4 + 6 + 8 + 10}{4} = \frac{28}{4} = \mathbf{7}

Representing these means as a vector yields the centroid:

μ=[μ1μ2]=[57]\boldsymbol{\mu} = \begin{bmatrix} \mu_1 \\ \mu_2 \end{bmatrix} = \begin{bmatrix} 5 \\ 7 \end{bmatrix}

The point (5,7)(5, 7) is the geometric center of mass of the four points. Our objective is to translate this center to (0,0)(0, 0).


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: 10,20,30,4010, \quad 20, \quad 30, \quad 40

Their average position is: μ=10+20+30+404=25\mu = \frac{10 + 20 + 30 + 40}{4} = \mathbf{25}

Now shift every person 2525 units to the left: 10−25=−15,20−25=−5,30−25=5,40−25=1510 - 25 = -15, \quad 20 - 25 = -5, \quad 30 - 25 = 5, \quad 40 - 25 = 15

Calculate the new mean: μ′=−15−5+5+154=04=0\mu' = \frac{-15 - 5 + 5 + 15}{4} = \frac{0}{4} = \mathbf{0}

TEXT
Original:    ──[10]────[20]────[μ=25]────[30]────[40]──►
                          │ Shift -25
                          ▼
Centered:    ──[-15]───[-5]────[μ'=0]────[+5]────[+15]──►

Because every point moved by the exact same displacement (−25-25), the distances between people did not change (20−10=1020 - 10 = 10, and −5−(−15)=10-5 - (-15) = 10). The center simply moved from 2525 to 00.

lightbulb

Fundamental 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 μ=[5,7]T\boldsymbol{\mu} = [5, 7]^T, we subtract μ\boldsymbol{\mu} from every observation vector xi\mathbf{x}_i:

xi′=xi−μ\boxed{\mathbf{x}_i' = \mathbf{x}_i - \boldsymbol{\mu}}

Subtracting from Each Point

  • Observation A: xA′=[24]−[57]=[−3−3]\mathbf{x}_A' = \begin{bmatrix} 2 \\ 4 \end{bmatrix} - \begin{bmatrix} 5 \\ 7 \end{bmatrix} = \begin{bmatrix} -3 \\ -3 \end{bmatrix}

  • Observation B: xB′=[46]−[57]=[−1−1]\mathbf{x}_B' = \begin{bmatrix} 4 \\ 6 \end{bmatrix} - \begin{bmatrix} 5 \\ 7 \end{bmatrix} = \begin{bmatrix} -1 \\ -1 \end{bmatrix}

  • Observation C: xC′=[68]−[57]=[11]\mathbf{x}_C' = \begin{bmatrix} 6 \\ 8 \end{bmatrix} - \begin{bmatrix} 5 \\ 7 \end{bmatrix} = \begin{bmatrix} 1 \\ 1 \end{bmatrix}

  • Observation D: xD′=[810]−[57]=[33]\mathbf{x}_D' = \begin{bmatrix} 8 \\ 10 \end{bmatrix} - \begin{bmatrix} 5 \\ 7 \end{bmatrix} = \begin{bmatrix} 3 \\ 3 \end{bmatrix}

The transformed points are: A′=(−3,−3),B′=(−1,−1),C′=(1,1),D′=(3,3)A' = (-3, -3), \quad B' = (-1, -1), \quad C' = (1, 1), \quad D' = (3, 3)

TEXT
    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: μ′=14[(−3,−3)+(−1,−1)+(1,1)+(3,3)]=(0,0)\boldsymbol{\mu}' = \frac{1}{4}\Big[(-3,-3) + (-1,-1) + (1,1) + (3,3)\Big] = \mathbf{(0, 0)}


6. The Mathematical Proof: Why the New Mean is Always Zero

Let x1,x2,…,xnx_1, x_2, \dots, x_n be nn observations of a feature with mean: μ=1n∑i=1nxi  ⟹  ∑i=1nxi=nμ\mu = \frac{1}{n} \sum_{i=1}^{n} x_i \implies \sum_{i=1}^{n} x_i = n\mu

Define the centered observations as xi′=xi−μx_i' = x_i - \mu. The mean of the transformed data is:

μ′=1n∑i=1nxi′=1n∑i=1n(xi−μ)\mu' = \frac{1}{n}\sum_{i=1}^{n} x_i' = \frac{1}{n}\sum_{i=1}^{n}(x_i - \mu)

Using the distributive linearity of summation:

μ′=1n(∑i=1nxi−∑i=1nμ)\mu' = \frac{1}{n}\left( \sum_{i=1}^{n} x_i - \sum_{i=1}^{n} \mu \right)

Because μ\mu is a constant across all observations, summing it nn times gives ∑i=1nμ=nμ\sum_{i=1}^n \mu = n\mu:

μ′=1n(∑i=1nxi−nμ)\mu' = \frac{1}{n}\left( \sum_{i=1}^{n} x_i - n\mu \right)

Substituting ∑i=1nxi=nμ\sum_{i=1}^{n} x_i = n\mu:

μ′=1n(nμ−nμ)=0n=0\mu' = \frac{1}{n}(n\mu - n\mu) = \frac{0}{n} = \mathbf{0}

1n∑i=1n(xi−μ)≡0\boxed{\frac{1}{n}\sum_{i=1}^n (x_i - \mu) \equiv 0}

This identity holds identically for every dimension in any dd-dimensional space.


7. Mean Centering Using Matrix Notation

In machine learning and linear algebra, data is represented as an n×dn \times d design matrix XX:

X∈Rn×dX \in \mathbb{R}^{n \times d}

For our running example (n=4,d=2n=4, d=2):

X=[244668810]X = \begin{bmatrix} 2 & 4 \\ 4 & 6 \\ 6 & 8 \\ 8 & 10 \end{bmatrix}

The feature means form a row vector μ∈R1×d\boldsymbol{\mu} \in \mathbb{R}^{1 \times d}: μ=[57]\boldsymbol{\mu} = \begin{bmatrix} 5 & 7 \end{bmatrix}

Using an n×1n \times 1 column vector of ones 1n=[1111]T\mathbf{1}_n = \begin{bmatrix} 1 & 1 & 1 & 1 \end{bmatrix}^T, we express mean centering in compact matrix notation:

Xc=X−1nμ\boxed{X_c = X - \mathbf{1}_n \boldsymbol{\mu}}

Xc=[244668810]−[1111][57]=[244668810]−[57575757]=[−3−3−1−11133]X_c = \begin{bmatrix} 2 & 4 \\ 4 & 6 \\ 6 & 8 \\ 8 & 10 \end{bmatrix} - \begin{bmatrix} 1 \\ 1 \\ 1 \\ 1 \end{bmatrix} \begin{bmatrix} 5 & 7 \end{bmatrix} = \begin{bmatrix} 2 & 4 \\ 4 & 6 \\ 6 & 8 \\ 8 & 10 \end{bmatrix} - \begin{bmatrix} 5 & 7 \\ 5 & 7 \\ 5 & 7 \\ 5 & 7 \end{bmatrix} = \mathbf{\begin{bmatrix} -3 & -3 \\ -1 & -1 \\ 1 & 1 \\ 3 & 3 \end{bmatrix}}

In code, modern numerical libraries like NumPy achieve this automatically through broadcasting.


8. Invariants: What Changes and What Remains the Same?

PropertyOriginal DatasetCentered DatasetStatus
Centroidμ=(5,7)\boldsymbol{\mu} = (5, 7)μ′=(0,0)\boldsymbol{\mu}' = (0, 0)Changed (Shifted to origin)
Distance d(A,B)d(A, B)(4−2)2+(6−4)2=8\sqrt{(4-2)^2 + (6-4)^2} = \sqrt{8}(−1−(−3))2+(−1−(−3))2=8\sqrt{(-1 - (-3))^2 + (-1 - (-3))^2} = \sqrt{8}Preserved (Unchanged)
Relative VectorsAB⃗=B−A=(2,2)\vec{AB} = B - A = (2, 2)A′B′⃗=B′−A′=(2,2)\vec{A'B'} = B' - A' = (2, 2)Preserved (Identical)
Angles & CorrelationsCollinear along y=x+2y = x + 2Collinear along y=xy = xPreserved (Slope unchanged)
Shape & SpreadSame bounding dimensionsSame bounding dimensionsPreserved (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: Var⁡(X)=1n−1∑i=1n(xi−μ)2\operatorname{Var}(X) = \frac{1}{n-1}\sum_{i=1}^{n}(x_i - \mu)^2

When data is centered (XcX_c), the sample covariance matrix takes a particularly elegant form:

C=1n−1XcTXc\boxed{C = \frac{1}{n-1} X_c^T X_c}

Here is why centering is non-negotiable for PCA:

  1. If you forget to center: The uncentered product XTXX^T X measures the second moment around the arbitrary origin (0,0)(0, 0), not around the data's center of mass. The first principal component would simply point from (0,0)(0, 0) toward the cluster centroid, wasting a dimension on the dataset's offset rather than its internal variance.
  2. When centered: The origin (0,0)(0, 0) coincides with the data's center of mass. The eigenvectors of CC 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 (0,0)(0, 0). However, features can still have dramatically different spreads.

Consider two centered 1D features: x1=[−1,0,1]x_1 = [-1, \quad 0, \quad 1] x2=[−10,0,10]x_2 = [-10, \quad 0, \quad 10]

Both have a mean of zero: μ1=−1+0+13=0,μ2=−10+0+103=0\mu_1 = \frac{-1 + 0 + 1}{3} = 0, \quad \mu_2 = \frac{-10 + 0 + 10}{3} = 0

Yet their spreads are wildly different:

  • x1x_1 ranges from −1-1 to +1+1 (span of 22).
  • x2x_2 ranges from −10-10 to +10+10 (span of 2020).

If you feed both features into gradient descent, KNN, or PCA, the feature with the larger numerical scale (x2x_2) 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:

σ2=1m∑i=1m(x(i)−μ)2\sigma^2 = \frac{1}{m}\sum_{i=1}^{m}(x^{(i)} - \mu)^2

Because we already mean-centered the data in Step 1 (μ=0\mu = 0), the formula simplifies dramatically:

σ2=1m∑i=1m(x(i))2\boxed{\sigma^2 = \frac{1}{m}\sum_{i=1}^{m}\big(x^{(i)}\big)^2}

(Variance of centered data is simply the average of its squared values.)

Step-by-Step Variance Calculation

  • For x1=[−1,0,1]x_1 = [-1, 0, 1]:

    1. Square every observation: x12=[1,0,1]x_1^2 = [1, 0, 1]
    2. Sum squares: 1+0+1=21 + 0 + 1 = 2
    3. Divide by m=3m = 3: σ12=23≈0.667\sigma_1^2 = \frac{2}{3} \approx \mathbf{0.667}
  • For x2=[−10,0,10]x_2 = [-10, 0, 10]:

    1. Square every observation: x22=[100,0,100]x_2^2 = [100, 0, 100]
    2. Sum squares: 100+0+100=200100 + 0 + 100 = 200
    3. Divide by m=3m = 3: σ22=2003≈66.667\sigma_2^2 = \frac{200}{3} \approx \mathbf{66.667}
FeatureMeanVariance (σ2\sigma^2)Spread Comparison
x1x_1000.6670.667Base variance
x2x_20066.66766.667100×100\times larger variance

12. What is Standard Deviation and Why Do We Divide by It?

Standard deviation is the square root of variance:

σ=σ2\boxed{\sigma = \sqrt{\sigma^2}}

  • σ1=0.6667≈0.8165\sigma_1 = \sqrt{0.6667} \approx \mathbf{0.8165}
  • σ2=66.667≈8.1650\sigma_2 = \sqrt{66.667} \approx \mathbf{8.1650}

Why take the square root?

Variance is measured in squared units (e.g., cm2\text{cm}^2 or kg2\text{kg}^2). Taking the square root brings the scale back to the original units (cm\text{cm} or kg\text{kg}), matching the units of the data values themselves.


13. The Normalization Transformation: Dividing by σ\sigma

To give every feature unit variance (σ2=1\sigma^2 = 1), divide every observation of feature jj by its standard deviation σj\sigma_j:

x~j(i)=xj(i)σj\boxed{\tilde{x}_j^{(i)} = \frac{x_j^{(i)}}{\sigma_j}}

Normalizing Feature 1

x~1=[−10.8165,  00.8165,  10.8165]=[−1.225,  0,  1.225]\tilde{x}_1 = \left[ \frac{-1}{0.8165}, \; \frac{0}{0.8165}, \; \frac{1}{0.8165} \right] = \mathbf{[-1.225, \; 0, \; 1.225]}

Normalizing Feature 2

x~2=[−108.165,  08.165,  108.165]=[−1.225,  0,  1.225]\tilde{x}_2 = \left[ \frac{-10}{8.165}, \; \frac{0}{8.165}, \; \frac{10}{8.165} \right] = \mathbf{[-1.225, \; 0, \; 1.225]}

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 σ\sigma Produces Unit Variance

Let xx be a centered random variable with variance σ2=1m∑i=1m(x(i))2\sigma^2 = \frac{1}{m}\sum_{i=1}^m (x^{(i)})^2.

Define the normalized variable x~=xσ\tilde{x} = \frac{x}{\sigma}. Calculate its variance:

Var⁡(x~)=1m∑i=1m(x~(i))2=1m∑i=1m(x(i)σ)2\operatorname{Var}(\tilde{x}) = \frac{1}{m}\sum_{i=1}^{m} (\tilde{x}^{(i)})^2 = \frac{1}{m}\sum_{i=1}^{m} \left(\frac{x^{(i)}}{\sigma}\right)^2

Distributing the square:

=1m∑i=1m(x(i))2σ2= \frac{1}{m}\sum_{i=1}^{m} \frac{(x^{(i)})^2}{\sigma^2}

Since σ2\sigma^2 is a constant scalar for this feature, factor it outside the summation:

=1σ2[1m∑i=1m(x(i))2]= \frac{1}{\sigma^2} \left[ \frac{1}{m}\sum_{i=1}^{m} (x^{(i)})^2 \right]

The bracketed expression is by definition the original variance σ2\sigma^2:

Var⁡(x~)=1σ2⋅σ2=1\operatorname{Var}(\tilde{x}) = \frac{1}{\sigma^2} \cdot \sigma^2 = \mathbf{1}

Var⁡(Xσ)≡1\boxed{\operatorname{Var}\left(\frac{X}{\sigma}\right) \equiv 1}

lightbulb

Key Rule of Variance: Scaling a variable by a constant aa scales its variance by a2a^2: Var⁡(aX)=a2Var⁡(X)\operatorname{Var}(aX) = a^2 \operatorname{Var}(X). Setting a=1σa = \frac{1}{\sigma} yields a2=1σ2a^2 = \frac{1}{\sigma^2}, canceling the original variance to exactly 11.


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.
TEXT
    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 (0,0)(0, 0).

This is mathematically incorrect when features are correlated.

Making each feature have unit variance guarantees: Var⁡(x1)=1,Var⁡(x2)=1\operatorname{Var}(x_1) = 1, \quad \operatorname{Var}(x_2) = 1

However, the diagonal elements of the covariance matrix are 11, while the off-diagonal elements (covariances) remain nonzero!

Consider our 4-point centered dataset: Xc=[−3−3−1−11133]X_c = \begin{bmatrix} -3 & -3 \\ -1 & -1 \\ 1 & 1 \\ 3 & 3 \end{bmatrix}

Both columns are identical (x2=x1x_2 = x_1). Each column has variance: σ2=(−3)2+(−1)2+12+324=9+1+1+94=204=5  ⟹  σ=5\sigma^2 = \frac{(-3)^2 + (-1)^2 + 1^2 + 3^2}{4} = \frac{9 + 1 + 1 + 9}{4} = \frac{20}{4} = 5 \implies \sigma = \sqrt{5}

Dividing each column by σ=5\sigma = \sqrt{5}:

Xnormalized=15[−3−3−1−11133]≈[−1.342−1.342−0.447−0.4470.4470.4471.3421.342]X_{\text{normalized}} = \frac{1}{\sqrt{5}} \begin{bmatrix} -3 & -3 \\ -1 & -1 \\ 1 & 1 \\ 3 & 3 \end{bmatrix} \approx \begin{bmatrix} -1.342 & -1.342 \\ -0.447 & -0.447 \\ 0.447 & 0.447 \\ 1.342 & 1.342 \end{bmatrix}

Both features now have variance 11, yet all points still lie strictly along the 45∘45^\circ line y=xy = x. The distribution is not a circular disk — it is a 11-dimensional line!

TEXT
  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 X∈Rn×dX \in \mathbb{R}^{n \times d}:

  1. Compute the 1×d1 \times d mean vector: μ=1n1TX\boldsymbol{\mu} = \frac{1}{n} \mathbf{1}^T X
  2. Mean-center: Xc=X−1μX_c = X - \mathbf{1} \boldsymbol{\mu}
  3. Compute the 1×d1 \times d standard deviation vector: σ=1n1T(Xc⊙Xc)\boldsymbol{\sigma} = \sqrt{\frac{1}{n} \mathbf{1}^T (X_c \odot X_c)}
  4. Normalize variance: Xstd=Xc⊘(1σ)=X−1μ1σ\boxed{X_{\text{std}} = X_c \oslash (\mathbf{1} \boldsymbol{\sigma}) = \frac{X - \mathbf{1}\boldsymbol{\mu}}{\mathbf{1}\boldsymbol{\sigma}}} (where ⊙\odot is element-wise square and ⊘\oslash is element-wise division).

18. Python Implementation with NumPy

Here is the complete, self-contained implementation demonstrating both steps:

PYTHON
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:

TEXT
--- 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

PropertyStep 1: Mean CenteringStep 2: Variance NormalizationCombined: Z-Score Standardization
Mathematical OperationSubtract mean (x−μx - \mu)Divide by std dev (x/σx / \sigma)x−μσ\frac{x - \mu}{\sigma}
New Mean000000
New VarianceOriginal variance (σ2\sigma^2)1111
Geometric EffectRigid translationNon-uniform coordinate scalingTranslation + Rescaling
Preserves Pairwise Distances?Yes (Isometry)No (Distances rescaled)No
Preserves Point Cloud Shape?Yes (Rigid shift)No (Aspect ratio changes)No
Impact on PCARequired (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 (0,0)(0, 0). 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 (xi<μ  ⟹  xi−μ<0x_i < \mu \implies x_i - \mu < 0), 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

  1. Mean Centering Shifts the Centroid: Subtracting the mean vector translates the center of gravity to the origin without altering pairwise distances or cluster geometry.
  2. The Sum of Mean Deviations is Identically Zero: ∑i=1n(xi−μ)≡0\sum_{i=1}^n (x_i - \mu) \equiv 0 guarantees that the new mean is always 0.
  3. Variance Normalization Scales Spread: Dividing by standard deviation divides the variance by σ2\sigma^2, forcing the new variance to equal exactly 11.
  4. Standardization Combines Both: Z-score standardization (x~=x−μσ\tilde{x} = \frac{x - \mu}{\sigma}) 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: μ=4+8+12+164=404=10\mu = \frac{4 + 8 + 12 + 16}{4} = \frac{40}{4} = \mathbf{10}

schoolQuestion 2: Subtract the mean from every observation in X = [4, 8, 12, 16].
expand_more

Answer: 4−10=−6,8−10=−2,12−10=+2,16−10=+64 - 10 = \mathbf{-6}, \quad 8 - 10 = \mathbf{-2}, \quad 12 - 10 = \mathbf{+2}, \quad 16 - 10 = \mathbf{+6} The centered dataset is Xc=[−6,−2,2,6]X_c = [-6, -2, 2, 6].

schoolQuestion 3: Verify that the mean of X_c = [-6, -2, 2, 6] is zero.
expand_more

Answer: μ′=−6+(−2)+2+64=04=0\mu' = \frac{-6 + (-2) + 2 + 6}{4} = \frac{0}{4} = \mathbf{0}

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 aa and bb. The original distance is ∣a−b∣|a - b|. The new distance is: ∣(a−10)−(b−10)∣=∣a−10−b+10∣=∣a−b∣|(a - 10) - (b - 10)| = |a - 10 - b + 10| = |a - b| 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: μ=[58]\boldsymbol{\mu} = \begin{bmatrix} 5 \\ 8 \end{bmatrix}

schoolQuestion 6: Explain the difference between mean centering and standardization.
expand_more

Answer:

  • Mean Centering: x′=x−μx' = x - \mu. Result has mean =0= 0, but retains its original measurement units and variance.
  • Standardization: z=x−μσz = \frac{x - \mu}{\sigma}. Result has mean =0= 0 and variance =1= 1 (dimensionless Z-scores).

  1. Principal Component Analysis (PCA) — How covariance matrices, eigenvalues, and eigenvectors project high-dimensional centered data onto maximal variance axes.
  2. Loss Functions & Gradient Descent — How feature scaling transforms elongated, poorly conditioned loss contours into symmetric circular bowls, speeding up gradient descent convergence.
  3. Batch & Layer Normalization — How deep neural networks dynamically center and scale intermediate activations across mini-batches during training.