Mathematical Foundations

IV.7 · Probability

How does an uncertain outcome become a number?

Map each die face to a value, then watch probability flow into the value groups. The function is fixed; uncertainty comes from the outcome that occurs.

A random variable maps outcomes to values

Face 1 → 0Mass = 1/6
Face 2 → 0Mass = 1/6
Face 3 → 1Mass = 1/6
Face 4 → 1Mass = 1/6
Face 5 → 2Mass = 1/6
Face 6 → 2Mass = 1/6
Induced probability mass function
Induced probability mass functionX = 0 has probability 1/3; X = 1 has probability 1/3; X = 2 has probability 1/310: approximately 0.33333333333333331: approximately 0.33333333333333332: approximately 0.3333333333333333012

Numerical values of X · bar height is probability mass

X = 0= 1/3
X = 1= 1/3
X = 2= 1/3

Face 1 maps to 0, with mass 1/6; Face 2 maps to 0, with mass 1/6; Face 3 maps to 1, with mass 1/6; Face 4 maps to 1, with mass 1/6; Face 5 maps to 2, with mass 1/6; Face 6 maps to 2, with mass 1/6. Six outcomes induce 3 numerical value(s) with positive mass. Matching values combine their original masses; the induced distribution still totals one.

Expected numerical value
1
Variance
2/30.666667…

= exact model quantity · ≈ numerical companion or observed estimate

from −4 to 6, up to 2 decimal places

from 0 to 100, whole numbers only

Six outcomes induce 3 numerical value(s) with positive mass. Matching values combine their original masses; the induced distribution still totals one.
X:Ω⟶RX:\Omega\longrightarrow\mathbb R
P(X=x)=∑ω:X(ω)=xP(ω)P(X=x)=\sum_{\omega:X(\omega)=x}P(\omega)

Keep the original outcomes

The six die faces remain distinguishable, each with its model probability.

∑ω∈ΩP(ω)=1\sum_{\omega\in\Omega}P(\omega)=1

Change a die face's assigned value and follow its probability into the induced PMF. Reset to values [0, 0, 1, 1, 2, 2] on a fair die.

Before editing, predict how many faces feed the value 1. Move just one face into another group: does the original die become less fair, or does only its numerical summary change?

Intuition: an outcome and its value

A die roll produces a face. A program might record the face itself, whether it is even, or a score assigned to it. Those are different numerical descriptions of the same experiment. The assignment does not have to give different numbers to different faces.

The canonical stage assigns faces 1 through 6 the values [0,0,1,1,2,2][0,0,1,1,2,2]. There are six equally likely outcomes but only three value groups. Keeping those two spaces distinct explains why each group has mass 1/31/3, rather than 1/61/6.

Definition

A real-valued random variable is a function X:Ω→RX:\Omega\to\mathbb R. On a finite sample space, it assigns exactly one real number to each outcome. For a value xx, its induced probability is

P(X=x)=∑ω:X(ω)=xpω.P(X=x)=\sum_{\omega:X(\omega)=x}p_\omega.

More generally, P(X∈S)=P({ω:X(ω)∈S})P(X\in S)=P(\{\omega:X(\omega)\in S\}). The set inside the probability is the preimage of the value event. Several outcomes can share a value; the function need not be one-to-one. Here every finite assignment defines measurable events automatically; general infinite-space measurability is outside this chapter.

Mechanics: group, then add

Read each row as an original outcome, its probability weight, and its assigned value. Edit one value or weight and compare the induced bars, probability inspector, formula, and trace. Raw weights are normalized by their positive total; they are not probabilities until normalized. Changing a value redirects a face’s existing mass. Changing a weight changes the experiment’s mass distribution.

The trace first normalizes the source weights, then groups outcomes by equal value, and finally adds each group’s masses. The PMF describes the numerical variable, while the original outcome labels still describe the experiment. Reset restores the same mapping and equal weights.

Derivation: why total mass survives

Every outcome belongs to exactly one value group. Summing across the distinct values therefore counts every source mass exactly once:

∑xP(X=x)=∑x∑ω:X(ω)=xpω=∑ω∈Ωpω=1.\begin{aligned} \sum_x P(X=x)&=\sum_x\sum_{\omega:X(\omega)=x}p_\omega\\ &=\sum_{\omega\in\Omega}p_\omega=1. \end{aligned}

This establishes normalization without assuming equally likely value labels. Nonnegative source masses also make every induced mass nonnegative. A many-to-one mapping combines mass; it never duplicates mass.

Worked examples

For the canonical fair die, X=0X=0 on faces 1,21,2, X=1X=1 on 3,43,4, and X=2X=2 on 5,65,6. Each pair contributes 1/6+1/6=1/31/6+1/6=1/3. The event X≥1X\ge1 pulls back to {3,4,5,6}\{3,4,5,6\}, giving probability 2/32/3.

