18–20 min read Descriptive Statistics & Correlation Part 5 Progress (29 / 32)
Part 5 • Probabilistic AI & Statistical Foundations

Lesson 14.29: Descriptive Statistics, Variance & Correlation

Faced with a dataset containing millions of raw rows, human cognition cannot make informed decisions by inspecting individual numbers. We require rigorous mathematical metrics that capture the central tendency, measure dispersion, and expose latent relationships between variables. Transitioning from theoretical probability distributions to empirical data analysis is the domain of Descriptive Statistics.

1 Introduction: Extracting Meaning from Raw Observations

Imagine a scenario where 100 students complete an examination. After grading, you receive a raw list of scores. As a data scientist or educational administrator, you need immediate answers to critical questions:

  • What was the typical performance across the cohort? What represents the central balance point?
  • Are the scores tightly clustered around the average, or is there massive inequality between top and bottom performers?
  • Is there an observable association between the number of hours students spent studying and their final marks?

Staring at an unorganized table of 100 numbers provides little intuition. By applying mathematical techniques to condense the dataset into a few representative parameters, we extract actionable clarity. This discipline is known as Descriptive Statistics.

In machine learning and AI, descriptive statistics constitutes the foundation of Exploratory Data Analysis (EDA), feature scaling, anomaly detection, and loss evaluation.

2 What is Descriptive Statistics? The 3 Core Pillars

Descriptive Statistics is the branch of quantitative analysis focused on summarizing, organizing, and visualizing the key empirical characteristics of a collected dataset without drawing speculative inferences beyond the data itself.

Suppose an e-commerce website tracks daily revenue (in thousands of dollars) over a 7-day period: $100, 120, 110, 150, 130, 140, 150$. To understand this performance, we analyze three universal pillars:

1 Central Tendency

The Center: Locates the single representative value around which the data concentrates. (Mean, Median, Mode).

2 Dispersion / Spread

The Variability: Quantifies how tightly compressed or widely scattered the observations are. (Range, IQR, Variance, Std Dev).

3 Association

The Relationship: Evaluates how multiple features co-vary simultaneously. (Covariance, Pearson $r$, Spearman $\rho$).

3 Dataset, Population & Sample (Parameters vs. Statistics)

Before computing formulas, we must establish whether our dataset represents the entire target universe or merely an observed sample:

  • Population ($N$): The complete set of all possible entities under investigation (e.g., all 200 million smartphone users in a country). Metrics calculated from a population are called Parameters.
  • Sample ($n$): A subset drawn via random sampling representing the broader population (e.g., 5,000 randomly selected users). Metrics calculated from a sample are called Statistics.
Notation & Distinctions: Population Parameters vs. Sample Statistics
Measure Population Parameter (Size $N$) Sample Statistic (Size $n$)
Mean $\mu = \frac{\sum x_i}{N}$ $\bar{x} = \frac{\sum x_i}{n}$
Variance $\sigma^2 = \frac{\sum (x_i - \mu)^2}{N}$ $s^2 = \frac{\sum (x_i - \bar{x})^2}{n - 1}$
Standard Deviation $\sigma = \sqrt{\sigma^2}$ $s = \sqrt{s^2}$

Crucial observation: Sample variance divides by $n - 1$ instead of $n$. This adjustment is known as Bessel's Correction, detailed in Section 8.

4 Measures of Central Tendency

4.1 Mean (Arithmetic Average)

The sum of all values divided by total count. For a sample of size $n$:

$$\bar{x} = \frac{1}{n}\sum_{i=1}^n x_i$$

For test scores $[60, 70, 80, 90, 100]$, the sample mean is $\bar{x} = \frac{400}{5} = 80$.

Vulnerability: The mean is extremely sensitive to extreme outliers; a single astronomical value drags the mean dramatically.

4.2 Median: The Robust Central Value

The middle observation when data is sorted in ascending order.

  • Odd $n$: Exactly the middle element at position $\frac{n+1}{2}$. Example: $[10, 20, 30, 40, 50] \implies \text{Median} = 30$.
  • Even $n$: Average of the two central elements. Example: $[10, 20, 30, 40] \implies \text{Median} = \frac{20 + 30}{2} = 25$.

Outlier Robustness: The Startup Salary Paradox

Suppose 5 startup employees earn monthly salaries of: $\$15k, \$18k, \$20k, \$22k$, while the founder earns $\$200k$.
• $\text{Mean} = \frac{\$275k}{5} = \$55k$. No regular employee earns anything close to $\$55k$!
• $\text{Median} = \$20k$. Accurately describes the typical earnings of a standard employee.
For skewed distributions (salaries, web response latency, real estate prices), the Median is far more representative.

