Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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 v,w∈Rnv,w \in \mathbb{R}^n (think of vv as our data and ww as what we expect), the natural quantity to look at is the mean deviation ∑i=1nvi−win\sum_{i=1}^n \frac{v_i - w_i}{n}. The trouble with it is that positive and negative deviations cancel each other out.

Absolute deviation

The sum without the factor 1n\frac1n is the 1-norm of the difference,

d1(v,w):=∑i=1n∣vi−wi∣=∥v−w∥1=n⋅mae(v,w),d_1(v,w) := \sum_{i=1}^n \left| v_i - w_i \right| = \left\| v - w \right\|_1 = n \cdot \texttt{mae}(v,w),

and the factor 1n\frac1n in the definition is exactly what makes mae\texttt{mae} independent of the length of the vector: d1d_1 grows with nn even when the model is no worse, mae\texttt{mae} 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 L0L_0, L1L_1 and L2L_2 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 vv, is which vector ww has the smallest mean absolute error. Without further conditions on ww, though, the answer is immediate: w=vw=v. We will come back to this question later; for now we content ourselves with asking which c∈Rc \in \mathbb{R} minimises mae(v,c)\texttt{mae}(v,c). Graphically: put the numbers from 1 to nn on the xx-axis and plot the values viv_i above them. A choice of c∈Rc \in \mathbb{R} 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 c∈Rc \in \mathbb{R} at which mae(v,c)\texttt{mae}(v,c) is minimal. That is, for all cc we have mae(v,c)≥mae(v,median(v))\texttt{mae}(v,c) \geq \texttt{mae}(v,\texttt{median}(v)). 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 cc, it plays no part in finding the minimum. Applying this inductively, all that remains is to determine mae(v,c)\texttt{mae}(v,c) for vectors of length 1 and 2. We have mae((v1),c)=∣v1−c∣\texttt{mae}((v_1),c) = |v_1 - c|, which is minimal for c=v1c = v_1, and mae((v1,v2),c)=v2−v12\texttt{mae}((v_1,v_2),c) = \frac{v_2 - v_1}{2}, which is minimal for every cc between v1v_1 and v2v_2. 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 median((v1,v2))=v1+v22\texttt{median}((v_1,v_2)) = \dfrac{v_1+v_2}{2}, and that is what we will do from here on. Convince yourself that for every cc with a≤c≤ba \leq c \leq b the mean distance to (a,b)(a,b) is b−a2\frac{b-a}{2}, so the vector v=(a,b)v = (a,b) 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 1n\frac1n is a norm, this time the squared 2-norm:

d2(v,w)2:=∑i=1n(vi−wi)2=∥v−w∥22=n⋅mse(v,w).d_2(v,w)^2 := \sum_{i=1}^n {\left( v_i - w_i \right)}^2 = \left\| v - w \right\|_2^2 = n \cdot \texttt{mse}(v,w).

Compared with mae\texttt{mae}, the mse\texttt{mse} 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 w=mean(v)w = \texttt{mean}(v) 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 v∈Rnv \in \mathbb{R}^n carries information for us depends on how much we already know about vv. If we know, for example, that vv is a sample of a random variable uniformly distributed on {0,1}\{0,1\}, we will not be surprised when vv looks like one. Every entry of vv corresponds to exactly one bit of information. Suppose instead that the random variable is not uniform but follows, on the numbers {1,…,26}\{1,\dots, 26\}, the frequency of the letters of the German language, say (with 1 for “a”, 26 for “z” and so on). Then an entry of vv 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: mean(v)\texttt{mean}(v) is a number that comes from nn 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 XX be a random variable with finitely many values y1,…,yky_1,\dots,y_k and distribution p=(p1,…,pk)p = (p_1,\dots,p_k), so pj=P(X=yj)p_j = P(X = y_j). Suppose for a moment that the pjp_j are rational numbers with a common denominator NN, say pj=ajNp_j = \frac{a_j}{N} with a1+⋯+ak=Na_1 + \dots + a_k = N. Then there is a sample of size NN that hits this distribution exactly: the one in which the value yjy_j occurs precisely aja_j times. We call it the idealised sample D~\tilde{D} for pp – 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:

