Mathematical Foundations

IV.4 · Probability

What changes when we know B happened?

Restrict the visible probability mass to B, then normalize what remains. The denominator changes from the whole experiment to the mass of the known event.

Restrict, then renormalize

1Original P = 1/6Inside B: 0
2Original P = 1/6Inside B: 0
3Original P = 1/6Inside B: 0
4Original P = 1/6Inside B: 1/3
5Original P = 1/6Inside B: 1/3
6Original P = 1/6Inside B: 1/3
1= 1/6
2= 1/6
3= 1/6
4= 1/6
5= 1/6
6= 1/6

Sample space: 1, 2, 3, 4, 5, 6. Equal weights explicitly assume equiprobable outcomes. A = {2, 4, 6}; B = {4, 5, 6}. The denominator changes from 1 to P(B) = 0.5. Inside B, P(A|B) = 2/3.

Total probability
1
Event A
0.5
Event B
0.5
Intersection
1/30.333333…
Conditional probability
2/30.666667…

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

The denominator changes from 1 to P(B) = 0.5. Inside B, P(A|B) = 2/3.
P(A)=∑ω∈Apω=0.5P(A)=\sum_{\omega\in A}p_\omega=0.5
P(A∣B)=130.5=23P(A\mid B)=\frac{\frac{1}{3}}{0.5}=\frac{2}{3}

Start with total mass one

Equal weights explicitly assume equiprobable outcomes.

∑ωpω=1\sum_\omega p_\omega=1
1= 1/6
2= 1/6
3= 1/6
4= 1/6
5= 1/6
6= 1/6

Select the conditioning event B and the target event A. Remove a face from B to change the retained denominator, then inspect the normalized mass of A within B; empty B to examine undefined conditioning.

With a fair die, take A={2,4,6}A=\{2,4,6\} and B={4,5,6}B=\{4,5,6\}. Given that B happened, the face must be 4, 5, or 6. Predict the chance of an even face before reading the equation.

Intuition: information changes the reference total

Before observing B, all six die faces are relevant. After learning B, only three can explain the information. Of those, two are even. The original chance of evenness is 1/21/2, the original shared mass is 1/31/3, and the conditional chance is 2/32/3. These are three different questions about the same experiment.

Restriction keeps only outcomes compatible with the evidence. Normalization rescales their total to one. It preserves relative weights among the survivors rather than inventing a new equal-weight model.

Definition

For events A,BA,B with P(B)>0P(B)>0, conditional probability is

P(A∣B)=P(A∩B)P(B).P(A\mid B)=\frac{P(A\cap B)}{P(B)}.

For an individual outcome in a finite space, the conditional mass is pω/P(B)p_\omega/P(B) when ω∈B\omega\in B, and zero otherwise. The event after the bar is the known condition and supplies the denominator. If P(B)=0P(B)=0, this event-ratio definition is undefined.

Mechanics: retain, total, normalize

The stage separates original event mass from conditional mass. Changing B changes which outcomes survive and the retained total. Changing A selects which of those survivors answer the target question. The original weights continue to define the experiment; the conditional view is derived from them.

Follow the trace: find A∩BA\cap B, add its original masses, find the original mass of B, and divide. The equation and inspector make the denominator visible. Replay after a membership change to explain why the same numerator can produce a different conditional answer.

Derivation: why divide by P(B)?

Suppose every surviving weight is multiplied by a common factor cc. We require a normalized conditional space, so

∑ω∈Bcpω=cP(B)=1.\sum_{\omega\in B}cp_\omega=cP(B)=1.

Thus c=1/P(B)c=1/P(B), which exists only for positive retained mass. Summing these normalized weights over the target survivors gives the conditional formula. Rearranging also gives

P(A∩B)=P(B)P(A∣B),P(B)>0.P(A\cap B)=P(B)P(A\mid B),\qquad P(B)>0.

This multiplication rule does not assume independence. It pairs the probability of the evidence with the chance of the target after that evidence.

Worked examples

For the canonical die, P(A∩B)=2/6=1/3P(A\cap B)=2/6=1/3 and P(B)=3/6=1/2P(B)=3/6=1/2. Therefore

P(A∣B)=1/31/2=23.P(A\mid B)=\frac{1/3}{1/2}=\frac23.

Within B, faces 4, 5, and 6 each have conditional mass 1/31/3. Two of them belong to A. Knowing B increases the chance of A from 1/21/2 to 2/32/3, so these events are dependent.

