Quantifying deviation¶
At the end of the previous chapter two distributions stood side by side: the distribution of the data and the model distribution. The question now facing us is how to capture their difference in a single number. The exact answer is the relative entropy, and we are saving that for a later chapter. But there is a much more direct route: instead of comparing the distributions, we compare the data themselves with what the model predicts – the real data against synthetic data, in data space, point by point. That is the route this chapter takes, and because it means taking distances between numbers, from here on we work with real-valued data.
Given two vectors (think of as our data and as what we expect), the natural quantity to look at is the mean deviation . The trouble with it is that positive and negative deviations cancel each other out.
Absolute deviation¶
The sum without the factor is the 1-norm of the difference,
and the factor in the definition is exactly what makes independent of the length of the vector: grows with even when the model is no worse, does not. Since comparing is almost always what we are after, we almost always take the mean. (On the role of the various norms, see also the remark on , and in the chapter Descriptive statistics, as well as L1 and L2 regularisation in the chapter Regression analysis.)
The obvious next question, for a given vector , is which vector has the smallest mean absolute error. Without further conditions on , though, the answer is immediate: . We will come back to this question later; for now we content ourselves with asking which minimises . Graphically: put the numbers from 1 to on the -axis and plot the values above them. A choice of is then a horizontal line, and we are asking which such line has the smallest combined distance to all the points.
So the median is defined as a number at which is minimal. That is, for all we have . Careful: defined this way, several numbers can be “the” median. That is not a bug, it is a feature.
This definition may be unfamiliar, but it has the following property:
Since the second summand does not depend on , it plays no part in finding the minimum. Applying this inductively, all that remains is to determine for vectors of length 1 and 2. We have , which is minimal for , and , which is minimal for every between and . So the median of a sorted list depends only on the middle value, or on the two middle values. The usual definition settles the latter case by choosing , and that is what we will do from here on. Convince yourself that for every with the mean distance to is , so the vector has many medians.
The median, then, reflects the data rather poorly – it is completely independent of most of them! – so we need a better measure. Idea: square the individual error terms in the sum, so that large errors contribute a larger share of it. Conveniently, squaring also spares us the absolute value: it takes care of the sign by itself.
Squared deviation¶
As with the absolute deviation, the sum without is a norm, this time the squared 2-norm:
Compared with , the comes in the square of the unit – for heights in centimetres that is square centimetres, which is hard to interpret. So the square root is usually taken at the end; for the constant model that gives the sample standard deviation of the next subsection.
Sample standard deviation¶
For computation the definition is awkward: you first have to determine the mean and then go over all the entries a second time. The following rearrangement needs only the sum of the entries and the sum of their squares:
This view carries further than it first appears. In the chapter Covariance and dependence it will turn out that the covariance of two random variables behaves exactly like an inner product – the variance is then the special case “vector with itself”, and the correlation coefficient is the cosine of the angle between two centred vectors.
Information content¶
Whether a vector carries information for us depends on how much we already know about . If we know, for example, that is a sample of a random variable uniformly distributed on , we will not be surprised when looks like one. Every entry of corresponds to exactly one bit of information. Suppose instead that the random variable is not uniform but follows, on the numbers , the frequency of the letters of the German language, say (with 1 for “a”, 26 for “z” and so on). Then an entry of potentially carries less information. The “e” is so frequent that we are hardly surprised to see one. An “x”, on the other hand, would surprise us a great deal – but then it does not come up very often either. The average information content is therefore lower than for a uniform distribution.
Measures of central tendency¶
Median and mean are traditionally joined by the mode, the most frequent value. It fits the same pattern: the median is the best constant model for the absolute error, the mean for the squared one, and the mode for the counting error, which counts every deviation the same, however large it is. For a nominal feature, say the Survived column of the Titanic list, that is the only error that makes sense; the best constant model is then the most frequent class, and the proportion of the time it is right is its accuracy (see Titanic EDA).
Here is a short explainer video from Crash Course Statistics on mean, median and mode. The video that follows it in the playlist discusses the related notions for the spread of data (the deviation we started with).
Moments of a random variable¶
From the mean to the expected value¶
So far we have computed with samples: is a number that comes from concrete measurements. Now we reverse the point of view and ask which number belongs to a distribution, that is, to the model the data might have come from. The route there is short, and it explains why the expected value looks exactly the way it does.
Let be a random variable with finitely many values and distribution , so . Suppose for a moment that the are rational numbers with a common denominator , say with . Then there is a sample of size that hits this distribution exactly: the one in which the value occurs precisely times. We call it the idealised sample for – the sample you would get if chance kept to the probabilities perfectly, just once.
We can write down the mean of this idealised sample directly, since we know how often each value occurs:
On the right there is no sample any more, only the distribution. With that, the assumption that the are rational has become superfluous too: the right-hand side makes sense for every distribution, and the detour through served only to find the formula. This quantity is exactly what we call the expected value of .
The special case is the acid test: a distribution that takes a single value with probability 1 – the Dirac measure from the chapter The formalism of stochastics – has the idealised sample and so the expected value . A constant model and the value it predicts are the same thing. In the language of the previous section: the best constant model for the squared error was the mean of the data – and read as a distribution, a constant model is a Dirac measure.
With that we can set the formula down as a definition. It works word for word when is countably infinite; the finite sum then becomes a series, which need no longer converge.
Expected value, discrete¶
So the expected value is the mean of the values of , weighted by the probabilities.
For finite the sum is finite and always exists. If is countably infinite, the sum is a series, and a series need not converge: there are random variables for which no expected value can be determined. An example: on , defines a probability measure (because ), and for the series is the harmonic series, which diverges. This random variable has no expected value.
What we can say is this: if takes only finitely many values, then not only does the expected value exist but so do all the higher moments – they are finite sums, and those always converge. With countably infinitely many values, by contrast, you have to check each time. An example that is more than a mathematical curiosity: in the St Petersburg paradox a coin is tossed until heads first comes up, and if that takes tosses, euros are paid out. The probability of that is , so the expected value is . A game with infinite expected value – and yet nobody would pay a high stake to play it.
For continuous random variables, which take uncountably many values, an integral over a density takes the place of the sum: . We give this definition in the chapter Continuous distributions, once we know about densities. Everything we establish about the expected value in this chapter holds for continuous random variables in just the same way, with integrals in place of sums.
Digression: the expected value in general¶
The expected value and the samples of a random variable are intimately connected:
Law of large numbers
An infinite sequence of random variables is said to satisfy a strong law of large numbers if the mean-deviation random variables converge to 0, and do so -almost surely (that is, ).
If the are independent and identically distributed (iid for short: every has the same distribution as a fixed , and we write ) and the expected value exists, then the satisfy a strong law of large numbers. That is, – the deviation of the arithmetic mean of a sample of of size from the expected value – converges -almost surely to 0. Read the other way round: the probability that the sample mean deviates from the expected value for arbitrarily large is 0.
-almost sure convergence also implies convergence in probability: for every .
In what follows we shall not rack our brains any further over the notions of convergence in stochastics (that can always be caught up on later, and depending on the application it is worth doing). Instead, in the usual tradition, we take with us the reassurance that the expected value is a suitable quantity for analysing a sample expectantly. The larger the sample, the smaller the deviation of the sample mean from the expected value should be – so the law would have it. Put the other way round: for every prescribed bound there is a sample size such that the sample mean of a randomly drawn sample almost always deviates from the expected value by less than .
That closes the circle back to the idealised sample at the start of the section: there we pretended that a sample kept to the probabilities exactly, just to arrive at the formula at all. The law of large numbers says that real samples do so arbitrarily well for large – so the detour was no detour.
Rules of calculation for the expected value:
Linearity: the expected value is linear in , so for and random variables ,
Monotonicity: the expected value is monotone in , so for we have .
-additivity: for a sequence we have .
Product rule: if and are independent, then .
Without proof
We have not yet explained what independent means (independently of the pmfs in the discrete case); that comes further down.
Variance¶
Let be a random variable. Then
is called the variance of .
(Shortcut formula)
We have .
We have , and so by the linearity of the expected value
This is the counterpart of the shortcut formula for samples above. For a centred random variable, one with , this simply gives .
More generally, is called the -th moment and the -th central moment. So the expected value is the first moment and the variance the second central moment. The third central moment divided by is the skewness, and the fourth divided by the kurtosis; the division makes both unit-free and independent of scale. The skewness measures how symmetric the distribution is about the expected value. is called the standard deviation of X.
The variance helps us judge how probable a given deviation from the expected value is. The key is an inequality that, to begin with, uses only the expected value:
Let be the indicator function of the event , so 1 on and 0 elsewhere. Then holds pointwise: where the indicator is 1 we have , and where it is 0 we have by assumption. The expected value of an indicator function is the probability of the event – in the discrete case, . By the linearity and monotonicity of the expected value (rules of calculation above),
and dividing by gives the claim.
Markov’s inequality is crude, but it immediately yields the inequality we actually want:
The random variable is non-negative, and by the definition of the variance . Markov’s inequality for with the bound gives
Because , we have exactly when . The two events are therefore the same, and that is the claim.
The special case is trivial: the right-hand side is just 1, and every probability is . The special case with , however, simplifies to
So deviations of have probability , and deviations of only . Measured in multiples of , then, the probability of a deviation that large is roughly inversely proportional to the square – which is just what the inequality above says. That also gives us a criterion for weeding faulty data points out of a dataset: if deviations larger than with turn up more often than expected, then those data points at least do not belong to the distribution we expect.
The most important application of the inequality is to the sample mean itself. With it we can actually prove the law of large numbers from above, in a weaker form and with exactly the tools we now have:
(Weak law of large numbers)
Let be independent and identically distributed like (iid for short; every has the same distribution as ), and let have finite variance. Then for the sample mean and every
By the linearity of the expected value, , since every has the same expected value as . By the rules of calculation for the variance (section Rules of calculation for the variance further down: , and the variance of a sum of independent random variables is the sum of the variances),
Chebyshev’s inequality for now gives , and this expression tends to 0 as .
This is exactly the convergence in probability that we deduced above from the (unproved) strong law of large numbers: the weak law is the form we can prove with the means at hand; the strong law, with its almost sure convergence, needs more machinery but does without the assumption of finite variance.
The weak law is also the law of large numbers with a number attached: the probability of a deviation by more than falls like – or, read differently, the typical error of the sample mean shrinks like . To halve the error you need four times the sample. The bound is crude; the chapter The normal distribution supplies a sharper one with the central limit theorem, and the chapter Statistical tests turns that into the recipe for inferring from sample to population.
In deep learning the true loss of a model is the expected value of the loss function over the distribution of the data, and it cannot be computed, because that distribution is unknown. A mini-batch of a few data points supplies a sample mean of the loss instead: cheap, but with high variance. That is exactly the situation of the weak law of large numbers, and says how much noise a batch of size brings with it. The course Introduction to Deep Learning builds on this (stochastic gradient descent).
Applying the law of large numbers to the random variable shows that the sample standard deviation converges to the standard deviation as well. So the sample standard deviation is a good substitute when the true variance of the random variable cannot be determined.
Interlude: the logarithm¶
The next section computes with logarithms throughout. Since school may be a while ago, here is what you need, in half a page.
For , , the logarithm to base is the inverse of exponentiation: from it follows that , and conversely. It is defined for .
Three bases have names of their own: (the natural logarithm, to base ), (the binary logarithm, also written ) and (the common one).
The logarithm counts orders of magnitude. To base 10 you can read that off directly: and , and because the logarithm is strictly increasing, lies between 2 and 3 for every number between 100 and 1000. The number of decimal digits of a natural number is therefore – and to base 2, likewise, the number of binary digits.
The rules of calculation all follow from and together with the power law :
The last line is the change-of-base formula: logarithms to different bases differ only by a constant factor. That is why the choice of base for the entropy is a question of units, not of substance – to base 2 you measure in bits, to base in nats, and the two differ by the factor .
The number 77 is 10011012 in binary, that is , and so needs 7 binary digits. Check: , and gives the expected 7 digits. Read the other way round: with 7 bits you can distinguish different things, with 6 bits only 64 – too few for 77.
In numpy the three functions are called np.log (natural, not common – a frequent source of errors), np.log2 and np.log10.
Entropy¶
Looking ahead (not part of the course proper): where the word comes from. The notion of entropy comes from thermodynamics, and the physical picture goes a long way towards explaining why the formula below looks the way it does. You do not need this section for the course.
Picture two identical containers with the same number of gas particles in them. In the first the particles are evenly distributed, in the second they are all huddled in one corner.

