Mathematical Foundations

IV.11 · Probability

Where does a distribution balance when its values have unequal weights?

Move values and weights to see their contributions to a probability-weighted center. Then apply linearity to a pair of explicitly dependent variables.

Probability makes a weighted balance point

The original population and its balance point
The original population and its balance pointDashed marker at expectation 0.5. Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.1-2: approximately 0.250: approximately 0.54: approximately 0.25-204

X values · bar height is probability mass · dashed line is E[X]

The exact weighted sum
xpp·x
−20.25−0.5
00.50
40.251

Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.

Population expectation
0.5
Second moment
5
Population variance
4.75
Standard deviation
√19/22.179449…
Transformed expectation
0.5
Transformed variance
4.75
Expectation of dependent sum
2.5

= exact model quantity · ≈ numerical companion or observed estimate

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.
E[X]=∑ipixi=0.5E[X]=\sum_i p_ix_i=0.5
E[X+Y]=E[X]+E[Y]=0.5+2=2.5E[X+Y]=E[X]+E[Y]=0.5+2=2.5
E[aX+b]=aE[X]+b=0.5,Var⁡(aX+b)=a2Var⁡(X)=4.75E[aX+b]=aE[X]+b=0.5,\quad\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)=4.75

Assign population probability mass

Weights divide by their positive total; these are theoretical probabilities, not sample estimates.

∑ipi=1\sum_i p_i=1
Outcome 1: X = −2= 0.25
Outcome 2: X = 0= 0.5
Outcome 3: X = 4= 0.25

Begin with values [−2, 0, 4] and raw weights [1, 2, 1]. Compare the normalized masses, each weighted contribution, and their sum E[X] = 1/2.

Predict the center before inspecting it. Compare the equal-label average with the probability-weighted average: the middle value has twice the mass of either outer value.

Intuition: a center of probability mass

Expectation is a weighted balance point, not a guarantee about the next result. Imagine each value carrying its probability mass on a number line. A larger mass contributes more strongly to the center. Negative values pull in the negative direction; they do not require negative probabilities.

For values [−2,0,4][-2,0,4] and raw weights [1,2,1][1,2,1], the normalized masses are [1/4,1/2,1/4][1/4,1/2,1/4]. Their center is 1/21/2, even though no outcome takes that value. The ordinary average of the three labels, 2/32/3, describes a different equal-weight model.

Definition

For a finite random variable with values xix_i and probabilities pip_i, its expectation is

E[X]=∑ipixi.\mathbb E[X]=\sum_i p_i x_i.

For a function gg, E[g(X)]=∑ipig(xi)\mathbb E[g(X)]=\sum_i p_i g(x_i). In particular, the second moment is E[X2]=∑ipixi2\mathbb E[X^2]=\sum_i p_i x_i^2; it is generally different from (E[X])2(\mathbb E[X])^2.

For a continuous variable with density ff, E[X]=∫−∞∞xf(x) dx\mathbb E[X]=\int_{-\infty}^{\infty}x f(x)\,dx when the expectation exists. A finite absolute first moment ensures this definition is well behaved; not every infinite-support distribution has one. The finite models in this stage always do.

Mechanics: normalize before summing

The stage begins with affine scale 11 and shift 00. Change values or nonnegative raw weights, then read each table row’s normalized mass and product pixip_i x_i. The formula, center marker, inspector, and trace use the same derived distribution. The total raw weight must be positive.

Scale and shift define a companion affine variable aX+baX+b while preserving its masses. Read its expectation and variance in the transformed inspector rows; the plot and weighted-sum table show the original XX. The presets Zero variance, Shift by 2, and Scale by −2 expose a constant source variable or an affine comparison. Reset restores the canonical values, weights, scale, and shift.

Derivation: linearity does not need independence

For constants a,ba,b,

E[aX+b]=∑ipi(axi+b)=aE[X]+b∑ipi=aE[X]+b.\mathbb E[aX+b]=\sum_i p_i(ax_i+b) =a\mathbb E[X]+b\sum_i p_i=a\mathbb E[X]+b.

For two jointly defined finite variables, sum over their common outcomes. Distributing the sum gives E[X+Y]=E[X]+E[Y]\mathbb E[X+Y]=\mathbb E[X]+\mathbb E[Y]. Independence is unnecessary: both values can depend on the same outcome. In general settings these identities require the relevant expectations to exist.

An event indicator IAI_A is 11 on AA and 00 elsewhere, so E[IA]=P(A)\mathbb E[I_A]=P(A). A binomial count is a sum of Bernoulli indicators; linearity gives mean npnp. Independence is required for its binomial distribution, but not for the expectation of a sum of indicators with given marginal success probabilities.

Worked examples

The canonical weighted calculation is

E[X]=−2+2×0+44=12,E[X2]=4+2×0+164=5.\mathbb E[X]=\frac{-2+2\times0+4}{4}=\frac12, \qquad \mathbb E[X^2]=\frac{4+2\times0+16}{4}=5.

Worked example: Probability makes a weighted balance point