Worked example: Restrict, then renormalize

1Original P = 1/6Inside B: 0
2Original P = 1/6Inside B: 0
3Original P = 1/6Inside B: 0
4Original P = 1/6Inside B: 1/3
5Original P = 1/6Inside B: 1/3
6Original P = 1/6Inside B: 1/3
1= 1/6
2= 1/6
3= 1/6
4= 1/6
5= 1/6
6= 1/6

Sample space: 1, 2, 3, 4, 5, 6. Equal weights explicitly assume equiprobable outcomes. A = {2, 4, 6}; B = {4, 5, 6}. The denominator changes from 1 to P(B) = 0.5. Inside B, P(A|B) = 2/3.

Total probability
1
Event A
0.5
Event B
0.5
Intersection
1/30.333333…
Conditional probability
2/30.666667…

= exact model quantity · ≈ numerical companion or observed estimate

from 0 to 100, whole numbers only

The denominator changes from 1 to P(B) = 0.5. Inside B, P(A|B) = 2/3.
P(A)=∑ω∈Apω=0.5P(A)=\sum_{\omega\in A}p_\omega=0.5
P(A∣B)=130.5=23P(A\mid B)=\frac{\frac{1}{3}}{0.5}=\frac{2}{3}

Start with total mass one

Equal weights explicitly assume equiprobable outcomes.

∑ωpω=1\sum_\omega p_\omega=1
1= 1/6
2= 1/6
3= 1/6
4= 1/6
5= 1/6
6= 1/6

Toggle face 5 out of the worked conditioning event B. Predict P(A | B) = 1 because all retained faces are even, then restore B = {4, 5, 6} and replay the 2/3 update.

For masses px=1/2p_x=1/2, py=1/3p_y=1/3, pz=1/6p_z=1/6, condition on B={y,z}B=\{y,z\}. Its mass is 1/21/2, so the new masses are 2/32/3 and 1/31/3. Restricting to two outcomes does not make them equally likely.

Direction matters too. On a fair die, let C={2}C=\{2\} and D={2,4,6}D=\{2,4,6\}. Then P(C∣D)=1/3P(C\mid D)=1/3, but P(D∣C)=1P(D\mid C)=1. The shared numerator is the same; the two denominators differ.

Executable reference code

The Python program validates normalized weights and events, constructs the full conditional distribution with exact fractions, and reports None for zero evidence. It checks normalization and the die and unequal-weight examples. NumPy masks the original array before division and checks the denominator first; its decimals are approximations of exact hand-worked answers.

code/python/probability_conditional.py
"""Condition by restricting original masses, then normalizing their total.

None means undefined conditioning, not probability zero. Fraction keeps a tiny
positive evidence mass distinct from impossible evidence without an epsilon.
"""
from fractions import Fraction as F


def conditional_distribution(weights, evidence):
    if not weights or any(not isinstance(p, F) or p < 0 for p in weights.values()):
        raise ValueError("Use nonnegative Fraction masses in a nonempty model")
    if sum(weights.values(), F(0)) != 1:
        raise ValueError("Masses must sum exactly to one")
    evidence = set(evidence)
    if not evidence <= weights.keys():
        raise ValueError("Evidence must be inside the sample space")
    retained = sum((weights[x] for x in evidence), F(0))
    if retained == 0:
        return None
    return {x: p / retained if x in evidence else F(0) for x, p in weights.items()}


def conditional_probability(weights, target, evidence):
    target = set(target)
    if not target <= weights.keys():
        raise ValueError("Target must be inside the sample space")
    conditioned = conditional_distribution(weights, evidence)
    if conditioned is None:
        return None
    return sum((conditioned[x] for x in target), F(0))