mean(D~)=1N∑j=1kajyj=∑j=1kajNyj=∑j=1kpjyj.\texttt{mean}(\tilde{D}) = \dfrac{1}{N} \sum_{j=1}^k a_j y_j = \sum_{j=1}^k \dfrac{a_j}{N} y_j = \sum_{j=1}^k p_j y_j.

On the right there is no sample any more, only the distribution. With that, the assumption that the pjp_j are rational has become superfluous too: the right-hand side makes sense for every distribution, and the detour through D~\tilde{D} served only to find the formula. This quantity is exactly what we call the expected value of XX.

The special case k=1k = 1 is the acid test: a distribution that takes a single value y1y_1 with probability 1 – the Dirac measure δy1\delta_{y_1} from the chapter The formalism of stochastics – has the idealised sample (y1,…,y1)(y_1,\dots,y_1) and so the expected value y1y_1. 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 Ω\Omega 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 XX, weighted by the probabilities.

For finite Ω\Omega the sum is finite and always exists. If Ω\Omega 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 Ω={1,2,3,… }\Omega = \{1, 2, 3, \dots\}, P({k}):=6π2k2P(\{k\}) := \frac{6}{\pi^2 k^2} defines a probability measure (because ∑k≥11k2=π26\sum_{k \geq 1} \frac{1}{k^2} = \frac{\pi^2}{6}), and for X(k):=kX(k) := k the series ∑k≥1k⋅6π2k2=6π2∑k≥11k\sum_{k \geq 1} k \cdot \frac{6}{\pi^2 k^2} = \frac{6}{\pi^2} \sum_{k \geq 1} \frac{1}{k} is the harmonic series, which diverges. This random variable has no expected value.

What we can say is this: if XX takes only finitely many values, then not only does the expected value exist but so do all the higher moments E(Xk)\mathbb{E}(X^k) – 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 kk tosses, 2k2^k euros are paid out. The probability of that is 2−k2^{-k}, so the expected value is ∑k≥12k⋅2−k=∑k≥11=∞\sum_{k \geq 1} 2^k \cdot 2^{-k} = \sum_{k \geq 1} 1 = \infty. 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 ff takes the place of the sum: E(X)=∫xf(x) dx\mathbb{E}(X) = \int x f(x)\,dx. 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:

PP-almost sure convergence also implies convergence in probability: lim⁡n→∞P(∣Xn∗‾∣≥ϵ)=lim⁡n→∞P(∣Xn‾−EX∣≥ϵ)=0\lim_{n\to\infty} P\left(|\overline{X_n^\ast}| \geq \epsilon \right) = \lim_{n\to\infty} P\left(|\overline{X_n} - \mathbb{E}X| \geq \epsilon \right) = 0 for every ϵ>0\epsilon > 0.

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 ϵ>0\epsilon > 0 there is a sample size nn such that the sample mean of a randomly drawn sample almost always deviates from the expected value by less than ϵ\epsilon.

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 nn – so the detour was no detour.

We have not yet explained what independent means (independently of the pmfs in the discrete case); that comes further down.

Variance

This is the counterpart of the shortcut formula rmse(v)2=mean(v2)−mean(v)2\texttt{rmse}(v)^2 = \texttt{mean}(v^2) - \texttt{mean}(v)^2 for samples above. For a centred random variable, one with E(X)=0\mathbb{E}(X) = 0, this simply gives V(X)=E(X2)\mathbb{V}(X) = \mathbb{E}(X^2).

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:

Markov’s inequality is crude, but it immediately yields the inequality we actually want:

The special case c=σc=\sigma is trivial: the right-hand side is just 1, and every probability is ≤1\leq 1. The special case c=kσc = k\sigma with k∈Nk \in \mathbb{N}, however, simplifies to

P(∣X−EX∣≥kσ)≤1k2.P\left( | X - \mathbb{E} X | \geq k\sigma \right) \leq \dfrac{1}{k^2}.