Worked example: A random variable maps outcomes to values

Face 1 → 0Mass = 1/6
Face 2 → 0Mass = 1/6
Face 3 → 1Mass = 1/6
Face 4 → 1Mass = 1/6
Face 5 → 2Mass = 1/6
Face 6 → 2Mass = 1/6
Induced probability mass function
Induced probability mass functionX = 0 has probability 1/3; X = 1 has probability 1/3; X = 2 has probability 1/310: approximately 0.33333333333333331: approximately 0.33333333333333332: approximately 0.3333333333333333012

Numerical values of X · bar height is probability mass

X = 0= 1/3
X = 1= 1/3
X = 2= 1/3

Face 1 maps to 0, with mass 1/6; Face 2 maps to 0, with mass 1/6; Face 3 maps to 1, with mass 1/6; Face 4 maps to 1, with mass 1/6; Face 5 maps to 2, with mass 1/6; Face 6 maps to 2, with mass 1/6. Six outcomes induce 3 numerical value(s) with positive mass. Matching values combine their original masses; the induced distribution still totals one.

Expected numerical value
1
Variance
2/30.666667…

= exact model quantity · ≈ numerical companion or observed estimate

from −4 to 6, up to 2 decimal places

from 0 to 100, whole numbers only

Six outcomes induce 3 numerical value(s) with positive mass. Matching values combine their original masses; the induced distribution still totals one.
X:Ω⟶RX:\Omega\longrightarrow\mathbb R
P(X=x)=∑ω:X(ω)=xP(ω)P(X=x)=\sum_{\omega:X(\omega)=x}P(\omega)

Keep the original outcomes

The six die faces remain distinguishable, each with its model probability.

∑ω∈ΩP(ω)=1\sum_{\omega\in\Omega}P(\omega)=1

Rebuild the three equal-mass groups and identify the four faces in X ≥ 1. Then merge every face into the single value 2.

For a weighted experiment with outcomes a,b,ca,b,c of masses 1/2,1/4,1/41/2,1/4,1/4, map a,ba,b to 00 and cc to 11. The resulting masses are 3/43/4 and 1/41/4. The number of labels has fallen to two, but equal-label counting would discard the source weights.

Executable reference code

The standard-library program explicitly loops over outcome/value pairs and accumulates exact Fraction masses. It asserts the canonical PMF, the pulled-back event probability, unequal-weight grouping, zero-mass labels, and rejection of invalid models. The NumPy version uses unique to form groups and bincount to accumulate their masses. Read the loop first; the array indices implement the same grouping mechanics.

code/python/probability_variables.py
"""Push a finite experiment through a random-variable function, exactly."""
from fractions import Fraction as F


def induced_distribution(values, masses):
    if not values or len(values) != len(masses):
        raise ValueError("One value and one mass are required per outcome")
    if any(not isinstance(x, (int, F)) or isinstance(x, bool) for x in values):
        raise ValueError("Values must be integers or exact Fractions")
    if any(not isinstance(p, F) or p < 0 for p in masses) or sum(masses, F(0)) != 1:
        raise ValueError("Nonnegative Fraction masses must sum to 1")
    result = {}
    for value, mass in zip(values, masses):
        result[value] = result.get(value, F(0)) + mass
    return result


def main():
    values = [0, 0, 1, 1, 2, 2]
    masses = [F(1, 6)] * 6
    induced = induced_distribution(values, masses)
    assert induced == {0: F(1, 3), 1: F(1, 3), 2: F(1, 3)}
    assert sum(p for x, p in induced.items() if x >= 1) == F(2, 3)
    assert sum(p for x, p in zip(values, masses) if x >= 1) == F(2, 3)
    assert induced_distribution([0, 0, 1], [F(1, 2), F(1, 4), F(1, 4)]) == {0: F(3, 4), 1: F(1, 4)}
    assert induced_distribution([2, 2], [F(0), F(1)]) == {2: F(1)}
    assert induced_distribution([9, 0], [F(0), F(1)])[9] == 0
    for values_bad, masses_bad in (([], []), ([0], [F(1, 2)]), ([0], [1.0]),
                                   ([0, 1], [F(-1), F(2)]), ([0, 1], [F(1)]), ([float('nan')], [F(1)])):
        try:
            induced_distribution(values_bad, masses_bad)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid finite mapping accepted")
    print("Exact induced PMF:", induced)
    print("P(X >= 1) =", sum(p for x, p in induced.items() if x >= 1))


if __name__ == "__main__":
    main()