The original population and its balance point
The original population and its balance pointDashed marker at expectation 0.5. Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.1-2: approximately 0.250: approximately 0.54: approximately 0.25-204

X values · bar height is probability mass · dashed line is E[X]

The exact weighted sum
xpp·x
−20.25−0.5
00.50
40.251

Value −2 has mass 0.25, deviation −2.5, squared distance 6.25; Value 0 has mass 0.5, deviation −0.5, squared distance 0.25; Value 4 has mass 0.25, deviation 3.5, squared distance 12.25. The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.

Population expectation
0.5
Second moment
5
Population variance
4.75
Standard deviation
√19/22.179449…
Transformed expectation
0.5
Transformed variance
4.75
Expectation of dependent sum
2.5

= exact model quantity · ≈ numerical companion or observed estimate

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from −5 to 5, up to 2 decimal places

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from 0 to 100, whole numbers only

from −3 to 3, up to 2 decimal places

from −4 to 4, up to 2 decimal places

The weighted balance point is E[X] = 0.5. Y = 2X + 1 depends on X, yet E[X+Y] = E[X]+E[Y] = 2.5.
E[X]=∑ipixi=0.5E[X]=\sum_i p_ix_i=0.5
E[X+Y]=E[X]+E[Y]=0.5+2=2.5E[X+Y]=E[X]+E[Y]=0.5+2=2.5
E[aX+b]=aE[X]+b=0.5,Var⁡(aX+b)=a2Var⁡(X)=4.75E[aX+b]=aE[X]+b=0.5,\quad\operatorname{Var}(aX+b)=a^2\operatorname{Var}(X)=4.75

Assign population probability mass

Weights divide by their positive total; these are theoretical probabilities, not sample estimates.

∑ipi=1\sum_i p_i=1
Outcome 1: X = −2= 0.25
Outcome 2: X = 0= 0.5
Outcome 3: X = 4= 0.25

Add the exact row contributions to recover mean 1/2 and second moment 5. Shift the values by 2 or scale by −2 and predict the new center first.

Define Y=2X+1Y=2X+1 on the same outcome. This is a dependent pair, not a second independent draw. Its values are [−3,1,9][-3,1,9], with the same masses. Since E[Y]=2E[X]+1=2\mathbb E[Y]=2\mathbb E[X]+1=2,

E[X+Y]=3E[X]+1=52.\mathbb E[X+Y]=3\mathbb E[X]+1=\frac52.

By contrast, XY=2X2+XXY=2X^2+X gives E[XY]=21/2\mathbb E[XY]=21/2, whereas E[X]E[Y]=1\mathbb E[X]\mathbb E[Y]=1. Linearity concerns sums and constant multiples, not arbitrary products.

Executable reference code

The standard-library program normalizes raw weights with exact Fraction arithmetic and computes first and second moments by explicit sums. It constructs YY from each value of XX, then directly checks the dependent sum and product calculations. It also verifies weight-rescaling invariance, affine transformations, constant values, and invalid-input rejection.

The NumPy version uses normalized weight vectors and dot products. It exposes the array mechanics after the mathematical calculation, rather than treating an array routine as a definition of expectation. Neither program simulates samples to manufacture a theoretical answer.

code/python/probability_expectation.py
"""Expectations from exact raw weights, including dependent linearity."""
from fractions import Fraction as F


def moments(values, weights):
    if not values or len(values) != len(weights):
        raise ValueError("Require matching nonempty values and weights")
    if any(not isinstance(x, (int, F)) or isinstance(x, bool) for x in (*values, *weights)):
        raise ValueError("Use integer or Fraction values and weights")
    total = sum(weights, F(0))
    if any(w < 0 for w in weights) or total <= 0:
        raise ValueError("Weights must be nonnegative with positive total")
    mean = sum((x*w for x, w in zip(values, weights)), F(0)) / total
    second = sum((x*x*w for x, w in zip(values, weights)), F(0)) / total
    return mean, second


def main():
    x, w = [-2, 0, 4], [1, 2, 1]
    mean, second = moments(x, w)
    assert (mean, second) == (F(1, 2), F(5))
    y = [2*v + 1 for v in x]  # Y shares X's outcome: these are dependent.
    assert moments(y, w)[0] == 2
    assert moments([a+b for a, b in zip(x, y)], w)[0] == F(5, 2) == 3*mean + 1
    assert moments([a*b for a, b in zip(x, y)], w)[0] == F(21, 2)
    assert mean * moments(y, w)[0] == 1
    assert moments([-2*v + 5 for v in x], w)[0] == 4
    assert moments([v + 2 for v in x], w)[0] == F(5, 2)
    assert moments([2, 2, 2], w) == (F(2), F(4))
    assert moments(x, [10, 20, 10]) == (mean, second)
    assert moments([99, 2], [0, 1]) == (F(2), F(4))
    for values, weights in (([], []), ([0], [0]), ([0, 1], [1, -1]), ([0, 1], [1]), ([0.5], [1])):
        try:
            moments(values, weights)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid exact weighted model accepted")
    print("E[X] =", mean, "; E[X²] =", second)
    print("Dependent Y = 2X+1: E[X+Y] = 5/2; E[XY] = 21/2, not E[X]E[Y] = 1")