def main():
    die = {face: F(1, 6) for face in range(1, 7)}
    a, b = {2, 4, 6}, {4, 5, 6}
    original = dict(die)
    given_b = conditional_distribution(die, b)
    assert given_b == {1: F(0), 2: F(0), 3: F(0), 4: F(1, 3), 5: F(1, 3), 6: F(1, 3)}
    assert sum(given_b.values(), F(0)) == 1
    assert conditional_probability(die, a, b) == F(2, 3)
    assert conditional_probability(die, a, {4, 6}) == 1
    assert conditional_probability(die, a, {5}) == 0
    assert conditional_probability(die, a, set(die)) == F(1, 2)
    assert conditional_probability(die, a, set()) is None
    assert die == original  # Conditioning must not overwrite the base experiment.
    weighted = {"x": F(1, 2), "y": F(1, 3), "z": F(1, 6)}
    assert conditional_distribution(weighted, {"y", "z"}) == {"x": F(0), "y": F(2, 3), "z": F(1, 3)}
    assert conditional_probability(die, {2}, a) == F(1, 3)
    assert conditional_probability(die, a, {2}) == 1
    zero_weight = {"x": F(1), "z": F(0)}
    assert conditional_distribution(zero_weight, {"z"}) is None
    tiny = F(1, 10 ** 100)
    assert conditional_probability({"rare": tiny, "other": 1 - tiny}, {"rare"}, {"rare"}) == 1
    for weights, target, evidence in ((die, {7}, b), (die, a, {7}),
                                      ({1: F(-1), 2: F(2)}, {1}, {2}),
                                      ({1: F(1, 2)}, {1}, {1}), ({}, set(), set())):
        try:
            conditional_probability(weights, target, evidence)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid model or event was accepted")
    print("Die given B = {4, 5, 6}: exact normalized masses", given_b)
    print("Exact P(A | B) =", conditional_probability(die, a, b))
    print("Unequal survivors y, z:", conditional_distribution(weighted, {"y", "z"}))
    print("P({2} | even) = 1/3; P(even | {2}) = 1")
    print("Empty or zero-mass evidence: undefined (None)")


if __name__ == "__main__":
    main()
code/python/probability_conditional_numpy.py
"""Mask and normalize; zero represented evidence returns None before division.

The exact Fraction reference determines mathematical impossibility. These small
examples use moderate representable weights; underflow in other inputs needs
scaling or exact arithmetic, not an arbitrary denominator epsilon.
"""
from fractions import Fraction as F
import numpy as np

ATOL = 1e-12


def condition(weights, evidence):
    p = np.asarray(weights, dtype=float)
    b = np.asarray(evidence)
    if p.ndim != 1 or p.size == 0 or np.any(p < 0) or not np.all(np.isfinite(p)):
        raise ValueError("Use a nonempty finite nonnegative mass vector")
    if not np.isclose(p.sum(), 1.0, rtol=0, atol=ATOL):
        raise ValueError("Masses must sum to one within floating-point tolerance")
    if b.dtype != np.bool_ or b.shape != p.shape:
        raise ValueError("Evidence needs a boolean mask with one entry per outcome")
    retained = np.where(b, p, 0.0)
    total = retained.sum()
    if total == 0.0:
        return None
    return retained / total


def main():
    faces = np.arange(1, 7)
    p = np.full(6, 1 / 6)
    original = p.copy()
    a, b = np.isin(faces, [2, 4, 6]), np.isin(faces, [4, 5, 6])
    posterior = condition(p, b)
    exact = [F(0), F(0), F(0), F(1, 3), F(1, 3), F(1, 3)]
    np.testing.assert_allclose(posterior, [float(x) for x in exact], rtol=0, atol=ATOL)
    np.testing.assert_allclose(posterior.sum(), 1.0, rtol=0, atol=ATOL)
    np.testing.assert_allclose(posterior[a].sum(), float(F(2, 3)), rtol=0, atol=ATOL)
    np.testing.assert_array_equal(p, original)
    weighted = condition([0.5, 1 / 3, 1 / 6], [False, True, True])
    np.testing.assert_allclose(weighted, [0.0, float(F(2, 3)), float(F(1, 3))], rtol=0, atol=ATOL)
    np.testing.assert_allclose(condition(p, a)[faces == 2].sum(), float(F(1, 3)), rtol=0, atol=ATOL)
    np.testing.assert_allclose(condition(p, faces == 2)[a].sum(), 1.0, rtol=0, atol=ATOL)
    assert condition(p, np.zeros(6, dtype=bool)) is None
    assert condition([1.0, 0.0], [False, True]) is None
    # Do not use ATOL to classify small positive evidence as impossible.
    np.testing.assert_allclose(condition([1e-100, 1.0], [True, False]), [1.0, 0.0], rtol=0, atol=ATOL)
    for bad_p, mask in (([], []), ([0.5, 0.4], [True, False]),
                        ([-0.1, 1.1], [True, False]), ([np.nan], [True]),
                        ([1.0], [1]), ([1.0], [True, False])):
        try:
            condition(bad_p, mask)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid masses or evidence mask were accepted")
    print("Die conditional masses ≈", posterior, "; exact reference", exact)
    print("P(A | B) ≈", posterior[a].sum(), "(exact 2/3)")
    print("Weighted conditional masses ≈", weighted, "(exact 0, 2/3, 1/3)")
    print("Zero-mass evidence: undefined (None); original weights remain unchanged")


