Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Bin Analogy ML

Imports

%load_ext autoreload
%autoreload 2

import logging

import matplotlib.pyplot as plt
import seaborn as sns

import L05_01_02_bin_analogy_ml_utils as utils

# Set plotting style.
sns.set_style("whitegrid")
plt.rcParams["figure.figsize"] = (12, 6)
WARNING (pytensor.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
import msml610.tutorials.msml610_utils as ut

ut.config_notebook()

# Initialize logger.
logging.basicConfig(level=logging.INFO)
_LOG = logging.getLogger(__name__)
vim support installed: restart the notebook, if needed
Python 3.12.3
Linux 589569fe8102 6.12.67-linuxkit #1 SMP Sun Jan 25 02:26:28 UTC 2026 aarch64 aarch64 aarch64 GNU/Linux

Cell 1: Visual Bin: Population of Marbles

Goal:

  • Visualize the concept of an unknown population of marbles in a bin
  • Introduce the parameter μ\mu as the true (unknown) proportion of red marbles
  • Build intuition for how we have a fixed population with a fixed proportion

Plots:

  • Display a single plot:
    • Bin with Marbles: A 2D grid showing red and green marbles arranged in the bin
    • The visual distribution reflects the true proportion μ\mu

Parameters:

  • mu (μ\mu): True proportion of red marbles in the population (0 to 1)
  • seed: Random seed controlling the spatial arrangement of marbles (for reproducibility)

Key observations:

  • The bin represents a population with a fixed but “unknown” parameter μ\mu
  • In real-world scenarios, we don’t know the true μ\mu - we can only sample from the population
  • The spatial arrangement of marbles is random, but the overall proportion is always μ\mu
  • This sets up the fundamental problem: How do we estimate μ\mu from samples?
utils.cell1_draw_bin_with_marbles_interactive()
Loading...

Cell 2: Single Experiment: Is ν\nu Close to μ\mu?

Goal:

  • Demonstrate a single sampling experiment to estimate the population parameter
  • Show how we compute the sample proportion ν\nu from NN random draws
  • Examine the relationship between ν\nu (sample statistic) and μ\mu (population parameter)
  • Understand that a single experiment gives us one estimate, which may or may not be close to μ\mu

Plots:

  • Display two panels:
    • Population vs Sample: Bar chart comparing μ\mu (population) and ν\nu (sample)
      • Color-coded bars indicate how close ν\nu is to μ\mu (green = close, yellow = medium, red = far)
    • Interpretation: Text box showing parameters, results, and assessment of the single experiment

Parameters:

  • mu (μ\mu): True proportion of red marbles in the population (0 to 1)
  • N (NN): Number of marbles to sample (sample size)
  • seed: Random seed for reproducibility of sampling

Key observations:

  • A single experiment produces one sample proportion ν=1Ni=1Nxi\nu = \frac{1}{N}\sum_{i=1}^{N} x_i
  • The error νμ|\nu - \mu| varies depending on the random sample drawn
  • Sometimes ν\nu is close to μ\mu, sometimes it’s not - we see natural sampling variability
  • Try different seeds to observe how ν\nu changes across different random samples
  • This demonstrates why a single experiment is insufficient - we need to understand the distribution of ν\nu
utils.cell2_plot_single_experiment_interactive()
Loading...

Cell 2.1: Limitations of Single Experiments

  • Single experiments don’t tell the full story:
    • We saw that ν\nu can vary significantly across different random samples
    • One experiment gives us a point estimate, but no information about reliability
    • What we really need to know: P(νμ>ϵ)P(|\nu - \mu| > \epsilon) - the probability that our estimate is “far” from truth
  • Critical questions to consider:
    • What if we got unlucky in our sample? How would we know?
    • How confident can we be that νμ\nu \approx \mu based on a single observation?
    • Does sample size NN matter? How much does it help?
    • Can we quantify the uncertainty in our estimate?
  • The solution: “Let’s repeat this many times...”
    • By running many experiments, we can:
      • Observe the distribution of ν\nu values
      • Estimate P(νμ>ϵ)P(|\nu - \mu| > \epsilon) empirically
      • Understand how sample size NN affects the accuracy of ν\nu

Cell 3: Monte Carlo Simulation: Distribution of ν\nu

Goal:

  • Run many repeated sampling experiments to understand the distribution of ν\nu
  • Empirically estimate P(νμ>ϵ)P(|\nu - \mu| > \epsilon) - the probability that ν\nu is far from μ\mu
  • Observe how the distribution of ν\nu concentrates around μ\mu as we increase sample size NN
  • Build intuition for the Law of Large Numbers and Central Limit Theorem

Plots:

  • Display two panels:
    • Distribution of nu: Histogram with KDE overlay showing the distribution of sample proportions across experiments
      • Green dashed line: True parameter μ\mu
      • Red shaded regions: Areas where νμ>ϵ|\nu - \mu| > \epsilon
      • Statistics box: Mean, standard deviation, and empirical probability
    • Key Insights: Text box summarizing parameters, results, and observations

Parameters:

  • mu (μ\mu): True proportion of red marbles in the population (0 to 1)
  • N (NN): Number of samples per experiment (sample size)
  • n_experiments: Number of repeated experiments to run
  • eps (ϵ\epsilon): Tolerance threshold for defining “far from μ\mu
  • seed: Random seed for reproducibility

Key observations:

  • The distribution of ν\nu values clusters around the true μ\mu - demonstrating unbiasedness
  • As NN increases, the distribution becomes tighter (smaller variance) - Law of Large Numbers
  • The empirical probability P(νμ>ϵ)P(|\nu - \mu| > \epsilon) decreases with larger NN
  • The distribution approaches a normal shape - Central Limit Theorem
  • We can now quantify: “What fraction of experiments produce estimates within ϵ\epsilon of μ\mu?”
  • This connects to confidence intervals and the precision of statistical estimates
utils.cell3_monte_carlo_simulation_interactive()
Loading...

Cell 3.1: Observations from Monte Carlo Simulation

  • Distribution properties:
    • The distribution of ν\nu values is centered around the true μ\mu - this shows that ν\nu is an unbiased estimator
    • The shape of the distribution approximates a normal (Gaussian) distribution - illustrating the Central Limit Theorem
    • Most ν\nu values fall close to μ\mu, with fewer extreme outliers
  • Effect of sample size NN:
    • As NN increases, the distribution becomes tighter (smaller variance: Var(ν)1N\text{Var}(\nu) \propto \frac{1}{N})
    • Larger NN means more precise estimates - the “spread” of possible ν\nu values shrinks
    • This is the Law of Large Numbers in action: νPμ\nu \xrightarrow{P} \mu as NN \to \infty
  • Probabilistic guarantees:
    • The empirical probability P(νμ>ϵ)P(|\nu - \mu| > \epsilon) decreases with larger NN
    • We can quantify confidence: “With sample size NN, approximately X% of experiments yield ν\nu within ϵ\epsilon of μ\mu
    • This connects to Hoeffding’s inequality and other concentration bounds
  • Connection to machine learning:
    • Replace “marbles in bin” with “data points” and “μ\mu” with “expected error”
    • Sample proportion ν\nu represents training error on NN samples
    • True μ\mu represents generalization error on the full population
    • Key insight: With enough samples (NN large), training error ν\nu is close to generalization error μ\mu