4.3 Mode (Most Frequent Value)

The value that appears with the highest frequency in the dataset.

  • $[2, 3, 3, 4, 5, 5, 5, 7] \implies \text{Mode} = 5$ (Unimodal).
  • $[1, 1, 2, 2, 3] \implies \text{Modes} = 1 \text{ and } 2$ (Bimodal).
  • $[1, 2, 3, 4] \implies \text{No mode}$ (Uniform frequency).

Mode is the only measure of central tendency applicable to categorical/discrete text data (e.g., most purchased shoe size or dominant classification class).

5 Measures of Dispersion: Why Spread Matters

Central tendency alone fails to capture the true distribution of data. Consider two classroom cohorts:

Class A: $[48, 49, 50, 51, 52]$
Mean = 50 | Tightly clustered, virtually identical performance.
Class B: $[10, 30, 50, 70, 90]$
Mean = 50 | Extreme inequality between struggling and excelling students.

Both cohorts share the identical mean ($50$), yet their educational dynamics are polar opposites. Dispersion metrics quantify this variation.

6. Range

The difference between highest and lowest observations: $\text{Range} = x_{\max} - x_{\min}$.

While simple, Range relies exclusively on two extremes and ignores all intermediate structure, making it notoriously fragile to noise.

7 Quartiles & Interquartile Range (IQR) — Foundation of Box Plots

Dividing an ordered dataset into four equal segments produces three division cutoffs called Quartiles:

  • $Q_1$ (First Quartile / 25th Percentile): Boundary below which $25\%$ of observations fall.
  • $Q_2$ (Second Quartile / 50th Percentile): Exactly identical to the Median.
  • $Q_3$ (Third Quartile / 75th Percentile): Boundary below which $75\%$ of observations fall.

The span between the 75th and 25th percentiles is the Interquartile Range (IQR):

$$\text{IQR} = Q_3 - Q_1$$

IQR represents the spread of the central 50% of the dataset and is entirely impervious to extreme outliers.

Tukey's $1.5 \times \text{IQR}$ Outlier Detection Rule:

In data cleaning and preprocessing pipelines, outlier fences are established via:

Lower Fence: $\text{LF} = Q_1 - 1.5 \times \text{IQR}$ Upper Fence: $\text{UF} = Q_3 + 1.5 \times \text{IQR}$

Any data point lying outside $[LF, UF]$ is flagged as a statistical outlier for further inspection.

8 Variance: Average Squared Deviation & Bessel's Correction

Because unsquared deviations around the mean sum to zero ($\sum (x_i - \bar{x}) = 0$), we square each deviation before averaging:

Population Variance ($\sigma^2$)
$$\sigma^2 = \frac{\sum_{i=1}^N (x_i - \mu)^2}{N}$$

Used when complete census data for the entire population is available. Denominator is $N$.

Sample Variance ($s^2$) — Bessel's Correction
$$s^2 = \frac{\sum_{i=1}^n (x_i - \bar{x})^2}{n - 1}$$

Used when estimating population spread from sample observations. Denominator is $n - 1$.