if __name__ == "__main__":
    main()

Explore

Keep A fixed and shrink B to {4,6}\{4,6\}: the conditional probability becomes one. Change B to {5}\{5\}: it becomes zero. Set B to the whole space: conditioning changes nothing. Finally empty B: no conditional distribution exists.

Compare each case with the numerator and denominator separately. A zero numerator with positive denominator is a valid zero answer. A zero denominator prevents normalization entirely. You can perform these comparisons through membership controls and replay the derivation without waiting for random observations.

Common mistakes and counterexamples

Keeping the original denominator computes the joint event, not the conditional probability. Swapping the events after and before the bar changes the question. Neither conditioning nor changing a diagram establishes causation: learning an event occurred is not the same operation as intervening to force it.

Another mistake is overwriting the original mass vector with a conditional one and then treating it as the original model in later calculations. Retain the base experiment so marginal, joint, and conditional quantities stay comparable.

Numerical considerations

Exact fractions preserve the denominator-zero distinction. Small positive evidence is still valid evidence, not impossible evidence merely because its displayed decimal rounds to zero. However, division by a small evidence mass can amplify absolute input error, especially if the weights are measurements rather than exact specified values.

The NumPy reference checks small known answers within absolute tolerance 10−1210^{-12} and zero relative tolerance. This is a reference-comparison tolerance, not a rule for replacing tiny positive evidence with zero. Larger inference systems may need scaled or logarithmic weights to avoid underflow; such numerical choices must keep impossible evidence distinct from numerical loss of representable mass.

Engineering and ML connections

Conditional summaries compare data inside an observed subgroup. Their denominator is subgroup size or subgroup weight, not full dataset size. Conditional models likewise describe predictions given inputs or context. A selection filter can change rates even when the original population is unchanged, so always name the conditioned population before interpreting a metric.

Exercises

calculation

Change the denominator

A fair die has A = {2, 4, 6}, B = {4, 5, 6}. Find P(A | B).

calculation

Renormalize unequal weights

Outcomes x, y, z have masses 1/2, 1/3, 1/6. Given B = {y, z}, give the conditional masses of y and z.

calculation

Condition on the smaller event

For a fair die let A = {2} and B = {2, 4, 6}. Give P(A | B) and P(B | A).

explanation

Refuse division by zero

A finite model gives P(B) = 0. What should a program return for P(A | B) using the event-ratio definition?

Choose one answer

prediction

Read a conditional trace

After selecting B, a trace says “retain intersection mass 1/3; retained total 1/2; normalize”. Which statement is correct?

Choose one answer

Summary and checkpoints

Conditioning restricts to B and divides by its original mass. Check that you can explain the changed denominator, renormalize unequal survivors, distinguish joint from conditional probability, reverse a conditional question correctly, and report zero-probability evidence as undefined.

The map of the book

97 of 97 chapters written · eight Parts

demo Foundation demo Try the live vector example Open as a page

Part I

Mathematical Language

The notation and mental objects everything else uses.

9 of 9 chapters written

  1. I.1 Scalars, quantities, units, powers and roots available
  2. I.2 Coordinates and points available
  3. I.3 Vectors: components, magnitude, and direction reference chapter available
  4. I.4 Algebraic expressions, equations and inequalities available
  5. I.5 Functions as input → transformation → output available
  6. I.6 Essential function families available
  7. I.7 Sets, intervals, and relations available
  8. I.8 Indexed quantities and summation available
  9. I.9 The notation map for ML available

Part II

Linear Algebra

Matrices as transformations: the strongest foundation in the book.

19 of 19 chapters written

  1. II.1 Vector addition and subtraction available
  2. II.2 Scalar multiplication and vector scaling available
  3. II.3 Norms, magnitude, and normalization available
  4. II.4 Dot product, angle, and orthogonality available
  5. II.5 Projection and distance to a direction available
  6. II.6 Linear combinations and span available
  7. II.7 Linear independence, basis, and coordinates available
  8. II.8 Matrices as linear transformations available
  9. II.9 Matrix × vector available
  10. II.10 Matrix × matrix as composition available
  11. II.11 Transpose and orthogonality available
  12. II.12 Determinant: orientation and area/volume scaling available
  13. II.13 Linear systems as intersecting constraints available
  14. II.14 Gaussian elimination and row operations available
  15. II.15 Rank and invertibility available
  16. II.16 Inverse matrices available
  17. II.17 Eigenvalues and eigenvectors available
  18. II.18 Orthogonal bases and least-squares geometry available
  19. II.19 Singular Value Decomposition available

