Create your own
Lesson illustration

Expectation, Variance, and Covariance of Random Variables

Hello. In the previous lesson, you used conditional probability and Bayes’ rule to update a belief after observing evidence. That required a probability model, but it did not yet give us a compact way to describe the center, spread, or co-movement of the quantities in that model.

This completes the probability portion of the mathematical-foundations module. You will learn to calculate three core summaries of random variables:

  • Expectation: the probability-weighted average.
  • Variance: typical squared spread around that average.
  • Covariance: whether two variables tend to be above or below their means together.

These are not merely descriptive statistics. They appear in loss functions, uncertainty estimates, feature analysis, PCA, optimization diagnostics, and the evaluation of model and business metrics.


Expectation: a weighted long-run average

A random variable maps an uncertain outcome to a number. For example:

  • : number of relevant documents retrieved for a query;
  • : inference latency in milliseconds;
  • : whether a fraud case is truly positive, encoded as for yes and for no.

If a discrete random variable can take values , its expectation is

Read this as: multiply every possible value by its probability, then add the results.

Expectation is often denoted by

It is a population quantity determined by the probability distribution, not necessarily a value you will observe on any particular draw.

Expected Value and Variance of Discrete Random Variables

Watch “Expected Value and Variance of Discrete Random Variables” by jbstatistics for a concise introduction to expectation, variance, and the computational shortcut for variance.

Watch expectation for the weighted-average definition. Then continue with variance formulas, focusing on why variance averages squared deviations and why the shortcut uses the expectation of X^2, not the square of each probability.

Worked example: expected retrieval count

Suppose is the number of relevant documents returned in the top two results for a randomly selected query.

Then

Across many queries, the system returns an average of relevant documents in the top two. Of course, no individual query returns documents; each returns , , or .

That distinction matters in ML interviews: an expected value summarizes behavior across a distribution. It is not a prediction that every individual example should equal the mean.

Expectation rules worth using

Expectation is linear. For constants and ,

And for any two random variables,

The second result does not require independence. If one random variable rises whenever the other rises, their expected sum is still the sum of their expectations.

For a collection of variables,

This is why the expected number of conversions in a cohort is the sum of the individual conversion probabilities, even when the conversions are not independent.

For a continuous random variable with density , the sum becomes an integral:

The interpretation is unchanged: values are weighted by how much probability density lies near them.


Variance: how much uncertainty remains around the mean

Expectation alone is incomplete. Consider two model-serving systems:

  • both have mean latency ms;
  • one is reliably near ms;
  • the other is usually fast but occasionally takes several seconds.

The means are equal, but their operational behavior clearly is not. Variance measures this spread.

Let

The variance of is

Variance is the expected squared distance from the mean.

We square deviations for two related reasons:

  1. Positive and negative deviations should not cancel.
  2. Large deviations should count more heavily than small ones.

Variance is always nonnegative:

A constant has no uncertainty, so

The computational form

Directly computing deviations from the mean is intuitive, but the following identity is usually faster:

Be precise about the parentheses. These are different operations:

in general.

Returning to the retrieval example, we already found

Now calculate the second moment:

Therefore,

Apply the shortcut:

The standard deviation is the square root of variance:

Variance is measured in squared units. If is latency in milliseconds, variance has units of milliseconds squared. Standard deviation returns to the original units, which often makes it easier to interpret.

How transformations change variance

A shift changes the mean but not the spread:

A rescaling multiplies variance by the square of the scale factor:

Combined:

For example, converting latency from seconds to milliseconds multiplies values by , so it multiplies variance by

This square is a frequent interview error.


Covariance: joint deviations, not just individual spread

Variance describes one random variable. In ML, we also care about relationships:

  • Do GPU utilization and latency rise together?
  • Do two input features tend to move together?
  • Does retrieval latency rise as corpus size rises?
  • Do two model errors co-occur?

Covariance is the basic quantity for measuring whether two variables tend to deviate from their means in the same direction.

Two scatter plots illustrate positive covariance, where larger \(x\) values tend to occur with larger \(y\) values, and negative covariance, where larger \(x\) values tend to occur with smaller \(y\) values.

Let

The covariance of and is

The product inside this expectation explains the sign:

Position relative to meanProductContribution
high, highpositivepositive covariance
low, lowpositivepositive covariance
high, lownegativenegative covariance
low, highnegativenegative covariance

Thus:

  • : they tend to move together.
  • : one tends to be high when the other is low.
  • : there is no linear co-movement captured by covariance.

Covariance of a variable with itself is its variance:

The computational form of covariance

As with variance, expanding the centered expression gives a convenient identity:

For a discrete joint distribution, calculate by summing over pairs:

Lecture 09: Expectation, Variance, and Introduction to Regression

Watch the covariance portion of “Lecture 09: Expectation, Variance, and Introduction to Regression” from MIT OpenCourseWare. It connects the formulas to association between variables and highlights the distinction between covariance, correlation, and independence.

Watch covariance and correlation. Focus especially on the centered-product definition, the identity involving \mathbb{E}[XY], and the warning that zero covariance does not generally imply independence.

Worked covariance calculation

Let and be binary indicators for two events in a system:

  • : a request has a high retrieval latency;
  • : the request triggers a downstream timeout.

Suppose their joint distribution is:

First, calculate each expectation:

Similarly,

Because only when both and ,

Now apply the shortcut:

The covariance is positive. High retrieval latency and timeouts occur together more often than they would if the events had no association.


Independence, covariance, and variance of sums

For independent variables,

Why? Under independence,

so the covariance formula becomes zero.

The reverse statement is not generally true:

For example, let be uniformly distributed over

and define

Here is completely determined by , so the variables are certainly dependent. But symmetry gives

and

Therefore,

Covariance detects linear association, not every possible dependence pattern. This is especially relevant in feature analysis: a near-zero correlation between two features does not establish that one feature adds no nonlinear information.

Variance of a sum

For any pair of random variables,

The covariance term determines how the uncertainties combine:

  • Positive covariance makes the total more variable.
  • Negative covariance makes the total less variable.
  • Independence implies zero covariance, yielding:

More generally,

This formula is foundational for understanding ensembles, portfolio-style risk calculations, aggregating noisy measurements, and later the covariance matrices used in multivariate ML methods.


From distributions to observed datasets

So far, calculations used known probability distributions. In applied ML, we usually have a finite dataset instead.

For observed values , the empirical mean is

The empirical covariance between features and is commonly computed as

Similarly, the usual sample variance is

The version is the standard unbiased sample estimator of a population variance under common assumptions. In ML code, you may also encounter division by , especially when treating the observed batch or dataset itself as the full population of interest. The key is to state which convention is being used and avoid mixing them silently.


Key takeaways

Expectation is the probability-weighted long-run average:

Variance measures expected squared deviation from the mean:

Covariance measures whether two variables deviate from their means together:

Finally, remember the logical distinction:

but zero covariance alone does not prove independence.

You have now completed the core mathematical-foundations module. Next, the course moves into statistical reasoning, beginning with how to match common probability distributions—Bernoulli, binomial, Gaussian, and categorical—to modeling situations.

Can't find a good explanation? Sign up and we'll make it for you

Sign up