code/python/probability_variables_numpy.py
"""NumPy groups equal values with unique/inverse indices and weighted bincount."""
import numpy as np


def induced_distribution(values, masses):
    x, p = np.asarray(values, dtype=float), np.asarray(masses, dtype=float)
    if x.ndim != 1 or p.shape != x.shape or x.size == 0 or not np.all(np.isfinite(x)):
        raise ValueError("Provide a nonempty finite value vector and matching masses")
    if not np.all(np.isfinite(p)) or np.any(p < 0) or abs(p.sum() - 1) > 1e-12:
        raise ValueError("Nonnegative finite masses must sum to 1 within 1e-12")
    labels, inverse = np.unique(x, return_inverse=True)
    return labels, np.bincount(inverse, weights=p, minlength=labels.size)


def main():
    labels, masses = induced_distribution([0, 0, 1, 1, 2, 2], [1/6] * 6)
    np.testing.assert_array_equal(labels, [0, 1, 2])
    np.testing.assert_allclose(masses, [1/3, 1/3, 1/3], rtol=0, atol=1e-12)
    np.testing.assert_allclose(masses[labels >= 1].sum(), 2/3, rtol=0, atol=1e-12)
    np.testing.assert_allclose(induced_distribution([0, 0, 1], [0.5, 0.25, 0.25])[1], [0.75, 0.25], rtol=0, atol=1e-12)
    np.testing.assert_array_equal(induced_distribution([9, 0], [0, 1])[1], [1, 0])
    for x, p in (([], []), ([0], [0.5]), ([0, 1], [-1, 2]), ([np.nan], [1]), ([0], [np.inf])):
        try:
            induced_distribution(x, p)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid mapping accepted")
    print("Value labels:", labels, "induced masses ≈", masses)


if __name__ == "__main__":
    main()

Explore

Choose Every face maps to 2. Predict the sole induced mass before inspecting it: P(X=2)=1P(X=2)=1, although the die still has six source outcomes. Choose Distinct values to recover one value per face. Compare the bar count and the source-outcome count in both states.

Reset and change one source weight. Explain how that face’s value group gains or loses probability after normalization. Then move that face to another value without changing its weight. Trace the mass through both operations; do not infer an event probability from the number of bars.

Common mistakes and counterexamples

“Random” does not mean the assignment itself must be redrawn after every roll. Once the model fixes XX, observing a face fixes its value. Assigning two values to one outcome without a selection rule would fail the definition of a function.

A value is not its probability: X=2X=2 can have mass 1/31/3, and a negative score can have positive probability. A constant random variable is valid. A listed value whose only preimages have zero mass is also valid and has probability zero; this differs from an invalid all-zero weight model.

Numerical considerations

Grouping needs a rule for equality. These examples use integer or exact rational values, so equal labels can be identified exactly. With floating-point measurements, two nearly equal numbers are not automatically the same category; a rounding or binning policy would define a different variable and must be stated.

Exact Fraction arithmetic preserves the finite sums. NumPy uses finite floating-point inputs and checks mass normalization within absolute tolerance 10−1210^{-12}. A tolerance in a numerical check does not turn probability-zero values into missing observations or justify merging nearby labels.

Engineering and ML connections

A loss function turns an uncertain example into a number. An indicator maps an event to 11 and its complement to 00. A class-count variable groups detailed trial sequences by their success totals. In each case, probabilities belong to the underlying experiment and flow through the chosen function.

Changing a scoring function changes the random variable, while changing the data-generating model changes the source probabilities. Keeping these decisions separate prevents a visualization or evaluation metric from silently inventing equal weights.

Exercises

Use exact fractions for finite masses. Each attempt provides corrective feedback and a worked solution.

calculation

Group outcomes by value

A fair die maps faces 1 through 6 to values [0, 0, 1, 1, 2, 2]. Give P(X = 0), P(X = 1), P(X = 2).

calculation

Pull a value event back to faces

For the same fair-die mapping, find P(X ≥ 1).

calculation

Preserve unequal outcome weights

Outcomes a, b, c have masses 1/2, 1/4, 1/4. Map a and b to 0, c to 1. Give the induced masses at 0 and 1.

explanation

What must a random variable assign?

Which rule defines a real-valued random variable on a finite sample space?

Choose one answer

explanation

Is a zero-mass value impossible as a label?

A listed outcome has mass 0 and is the only outcome mapped to 9. What is P(X = 9)?

Choose one answer

Summary and checkpoints

A random variable assigns numbers to outcomes. Its distribution sums source masses over equal-value groups, and a value event pulls back to an outcome event. Check that you can recover the canonical three 1/31/3 masses, preserve unequal weights, and distinguish constant or zero-mass values from invalid models.

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