Part III

Calculus

Change, local approximation, and sensitivity made visible.

15 of 15 chapters written

  1. III.1 Limits through approach available
  2. III.2 Continuity and local behavior available
  3. III.3 Derivative as secant → tangent available
  4. III.4 Derivative as rate of change and local linear model available
  5. III.5 Derivative rules available
  6. III.6 Chain rule available
  7. III.7 Multivariable functions and partial derivatives available
  8. III.8 Gradient and directional derivatives available
  9. III.9 Jacobian available
  10. III.10 Computational graphs and automatic differentiation available
  11. III.11 Hessian and curvature available
  12. III.12 Integrals as accumulation available
  13. III.13 Fundamental derivative/integral connection available
  14. III.14 Numerical differentiation available
  15. III.15 Numerical integration available

Part IV

Probability

Uncertainty through sample spaces, evidence, and repetition.

16 of 16 chapters written

  1. IV.1 Random experiments, outcomes, and sample spaces available
  2. IV.2 Events and probability mass available
  3. IV.3 Counting and finite probability where needed available
  4. IV.4 Conditional probability as restricted sample space available
  5. IV.5 Independence available
  6. IV.6 Bayes' theorem as probability-mass update available
  7. IV.7 Random variables available
  8. IV.8 PMF, PDF, and CDF available
  9. IV.9 Bernoulli and Binomial distributions available
  10. IV.10 Uniform and Gaussian distributions available
  11. IV.11 Expectation available
  12. IV.12 Variance and standard deviation available
  13. IV.13 Joint, marginal, and conditional distributions available
  14. IV.14 Covariance and correlation available
  15. IV.15 Law of Large Numbers available
  16. IV.16 Central Limit Theorem available

Part V

Statistics

From observed data to estimates, intervals, and likelihood.

10 of 10 chapters written

  1. V.1 Data summaries: mean, median, mode available
  2. V.2 Spread: variance, standard deviation, robust interpretation available
  3. V.3 Population, sample, and sampling variability available
  4. V.4 Estimators and estimation available
  5. V.5 Confidence intervals through repeated sampling available
  6. V.6 Covariance matrices and multivariate spread available
  7. V.7 Regression fundamentals available
  8. V.8 Likelihood available
  9. V.9 Maximum Likelihood Estimation available
  10. V.10 Maximum A Posteriori estimation available

Part VI

Optimization

Learning as repeated parameter updates governed by an objective.

10 of 10 chapters written

  1. VI.1 Objective functions and optimization landscapes available
  2. VI.2 Local vs global optima and stationary points available
  3. VI.3 Convexity available
  4. VI.4 Gradient descent flagship chapter available
  5. VI.5 Learning rate and convergence behavior available
  6. VI.6 Momentum available
  7. VI.7 Stochastic and mini-batch gradient descent available
  8. VI.8 Adam intuition available
  9. VI.9 Constraints and projected/penalized intuition available
  10. VI.10 Numerical stopping and optimization diagnostics available

Part VII

Information Theory

Logarithms, entropy, and the loss behind token prediction.

8 of 8 chapters written

  1. VII.1 Logarithms and log probabilities in computation available
  2. VII.2 Self-information available
  3. VII.3 Entropy available
  4. VII.4 Cross entropy and negative log-likelihood available
  5. VII.5 KL divergence available
  6. VII.6 Logits and softmax available
  7. VII.7 Numerical stability: log-sum-exp and stable softmax available
  8. VII.8 From token logits to language-model loss available

Part VIII

Numerical Computing

Why equivalent expressions behave differently on real machines.

10 of 10 chapters written

  1. VIII.1 Floating-point representation available
  2. VIII.2 Rounding and representation error available
  3. VIII.3 Error propagation and conditioning available
  4. VIII.4 Catastrophic cancellation available
  5. VIII.5 Overflow and underflow available
  6. VIII.6 Stable algorithms available
  7. VIII.7 Numerical linear algebra realities available
  8. VIII.8 Sparse matrices and sparse structure available
  9. VIII.9 Vectorized computation available
  10. VIII.10 Reproducibility, random seeds, and nondeterminism available