2  Kitty Dice & Treat Probabilities

Probability, Bayes, Distributions, MLE, MAP

🐾 Evergreen Chapter: Core mathematics and theory do not expire. Last verified: 2026-02-24

Prerequisites: Chapter 1 Technical Keywords: Probability Theory, Random Variables, Distributions, Conditional Probability, Bayes’ Theorem, Expectation, Variance, Covariance, Entropy, KL Divergence


In Chapter 1, Pixel lived in a deterministic world of geometry. If he jumped exactly vector \vec{v}, he landed exactly on the sunbeam.

But let’s be honest: the real world is messy. Sometimes the hardwood floor is slippery, and a perfect jump ends in a slide. Sometimes the human opens a can, but it turns out to be beans, not tuna.

To an AI, the world is filled with uncertainty, noise, and hidden variables. Machine learning isn’t just about drawing lines in space; it’s about making the best possible guess when you don’t have all the facts. To do that, Pixel needs Probability Theory.

If Linear Algebra is the language of space, Probability is the language of uncertainty. Let’s look at how Pixel calculates the odds.


2.1 Random Variables: The Treat Drop

Suppose the human walks into the kitchen. Pixel knows a treat might drop.

In math, a Random Variable is not a fixed number. It is a function that maps an uncertain event to a number.

For notation consistency in this book, we reserve X for the dataset matrix and use T (treat count) for this first probability example.

If we define T as the number of treats dropped:

  • T = 0 (Human was just getting water)
  • T = 1 (A single treat)
  • T = 3 (Jackpot)

A random variable can be discrete (countable, like the number of treats) or continuous (measurable, like the exact weight of the treat in grams, which could be 2.1g, 2.15g, 2.158g…).

Analogy

The event is the human dropping something. The Random Variable T translates that chaotic physical event into a clean mathematical number Pixel can track.


2.2 Probability Distributions: Where Will Kitty Nap?

A Probability Distribution tells us exactly how likely each outcome of a random variable is.

If T is discrete, we use a Probability Mass Function (PMF), denoted as P(T=t). All the probabilities must add up to 1 (or 100%). \sum P(T=t) = 1

If Z is continuous, we use a Probability Density Function (PDF), denoted as p(z). Because a continuous variable has infinite possible exact values, the probability of any exact point is zero! Instead, we measure the area under the curve to find the probability of a range: \int p(z) dz = 1

The most famous continuous distribution is the Normal (Gaussian) Distribution, which looks like a bell curve.

Analogy

Imagine a sunbeam hits the middle of the rug. Where will Pixel nap? He will probably sleep right in the exact center. He might sleep a few inches to the left or right. He is very unlikely to sleep in the cold dark corner. If you graph his nap locations over a year, it creates a perfect bell curve—a Gaussian distribution—centered on the sunbeam.

Gaussian distribution showing where Pixel naps in a sunbeam

The Gaussian Nap Zone

Rosetta Stone

Kitten World Math Python (scipy.stats)
“Odds of getting exactly 2 treats” P(T=2) stats.binom.pmf(2, n, p)
“Nap location curve” p(x) = \frac{1}{\sigma\sqrt{2\pi}} e^{-\frac{1}{2}\left(\frac{x-\mu}{\sigma}\right)^2} stats.norm.pdf(x, loc=mu, scale=sigma)
“Odds of napping within 3 inches of center” \int_{\mu-3}^{\mu+3} p(x)\,dx stats.norm.cdf(mu + 3, loc=mu, scale=sigma) - stats.norm.cdf(mu - 3, loc=mu, scale=sigma)

2.3 Expectation, Variance, and Covariance

If Pixel lives with this human for a year, what can he expect on an average day?

1. Expectation (Mean): The long-term average. It is the sum of all possible outcomes, weighted by how likely they are. \mathbb{E}[T] = \sum t \cdot P(T=t) If 80% of the time he gets 0 treats, and 20% of the time he gets 5 treats, his expectation is (0 \times 0.8) + (5 \times 0.2) = 1 treat.