if __name__ == "__main__":
    main()
code/python/probability_expectation_numpy.py
"""Normalize a weight vector, then compute expectations as dot products."""
import numpy as np


def moments(values, weights):
    x, w = np.asarray(values, dtype=float), np.asarray(weights, dtype=float)
    if x.ndim != 1 or x.size == 0 or w.shape != x.shape or not np.all(np.isfinite(x)):
        raise ValueError("Require finite nonempty values and matching weights")
    if not np.all(np.isfinite(w)) or np.any(w < 0) or not np.isfinite(w.sum()) or w.sum() <= 0:
        raise ValueError("Require nonnegative finite weights with positive finite total")
    p = w / w.sum()
    return float(np.dot(p, x)), float(np.dot(p, x*x))


def main():
    x, w = np.array([-2., 0., 4.]), np.array([1., 2., 1.])
    mean, second = moments(x, w)
    np.testing.assert_array_equal([mean, second], [0.5, 5])
    y = 2*x + 1
    assert moments(y, w)[0] == 2
    assert moments(x + y, w)[0] == 2.5
    assert moments(x*y, w)[0] == 10.5 != mean * moments(y, w)[0]
    assert moments(-2*x + 5, w)[0] == 4
    assert moments(x + 2, w)[0] == 2.5
    assert moments(np.full(3, 2.), w) == (2., 4.)
    assert moments(x, 10*w) == (mean, second)
    assert moments([99, 2], [0, 1]) == (2., 4.)
    for values, weights in (([], []), ([0], [0]), ([0, 1], [1, -1]), ([np.nan], [1]), ([0], [np.inf])):
        try:
            moments(values, weights)
        except ValueError:
            pass
        else:
            raise AssertionError("Invalid weighted model accepted")
    print("Normalized weights:", w/w.sum(), "E[X] ≈", mean, "E[X²] ≈", second)
    print("Same-outcome Y = 2X+1:", y, "E[X+Y] ≈", moments(x+y, w)[0])


if __name__ == "__main__":
    main()

Explore

Increase the raw weight at 44 and predict the center moving toward 44. Multiply all weights by the same positive factor: normalization cancels that factor and the mean stays unchanged. Give one value zero weight and explain why it no longer contributes to the weighted sum.

Choose Shift by 2 to obtain transformed mean 5/25/2. Choose Scale by −2 from the canonical model to obtain transformed mean −1-1. Compare those inspector rows with the source mean 1/21/2. Choose Zero variance, which sets every source value to 22: the source mean becomes 22. Use affine scale −2-2 and shift 33 on the canonical values to predict transformed mean 22 before reading it.

Common mistakes and counterexamples

The mean need not be a possible value or the most probable one. Here the most probable value is 00, while the mean is 1/21/2. Rounding the mean to a support point changes the quantity rather than correcting it.

Squaring before averaging differs from squaring afterward: E[X2]=5\mathbb E[X^2]=5 but (E[X])2=1/4(\mathbb E[X])^2=1/4. Also, independence is not a prerequisite for linearity. The explicit Y=2X+1Y=2X+1 example is dependent and still obeys the sum rule. Its product calculation refutes a careless extension of that rule.

Numerical considerations

Finite rational values and weights allow exact expectations. Construct fractions from integers or decimal strings rather than first rounding them to binary floats. NumPy calculations are approximate in general; exact-looking canonical decimals do not imply every weighted input remains exact.

A sample mean averages observed data, whereas this stage computes a theoretical expectation from a specified model. Raw weights describe proportional probabilities here, not necessarily sample frequencies. Agreement between a short observed average and the model mean is not guaranteed; the sampling chapters study that distinction later.

Engineering and ML connections

Expected loss weights per-outcome losses by the model’s probabilities. Combining loss terms uses linearity even when they depend on the same example. Replacing theoretical probabilities with observed frequencies yields an empirical average; it estimates a model quantity under additional assumptions rather than becoming an exact expectation automatically.

Exercises

Use exact rational answers for the finite model. The explanations test the limits of linearity as well as its useful identities.

calculation

Normalize weights before averaging

X has values [−2, 0, 4] with raw weights [1, 2, 1]. Give E[X] and E[X²].

calculation

Apply linearity to dependent variables

For that X, define Y = 2X + 1 on the same outcome. Find E[X + Y].

prediction

Predict a negative scale and shift

For the same X with E[X] = 1/2, define Z = −2X + 5. Find E[Z].

explanation

Must the expectation be observed?

The canonical X takes only −2, 0, and 4, but E[X] = 1/2. Is this valid?

Choose one answer

explanation

Do not extend linearity to products

For canonical X and Y = 2X + 1, compare E[XY] with E[X]E[Y].

Choose one answer

Summary and checkpoints

Expectation is a normalized probability-weighted sum. Check that you can obtain 1/21/2 and 55 as first and second moments, predict affine changes to the center, justify dependent linearity for Y=2X+1Y=2X+1, and distinguish a theoretical mean from an observation or sample estimate.

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