Figure 1:Evenly distributed particles: high entropy.

Figure 2:All the particles in one corner: low entropy.
The second state surprises us; the first does not. We also know how the story continues: before long the second container will look like the first, while the first will never look like the second. That is the second law of thermodynamics: in a closed system, entropy cannot decrease. A fried egg cannot be turned back into a raw one.
The obvious gloss, “entropy = disorder”, is misleading. More precise is the distinction between macrostate and microstate. The macrostate is what can be measured – temperature, pressure, “all the particles on the left” – and the microstate is the complete specification of where every single particle sits. A macrostate usually comprises an enormous number of microstates, and exactly that number is the measure: the macrostate “evenly distributed” comprises unimaginably more arrangements than the macrostate “all in the top left corner”. Ludwig Boltzmann cast this into the formula
in which is the number of microstates belonging to the given macrostate and a physical constant whose only job is to get the unit right. Put a partition into both containers and the difference becomes tangible:

Figure 3:With a partition: there is roughly the same amount of gas on the left and on the right – this macrostate can be produced in a great many ways.

Figure 4:With a partition: all the gas is on the left – this macrostate admits only a few arrangements.
Entropy is always defined relative to a macrostate. We count the possibilities compatible with what we know, and then take the logarithm.
Carry that sentence over unchanged when you read the definition for random variables in a moment: there the macrostate is the distribution we know, and what gets counted (more precisely, weighted) are the outcomes it allows. The logarithm stays.
Claude Shannon (1916–2001) carried the notion from physics into communications engineering in his 1948 paper A Mathematical Theory of Communication Shannon (1948), with which information theory began as a field of its own. Shannon asked how many bits are needed, at the very least, to transmit a message, and found the same quantity Boltzmann had written down for gas particles. In his honour it is also called the Shannon entropy.
For a discrete probability space and we call the information (also the self-information) of
The base of the logarithm is usually 2, but in the end it does not matter much. For a random variable we can now consider the composition , a real random variable. Its expected value is the average information of , which we also call the entropy
The sum for has a problem: for , is undefined. So we extend the function to 0 by its limit,
(l’Hôpital applied to ) and set . Summands belonging to impossible outcomes then contribute nothing, and the sum effectively runs only over the with . That is the convention behind the sums written “over ” in the chapter Relative entropy.
For a uniform distribution on we always have for , so and hence . This number tells us that on average we need bits to communicate a single outcome of , provided sender and receiver know the distribution; a sample of size then costs bits. There are other distributions for which less information per outcome suffices on average – strictly speaking every other one, in fact, since the uniform distribution has maximal entropy among all discrete distributions. It corresponds to knowing as little as possible and therefore taking all outcomes to be equally probable.
How much information is there in a letter? Count the frequencies of the letters in German texts, put them into the formula, and out comes an entropy of about 4.06 bits per character Fox (2008). For comparison: if all 26 letters were equally probable it would be bits. The difference is exactly what the unequal frequencies of “e” and “x” save.
Take into account which letters have gone before as well, and the value drops to about 1.5 bits per letter – after “sch” the next letter is hardly a surprise. Language, then, is highly redundant, which is why text compresses so well and why you can still understand a sentence with half of it missing.
What that means in practice shows up in guessing. A random string of length 10 over the alphabet, say pashglwnmv, carries bits – guessing it takes on the order of 247 attempts. If the guesser knows instead that it is a German word, say kabelkanal, that is only bits, or attempts. That is the difference between “practically impossible” and “done in a second”, and it comes not from the length of the string but from what the guesser knows about it.
This very argument is at the heart of one of the best-known comics on security:

Figure 5:Randall Munroe, xkcd 936 “Password Strength” (CC BY-NC 2.5)
The password Tr0ub4dor&3 looks complicated, but it was built by a procedure an attacker knows (a word, a few of the usual substitutions, a digit, a special character) – it carries around 28 bits. Four randomly chosen words such as correct horse battery staple carry around 44 bits, so they are about times harder to guess – and easier to remember into the bargain.
The lesson is the same as in the previous example: entropy depends not on how the outcome looks but on the procedure that produced it. A password is secure not because it looks cryptic but because the set of passwords it could have come from is large. That is why the question “how strong is this password?” strictly speaking has no answer for a single password – what can be answered is how strong the procedure is.
At the other end of the scale stands the Dirac distribution: if for a single and for all the others, then and hence (the summands with fall under the convention from above). That is the smallest possible value, since is a sum of non-negative terms. On a finite set , then, we always have , with the minimum attained exactly by the Dirac distributions (there are of them, one per element) and the maximum only by the uniform distribution.
Entropy is best understood as a relative quantity, and that is how we shall treat it later on. In the rest of the course it turns up in two places: in setting up statistical models – the maximum entropy principle in the chapter The normal distribution and the closely related maximum likelihood principle in the chapter Statistical models and estimators – and in assessing how good a model is, where the tools are cross-entropy and relative entropy in the chapter Relative entropy.
Independence¶
In general it makes a real difference whether a family is independent or only pairwise independent, which is why the definition in terms of families matters.
Independent: two dice. We throw two fair six-sided dice. As the probability space we take with the uniform distribution, so 36 equally probable outcomes . Let be the event “the first die shows an even number” and the event “the second die shows a six”. Then
For the intersection we count rather than use a formula: , so . And indeed , so the two events are independent.
That we counted matters: had we computed as a product straight away, we would have assumed independence instead of checking it. Here it is obvious anyway, since and refer to different dice.
Dependent: sweets without replacement. There are three sweets in a bag: a red one, a green one and a blue one. We draw two of them one after the other, without putting the first back. The probability space is the set of the 6 ordered pairs of distinct colours,
again with the uniform distribution. Let be the event “the first sweet is red” and the event “the second sweet is green”. Then with and with . The intersection contains just one outcome, , so
The two events are therefore not independent. That makes sense too: if the red sweet was drawn first, only green and blue are left, and green has suddenly become more probable on the second draw – up from to . That number gets a name further down: it is the conditional probability .
Drawing without replacement is random.sample in Python, drawing with replacement random.choices (see Programming with stochastics) – the difference between the two functions is exactly the difference between dependent and independent.
Let be a probability space. A family of random variables , , is called independent if for arbitrary events the family is independent in .
For two random variables this reads as follows: and are independent exactly when
holds for all events . The left-hand side is shorthand for – so it is not about and separately but about the pair , understood as one random variable with values in . Its distribution is called the joint distribution of and ; we define it formally in the chapter Covariance and dependence.
The direction matters: the joint distribution is the real information, and the distributions of and separately follow from it. The other way round does not work – from the individual distributions alone the joint one generally cannot be reconstructed. That is exactly what independence says: it is the extra assumption under which the product of the two pmfs is the joint pmf.
For and each discrete, are independent exactly when for all outcomes :
Another notion comes up very often in this connection:
Clearly, for , and are independent of each other exactly when . In the sweets example above, , which is not – that is what dependence looks like in numbers. Conditional probabilities therefore come up (or rather, become interesting) precisely when two events, or two random variables, are not independent.
Independence is an all-or-nothing property; in real data the more interesting question is how strongly two quantities are related. We will meet two measures for that, and it is worth keeping them apart from the start.
The first is the covariance and the correlation coefficient formed from it (chapter Covariance and dependence). It measures linear relationships. Independence implies that the covariance is 0 – but not conversely: two quantities can depend on each other perfectly and still be uncorrelated, for instance and for symmetrically distributed . So “correlated” is a stronger statement than “dependent”, and “uncorrelated” a weaker one than “independent”.
The second measure captures dependence of any shape: the relative entropy between the joint distribution and the product of the individual distributions, also called transinformation or mutual information (chapter Relative entropy). It is 0 exactly when the two random variables are independent – so it really does measure dependence and not just its linear part. The price: you need the joint distribution, and estimating that is considerably more work than computing a covariance.
Rules of calculation for the variance¶
The expected value is linear; the variance is not. Instead, the following two rules hold, and we will need them constantly in the next chapter.
Let be a random variable with finite variance.
For , .
If and are independent, then . More generally, for pairwise independent ,
(1) By the linearity of the expected value, , so
and hence . In particular, a shift by does not change the variance.
(2) We expand and use linearity:
If and are independent, the bracketed expression equals 0 by the product rule. The general case follows the same way: expand, and all the mixed terms with vanish – pairwise independence is enough for that (chapter Covariance).
The term that has just vanished is an interesting quantity in its own right: it is called the covariance of and , and it measures how strongly the two variables are linearly related. In the chapter Covariance we put it under the microscope and prove the rule once more there, in its general form, without the assumption of independence.
Rule (2) is why the variance of a sum of independent repetitions of the same experiment is so easy to compute – we use that in the chapter The most important discrete distributions for the binomial distribution.
- Shannon, C. E. (1948). A Mathematical Theory of Communication. The Bell System Technical Journal, 27, 379–423, 623–656.
- Fox, D. (2008). Entropie. Datenschutz Und Datensicherheit (DuD), 32, 543.