2. Variance: How wild and unpredictable is the human? Variance measures how far the outcomes typically stray from the expectation. High variance means chaos; low variance means consistency. \text{Var}(T) = \mathbb{E}[(T - \mathbb{E}[T])^2] (Note: Standard Deviation, \sigma, is just the square root of Variance).

3. Covariance: Do two random variables move together? If U is “loudness of Pixel’s purr” and T is “number of treats given”, do they rise together? If they do, they have a positive covariance. \text{Cov}(U,T) = \mathbb{E}[(U - \mathbb{E}[U])(T - \mathbb{E}[T])]

Analogy

  • Expectation: “I usually get 1 treat a day.”
  • Variance: “But this human is crazy—some days I get 0, some days I get 10!”
  • Covariance: “When I purr louder, more treats magically appear. They are correlated!”

2.4 Conditional Probability: “Given That I Purred…”

In ML, we rarely care about events in isolation. We care about events given some context. This is Conditional Probability, written as P(A \mid B) — “the probability of A, given that B has already happened.”

P(A \mid B) = \frac{P(A \text{ and } B)}{P(B)}

If A and B have absolutely nothing to do with each other (like the human sneezing, and a car driving by outside), they are Independent. If they are independent, knowing B tells you nothing about A, so P(A \mid B) = P(A).

Catastrophic Failure: Assuming Independence

Naive Bayes is an algorithm that assumes all inputs are conditionally independent given the class to make math easier. But in real life, features are still correlated! If a picture is a “cat”, and it has “whiskers” (A), it is highly likely to also have “pointy ears” (B). Treating them as completely independent given the class can severely confuse your model.


2.5 Bayes’ Theorem: Updating Kitty’s Beliefs

Pixel is sleeping. Suddenly, he hears the sound of a metal can opening in the kitchen.

Before the sound, the probability of getting wet food was low. This baseline belief is called the Prior (P(A)). But now he has new evidence (the sound). He needs to update his belief to figure out the Posterior — the probability of food, given the sound (P(A \mid B)).

Bayes’ Theorem is the mathematical formula for updating beliefs based on new evidence:

P(\text{Food} \mid \text{Sound}) = \frac{P(\text{Sound} \mid \text{Food}) \cdot P(\text{Food})}{P(\text{Sound})}

Let’s break it down:

  • P(\text{Food}) (Prior): General chance of getting wet food (say, 10%).
  • P(\text{Sound} \mid \text{Food}) (Likelihood): If they are opening cat food, how likely is it to make that can sound? (Very high, 99%).
  • P(\text{Sound}) (Evidence/Marginal): How often do metal cans open in general? (Maybe it’s soup, maybe it’s beans… let’s say 30% of the time).

P(\text{Food} \mid \text{Sound}) = \frac{0.99 \times 0.10}{0.30} = 0.33

Even though cat food always makes that sound, because humans eat a lot of canned soup, the probability that this specific sound means cat food is only 33%. Pixel shouldn’t sprint to the kitchen just yet!

Analogy

Bayes’ theorem is exactly how Pixel learns. Start with a guess (Prior). Observe the world (Likelihood). Update your guess (Posterior). This is the foundation of Bayesian inference in AI.


2.6 Information Theory: How Surprised is Pixel?

As we prepare for Machine Learning, we need to know how to measure “surprise.”

If human drops a treat at 5 PM every single day, Pixel expects it. Probability = 1.0. Surprise = 0. If human drops a treat at 3 AM out of nowhere, Probability is low. Surprise is massive!

In Information Theory, we measure surprise using Entropy (H). Entropy is the average level of uncertainty or surprise in a probability distribution.

H(Z) = - \sum P(z) \log P(z)

If we have two different distributions—say, Pixel’s internal guess of when treats happen (Q), and the actual reality of when treats happen (P)—we want to measure how different they are. We use Kullback-Leibler (KL) Divergence:

D_{KL}(P \parallel Q) = \sum P(x) \log \left( \frac{P(x)}{Q(x)} \right)

In deep learning, we will try to make the neural network’s predictions (Q) match the true labels (P). To do this, we minimize the difference between them using Cross-Entropy, which is directly derived from these formulas.

Rosetta Stone

Kitten World Math Python (scipy / PyTorch)
“How uncertain is the environment?” Entropy H(P) scipy.stats.entropy(pk)
“Difference between expected and reality” D_{KL}(P \parallel Q) scipy.stats.entropy(pk, qk)
“Punishing the model for wrong guesses” Cross-Entropy Loss torch.nn.CrossEntropyLoss()

Micro-notebook (optional): micro-notebooks/phase01_ch02_bayes_update.ipynb
Time: ~15 minutes. Goal: run sequential Bayes updates and track posterior belief changes over evidence steps.


2.7 Removing the Training Wheels

The Real Engineering

We used a Gaussian nap zone to explain Probability Distributions. In reality, you are dealing with log-probabilities to prevent floating-point underflow. Bayes’ Theorem isn’t just about cat food sounds; it’s the mathematical foundation for how language models update their token probabilities given previous context. When you use CrossEntropyLoss in PyTorch, you are directly minimizing the KL Divergence between the one-hot encoded true label distribution and your model’s softmax logits.

2.8 Paws and Reflect: Chapter Quiz

Work through these conceptually before checking the answers.

  1. Pixel gets 2 treats 50% of the time, and 4 treats 50% of the time. What is the expected value of his treats? Does he ever actually get exactly that number?

  2. The human buys an automatic laser pointer that spins completely randomly. Is the variance of the laser’s position high or low?

  3. Pixel knows the probability of getting a belly rub (P(A)) and the probability of being told “No” (P(B)). Why can’t he just multiply P(A) \times P(B) to find the odds of both happening at the same time?

  4. You build a neural network to predict if an image is a dog or a cat. Its predictions are currently a high-entropy distribution. What does this mean about the model’s confidence?

Reveal answers
  1. Expectation is 3. No, he never actually gets exactly 3 treats! Expectation is a mathematical average, not a guaranteed outcome.
  2. High (assuming the laser sweeps widely across the whole room rather than staying in a tiny spot). The position is spread out instead of clustered around one point.
  3. Because they are likely not independent! Biting during a belly rub changes the odds of being told “No”. You need conditional probability.
  4. High entropy means high uncertainty. The model is essentially guessing 50/50 and is very confused.

2.9 Chapter 2 Summary

You’ve learned the probabilistic language of machine learning:

  • Random Variables map chaotic real-world events (treats, noises) to mathematical numbers.
  • Probability Distributions (PMF/PDF) map out the landscape of likelihoods, like the Gaussian nap zone.
  • Expectation and Variance summarize what usually happens, and how chaotic it is.
  • Conditional Probability lets us measure events given context (like predicting treats given a purr).
  • Bayes’ Theorem is the ultimate formula for updating beliefs based on new evidence.
  • Entropy and KL Divergence measure surprise and the difference between distributions, setting the stage for AI loss functions.

In Chapter 1, we learned how to move in space. In Chapter 2, we learned how to guess the future.

In Chapter 3, we finally combine them. We will teach Pixel how to take tiny, math-guided steps through space to find the optimal spot for maximum treats. It’s time for Optimization. 🐈🐾


AI Safety Thread: Chapter 2

Distribution Shift: When you train an AI, it learns the probability distribution of its training data (P_{train}). But what happens if Pixel is adopted by a new family? The rules change. The new distribution (P_{real-world}) does not match the old one. If an AI trained on bright daylight images is deployed on a self-driving car at night, the probabilities break down. The model will make decisions with high confidence that are completely, dangerously wrong. A safe AI must know when the data it is looking at falls outside the distribution it understands (Out-of-Distribution detection).


Next: Chapter 3: Tiny Paw Steps →