z-Score (Standard Score)

The zz-score (or standard score) measures how many standard deviations an observation xx lies above or below the population mean μ\mu.

Formula

Population zz-Score:

z=x−μσz = \frac{x - \mu}{\sigma}

Where:

  • xx is the raw value.
  • μ\mu is the population mean: μ=1N∑i=1Nxi\mu = \frac{1}{N}\sum_{i=1}^N x_i.
  • σ\sigma is the population standard deviation: σ=1N∑i=1N(xi−μ)2\sigma = \sqrt{\frac{1}{N}\sum_{i=1}^N (x_i - \mu)^2}.

Sample zz-Score:

z=x−xˉsz = \frac{x - \bar{x}}{s}

Where xˉ\bar{x} is sample mean and ss is sample standard deviation (using n−1n-1 degrees of freedom).

Key Properties

  1. Standardized Distribution: After applying zz-score transformation, the new distribution has a mean of 0 and a standard deviation of 1.
  2. Empirical Rule (68-95-99.7 Rule for Normal Distributions):
    • ≈68.27%\approx 68.27\% of values fall within ∣z∣≤1|z| \le 1.
    • ≈95.45%\approx 95.45\% of values fall within ∣z∣≤2|z| \le 2.
    • ≈99.73%\approx 99.73\% of values fall within ∣z∣≤3|z| \le 3.

Common Use Cases in Machine Learning

1. Feature Standardization

Gradient descent and distance-based algorithms (SVM, KNN, PCA, Logistic Regression, Deep Learning) require normalized feature magnitudes to prevent large-scale features from dominating gradients:

from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_standardized = scaler.fit_transform(X_train)

2. Statistical Outlier Detection

Points with ∣z∣>3|z| > 3 (or ∣z∣>2.5|z| > 2.5) are commonly flagged as potential outliers in normally distributed data:

from scipy import stats
import numpy as np

z_scores = np.abs(stats.zscore(data))
outliers = np.where(z_scores > 3.0)

Robust Alternatives (For Heavy Outliers / Skewed Data)

Because mean (μ\mu) and standard deviation (σ\sigma) are sensitive to extreme outliers, standard zz-scores can be distorted. Robust alternatives include:

1. Modified zz-Score (using Median Absolute Deviation)

zmodified=0.6745×(x−median)MADz_{\text{modified}} = \frac{0.6745 \times (x - \text{median})}{\text{MAD}}

Where MAD=median(∣xi−median(x)∣)\text{MAD} = \text{median}(|x_i - \text{median}(x)|).

2. Robust Scaler (IQR)

xscaled=x−medianQ3−Q1x_{\text{scaled}} = \frac{x - \text{median}}{Q_3 - Q_1}
from sklearn.preprocessing import RobustScaler
scaler = RobustScaler()
X_robust = scaler.fit_transform(X_train)