S30 Logo
S30 AI Labwww.thes30.com
Back
#7

Statistics for ML

EasyπŸ“ Math for MLW2 D4

Before You Start

Required knowledge
Mean, variance, probability, and NumPy random sampling.
Libraries used
NumPy
Dataset and source
Synthetic samples and A/B groups generated in the notebook.
Expected output
Confidence intervals, coverage estimates, permutation-test results, and multiple-testing corrections.

Statistics for ML β€” Theory & Concepts

Read this before attempting the exercises. Statistics bridges data and decisions. These concepts appear constantly in ML interviews and practice.


1. Descriptive Statistics

import numpy as np

data = np.array([2, 4, 4, 4, 5, 5, 7, 9])

np.mean(data)      # 5.0 β€” average
np.median(data)    # 4.5 β€” middle value (robust to outliers)
np.std(data)       # 2.0 β€” standard deviation
np.percentile(data, [25, 50, 75])  # quartiles

Interview Tip: When asked "mean vs median?", say: mean is sensitive to outliers (e.g., income data), median is robust. Use median for skewed distributions.


2. Hypothesis Testing

Framework:

  1. ●Null hypothesis (Hβ‚€): No effect / no difference
  2. ●Alternative hypothesis (H₁): There is an effect
  3. ●Test statistic: Computed from data
  4. ●p-value: Probability of seeing this result (or more extreme) if Hβ‚€ is true
  5. ●Decision: Reject Hβ‚€ if p-value < Ξ± (typically 0.05)
from scipy import stats

# Two-sample t-test: are means different?
t_stat, p_value = stats.ttest_ind(group_a, group_b)
if p_value < 0.05:
    print("Statistically significant difference")

Common tests:

TestUse Case
t-testCompare means of two groups
chi-squaredTest independence of categorical variables
KS testCompare two distributions
ANOVACompare means of 3+ groups

3. Confidence Intervals

A 95% CI means: if we repeated the experiment many times, 95% of the intervals would contain the true parameter.

from scipy import stats

mean = np.mean(data)
se = stats.sem(data)                    # standard error
ci = stats.t.interval(0.95, df=len(data)-1, loc=mean, scale=se)

FAANG Gotcha: A 95% CI does NOT mean "95% probability the true value is in this interval." It's a frequentist statement about the procedure, not the parameter.


4. Bias-Variance in Estimators

  • ●Bias: How far the expected estimate is from the true value
  • ●Variance: How much the estimate varies across different samples
  • ●MSE = BiasΒ² + Variance β€” the fundamental tradeoff
High bias, low variance:     Low bias, high variance:
  o o                           o
  o o  < clustered but           o    < scattered but
  o o    off-center           o        centered on average
       βœ• (true value)        o  βœ•  o

5. Correlation vs Causation

# Pearson correlation: linear relationship
r = np.corrcoef(x, y)[0, 1]

# Spearman correlation: monotonic relationship (rank-based)
rho, p = stats.spearmanr(x, y)

Key insight: Correlation β‰  causation. Ice cream sales correlate with drowning deaths (both caused by summer heat).

To establish causation, you need: randomized controlled experiments (A/B tests) or careful causal inference methods.


6. A/B Testing (Practical Statistics)

# Sample size calculation for A/B test
from statsmodels.stats.power import TTestIndPower
analysis = TTestIndPower()
n = analysis.solve_power(effect_size=0.1, alpha=0.05, power=0.8)

Key concepts:

  • ●Effect size β€” how big a difference you want to detect
  • ●Power β€” probability of detecting a real effect (typically 0.8)
  • ●Multiple testing β€” testing many metrics inflates false positives (use Bonferroni correction)

7. Bootstrap β€” The Swiss Army Knife

When you don't know the distribution, bootstrap it:

def bootstrap_ci(data, stat_fn=np.mean, n_boot=10000, alpha=0.05):
    stats = [stat_fn(np.random.choice(data, size=len(data), replace=True))
             for _ in range(n_boot)]
    return np.percentile(stats, [100*alpha/2, 100*(1-alpha/2)])

ML Use: Bootstrap confidence intervals for model metrics (AUC, F1, etc.) when you can't derive them analytically.


Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!

Ready to practice?

Python 3 β€” Notebook
0/6 solvedSubstack Notes
1
Dataset & Setup

Statistics for ML β€” FAANG-Level Lab

Goal: Confidence intervals, hypothesis testing, and interpretation for ML engineering.

Outcome: You can quantify uncertainty and avoid p-value traps.

Loading editor...
1

Estimators (Mean/Variance)

2
Unbiased sample variance
2

Section 1 β€” Estimators (Mean/Variance)

Task 1.1: Unbiased sample variance

Implement sample mean and unbiased sample variance (ddof=1) without calling np.var(..., ddof=1).

  • ●mean = sum(x)/n
  • ●unbiased var = sum((x-mean)^2)/(n-1)

Explain: Why divide by (n-1) instead of n?

Explain: Why divide by (n-1) instead of n?
Loading editor...
2

Confidence Interval for Mean (Normal approx)

3
95% CI for mean
1

Section 2 β€” Confidence Interval for Mean (Normal approx)

Task 2.1: 95% CI for mean

Compute a 95% CI for mean using normal approximation: CI = mean Β± z * s/sqrt(n), where zβ‰ˆ1.96.

  • ●Use unbiased sample std

FAANG gotcha: CI is about the mean, not individual outcomes.

Loading editor...
4
Coverage simulation
1

Task 2.2: Coverage simulation

Simulate repeated sampling from Normal(mu=0, sigma=1). Estimate how often 95% CI contains true mean.

  • ●Run many trials
  • ●Count coverage

Explain: Why isn't coverage exactly 0.95 in finite simulation?

Explain: Why isn't coverage exactly 0.95 in finite simulation?
Loading editor...
3

Hypothesis Testing (Two-sample test intuition)

5
Permutation test for A/B (no scipy)
1

Section 3 β€” Hypothesis Testing (Two-sample test intuition)

Task 3.1: Permutation test for A/B (no scipy)

Given samples A and B, test whether mean(B) - mean(A) is significant via permutation.

  • ●Combine samples
  • ●Shuffle and split
  • ●Compute diff distribution
  • ●p-value = fraction of diffs >= observed (two-sided if needed)

FAANG gotcha: p-value is not P(H0 true).

Loading editor...
4

Multiple Comparisons (Gotcha)

6
Bonferroni correction
1

Section 4 β€” Multiple Comparisons (Gotcha)

Task 4.1: Bonferroni correction

If you run m tests at alpha=0.05, Bonferroni uses alpha/m per test.

Compute adjusted alpha for m=20 and explain why this matters in feature slicing / metric dashboards.

Loading editor...

Need help? Share feedback