So deviations of 2σ2\sigma have probability ≤14\leq \frac{1}{4}, and deviations of 3σ3\sigma only ≤19\leq \frac{1}{9}. Measured in multiples of σ\sigma, 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 kσk\sigma with k>1k > 1 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:

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 cc falls like 1/n1/n – or, read differently, the typical error of the sample mean shrinks like 1/n1/\sqrt{n}. 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.

Applying the law of large numbers to the random variable (X−E(X))2{\left(X-\mathbb{E}(X)\right)}^2 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.

The logarithm counts orders of magnitude. To base 10 you can read that off directly: log⁡10(100)=2\log_{10}(100) = 2 and log⁡10(1000)=3\log_{10}(1000) = 3, and because the logarithm is strictly increasing, log⁡10(y)\log_{10}(y) lies between 2 and 3 for every number yy between 100 and 1000. The number of decimal digits of a natural number yy is therefore ⌊log⁡10(y)⌋+1\lfloor \log_{10}(y) \rfloor + 1 – and to base 2, likewise, the number of binary digits.

The rules of calculation all follow from eln⁡(y)=ye^{\ln(y)} = y and ln⁡(ex)=x\ln(e^x) = x together with the power law (eu)v=euv(e^u)^v = e^{uv}:

bx=(eln⁡b)x=eln⁡(b) x,ln⁡(bx)=xln⁡(b),ln⁡(y)=ln⁡(blog⁡b(y))=ln⁡(b)log⁡b(y),solog⁡b(y)=ln⁡(y)ln⁡(b).\begin{aligned} b^x &= \left( e^{\ln b} \right)^x = e^{\ln(b)\, x}, \\ \ln\left( b^x \right) &= x \ln(b), \\ \ln(y) &= \ln\left( b^{\log_b(y)} \right) = \ln(b) \log_b(y), \\ \text{so}\quad \log_b(y) &= \dfrac{\ln(y)}{\ln(b)}. \end{aligned}

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 ee in nats, and the two differ by the factor ln⁡(2)≈0.693\ln(2) \approx 0.693.

In numpy the three functions are called np.log (natural, not common – a frequent source of errors), np.log2 and np.log10.

Entropy

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.

This very argument is at the heart of one of the best-known comics on security:

Randall Munroe, xkcd 936 “Password Strength” (CC BY-NC 2.5)

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 216≈65,0002^{16} \approx 65{,}000 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 P({ξ})=1P(\{\xi\}) = 1 for a single ξ∈Ω\xi \in \Omega and P({ω})=0P(\{\omega\}) = 0 for all the others, then I(ξ)=−log⁡2(1)=0I(\xi) = -\log_2(1) = 0 and hence H(X)=0H(X) = 0 (the summands with P({ω})=0P(\{\omega\}) = 0 fall under the convention 0log⁡0=00\log 0 = 0 from above). That is the smallest possible value, since H(X)H(X) is a sum of non-negative terms. On a finite set Ω\Omega, then, we always have 0≤H(X)≤log⁡2∣Ω∣0 \leq H(X) \leq \log_2|\Omega|, with the minimum attained exactly by the Dirac distributions (there are ∣Ω∣|\Omega| 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.

Another notion comes up very often in this connection:

Clearly, for P(B)>0P(B) > 0, AA and BB are independent of each other exactly when P(A∣B)=P(A)P(A | B) = P(A). In the sweets example above, P(B∣A)=P(A∩B)P(A)=1/61/3=12P(B \mid A) = \frac{P(A \cap B)}{P(A)} = \frac{1/6}{1/3} = \frac12, which is not P(B)=13P(B) = \frac13 – 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.

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.

The term E(XY)−E(X)E(Y)\mathbb{E}(XY) - \mathbb{E}(X)\mathbb{E}(Y) that has just vanished is an interesting quantity in its own right: it is called the covariance of XX and YY, 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.

References
  1. Shannon, C. E. (1948). A Mathematical Theory of Communication. The Bell System Technical Journal, 27, 379–423, 623–656.
  2. Fox, D. (2008). Entropie. Datenschutz Und Datensicherheit (DuD), 32, 543.