Why Divide by $n - 1$? (Bessel's Correction)

Sample points cluster closer to their own sample mean $\bar{x}$ than to the unknown population mean $\mu$. Dividing by $n$ introduces systematic downward bias, underestimating true variance.
Dividing by $n - 1$ (the degrees of freedom remaining after estimating $\bar{x}$) corrects this contraction, yielding an strictly unbiased estimator ($\mathbb{E}[s^2] = \sigma^2$).

Step-by-Step Calculation: $[2, 4, 4, 4, 5, 5, 7, 9]$

Count $n = 8$, Mean $\bar{x} = \frac{40}{8} = 5$.

Value $x_i$ Deviation $(x_i - \bar{x})$ Squared Deviation $(x_i - \bar{x})^2$
2−39
4, 4, 4−1, −1, −11, 1, 1
5, 50, 00, 0
7+24
9+416
Sum032

• If considered a Population: $\sigma^2 = \frac{32}{8} = 4$
• If considered a Sample: $s^2 = \frac{32}{8 - 1} = \frac{32}{7} \approx 4.5714$

9 Standard Deviation: Returning to Physical Units

Variance produces squared units (e.g., $\text{ms}^2$ or $\$^2$). To restore the dispersion measurement back into original physical units, we take the non-negative square root:

$$s = \sqrt{s^2} = \sqrt{\frac{\sum (x_i - \bar{x})^2}{n - 1}}$$

From our previous problem, Population Standard Deviation is $\sigma = \sqrt{4} = 2$, and Sample Standard Deviation is $s = \sqrt{4.5714} \approx 2.138$.

10 Coefficient of Variation (CV): Relative Dispersion

When comparing datasets measured in different physical units or with vastly different mean magnitudes, standard deviation alone can be misleading. We normalize dispersion relative to the mean via the Coefficient of Variation (CV):

$$\text{CV} = \frac{s}{|\bar{x}|} \times 100\%$$

Machine A ($\text{Mean}=100, s=10 \implies \text{CV}=10\%$) and Machine B ($\text{Mean}=200, s=20 \implies \text{CV}=10\%$) possess identical relative variability despite differing raw spreads.

11 Covariance: Measuring Joint Variability

While variance measures the dispersion of a single feature, Covariance determines the directional linear co-movement between two random variables $X$ and $Y$:

$$s_{XY} = \operatorname{Cov}(X, Y) = \frac{\sum_{i=1}^n (x_i - \bar{x})(y_i - \bar{y})}{n - 1}$$
Positive Covariance ($>0$)

Variables increase together. (e.g., Study hours vs. Exam score).

Negative Covariance ($\lt 0$)

As $X$ rises, $Y$ tends to decline. (e.g., Product price vs. Demand).

Zero Covariance ($\approx 0$)

No linear association detected.

The Scale Dependency Flaw: Covariance is unbounded and dependent on measurement units. Converting study hours into seconds inflates covariance by $3600\times$ without altering the underlying relationship!

12 Correlation: Pearson Correlation Coefficient ($r$)

Normalizing covariance by the product of both standard deviations eliminates scale dependency, yielding the Pearson Correlation Coefficient ($r$):

$$r = \frac{s_{XY}}{s_X s_Y} = \frac{\sum (x_i - \bar{x})(y_i - \bar{y})}{\sqrt{\sum (x_i - \bar{x})^2 \sum (y_i - \bar{y})^2}}$$

$r$ is strictly bounded on the closed interval $[-1, +1]$:

$$-1 \le r \le +1$$
Value of $r$ Interpretation Visual Geometry
+1.0 Perfect positive linear relationship All scatter points lie on an upward-sloping line
+0.7 to +0.9 Strong positive linear correlation Points tightly cluster along an upward trend
0.0 No linear correlation Points form an unstructured cloud or symmetric curve
-0.7 to -0.9 Strong negative linear correlation Points tightly cluster along a downward trend
-1.0 Perfect negative linear relationship All scatter points lie on a downward-sloping line

Worked Problem: Study Hours ($X$) vs. Score ($Y$)

5 students: $X = [1, 2, 3, 4, 5]$ and $Y = [50, 55, 65, 60, 70]$.
Means: $\bar{x} = 3, \bar{y} = 60$. Sums: $\sum (x-\bar{x})(y-\bar{y}) = 45$, $\sum (x-\bar{x})^2 = 10$, $\sum (y-\bar{y})^2 = 250$.

$$r = \frac{45}{\sqrt{10 \times 250}} = \frac{45}{\sqrt{2500}} = \frac{45}{50} = 0.90$$

$r = 0.90$ confirms a strong positive linear correlation between study duration and examination score.

13 Correlation vs. Causation: The Golden Rule

"Correlation does NOT imply Causation"

(Observing that two variables co-vary never proves that one causes the other!)

The Classic Confounder: Ice cream sales and drowning rates spike simultaneously in July ($r \approx 0.85$). Does eating ice cream induce drowning? Obviously not. The true driver is a third hidden variable—Summer Outdoor Temperature (Confounder). Heat causes both higher ice cream consumption and more frequent swimming excursions.

In machine learning, models frequently latch onto spurious correlations. Establishing true causality requires controlled experimentation (A/B testing) or causal graphical modeling.

14 Pearson vs. Spearman Rank Correlation

Real-world relationships are not always linear; many are curved yet monotonically increasing or decreasing. For non-linear monotonic curves, we employ Spearman's Rank Correlation ($\rho$):

Attribute Pearson Correlation ($r$) Spearman Rank Correlation ($\rho$)
Type of Relationship Linear Association Monotonic Association
Input Data Raw continuous values ($x_i, y_i$) Ordinal ranks of values ($\text{rank}(x_i)$)
Outlier Sensitivity Highly sensitive Highly robust
Non-linear Monotonic ($y = x^3$) $r \lt 1.0$ (Degrades) $\rho = 1.0$ (Perfect detection)

15 Practical Python Implementation with Pandas & SciPy

A standard Python EDA pipeline computing summary metrics, Tukey outlier bounds, and correlation coefficients:

descriptive_stats_eda.py
import numpy as np
import pandas as pd
from scipy import stats

# Dataset creation
hours = [1, 2, 3, 4, 5, 2, 4, 3]
scores = [50, 55, 65, 60, 70, 52, 68, 62]
df = pd.DataFrame({"hours": hours, "scores": scores})

# 1. Fundamental summary statistics
mean_val = df["scores"].mean()
median_val = df["scores"].median()
std_sample = df["scores"].std(ddof=1)  # Bessel's correction n-1

# 2. Quartiles and IQR
q1 = df["scores"].quantile(0.25)
q3 = df["scores"].quantile(0.75)
iqr = q3 - q1

# 3. Tukey Outlier Filtering
lower_bound = q1 - 1.5 * iqr
upper_bound = q3 + 1.5 * iqr
outliers = df[(df["scores"] < lower_bound) | (df["scores"] > upper_bound)]

# 4. Pearson & Spearman Correlation
pearson_r, _ = stats.pearsonr(df["hours"], df["scores"])
spearman_rho, _ = stats.spearmanr(df["hours"], df["scores"])

print(f"Mean: {mean_val:.2f}, Median: {median_val}, Std: {std_sample:.2f}")
print(f"IQR: {iqr:.2f} [Fences: {lower_bound} to {upper_bound}]")
print(f"Pearson r: {pearson_r:.4f} | Spearman rho: {spearman_rho:.4f}")

16 8 Common Pitfalls & Traps to Avoid

1. Reporting Mean Alone on Skewed Data

Outliers distort arithmetic averages. Always present the Median alongside percentiles ($p90, p99$) for latency or compensation data.

2. Forgetting Bessel's Correction ($n - 1$)

Dividing sample variance by $n$ produces a biased underestimate of true population variability.

3. Confounding Variance Units with Raw Units

Variance expresses squared dimensions ($\$^{2}$). Report standard deviation $s = \sqrt{\text{Var}}$ to preserve interpretable physical units.

4. Equating Correlation with Causation

Statistical co-movement never proves causal mechanisms; lurking confounding variables must be rigorously tested.

5. Assuming $r = 0$ Implies Independence

$r = 0$ implies the absence of a linear relationship only. Deterministic quadratic curves ($y = x^2$) yield $r \approx 0$.

6. Trusting Correlations on Tiny Samples

A sample of $n=4$ can easily yield $r=0.95$ purely by random chance. Hypothesis testing ($p$-value verification) is essential.

7. Calculating CV on Interval Scales

Coefficient of Variation is mathematically invalid on Celsius temperatures; it requires an absolute zero (ratio scale).

8. Relying on Range over IQR in Noisy Data

A single erroneous entry ($9999$) wrecks Range; IQR cleanly isolates the middle 50% core distribution.

Interactive Lab • 3 Dynamic Tools

Descriptive Statistics & Correlation Workbench

Manipulate empirical numbers live to observe Mean-Median drift, Box Plot outlier fences, and scatter plot regression lines.

Inject / Adjust Outlier Value: 20
Drag the slider rightward to observe how Mean rapidly inflates while Median stays robust.
Mean
15.00
Median
15.00
Std Dev ($s$)
3.42
Insight:
Adjust the slider to view mean-median divergence.
Number Line: Mean (Orange) vs. Median (Blue)

21 Key Takeaways

1. Descriptive Statistics

Summarizes datasets across three foundational pillars: Central Tendency, Dispersion, and Association.

2. Population vs Sample

Full universe metrics are Parameters ($\mu, \sigma$); estimates from random samples are Statistics ($\bar{x}, s$).

3. Mean vs Median

Mean excels on symmetric data but skews heavily with outliers; Median faithfully represents typical values in skewed sets.

4. IQR & Outliers

$\text{IQR} = Q_3 - Q_1$ captures middle 50% spread. Tukey's $1.5 \times \text{IQR}$ rule robustly flags extreme observations.

5. Bessel's Correction ($n - 1$)

Sample variance divides by $n - 1$ to correct for clustering around $\bar{x}$, delivering an unbiased estimator for $\sigma^2$.

6. Standard Deviation

$s = \sqrt{\text{Var}}$ restores dispersion measurements back to original physical units for intuitive interpretation.

7. Covariance Limitation

Reveals the directional co-movement of two variables, but is corrupted by measurement scale changes.

8. Pearson Correlation ($r$)

Bounded on $[-1, +1]$; measures the direction and strength of linear relationships. $r = 0$ indicates zero linearity.

9. Correlation $\ne$ Causation

Co-movement does not prove causal influence; lurking confounding factors must always be verified via controlled experiments.

Next Lesson • Lesson 14.30

Sampling, Estimation & Hypothesis Testing

The science of generalizing from samples: Sampling Distributions, Central Limit Theorem, Confidence Intervals, Null Hypotheses ($H_0$), $p$-values, and Type I / Type II errors.

Next Lesson