Appendix CSolutions to the Exercises
This appendix collects complete solutions to the end-of-chapter exercises. Before reading a solution, please be sure to work through the problem yourself at least once. If you get stuck along the way, go back to the hints at the end of the chapter and the worked examples in the text, and then read the solution here. From the end of each chapter’s solutions you can return to that chapter.
Chapter 1 What Is Machine Learning? — Learning Rules from Data
Exercise 1.1: Fitting a line to three points
Solution
(1) For the candidate $(w_0,w_1)=(1,1)$, the predicted values at $x=0,1,2$ are $1,2,3$, and the residuals are $1-1=0$, $2-2=0$, $4-3=1$. The sum of the squared residuals is $0+0+1=1$, so $L=\tfrac12\times1=0.5$. For the candidate $(0,2)$, the predicted values are $0,2,4$ and the residuals are $1,0,0$. The sum of squares is 1, so this one also gives $L=0.5$. The loss cannot distinguish the two lines.
(2) We compute the sums. $N=3$, $\sum x_n=0+1+2=3$, $\sum x_n^{2}=0+1+4=5$, $\sum y_n=1+2+4=7$, $\sum x_ny_n=0\times1+1\times2+2\times4=10$. The normal equations, Eq. (1.5) of Chapter 1, are
$$ 3w_0+3w_1=7,\qquad 3w_0+5w_1=10 . $$Subtracting the first equation from the second gives $2w_1=3$, so $\hat{w}_1=1.5$. Substituting back into the first equation gives $3w_0=7-4.5=2.5$, so $\hat{w}_0=5/6\approx0.833$. The predicted values at $x=0,1,2$ are $5/6,\ 7/3,\ 23/6$, and the residuals are $1-5/6=1/6$, $2-7/3=-1/3$, $4-23/6=1/6$. The sum of squares is $1/36+4/36+1/36=6/36=1/6$, so the minimum loss is $L=\tfrac12\times\tfrac16=\tfrac1{12}\approx0.0833$. This is smaller than the value 0.5 of the two lines in (1).
(3) Dividing the first normal equation, $Nw_0+\bigl(\sum_n x_n\bigr)w_1=\sum_n y_n$, by $N$ gives $w_0+\bar{x}w_1=\bar{y}$; that is,
$$ \hat{w}_0=\bar{y}-\hat{w}_1\bar{x}. $$Substitute this into the second equation, $\bigl(\sum_n x_n\bigr)w_0+\bigl(\sum_n x_n^{2}\bigr)w_1=\sum_n x_ny_n$. Using $\sum_n x_n=N\bar{x}$, we obtain
$$ \begin{aligned} &N\bar{x}(\bar{y}-w_1\bar{x})+\Bigl(\sum_n x_n^{2}\Bigr)w_1\\ &\qquad=\sum_n x_ny_n,\\ &\Bigl(\sum_n x_n^{2}-N\bar{x}^{2}\Bigr)w_1\\ &\qquad=\sum_n x_ny_n-N\bar{x}\bar{y}. \end{aligned} $$Here the expressions in parentheses on the right-hand and left-hand sides can be rewritten as sums of deviations from the mean.
$$ \begin{aligned} &\sum_n(x_n-\bar{x})(y_n-\bar{y})\\ &\quad=\sum_n x_ny_n-\bar{y}\sum_n x_n\\ &\qquad-\bar{x}\sum_n y_n+N\bar{x}\bar{y}\\ &\quad=\sum_n x_ny_n-N\bar{x}\bar{y}\\ &\qquad-N\bar{x}\bar{y}+N\bar{x}\bar{y}\\ &\quad=\sum_n x_ny_n-N\bar{x}\bar{y}. \end{aligned} $$The same calculation with $y_n$ replaced by $x_n$ gives $\sum_n(x_n-\bar{x})^{2}=\sum_n x_n^{2}-N\bar{x}^{2}$. Therefore, when the inputs are not all equal (so that the denominator is not 0),
$$ \hat{w}_1=\frac{\sum_n(x_n-\bar{x})(y_n-\bar{y})}{\sum_n(x_n-\bar{x})^{2}}. $$We check this with the numbers from (2). $\bar{x}=1$, $\bar{y}=7/3$, and the deviations are $-1,0,1$ for $x$ and $-4/3,-1/3,5/3$ for $y$. The numerator $=4/3+0+5/3=3$ and the denominator $=2$, so $\hat{w}_1=1.5$ and $\hat{w}_0=7/3-1.5=5/6$, which agrees.
Exercise 1.2: Classifying materials tasks
Solution
(1) Regression, supervised. The output is a numerical value, the hardness, and learning requires pairs of composition and heat-treatment conditions with the measured hardness.
(2) Classification (two classes), supervised. The experts’ judgments serve as the target values (labels). The number 300 is small for image classification, so one must watch out for overfitting.
(3) Clustering in a latent representation, unsupervised. The correct groups are not given; the groups are found from the distribution of the structural descriptors. The number of groups must also be decided from the data and the purpose.
(4) The stage of predicting the hidden word is self-supervised learning. The target value (the hidden word) is made from the text itself, and no person attaches labels. The task at this stage is a classification problem: deciding which word of the vocabulary it is. The subsequent stage, which takes the learned representation as input and predicts a physical property, uses labels of the property values and is supervised regression (or classification).
(5) Density estimation, unsupervised. The output is the distribution of the capacitance, and one computes the area (probability) outside the specification. When only a few units are out of specification, the assumption about the shape of the tail of the distribution (a Gaussian distribution or a heavy-tailed distribution) strongly affects the result.
Exercise 1.3: Extending from three points
Solution
The three points are $s=-1,-0.5,0$ with $y=74.2,81.4,87.3\ \%$. The means are $\bar{s}=-0.5$ and $\bar{y}=(74.2+81.4+87.3)/3$ $=242.9/3=80.967\ \%$. The deviations from the mean are $-0.5,0,0.5$ for $s$ and $-6.767,0.433,6.333$ for $y$.
$$ \begin{aligned} &\sum_n(s_n-\bar{s})(y_n-\bar{y})\\ &\quad=(-0.5)(-6.767)+0+(0.5)(6.333)\\ &\quad=6.55,\\ &\sum_n(s_n-\bar{s})^{2}=0.25+0+0.25=0.5 . \end{aligned} $$Hence $\hat{w}_1=6.55/0.5=13.1\ \%$ and $\hat{w}_0=\bar{y}-\hat{w}_1\bar{s}$ $=80.967+13.1\times0.5=87.517\ \%$.
At 1400 °C ($s=0.5$): $\hat{y}=87.517+6.55=94.07\ \%$ (observed 92.6 %, difference $+1.47$ %). At 1500 °C ($s=1$): $\hat{y}=87.517+13.1=100.62\ \%$ (observed 91.4 %, difference $+9.22$ %).
The prediction reaches 100 % when $87.517+13.1s=100$, that is, $s=12.483/13.1=0.953$, which in temperature is $T=1300+200\times0.953=1490.6$ °C. At temperatures higher than this, the prediction for the relative density exceeds 100 %, which is physically impossible. The causes are (a) that the three points at 1100–1300 °C contain no information that the densification levels off (extrapolation), and (b) that the form of the model, a straight line, does not contain the physical constraint that the relative density cannot exceed 100 %. Even in the true function of Data A, the relative density has its maximum at about 1425 °C ($s\approx0.62$) and decreases at higher temperatures.
Exercise 1.4: The number of pairs in self-supervised learning
Solution
(1) A sentence of $T$ words gives $T-1$ pairs, so $(6-1)+(9-1)+(12-1)$ $=5+8+11=24$ pairs.
(2) When predicting the 12th word, the input would originally be words 1 through 11, but since the context length is four words, only the four immediately preceding words (words 8 through 11) become the input. The target value remains the 12th word. The words that serve as target values (words 2 through 12) do not change, so the number of pairs stays at $12-1=11$. What changes is that the input of each pair is truncated to “at most the four preceding words,” so information from five or more words back can no longer be used.
(3) The target values are supplied by the text itself (no person attaches labels). What it shares with supervised learning: there are pairs of inputs and target values, and the mismatch between prediction and target value is minimized as a loss (a classification that picks the next word from the vocabulary). What it shares with unsupervised learning: it uses no labels given from outside and learns the distribution of the data itself (here, the way the words of the text are ordered). The difference is that in supervised learning the target values are prepared separately by experiments or human judgment, whereas in self-supervised learning the target values are created automatically by hiding a part of the data.
Exercise 1.5: The squared loss and the absolute-value loss
Solution
(1) Differentiating $L_2(w)=\tfrac12\sum_n(y_n-w)^{2}$ with respect to $w$ by the chain rule gives
$$ \begin{aligned} \diff{L_2}{w}&=\frac12\sum_{n=1}^{N}2(y_n-w)\times(-1)\\ &=-\sum_{n=1}^{N}(y_n-w)=-\sum_{n=1}^{N}y_n+Nw . \end{aligned} $$Setting this equal to 0 gives $w=\frac1N\sum_n y_n=\bar{y}$ (the sample mean). The second derivative is $N\gt0$, so this is the minimum. The value is $(95.1+95.4+94.8+95.2+89.0)/5$ $=469.5/5$ $=93.9\ \%$.
(2) $\abs{y_n-w}$ equals $y_n-w$ when $w\lt y_n$ (its derivative with respect to $w$ is $-1$), and $w-y_n$ when $w\gt y_n$ (its derivative is $+1$). Writing $N_{\lt}(w)$ for the number of $y_n$ smaller than $w$ and $N_{\gt}(w)$ for the number of $y_n$ larger than $w$, at any point where $w$ coincides with none of the data values we have
$$ \begin{aligned} \diff{L_1}{w}&=N_{\lt}(w)\times(+1)+N_{\gt}(w)\times(-1)\\ &=N_{\lt}(w)-N_{\gt}(w). \end{aligned} $$Arranging the values in increasing order gives $89.0,\ 94.8,\ 95.1,\ 95.2,\ 95.4$. When $w$ lies between $94.8$ and $95.1$, there are two smaller values and three larger ones, so the slope is $2-3=-1$ ($L_1$ decreases as $w$ increases). When $w$ lies between $95.1$ and $95.2$, there are three smaller values and two larger ones, so the slope is $+1$ (it increases as the variable increases). $L_1$ is a piecewise linear function, and it is minimized at $w=95.1\ \%$, where the slope changes from negative to positive. This is the middle value of the five, that is, the median. In general, the slope changes from negative to positive where the number of smaller values and the number of larger values balance, so the minimum point is the median (when the number of values is even, the minimum is attained anywhere between the two middle values).
(3) The mean of the four runs excluding the one outlier is $(95.1+95.4+94.8+95.2)/4$ $=380.5/4=95.125\ \%$. The median, 95.1 %, nearly agrees with this, but the mean, 93.9 %, is dragged down by the single outlier and is lower by more than 1.2 %. The squared loss penalizes large deviations more heavily, so it amounts to assuming that “the errors are small and uniform, and extreme outliers are rare” (as we will see in Chapter 8, this corresponds to the assumption that the errors follow a Gaussian distribution). The absolute-value loss is robust to outliers and suits data in which “values that occasionally deviate greatly” appear. Choosing a loss is choosing an assumption about the errors in the data.
Exercise 1.6: The curvature of the band gap and descriptors
Solution
(1) We use $E_g(x)=1.20+0.40x+0.80x^{2}$ obtained in Example 1.6 of Chapter 1. $E_g(0)=1.20\ \mathrm{eV}$, $E_g(0.5)=1.20+0.20+0.20=1.60\ \mathrm{eV}$, $E_g(1)=1.20+0.40+0.80=2.40\ \mathrm{eV}$.
(2) $\bar{x}=0.5$ and $\bar{E}=(1.20+1.60+2.40)/3$ $=5.20/3=1.7333\ \mathrm{eV}$. The deviations are $-0.5,0,0.5$ for $x$ and $-0.5333,-0.1333,0.6667$ for $E$.
$$ \begin{aligned} \text{numerator}&=(-0.5)(-0.5333)+0\times(-0.1333)\\ &\quad+(0.5)(0.6667)=0.6\ \mathrm{eV},\\ \text{denominator}&=0.25+0+0.25=0.5,\\ \hat{w}_1&=\frac{0.6}{0.5}=1.20\ \mathrm{eV}, \end{aligned} $$$\hat{w}_0=1.7333-1.20\times0.5=1.1333\ \mathrm{eV}$. The predicted values at $x=0,0.5,1$ are $1.1333,\ 1.7333,\ 2.3333\ \mathrm{eV}$, and the residuals are $1.20-1.1333=+0.0667$, $1.60-1.7333=-0.1333$, $2.40-2.3333=+0.0667\ \mathrm{eV}$.
(3) The largest residual is $0.133\ \mathrm{eV}$, about 4.4 times the standard deviation of the error, $0.03\ \mathrm{eV}$. Moreover, the residuals have a regular pattern: “positive at both ends, negative in the middle.” This cannot be explained by observation error alone, so the linear model is insufficient (the form of the model cannot express the curvature of the true relationship).
(4) The model $w_0+w_1x+w_2x^{2}$, with $x^{2}$ added to the descriptors, agrees with the true relationship at $(w_0,w_1,w_2)=(1.20,\ 0.40,\ 0.80)\ \mathrm{eV}$, and the residuals at the three points all become 0. However, with three parameters for three points, any three points can be passed through with zero residual. Since actual measured values have an error of 0.03 eV, to check whether the model is correct one must measure sufficiently more points than the number of parameters and look at whether any regular pattern remains in the residuals.
Exercise 1.7: Repeated measurements and data leakage
Solution
(1) Fix one row of interest among the 12 test rows. The remaining 11 test rows are then chosen with equal probability from the 59 rows other than that row. The probability that both of the other two rows of the same sample go into the test set is 11/59 for the first, and, given that it went in, 10/58 for the second, so
$$ \frac{11}{59}\times\frac{10}{58}=\frac{110}{3422}\approx0.032 . $$Therefore about $1-0.032=0.968$ (97 %) of the test rows have at least one measurement of the same sample among the training rows.
(2) The nearest row is, in most cases, another measurement of the same sample. The model merely returns that value, so the test error is almost equal to “the scatter when the same sample is measured again” (the repeatability error of the measurement). This is not the prediction error for a new sample (a material not yet made), which is much larger. The evaluation becomes optimistic, and data leakage has occurred.
(3) Split by sample, not by row. For example, of the 20 samples, put four (12 rows) in the test set and 16 (48 rows) in the training set, and always put the three rows of the same sample on the same side (a group-wise split; Chapter 6). Furthermore, if samples from the same raw-material lot or the same firing batch are also similar to one another, splitting by lot or by batch gives a more honest estimate of the prediction error for a new lot.
Exercise 1.8: The boundary between exploration and exploitation
Solution
(1) $\mathrm{UCB}(2.2)=-4.00+0.05\kappa$ and $\mathrm{UCB}(6.0)=-4.20+0.40\kappa$. They are equal when $-4.00+0.05\kappa=-4.20+0.40\kappa$, that is, $0.20=0.35\kappa$, so $\kappa=4/7\approx0.571$. If $\kappa\lt4/7$, $x=2.2$ is chosen; if $\kappa\gt4/7$, $x=6.0$ is chosen.
(2) $\mathrm{UCB}(9.0)=-4.70+0.30\kappa$. The difference from $x=6.0$ is
$$ \begin{aligned} &\mathrm{UCB}(6.0)-\mathrm{UCB}(9.0)\\ &\quad=(-4.20+4.70)+(0.40-0.30)\kappa\\ &\quad=0.50+0.10\kappa\gt0 \end{aligned} $$which is positive for every value $\kappa\ge0$. Since $x=9.0$ is inferior to $x=6.0$ both in the mean and in the width, it is never chosen, however $\kappa$ is selected.
(3) The observed value $-3.95$ was higher than the predicted mean $-4.20$. When this observation is incorporated by Bayesian inference, the predicted mean at $x=6.0$ is pulled up toward the observed value (the standard deviation of the observation error, 0.05, is much smaller than the predictive width, 0.40, so the mean moves to nearly $-3.95$), and the predictive standard deviation shrinks greatly (to about the same size as the observation error). At dopant amounts near $x=6.0$ as well, the mean rises and the width shrinks. As a result, the prospect that the large peak lies in this neighborhood grows stronger, and at the next measurement the chance increases that a not-yet-measured point around 6.0 mol% is chosen. The concrete numbers can be computed with Gaussian process regression (Chapter 12).
← Back to Chapter 1, “What Is Machine Learning? — Learning Rules from Data”
Chapter 2 Probability, Expectation, and Conditional Probability — Tools for Counting Uncertainty
Exercise 2.1: Firing atmosphere and cracking
Solution
Let the atmosphere be $x\in\{\text{air},\text{Ar}\}$ and the cracking be $y\in\{\text{cracked},\text{intact}\}$. There are 50 samples fired in air (15 cracked, 35 intact), 100 fired in Ar (10 cracked, 90 intact), and 150 in total.
(1) Divide the counts by 150.
| Cracked | Intact | $p(x)$ | |
|---|---|---|---|
| Air | $15/150=0.100$ | $35/150\approx0.233$ | $50/150=1/3$ |
| Ar | $10/150\approx0.067$ | $90/150=0.600$ | $100/150=2/3$ |
| $p(y)$ | $25/150=1/6$ | $125/150=5/6$ | 1 |
(2) By the sum rule, $p(\text{cracked})=0.100+0.067$ $=25/150=1/6\approx0.167$. By the definition of conditional probability,
$$ \begin{aligned} p(\text{cracked}\mid\text{air})&=\frac{p(\text{air},\text{cracked})}{p(\text{air})}\\ &=\frac{15/150}{50/150}=\frac{15}{50}=0.30,\\ p(\text{air}\mid\text{cracked})&=\frac{15/150}{25/150}=\frac{15}{25}=0.60 . \end{aligned} $$(3) We have $p(\text{air},\text{cracked})=0.100$, whereas $p(\text{air})\,p(\text{cracked})=\tfrac13\times\tfrac16=\tfrac1{18}\approx0.056$, so they do not agree. Therefore the two are not independent. In terms of conditional probabilities as well, $p(\text{cracked}\mid\text{air})=0.30$ and $p(\text{cracked}\mid\text{Ar})=10/100=0.10$, so the probability of cracking changes with the atmosphere.
(Supplement) In a 2×2 table, if $p(x,y)=p(x)p(y)$ holds in one cell, it holds in the others as well. For example, if it holds in the air–cracked cell, then by the sum rule
$$ \begin{aligned} p(\text{air},\text{intact})&=p(\text{air})-p(\text{air},\text{cracked})\\ &=p(\text{air})-p(\text{air})\,p(\text{cracked})\\ &=p(\text{air})\bigl(1-p(\text{cracked})\bigr)\\ &=p(\text{air})\,p(\text{intact}) \end{aligned} $$(and likewise for the other two cells).
Exercise 2.2: Judging a secondary phase with two kinds of analysis
Solution
Let $z\in\{\text{present},\text{absent}\}$ denote the presence or absence of a secondary phase, $x_1$ the XRD judgment, and $x_2$ the SEM–EDS judgment ($+$ means “detected”). We have $p(\text{present})=0.10$, $p(x_1=+\mid\text{present})=0.80$, $p(x_1=+\mid\text{absent})=0.10$, $p(x_2=+\mid\text{present})=0.90$, and $p(x_2=+\mid\text{absent})=0.02$.
(1) By Bayes’s theorem,
$$ \begin{aligned} &p(\text{present}\mid x_1=+)\\ &=\frac{0.80\times0.10}{0.80\times0.10+0.10\times0.90}\\ &=\frac{0.080}{0.080+0.090}=\frac{0.080}{0.170}\approx0.471 . \end{aligned} $$(2) By conditional independence, $p(x_1=+,x_2=+\mid z)$ $=p(x_1=+\mid z)\,p(x_2=+\mid z)$, so
$$ \begin{aligned} &p(\text{present}\mid +,+)\\ &=\frac{0.80\times0.90\times0.10}{0.80\times0.90\times0.10+0.10\times0.02\times0.90}\\ &=\frac{0.0720}{0.0720+0.0018}=\frac{0.0720}{0.0738}\approx0.976 . \end{aligned} $$Using the result of (1), $q_1=0.4706$ ($0.080/0.170$), as the prior probability and updating with the SEM–EDS result gives the same value:
$$ \begin{aligned} \frac{0.90\,q_1}{0.90\,q_1+0.02\,(1-q_1)}&=\frac{0.4235}{0.4235+0.0106}\\ &\approx0.976 . \end{aligned} $$(3) Since $p(x_2=-\mid\text{present})=0.10$ and $p(x_2=-\mid\text{absent})=0.98$,
$$ \begin{aligned} &p(\text{present}\mid +,-)\\ &=\frac{0.80\times0.10\times0.10}{0.80\times0.10\times0.10+0.10\times0.98\times0.90}\\ &=\frac{0.0080}{0.0080+0.0882}=\frac{0.0080}{0.0962}\approx0.083 . \end{aligned} $$SEM–EDS has a low false positive rate and a high sensitivity, so its “not detected” is strong evidence, and the probability falls below the prior probability 0.10.
(4) In the formula that updates in one step, the numerator is $p(x_1\mid\text{present})\,p(x_2\mid\text{present})\,p(\text{present})$, and the denominator is the sum of this and $p(x_1\mid\text{absent})\,p(x_2\mid\text{absent})\,p(\text{absent})$. A product does not depend on the order of multiplication, so using SEM–EDS first gives the same result. Indeed, if we use SEM–EDS first, $p(\text{present}\mid x_2=+)$ $=0.090/(0.090+0.018)$ $=0.833$, and then with XRD
$$ \begin{aligned} &\frac{0.80\times0.833}{0.80\times0.833+0.10\times0.167}\\ &=\frac{0.6667}{0.6833}\approx0.976 \end{aligned} $$which agrees with (2). If conditional independence does not hold (for example, if both methods overlook the aggregation of the same particles), this calculation cannot be used.
Exercise 2.3: The covariance formula
Solution
Let $\mu_x=\Ex[x]$ and $\mu_y=\Ex[y]$.
(1) Expand the product and use the linearity of expectation (expected value) ($\mu_x,\mu_y$ are constants).
$$ \begin{aligned} \Cov[x,y]&=\Ex[xy-\mu_y x-\mu_x y+\mu_x\mu_y]\\ &=\Ex[xy]-\mu_y\mu_x-\mu_x\mu_y+\mu_x\mu_y\\ &=\Ex[xy]-\mu_x\mu_y . \end{aligned} $$(2) Let $u=ax+by+c$. Then $\Ex[u]=a\mu_x+b\mu_y+c$ and $u-\Ex[u]=a(x-\mu_x)+b(y-\mu_y)$. Hence
$$ \begin{aligned} &\Var[u]\\ &=\Ex\!\left[\bigl(a(x-\mu_x)+b(y-\mu_y)\bigr)^{2}\right]\\ &=a^{2}\Ex[(x-\mu_x)^{2}]+b^{2}\Ex[(y-\mu_y)^{2}]\\ &\quad+2ab\,\Ex[(x-\mu_x)(y-\mu_y)]\\ &=a^{2}\Var[x]+b^{2}\Var[y]+2ab\,\Cov[x,y]. \end{aligned} $$Setting $a=b=1$, $c=0$ gives the formula in the main text (the variance of a sum). Setting $a=1$, $b=-1$ gives $\Var[x-y]=\Var[x]+\Var[y]-2\Cov[x,y]$.
(3) Let $\bm{\mu}=\Ex[\bm{x}]$. Then $\Ex[\bm{a}^{\tp}\bm{x}]=\bm{a}^{\tp}\bm{\mu}$ and $\Ex[\bm{b}^{\tp}\bm{x}]=\bm{b}^{\tp}\bm{\mu}$. The scalar $\bm{b}^{\tp}(\bm{x}-\bm{\mu})$ is unchanged by transposition, so it can be written as $(\bm{x}-\bm{\mu})^{\tp}\bm{b}$. Hence
$$ \begin{aligned} &\Cov[\bm{a}^{\tp}\bm{x},\bm{b}^{\tp}\bm{x}]\\ &=\Ex\!\left[\bm{a}^{\tp}(\bm{x}-\bm{\mu})(\bm{x}-\bm{\mu})^{\tp}\bm{b}\right]\\ &=\bm{a}^{\tp}\,\Ex\!\left[(\bm{x}-\bm{\mu})(\bm{x}-\bm{\mu})^{\tp}\right]\bm{b}\\ &=\bm{a}^{\tp}\bm{\Sigma}\bm{b}. \end{aligned} $$In components this is $\sum_{i}\sum_{j}a_i b_j\Cov[x_i,x_j]$; we have only taken the constants outside the expectation. Setting $\bm{b}=\bm{a}$ gives $\Var[\bm{a}^{\tp}\bm{x}]=\bm{a}^{\tp}\bm{\Sigma}\bm{a}$ of Theorem 2.7 in Chapter 2.
Exercise 2.4: The correlation coefficient lies between −1 and 1
Solution
In Exercise 2.3 (2), let $a=1/\sigma_x$ and $b=\pm1/\sigma_y$. Since $\Var[x]/\sigma_x^{2}=1$, $\Var[y]/\sigma_y^{2}=1$, and $\Cov[x,y]/(\sigma_x\sigma_y)=\rho$,
$$ \begin{aligned} \Var[u]&=\Var\!\left[\frac{x}{\sigma_x}+\frac{y}{\sigma_y}\right]\\ &=1+1+2\rho=2(1+\rho),\\ \Var[v]&=\Var\!\left[\frac{x}{\sigma_x}-\frac{y}{\sigma_y}\right]=2(1-\rho). \end{aligned} $$A variance is nonnegative, so $1+\rho\ge0$ and $1-\rho\ge0$; that is, $-1\le\rho\le1$.
When $\rho=1$, $\Var[v]=0$. A random variable with variance 0 equals its mean with probability 1, so $x/\sigma_x-y/\sigma_y$ equals the constant $c=\mu_x/\sigma_x-\mu_y/\sigma_y$ with probability 1. That is, $y=\dfrac{\sigma_y}{\sigma_x}x+\text{constant}$, which is the case where $y$ is a linear function of $x$ with positive slope (all the points lie on a line rising to the right). Similarly, $\rho=-1$ is the case where the points lie on a line with negative slope.
(Alternative solution) The 2×2 covariance matrix $\begin{pmatrix}\sigma_x^{2}&\rho\sigma_x\sigma_y\\\rho\sigma_x\sigma_y&\sigma_y^{2}\end{pmatrix}$ is positive semidefinite, so its determinant is nonnegative: $\sigma_x^{2}\sigma_y^{2}(1-\rho^{2})\ge0$, and hence $\rho^{2}\le1$.
Exercise 2.5: From the grain radius to the distribution of the volume
Solution
Take the unit of length to be $\mu\mathrm{m}$ and the unit of volume to be $\mu\mathrm{m}^{3}$. We have $p_r(r)=1$ ($1\le r\le2$).
(1) $V=\tfrac43\pi r^{3}$ is an increasing function, and $V$ ranges from $V_1=\tfrac43\pi\approx4.19$ to $V_2=\tfrac{32}{3}\pi\approx33.5$. The inverse function is $r=\left(\dfrac{3V}{4\pi}\right)^{1/3}$, and
$$ \begin{aligned} \diff{r}{V}&=\frac13\left(\frac{3V}{4\pi}\right)^{-2/3}\cdot\frac{3}{4\pi}\\ &=\frac{1}{4\pi}\left(\frac{3V}{4\pi}\right)^{-2/3}=\frac{1}{4\pi r^{2}} . \end{aligned} $$By the change-of-variables formula,
$$ \begin{gathered} p_V(V)=p_r(r)\,\abs{\diff{r}{V}}=\frac{1}{4\pi}\left(\frac{3V}{4\pi}\right)^{-2/3}\\ \left(\tfrac43\pi\le V\le\tfrac{32}{3}\pi\right). \end{gathered} $$The density is $1/(4\pi)\approx0.0796\ \mu\mathrm{m}^{-3}$ at $V_1$ and $1/(16\pi)\approx0.0199\ \mu\mathrm{m}^{-3}$ at $V_2$; the larger the volume, the more thinly the density is stretched out. For normalization, changing the integration variable back from $V$ to $r$ gives $\dd V=4\pi r^{2}\dd r$, so $\int_{V_1}^{V_2}p_V\,\dd V=\int_1^2\frac{1}{4\pi r^{2}}\cdot4\pi r^{2}\,\dd r=\int_1^2\dd r=1$.
(2) Using $p_r(r)=1$,
$$ \begin{aligned} \Ex[V]&=\int_1^2\tfrac43\pi r^{3}\,\dd r=\tfrac43\pi\cdot\frac{2^{4}-1^{4}}{4}\\ &=\tfrac43\pi\cdot\frac{15}{4}=5\pi\approx15.71\ \mu\mathrm{m}^{3}. \end{aligned} $$On the other hand, from $\Ex[r]=1.5\ \mu\mathrm{m}$ we get $\tfrac43\pi(1.5)^{3}$ $=\tfrac43\pi\times3.375$ $=4.5\pi\approx14.14\ \mu\mathrm{m}^{3}$.
(3) The volume computed from the mean grain size underestimates the mean volume by about 10% ($4.5\pi$ versus $5\pi$). Since $r^{3}$ is a convex function, the effect by which large grains pull the mean volume up is larger than the effect by which small grains pull it down (in general, for a convex $f$, $\Ex[f(x)]\ge f(\Ex[x])$; this is Jensen’s inequality, Appendix A, A.9). For a quantity that undergoes a nonlinear transformation, “the transform of the mean” differs from “the mean of the transform”; this is also a limitation of the first-order approximation of the propagation of error in this chapter.
Exercise 2.6: The area under the likelihood
Solution
Using the beta function,
$$ \begin{aligned} \int_0^1\theta^{m}(1-\theta)^{N-m}\,\dd\theta&=B(m+1,N-m+1)\\ &=\frac{m!\,(N-m)!}{(N+1)!}. \end{aligned} $$Therefore
$$ \begin{aligned} \int_0^1 L(\theta)\,\dd\theta&=\frac{N!}{m!\,(N-m)!}\cdot\frac{m!\,(N-m)!}{(N+1)!}\\ &=\frac{N!}{(N+1)!}=\frac{1}{N+1}. \end{aligned} $$For $N=10$ and $m=7$ this is $1/11$, in agreement with Example 2.9 in the main text.
Meaning: the fact that the result does not depend on $m$ says that, when $\theta$ is chosen from the uniform distribution on $[0,1]$ and $N$ trials are made with that $\theta$, each number of successes $m=0,1,\dots,N$ occurs with the same probability $1/(N+1)$ ($\int_0^1 p(m\mid\theta)\cdot1\,\dd\theta=p(m)$ is the continuous version of the sum rule). This is the simplest example of the marginal likelihood $p(\data)$ treated in Chapter 4, Section 4.3. The area under the likelihood is not 1, so the likelihood cannot be regarded as a distribution of $\theta$. To obtain a distribution of $\theta$, we must multiply by the prior distribution and divide by this area (Bayes’s theorem).
For 3 successes in 3 trials, $L(\theta)=\binom33\theta^{3}(1-\theta)^{0}=\theta^{3}$. Since this is an increasing function on $[0,1]$, the maximum is at $\theta=1$ (the maximum likelihood estimate $m/N=1$). $L(0.5)=0.125$. With only three data points, judging by the likelihood alone leads to the extreme conclusion that “it always succeeds.” This is the motivation for introducing the prior distribution in Chapter 4.
Exercise 2.7: Repeated measurements of hardness
Solution
(1) The sum is $612+598+631+605$ $+620+589+617+608$ $=4880$, so $\bar{x}=4880/8=610\ \mathrm{HV}$. The deviations from the mean are $2,\,-12,\,21,\,-5,\,10,\,-21,\,7,\,-2$, and the sum of their squares is
$$ \begin{aligned} &4+144+441+25\\ &+100+441+49+4=1208 . \end{aligned} $$$s^{2}=1208/(8-1)\approx172.6\ \mathrm{HV^{2}}$ and $s\approx13.1\ \mathrm{HV}$. The standard error is $s/\sqrt{8}\approx13.14/2.828\approx4.6\ \mathrm{HV}$. The report is written as, for example, “$610\pm5\ \mathrm{HV}$ (mean of 8 measurements ± standard error; scatter of a single measurement $s=13\ \mathrm{HV}$).”
(2) From $s/\sqrt{N}\le3$ we get $N\ge(s/3)^{2}=(13.14/3)^{2}\approx19.2$. Therefore 20 measurements are needed.
(3) It must not be reported as it stands (at least, it cannot be called, as it stands, the “uncertainty of the hardness of the material”). $s/\sqrt{N}$ presupposes that the 8 measurements are independent samples from the “distribution of the hardness of the material.” Values measured within a narrow region of a single sample share that sample’s local microstructure and its fabrication variability (batch), and are correlated with one another. As in Example 2.12 of Section 2.10, when there is correlation the standard error is underestimated, and no matter how many times a single sample is measured, the variability between samples and between batches does not become visible. Report $s/\sqrt{N}$ as “the uncertainty of the mean hardness of this region of this sample”; to state a value for the material, we must measure several samples (preferably from several batches).
Exercise 2.8: The number of batches and the number of samples
Solution
(1) Plan A: let $\bar{x}_b$ be the mean of the 4 samples in batch $b$ ($b=1,\dots,5$). By the result of Example 2.12 with $N=4$, $\Var[\bar{x}_b]=\dfrac{\sigma^{2}}{4}\bigl[1+3\rho\bigr]$. The overall mean is $\bar{x}=\frac15\sum_b\bar{x}_b$, and since the batch means are independent of one another,
$$ \Var[\bar{x}]=\frac{1}{5^{2}}\cdot5\cdot\frac{\sigma^{2}}{4}(1+3\rho)=\frac{\sigma^{2}}{20}(1+3\rho). $$(2) For $\rho=0.5$, $\Var[\bar{x}]=\sigma^{2}\times2.5/20=\sigma^{2}/8$. Comparing with the variance $\sigma^{2}/N_{\mathrm{eff}}$ of the mean of $N_{\mathrm{eff}}$ independent measurements gives $N_{\mathrm{eff}}=8$. Even though 20 samples are measured, there is only as much information as in 8 independent measurements.
(3) Plan B has $\Var[\bar{x}]=\sigma^{2}/20$, which gives the smallest uncertainty from the same 20 measurements. Moreover, since all 20 samples come from different batches, the variability between batches (the reproducibility of fabrication) is included as it is in the scatter of the samples, so there is no risk of underestimating the variability of the material. The drawbacks are that making the batches costs four times as much money and time, and that we cannot estimate “the variability within the same batch” and “the variability between batches” separately. When there are several samples in one batch, as in Plan A, the two can be estimated separately (decomposition of variance into components).
From the standpoint of machine learning, if the data of Plan A are split at random into training data and test data sample by sample, samples from the same batch end up in both, and the test performance looks better than the true ability (data leakage; Chapter 6, Section 6.8). If the data of Plan A are used, the split must be made batch by batch. With Plan B this problem is unlikely to arise, but since there is one sample per batch, the reproducibility of measurements within a batch is unknown. If the cost allows, a design that “increases the number of batches as much as possible and measures a few samples within each” is advantageous for both the precision of the mean and the prevention of leakage.
Chapter 3 Common Probability Distributions — Patterns of Variability in Data
Exercise 3.1: Binomial distribution of the number of defectives and its Poisson approximation
Solution
We have $N=100$ and $\mu=0.02$.
(1) Using the binomial distribution (the form $\binom{N}{m}\mu^{m}(1-\mu)^{N-m}$ of Eq. (3.3) in Chapter 3),
$$ \begin{aligned} P(m=0)&=0.98^{100}=\exp(100\ln0.98)\\ &=\exp(-2.0203)\approx0.1326, \end{aligned} $$ $$ P(m=1)=100\times0.02\times0.98^{99}\approx0.2707, $$ $$ \begin{aligned} P(m=2)&=\binom{100}{2}0.02^{2}\,0.98^{98}\\ &=4950\times0.0004\times0.98^{98}\\ &\approx0.2734 . \end{aligned} $$Hence $P(m\le2)$ $\approx0.1326+0.2707+0.2734$ $=0.6767$.
(2) In the Poisson approximation, $\lambda=N\mu=2$, so
$$ P(m=0)=e^{-2}\approx0.1353, $$ $$ \begin{aligned} P(m\le2)&=e^{-2}\left(1+2+\frac{2^{2}}{2}\right)\\ &=5e^{-2}\approx0.6767 . \end{aligned} $$The probability of zero defectives differs by about 2 % (0.1326 versus 0.1353), but the probabilities of two or fewer almost coincide (the differences in the individual terms cancel). Since $\mu=0.02$ is sufficiently small, the Poisson approximation works well.
(3) The variance of the binomial distribution is $N\mu(1-\mu)=100\times0.02\times0.98=1.96$, and the variance of the Poisson distribution is $\lambda=2$. Their ratio is $1-\mu=0.98$, so they are almost the same.
Exercise 3.2: Properties of the Poisson distribution
Solution
(1) The terms with $m=0,1,2$ vanish because $m(m-1)(m-2)=0$, so we sum from $m=3$ and use $m(m-1)(m-2)/m!=1/(m-3)!$.
$$ \begin{aligned} &\Ex[m(m-1)(m-2)]\\ &=\sum_{m=3}^{\infty}\frac{\lambda^{m}e^{-\lambda}}{(m-3)!}\\ &=\lambda^{3}e^{-\lambda}\sum_{j=0}^{\infty}\frac{\lambda^{j}}{j!}\\ &=\lambda^{3}e^{-\lambda}e^{\lambda}=\lambda^{3}. \end{aligned} $$(In the third line we put $j=m-3$.) In general, $\Ex[m(m-1)\cdots(m-r+1)]=\lambda^{r}$.
(2) The event $m_1+m_2=n$ occurs exactly when $m_1=j$ and $m_2=n-j$ for some $j=0,\dots,n$, and these cases are mutually exclusive. By independence, the probability of each case is a product, so
$$ \begin{aligned} &P(m_1+m_2=n)\\ &=\sum_{j=0}^{n}\frac{\lambda_1^{j}e^{-\lambda_1}}{j!}\cdot\frac{\lambda_2^{n-j}e^{-\lambda_2}}{(n-j)!}\\ &=\frac{e^{-(\lambda_1+\lambda_2)}}{n!}\sum_{j=0}^{n}\frac{n!\,\lambda_1^{j}\lambda_2^{n-j}}{j!\,(n-j)!}\\ &=\frac{e^{-(\lambda_1+\lambda_2)}}{n!}(\lambda_1+\lambda_2)^{n}. \end{aligned} $$In the last step we used the binomial theorem. This is $\mathrm{Pois}(n\mid\lambda_1+\lambda_2)$.
(3) The count over 20 seconds is the sum of the count $m_1$ over the first 10 seconds and the count $m_2$ over the last 10 seconds. If events occur independently at a constant rate, $m_1$ and $m_2$ are independent and both follow $\mathrm{Pois}(\lambda)$. By (2), the sum follows $\mathrm{Pois}(2\lambda)$. Both the mean and the variance are $2\lambda$, and the relative error decreases to $1/\sqrt{2\lambda}$, that is, by a factor of $1/\sqrt2$.
Exercise 3.3: Measurement time in XPS
Solution
(1) The count over a time $t$ (s) follows a Poisson distribution with mean $80t$ at the peak position and mean $30t$ in the background. The mean of the net intensity is $(80-30)t=50t$, and since the two counts are independent, the variance is the sum $80t+30t=110t$. The relative error is
$$ \frac{\sqrt{110t}}{50t}=\frac{\sqrt{110}}{50\sqrt{t}}\approx\frac{0.2098}{\sqrt{t}} . $$(2) From $\sqrt{110}/(50\sqrt t)\le0.01$ we get $\sqrt t\ge\sqrt{110}/0.5\approx20.98$, so $t\ge440\ \mathrm{s}$ (440 s each for the peak and the background, 880 s in total).
(3) Without a background, the mean is $50t$, the variance is $50t$, and the relative error is $1/\sqrt{50t}$. From $1/\sqrt{50t}\le0.01$ we get $t\ge200\ \mathrm{s}$.
Although the net intensity is the same $50\ \mathrm{s^{-1}}$, the presence of a background requires 2.2 times as long at each position, and 4.4 times as long when the background measurement is included. The background increases only the variance without increasing the signal, so conditions with a low background (the measurement geometry and the choice of excitation source) directly shorten the measurement time.
Exercise 3.4: Marginalization and regression for a two-dimensional Gaussian distribution
Solution
(1) Setting $\rho=0$ in the decomposition of Chapter 3, Section 3.6.4, factor (A) becomes $\dfrac{1}{\sqrt{2\pi}\sigma_a}\exp(-u^{2}/2)=\Normal(x_a\mid\mu_a,\sigma_a^{2})$, which does not depend on $x_b$. Therefore $p(x_a,x_b)$ $=\Normal(x_a\mid\mu_a,\sigma_a^{2})\,\Normal(x_b\mid\mu_b,\sigma_b^{2})$ $=p(x_a)p(x_b)$, and the variables are independent. For a Gaussian distribution, uncorrelated implies independent (this does not hold for general distributions; see Chapter 2, Section 2.5).
(2) Interchanging $a$ and $b$ gives
$$ \Ex[x_b\mid x_a]=\mu_b+\rho\frac{\sigma_b}{\sigma_a}(x_a-\mu_a), $$whose slope in the $(x_a,x_b)$ plane is $\dd x_b/\dd x_a=\rho\sigma_b/\sigma_a$. On the other hand, solving the line $\Ex[x_a\mid x_b]=\mu_a+\rho\frac{\sigma_a}{\sigma_b}(x_b-\mu_b)$ for $x_b$, the slope is $\dd x_b/\dd x_a=\sigma_b/(\rho\sigma_a)$. The ratio of the two slopes is $\rho^{2}$, and for $0\lt\abs{\rho}\lt1$ they do not coincide (both lines pass through the point $(\mu_a,\mu_b)$ but have different slopes).
(3) $\rho\sigma_b/\sigma_a=0.8\times30/1.5=16\ \mathrm{HV}/\%$, and $\sigma_b/(\rho\sigma_a)=30/(0.8\times1.5)=25\ \mathrm{HV}/\%$.
The line that predicts hardness from density (slope 16) is flatter than the line that predicts density from hardness (slope 25). In both predictions, when the conditioning quantity deviates from its mean by $k$ standard deviations, the predicted quantity deviates by only $\rho k$ standard deviations (smaller than $k$ because $\abs{\rho}\lt1$). This is called regression to the mean. Unless the correlation is perfect, the best prediction is “if one is extreme, the other is probably not so extreme,” and as a result the two lines do not coincide.
Exercise 3.5: Mahalanobis distance and the probability inside an ellipse
Solution
(1) From the eigenvalue equation $\det(\bm{\Sigma}-\lambda\bm{I})$ $=(5-\lambda)(2-\lambda)-4$ $=\lambda^{2}-7\lambda+6=0$ we get $\lambda_1=6$ and $\lambda_2=1$.
For $\lambda_1=6$: $(5-6)u_1+2u_2=0$ gives $u_1=2u_2$, and the unit vector is $\bm{u}_1=(2,1)^{\tp}/\sqrt5$. For $\lambda_2=1$: $4u_1+2u_2=0$ gives $u_2=-2u_1$, and $\bm{u}_2=(1,-2)^{\tp}/\sqrt5$ (the sign of either may be reversed). Since $\bm{u}_1^{\tp}\bm{u}_2=(2-2)/5=0$, they are orthogonal.
The ellipse $\Delta=1$ has its major axis, of radius $\sqrt6\approx2.45$, along $\bm{u}_1$ (the direction of slope $1/2$), and its minor axis, of radius 1, along $\bm{u}_2$.
(2) Since $\abs{\bm{\Sigma}}=5\times2-2\times2=6$, we have $\bm{\Sigma}^{-1}=\dfrac16\begin{pmatrix}2&-2\\-2&5\end{pmatrix}$.
For $\bm{x}=(2,1)^{\tp}$: $\Delta^{2}=\dfrac16(2\cdot4-2\cdot2\cdot2\cdot1+5\cdot1)$ $=\dfrac{8-8+5}{6}=\dfrac56\approx0.833$.
For $\bm{x}=(1,-2)^{\tp}$: $\Delta^{2}=\dfrac16\bigl(2\cdot1-2\cdot2\cdot1\cdot(-2)$ $+5\cdot4\bigr)=\dfrac{2+8+20}{6}=5$.
Both points have the same ordinary distance $\sqrt5$ from the origin, but $(2,1)^{\tp}$ lies along the major axis ($\sqrt5\,\bm{u}_1$), so $\Delta^{2}=5/6$ is small, whereas $(1,-2)^{\tp}$ lies along the minor axis ($\sqrt5\,\bm{u}_2$), so $\Delta^{2}=5$ is large. This is also confirmed with $\Delta^{2}=\sum_iy_i^{2}/\lambda_i$ of Eq. (3.13) in Chapter 3: from $y_1=\sqrt5$, $y_2=0$ we get $5/6$, and from $y_1=0$, $y_2=\sqrt5$ we get $5/1$.
(3) By Chapter 3, Section 3.6.2, $y_1,y_2$ are independent and $y_i\sim\Normal(0,\lambda_i)$. Putting $z_i=y_i/\sqrt{\lambda_i}$, the variables $z_1,z_2$ are independent and follow the standard Gaussian distribution, and $\Delta^{2}=z_1^{2}+z_2^{2}$. Using polar coordinates $z_1=r\cos\theta$, $z_2=r\sin\theta$ in the $z$ plane (Jacobian determinant $r$), we obtain
$$ \begin{aligned} P(\Delta\le c)&=\int_{0}^{2\pi}\!\!\int_{0}^{c}\frac{1}{2\pi}e^{-r^{2}/2}\,r\,\dd r\,\dd\theta\\ &=\Bigl[-e^{-r^{2}/2}\Bigr]_{0}^{c}=1-e^{-c^{2}/2}. \end{aligned} $$From $1-e^{-c^{2}/2}=0.95$ we get $c^{2}=-2\ln0.05=5.991$, so $c\approx2.45$. In two dimensions, the ellipse containing 95 % has $\Delta\approx2.45$, which is larger than the one-variable value 1.96.
Exercise 3.6: Weighted average and median for the Cauchy distribution
Solution
(1) We use the characteristic function $\varphi(k)=\exp(ix_0k-\gamma\abs{k})$ (Chapter 3, Section 3.7.3). By the independence of $x_1,x_2$,
$$ \begin{aligned} &\Ex\!\left[e^{ik(wx_1+(1-w)x_2)}\right]\\ &=\varphi(wk)\,\varphi((1-w)k)\\ &=e^{ix_0wk-\gamma w\abs{k}}\\ &\quad\times e^{ix_0(1-w)k-\gamma(1-w)\abs{k}}\\ &=e^{ix_0k-\gamma\abs{k}} . \end{aligned} $$Since $w\ge0$ and $1-w\ge0$, we used $\abs{wk}=w\abs{k}$ and $\abs{(1-w)k}=(1-w)\abs{k}$. The result is exactly the characteristic function of the original Cauchy distribution, so the weighted average also follows the same Cauchy distribution $(x_0,\gamma)$.
(2) Applying (1) repeatedly, any weighted average $\sum_jw_jx_j$ with nonnegative weights summing to 1 also follows the same Cauchy distribution. That is, no matter how many data points we average or how we weight them, the spread of the estimate of the center $x_0$ (the half width at half maximum $\gamma$) is no better than that of a single data point. For this distribution, the operation of averaging itself gathers no information.
(3) From the cumulative distribution function $F(x)=\frac12+\frac1\pi\arctan\frac{x-x_0}{\gamma}$, the median is $x_0$, where $F=1/2$, the quartiles are $x_0\mp\gamma$, where $F=1/4,3/4$, and the interquartile range is $2\gamma$. The median $\tilde x$ of three observations satisfies $P(\tilde x\le x)=3F^{2}-2F^{3}$, from the probability that “at least two of the three are at most $x$.” For $x_0=0$ and $\gamma=1$, solving $3F^{2}-2F^{3}=1/4$ gives $F=0.3264$, and $x=\tan(\pi(F-1/2))=-0.607$, so the interquartile range of $\tilde x$ is $1.21\gamma$, which is narrower than that of the sample mean (which remains $2\gamma$). Moreover, the tail of the density of $\tilde x$ decays as $\abs{x}^{-3}$ (even if one extreme value appears, the median is determined by one of the remaining two). In this way the median is not swayed by a single huge outlier, and it concentrates around $x_0$ as the sample grows.
Exercise 3.7: Finding the Weibull modulus from a Weibull plot
Solution
(1) $F_i=(i-0.5)/8$ takes the values $0.0625$, $0.1875$, $0.3125$, $0.4375$, $0.5625$, $0.6875$, $0.8125$, $0.9375$.
| $i$ | $s_i$ / MPa | $X_i=\ln s_i$ | $Y_i$ |
|---|---|---|---|
| 1 | 306 | 5.7236 | −2.7405 |
| 2 | 322 | 5.7746 | −1.5720 |
| 3 | 336 | 5.8171 | −0.9816 |
| 4 | 343 | 5.8377 | −0.5528 |
| 5 | 369 | 5.9108 | −0.1903 |
| 6 | 393 | 5.9738 | 0.1511 |
| 7 | 396 | 5.9814 | 0.5152 |
| 8 | 413 | 6.0234 | 1.0198 |
For example, for $i=1$: $1/(1-0.0625)=1.0667$, $\ln1.0667=0.06454$, and $\ln0.06454=-2.7405$.
(2) The means are $\bar X=5.8803$ and $\bar Y=-0.5439$. The sums of products and of squares of the deviations are $S_{XY}=\sum_i(X_i-\bar X)(Y_i-\bar Y)=0.8877$ and $S_{XX}=\sum_i(X_i-\bar X)^{2}=0.08194$.
$$ \hat m=\frac{S_{XY}}{S_{XX}}=\frac{0.8877}{0.08194}\approx10.83, $$ $$ \begin{aligned} c&=\bar Y-\hat m\bar X\\ &=-0.5439-10.83\times5.8803\\ &\approx-64.25 . \end{aligned} $$The intercept of the line in Eq. (3.25) of Chapter 3 (the Weibull plot line) is $-m\ln s_0$, so $\ln\hat s_0=-c/\hat m=5.9305$ and $\hat s_0=e^{5.9305}\approx376\ \mathrm{MPa}$.
(3) The values used for generation were $m=10$ and $s_0=400\ \mathrm{MPa}$, and the estimates $\hat m=10.8$ and $\hat s_0=376\ \mathrm{MPa}$ are reasonably close. With only eight specimens, however, the random variation is large. If the same procedure is repeated thousands of times, drawing eight specimens each time from a Weibull distribution with $m=10$, $\hat m$ scatters over roughly the range 5–20 (95 %). A value of $m$ obtained from eight specimens is accurate only to “around 10,” and a reliability evaluation calls for several tens of test specimens. That $\hat s_0$ is smaller than 400 is also because these eight specimens happened to be on the weak side.
(4) $F(300)=1-\exp[-(300/376.3)^{10.83}]$. Since $(300/376.3)^{10.83}$ $=\exp(10.83\times\ln0.7972)$ $=\exp(10.83\times(-0.2266))$ $=\exp(-2.454)$ $=0.0859$, we get $F(300)=1-e^{-0.0859}\approx0.082$. About 8 % are estimated to break at 300 MPa. However, as noted in (3), the uncertainty in $\hat m$ is large, so this value also carries a large uncertainty.
Exercise 3.8: Fitting a Lorentzian peak with a Gaussian
Solution
(1) The integral of the Lorentzian $h\gamma^{2}/((x-x_0)^{2}+\gamma^{2})$ is $\pi\gamma h$, from the normalization of the Cauchy distribution ($\int\frac1\pi\frac{\gamma}{y^{2}+\gamma^{2}}\dd y=1$). A Gaussian with the same full width at half maximum $2\gamma$ satisfies $2\sqrt{2\ln2}\,\sigma=2\gamma$, so $\sigma=\gamma/\sqrt{2\ln2}=0.8493\gamma$, and the integral of a Gaussian of height $h$ is $\sqrt{2\pi}\,\sigma h$. The ratio is
$$ \frac{\sqrt{2\pi}\,\sigma h}{\pi\gamma h}=\frac{\sqrt{2\pi}}{\pi\sqrt{2\ln2}}=\frac{1}{\pi}\sqrt{\frac{\pi}{\ln2}}\approx0.678 . $$The Gaussian underestimates the integrated intensity by about 32 %.
(2) Lorentzian: the fraction inside $\pm3\gamma$ is $\frac{2}{\pi}\arctan3=0.7952$, so the fraction outside is $0.205$ (20.5 %). Gaussian: $3\gamma=3\times\sqrt{2\ln2}\,\sigma=3.53\sigma$, so the fraction outside is $2[1-\Phi(3.53)]\approx4.1\times10^{-4}$ (0.04 %).
(3) Only the peak of the phase with a strongly Lorentzian character is underestimated, by about 30 %, so the fraction of that phase is estimated to be smaller and that of the other phase larger. For example, if the true ratio of integrated intensities is 1 : 1, the apparent ratio becomes $0.678:1$, and the fraction of that phase comes out as $0.678/1.678\approx40$ % rather than 50 % (the factor that converts an intensity ratio into a fraction is taken to be the same for both). One should fit the peaks of both phases with the same shape (for example, a Voigt profile or a pseudo-Voigt function) and check the tails of the residuals on a logarithmic vertical axis.
← Back to Chapter 3, “Common Probability Distributions — Patterns of Variability in Data”
Chapter 4 Maximum Likelihood, MAP, and Bayesian Estimation — Learning a Distribution from Data
Exercise 4.1: Posterior distribution and point estimates
Solution
The prior distribution is $\mathrm{Beta}(a,b)=\mathrm{Beta}(3,2)$, with $N=10$, $m=4$ successes, and $l=6$ failures.
(1) By conjugacy (Theorem 4.3 of Chapter 4), the posterior distribution is $\mathrm{Beta}(\mu\mid a+m,\ b+l)=\mathrm{Beta}(\mu\mid 7,\ 8)$.
(2) The maximum likelihood estimate is $m/N=4/10=0.4$. Since $A=7\gt1$ and $B=8\gt1$, the formula for the interior maximum point applies to the MAP estimate:
$$ \mu_{\mathrm{MAP}}=\frac{A-1}{A+B-2}=\frac{6}{13}\approx0.4615 . $$The posterior mean is $\dfrac{A}{A+B}=\dfrac{7}{15}\approx0.4667$.
(3) $w=\dfrac{N}{a+b+N}=\dfrac{10}{15}=\dfrac23$. The prior mean is $\dfrac{a}{a+b}=\dfrac35=0.6$, so
$$ \begin{aligned} &w\,\frac{m}{N}+(1-w)\,\frac{a}{a+b}\\ &\quad=\frac23\times0.4+\frac13\times0.6\\ &\quad=\frac{0.8+0.6}{3}=\frac{1.4}{3}\approx0.4667 \end{aligned} $$which agrees with the posterior mean in (2).
(4) By the formula for the variance of the beta distribution,
$$ \begin{aligned} \Var[\mu\mid\data]&=\frac{AB}{(A+B)^{2}(A+B+1)}\\ &=\frac{7\times8}{15^{2}\times16}=\frac{56}{3600}\\ &\approx0.01556 , \end{aligned} $$and the standard deviation is $\sqrt{0.01556}\approx0.125$.
(5) The posterior predictive probability equals the posterior mean: $p(x=1\mid\data)=7/15\approx0.467$.
Seen from the data (0.4), the prior distribution (mean 0.6) lies above, so the posterior mean and the MAP estimate are pulled back to the side larger than the maximum likelihood estimate 0.4.
Exercise 4.2: How fast does the posterior distribution narrow?
Solution
Let $A=a+m=a+\hat\mu N$, $B=b+l=b+(1-\hat\mu)N$, and $A+B=a+b+N$. The variance of the beta distribution is
$$ \Var[\mu\mid\data]=\frac{AB}{(A+B)^{2}(A+B+1)} . $$Expanding the numerator gives
$$ \begin{aligned} AB={}&\hat\mu(1-\hat\mu)N^{2}\\ &+\bigl[a(1-\hat\mu)+b\hat\mu\bigr]N+ab \end{aligned} $$and the highest-order term in $N$ is $\hat\mu(1-\hat\mu)N^{2}$. The denominator is $(a+b+N)^{2}(a+b+N+1)$ $=N^{3}+(\text{terms of order $N^{2}$ or lower})$. Dividing the numerator and denominator by $N^{3}$ and letting $N\to\infty$, we get
$$ \begin{aligned} \Var[\mu\mid\data]&=\frac{\hat\mu(1-\hat\mu)N^{2}+O(N)}{N^{3}+O(N^{2})}\\ &=\frac{\hat\mu(1-\hat\mu)}{N}\bigl(1+O(1/N)\bigr) . \end{aligned} $$Hence $\Var[\mu\mid\data]\approx\hat\mu(1-\hat\mu)/N$, and the standard deviation of the posterior distribution decreases at the rate $1/\sqrt{N}$.
Meaning: when $N$ trials with success rate $\mu$ are performed, the number of successes $m$ follows a binomial distribution with $\Var[m]=N\mu(1-\mu)$, so the variance of the maximum likelihood estimator $m/N$ is $\mu(1-\mu)/N$ (Chapter 3). When the data are plentiful, “the variability of the maximum likelihood estimate when the data are collected again” and “our ignorance about $\mu$ from a single data set (the width of the posterior distribution)” become about the same in magnitude. For this reason, when the data are sufficiently plentiful, the Bayesian credible interval and the frequentist confidence interval nearly coincide numerically. When the data are few, the contributions of $a,b$ remain, and the two do not coincide.
Exercise 4.3: The count rate of the XRD background
Solution
$N=5$ and $\sum_n x_n=12+9+15+11+13=60$.
(1) Because the observations are independent, the likelihood is a product.
$$ p(\data\mid\lambda)=\prod_{n=1}^{5}\frac{\lambda^{x_n}e^{-\lambda}}{x_n!}=\frac{\lambda^{\sum_n x_n}e^{-N\lambda}}{\prod_n x_n!} . $$Taking the logarithm gives $\ln p=\left(\sum_n x_n\right)\ln\lambda-N\lambda-\sum_n\ln x_n!$. Differentiate with respect to $\lambda$ and set the result to 0.
$$ \begin{gathered} \diff{}{\lambda}\ln p=\frac{\sum_n x_n}{\lambda}-N=0\\ \Longrightarrow\quad\lambda_{\mathrm{ML}}=\frac{1}{N}\sum_n x_n=\frac{60}{5}=12 . \end{gathered} $$The second derivative $-\sum_n x_n/\lambda^{2}\lt0$, so this is a maximum. As a count rate, $12$ counts per 10 s $=1.2$ counts per second.
(2) The posterior distribution is proportional (∝) to the likelihood × the prior distribution; dropping factors that do not depend on $\lambda$, we get
$$ \begin{aligned} p(\lambda\mid\data)&\propto\lambda^{60}e^{-5\lambda}\times\lambda^{2-1}e^{-0.1\lambda}\\ &=\lambda^{61}e^{-5.1\lambda}=\lambda^{62-1}e^{-5.1\lambda}. \end{aligned} $$This has the form of a gamma distribution $\mathrm{Gam}(\lambda\mid a',b')$ with $a'=a+\sum_n x_n=62$ and $b'=b+N=5.1$, so the posterior distribution is again a gamma distribution (the gamma distribution is the conjugate prior of the Poisson distribution). The posterior mean is $a'/b'=62/5.1\approx12.16$, and the mode is $(a'-1)/b'=61/5.1\approx11.96$ (the mode is obtained by differentiating $(a'-1)\ln\lambda-b'\lambda$ and setting the result to 0; since $a'\gt1$, it is an interior maximum). The posterior standard deviation is $\sqrt{a'}/b'=\sqrt{62}/5.1\approx1.54$.
(3) The posterior mean can be written as $\dfrac{a+\sum x_n}{b+N}=w\,\bar{x}+(1-w)\,\dfrac{a}{b}$ with $w=\dfrac{N}{b+N}=\dfrac{5}{5.1}\approx0.980$ (the prior mean is $a/b=20$). Indeed $0.980\times12+0.020\times20\approx12.16$ agrees. The weight of the prior distribution is about 2%, a weak prior distribution equivalent to “0.1 of a 10 s observation.” The posterior mean moves only 0.16 from the maximum likelihood estimate 12, which is small compared with the posterior standard deviation 1.54. Therefore the influence of the prior distribution is practically negligible.
Exercise 4.4: Sequential updating of the mean of a Gaussian distribution
Solution
Take the posterior distribution $\Normal(\mu\mid\mu_k,\sigma_k^{2})$ after $k$ observations as the prior distribution, and update it with one observation $x_{k+1}$ (likelihood $\Normal(x_{k+1}\mid\mu,\sigma^{2})$). This is the case of Theorem 4.5 of Chapter 4 with $N=1$, $\mu_0\to\mu_k$, $\sigma_0^{2}\to\sigma_k^{2}$, and $\bar{x}\to x_{k+1}$, so
$$ \begin{gathered} \frac{1}{\sigma_{k+1}^{2}}=\frac{1}{\sigma_k^{2}}+\frac{1}{\sigma^{2}},\\ \frac{\mu_{k+1}}{\sigma_{k+1}^{2}}=\frac{\mu_k}{\sigma_k^{2}}+\frac{x_{k+1}}{\sigma^{2}} . \end{gathered} $$(The second equation is the formula for the mean in Theorem 4.5 with both sides divided by $\sigma_{k+1}^{2}$.) Using the precision $\pi_k\equiv1/\sigma_k^{2}$ and the precision × mean $h_k\equiv\mu_k/\sigma_k^{2}$, the updates become the simple additions $\pi_{k+1}=\pi_k+1/\sigma^{2}$ and $h_{k+1}=h_k+x_{k+1}/\sigma^{2}$. Starting from $k=0$ ($\pi_0=1/\sigma_0^{2}$, $h_0=\mu_0/\sigma_0^{2}$) and repeating $N$ times,
$$ \begin{aligned} \pi_N&=\frac{1}{\sigma_0^{2}}+\frac{N}{\sigma^{2}},\\ h_N&=\frac{\mu_0}{\sigma_0^{2}}+\frac{1}{\sigma^{2}}\sum_{n=1}^{N}x_n\\ &=\frac{\mu_0}{\sigma_0^{2}}+\frac{N\bar{x}}{\sigma^{2}} . \end{aligned} $$$\sigma_N^{2}=1/\pi_N$ and $\mu_N=h_N/\pi_N=\sigma_N^{2}h_N$ are the same as the batch formula (Eq. (4.18) of Theorem 4.5 in Chapter 4). Since the order of addition does not change the result, the final result is the same even if the order of the observations is permuted.
Exercise 4.5: A literature value that is too strong
Solution
(1) The prior precision is $1/\sigma_0^{2}=1/0.0025=400\ \mathrm{pm^{-2}}$, and the data precision is $N/\sigma^{2}=9/0.09=100\ \mathrm{pm^{-2}}$. Their sum is $500\ \mathrm{pm^{-2}}$, so
$$ \begin{gathered} \sigma_N^{2}=\frac{1}{500}=0.002\ \mathrm{pm^{2}},\\ \sigma_N=\sqrt{0.002}\approx0.045\ \mathrm{pm}. \end{gathered} $$ $$ \begin{aligned} \mu_N&=0.002\times(400\times390.50\\ &\qquad+100\times391.10)\\ &=0.002\times(156200+39110)\\ &=390.62\ \mathrm{pm}. \end{aligned} $$The data weight is $w=\dfrac{N\sigma_0^{2}}{N\sigma_0^{2}+\sigma^{2}}$ $=\dfrac{9\times0.0025}{9\times0.0025+0.09}$ $=\dfrac{0.0225}{0.1125}=0.2$. The posterior mean lies 80% toward the literature value, and the posterior uncertainty of 0.045 pm looks very small.
(2) If both measure the same $\mu$, then $\bar{x}-\mu_0$ follows a Gaussian distribution with mean 0 and variance $\sigma_0^{2}+\sigma^{2}/N=0.0025+0.01=0.0125\ \mathrm{pm^{2}}$ (the variance of the difference of independent quantities is the sum of the variances). The standard deviation is $\sqrt{0.0125}\approx0.112\ \mathrm{pm}$, and
$$ \frac{\bar{x}-\mu_0}{\sqrt{\sigma_0^{2}+\sigma^{2}/N}}=\frac{391.10-390.50}{0.112}\approx5.4 . $$The probability that a deviation exceeding 5 standard deviations of a Gaussian distribution occurs by chance is about $10^{-6}$ or less, so the prior distribution and the data are not consistent. In this case, $\mu_N=390.62\ \mathrm{pm}$ and $\sigma_N=0.045\ \mathrm{pm}$ in (1) are numbers based on the premise that “both are correct,” and they cannot be trusted. Reporting a narrow interval between the two values would be wrong.
(3) Examples of possible causes:
- Difference in measurement temperature: the lattice constant changes with temperature through thermal expansion. If we assume a linear thermal expansion coefficient of $1\times10^{-5}\ \mathrm{K^{-1}}$, a lattice constant of 390.5 pm changes by about $390.5\times10^{-5}\times100\approx0.39\ \mathrm{pm}$ for a temperature difference of 100 K, which can explain most of the 0.6 pm difference. Check the temperatures of the literature measurement and of your own.
- Difference in the composition or state of the sample: oxygen nonstoichiometry, dissolved impurities, and, for a thin film, strain from the substrate can make the lattice constant differ even for a material with the same name. The literature sample is not necessarily the same as your sample.
- Systematic error of the instrument: an offset of the zero of the diffraction angle, an offset of the sample height, or a wrong wavelength setting produces a constant offset that does not appear in the repeatability $\sigma$. Check whether the instrument has been calibrated with a standard sample.
It is also possible that the literature $\sigma_0=0.05\ \mathrm{pm}$ is only the repeatability of the measurement and does not include systematic errors. In that case $\sigma_0$ should be re-chosen larger.
Exercise 4.6: The MAP estimate changes with the choice of variable
Solution
We have $\mu=1/(1+e^{-\eta})$ and $\dd\mu/\dd\eta=\mu(1-\mu)\gt0$. By the change-of-variables formula,
$$ \begin{aligned} p_\eta(\eta\mid\data)&=\mathrm{Beta}(\mu\mid A,B)\,\mu(1-\mu)\\ &\propto\mu^{A-1}(1-\mu)^{B-1}\cdot\mu(1-\mu)\\ &=\mu^{A}(1-\mu)^{B}. \end{aligned} $$When we differentiate with respect to $\eta$, the chain rule gives $\dfrac{\dd}{\dd\eta}=\mu(1-\mu)\dfrac{\dd}{\dd\mu}$, and since $\mu(1-\mu)\gt0$, the stationary point with respect to $\eta$ is the same as the stationary point of $\mu^{A}(1-\mu)^{B}$ with respect to $\mu$. Differentiating the logarithm,
$$ \frac{A}{\mu}-\frac{B}{1-\mu}=0\quad\Longrightarrow\quad\mu=\frac{A}{A+B}. $$Since $A,B\gt0$, $\mu^{A}(1-\mu)^{B}$ vanishes at both ends $\mu=0,1$ ($\eta\to\mp\infty$), so this point is the maximum. That is, the density of $\eta$ has a finite maximum even when $A,B$ are less than 1. Note that $A/(A+B)$ is the same value as the posterior mean of $\mu$.
Comparison of magnitudes:
$$ \begin{aligned} &\frac{A}{A+B}-\frac{A-1}{A+B-2}\\ &\quad=\frac{A(A+B-2)-(A-1)(A+B)}{(A+B)(A+B-2)}\\ &\quad=\frac{B-A}{(A+B)(A+B-2)} . \end{aligned} $$If $A\gt1$ and $B\gt1$, the denominator is positive, so if $B\gt A$ (the MAP estimate of $\mu$ is below 1/2), the value obtained with $\eta$ is larger, and if $A\gt B$ it is smaller. In either case, the value obtained with $\eta$ is closer to 1/2 than the MAP estimate of $\mu$. If $A=B$, both equal 1/2 and coincide.
For $\mathrm{Beta}(4,1)$, the MAP estimate of $\mu$ is the endpoint 1 (Example 4.5 of Chapter 4), but the density of $\eta$ takes an interior maximum at the point corresponding to $\mu=4/5=0.8$. The claim that “the most probable pass rate is 1, because all 3 of 3 passed” depends on having chosen $\mu$ as the variable; in terms of the log-odds, “the most probable value is 0.8.”
Discussion: since the MAP estimate depends on the arbitrary convention of the choice of variable, one should avoid reporting it alone. It is better to report quantities that are consistent under a change of variables (quantiles, the median, credible intervals), the posterior mean (= the posterior predictive probability), which can be used directly for prediction, or the posterior distribution itself (a figure, or the parameters of $\mathrm{Beta}(A,B)$). When reporting a MAP estimate, state clearly in which variable it was obtained.
Exercise 4.7: How many must we make to claim a defect rate of 1% or less?
Solution
The condition $c_{95}=1-0.05^{1/(N+1)}\le0.01$ is equivalent to $0.05^{1/(N+1)}\ge0.99$. Take the natural logarithm of both sides (the direction does not change because $\ln$ is monotone increasing).
$$ \frac{\ln0.05}{N+1}\ge\ln0.99 . $$Multiply both sides by $(N+1)\gt0$, then divide by the negative number $\ln0.99\approx-0.010050$, which reverses the direction of the inequality.
$$ N+1\ge\frac{\ln0.05}{\ln0.99}=\frac{-2.9957}{-0.010050}\approx298.07 . $$Since $N+1$ is an integer, $N+1\ge299$, that is, $N\ge298$. To check: for $N=298$, $c_{95}=1-0.05^{1/299}\approx0.00997\le0.01$, and for $N=297$, $c_{95}\approx0.01000$ ($0.0100024$) $\gt0.01$. Hence the smallest $N$ is 298.
With the rule of three, $3/N\le0.01$ gives $N\ge300$, which is almost the same value (because $c_{95}\approx-\ln0.05/(N+1)\approx3/(N+1)$).
If one cracked sample appears: with one crack among $N$, the posterior distribution is $\mathrm{Beta}(\mu\mid 2,\ N)$ ($a+m=1+1$, $b+l=1+(N-1)$). Find its 95% point $c$ by solving the cumulative distribution function (CDF) condition $P(\mu\le c\mid\data)=0.95$ numerically, and search for the $N$ with $c\le0.01$. Because of the one crack, the upper limit becomes larger, so more than 298 samples are needed for the same target (numerical computation gives about $N\ge472$). When making a plan of the form “accept if there are 0 cracks,” it is wise to decide in advance what to do if one appears (how many additional samples to make).
Exercise 4.8: When does the difference between prior distributions disappear?
Solution
(1) $m=18$ and $l=12$. A: $\mathrm{Beta}(1+18,\ 1+12)=\mathrm{Beta}(19,13)$, with posterior mean $19/32\approx0.594$. B: $\mathrm{Beta}(10+18,\ 2+12)=\mathrm{Beta}(28,14)$, with posterior mean $28/42\approx0.667$. The difference is about 0.073, and B is shifted well above the maximum likelihood estimate 0.6.
(2) If the fraction of successes stays 0.6 for $N$ trials, then $m=0.6N$, and the difference is
$$ d(N)=\frac{10+0.6N}{12+N}-\frac{1+0.6N}{2+N}. $$Putting it over a common denominator, the numerator is
$$ \begin{aligned} &(10+0.6N)(2+N)-(1+0.6N)(12+N)\\ &\quad=(20+11.2N+0.6N^{2})\\ &\qquad-(12+8.2N+0.6N^{2})\\ &\quad=8+3N \end{aligned} $$so $d(N)=\dfrac{3N+8}{(N+12)(N+2)}$. At $N=30$, $98/1344\approx0.073$, which agrees with (1). Solve $d(N)\lt0.02$. At $N=138$, $422/(150\times140)=422/21000\approx0.0201$, and at $N=139$, $425/(151\times141)=425/21291\approx0.0200$ ($0.01996$), so the smallest $N$ is 139. Roughly $d\approx3/N$, so the difference shrinks only as $1/N$.
(3) $\mathrm{Beta}(10,2)$ corresponds to pseudo-counts of “9 successes and 1 failure” and strongly asserts the mean $10/12\approx0.83$. If this track record does not apply to the new material, then while the data are few, the posterior mean of B comes out systematically higher than the true value. Moreover, the posterior distribution of B is narrower than that of A (it is regarded as having more information, by the amount of the prior distribution), so the credible interval is narrow, and a wrong value is reported with confidence. As in (2), nearly 140 trials are needed for the difference to fall below 0.02. Countermeasures include comparison with a weak prior distribution such as A (sensitivity analysis), examining the differences between the material on which the prior distribution was based and the new material, and reducing the pseudo-count of the prior distribution (for example, as in $\mathrm{Beta}(5,1)$, reducing $a+b$ from 12 to 6 while keeping the mean $5/6\approx0.83$).
Chapter 5 Information, Entropy, and the KL Divergence — Measuring the Difference Between Distributions
Exercise 5.1: Entropy and the effective number of choices
Solution
(1) Compute each term $-p\ln p$.
$$ \begin{aligned} -0.4\ln0.4&=0.4\times0.9163=0.3665,\\ -0.3\ln0.3&=0.3\times1.2040=0.3612,\\ -0.2\ln0.2&=0.2\times1.6094=0.3219,\\ -0.1\ln0.1&=0.1\times2.3026=0.2303 . \end{aligned} $$The sum is $H[p]=1.2799\ \mathrm{nat}$. In bits, $1.2799/\ln2=1.2799/0.6931\approx1.846\ \mathrm{bit}$.
(2) $\exp(1.2799)\approx3.60$. There are four values, but because of the imbalance, we are effectively as uncertain as if we were choosing among about 3.6 options.
(3) Let $u=(1/4,1/4,1/4,1/4)$ and compute $\KL(p\,\|\,u)=\sum_x p(x)\ln\{4p(x)\}$ term by term.
$$ \begin{aligned} &0.4\ln1.6=0.1880,\quad 0.3\ln1.2=0.0547,\\ &0.2\ln0.8=-0.0446,\quad 0.1\ln0.4=-0.0916 . \end{aligned} $$The sum is $0.1064\ \mathrm{nat}$. On the other hand, $\ln4-H[p]=1.3863-1.2799=0.1064\ \mathrm{nat}$, which agrees. This is a numerical example of the identity $\KL(p\,\|\,u)$ $=\sum p\ln p+\ln4\sum p$ $=-H[p]+\ln4$.
Exercise 5.2: Upper limit of the joint entropy
Solution
(1) Combine the chain rule of entropy $H[x,y]=H[x]+H[y\mid x]$ with the formula for mutual information $I[x;y]=H[y]-H[y\mid x]$, that is, $H[y\mid x]=H[y]-I[x;y]$. This gives
$$ H[x,y]=H[x]+H[y]-I[x;y]. $$The mutual information is the KL divergence $\KL(p(x,y)\,\|\,p(x)p(y))$, so Gibbs’s inequality gives $I[x;y]\ge0$. Hence $H[x,y]\le H[x]+H[y]$. Equality holds only when $I[x;y]=0$, that is, when $p(x,y)=p(x)p(y)$ (independence).
(2) For the joint distribution $(0.12,\,0.28,\,0.06,\,0.54)$, the terms $-p\ln p$ are $0.2544$, $0.3564$, $0.1688$, and $0.3327$, and their sum is $H[x,y]=1.1124\ \mathrm{nat}$. From Chapter 5, Example 5.7, $H[x]=0.6730$, $H[y]=0.4714$, and $I[x;y]=0.0320$, so $H[x]+H[y]-I$ $=0.6730+0.4714-0.0320$ $=1.1124$, which agrees. It is smaller than $H[x]+H[y]=1.1444$.
(3) Applying the chain rule with $y$ first gives $H[x,y]=H[y]+H[x\mid y]$, so $H[x\mid y]=1.1124-0.4714=0.6410\ \mathrm{nat}$. As a check, $H[x]-I=0.6730-0.0320=0.6410$ also agrees.
Exercise 5.3: Differential entropies of three distributions with the same variance
Solution
(1) The variance of a uniform distribution of width $a$ is $a^{2}/12$ (taking the interval $[-a/2,a/2]$, $\int_{-a/2}^{a/2}x^{2}\frac1a\,\dd x=\frac{1}{a}\cdot\frac{2}{3}\left(\frac a2\right)^{3}=\frac{a^{2}}{12}$). For variance 1, $a=\sqrt{12}\approx3.464$. The differential entropy is $\ln a=\ln\sqrt{12}=\tfrac12\ln12\approx1.2425\ \mathrm{nat}$.
(2) Since $\ln p(x)=-\ln(2b)-\abs{x}/b$,
$$ h=\Ex[-\ln p(x)]=\ln(2b)+\frac{\Ex[\abs{x}]}{b}. $$$\Ex[\abs{x}]$ is, because the integrand is an even function, $2\int_0^{\infty}x\,\frac{1}{2b}e^{-x/b}\,\dd x$ $=\frac1b\int_0^{\infty}xe^{-x/b}\,\dd x$ $=\frac1b\cdot b^{2}=b$ (using $\int_0^\infty xe^{-x/b}\dd x=b^{2}$). Hence $h=\ln(2b)+1$. Similarly, $\Ex[x^{2}]=\frac1b\int_0^\infty x^{2}e^{-x/b}\dd x=\frac1b\cdot2b^{3}=2b^{2}$, so variance 1 requires $b=1/\sqrt2$. Then $h=1+\ln\sqrt2=1+0.3466=1.3466\ \mathrm{nat}$.
(3) Setting $\sigma=1$ in the formula for the differential entropy of the Gaussian distribution in Chapter 5, Section 5.3.1 gives $h=\tfrac12\ln(2\pi e)=\tfrac12(1.8379+1)=1.4189\ \mathrm{nat}$.
In order of size, $1.2425\lt1.3466\lt1.4189$, so for a given variance the Gaussian distribution has the largest entropy. This is an example of Theorem 5.2 (b).
Exercise 5.4: Cross-entropy loss for binary classification
Solution
(1) The loss of one sample is $L_n=-\{y_n\ln\hat{y}_n+(1-y_n)\ln(1-\hat{y}_n)\}$. For a sample with $y=1$ it is $-\ln\hat{y}$, and for a sample with $y=0$ it is $-\ln(1-\hat{y})$.
$$ \begin{aligned} L_1&=-\ln0.9=0.1054,\\ L_2&=-\ln(1-0.2)=-\ln0.8=0.2231,\\ L_3&=-\ln0.6=0.5108,\\ L_4&=-\ln0.4=0.9163 . \end{aligned} $$The mean is $(0.1054+0.2231+0.5108+0.9163)/4$ $=1.7556/4$ $=0.4389\ \mathrm{nat}$. The fourth sample (a good item for which the probability of being good was given as 0.4) makes the largest contribution.
(2) If the classifier always outputs $c$, the mean loss over three good items and one defective item is
$$ \bar{L}(c)=-\frac14\bigl(3\ln c+\ln(1-c)\bigr). $$Differentiating and setting the result to 0 gives $-\frac14\left(\frac3c-\frac{1}{1-c}\right)=0$, so $3(1-c)=c$ and $c=3/4$. The loss at this value is $-(0.75\ln0.75+0.25\ln0.25)=0.5623\ \mathrm{nat}$, which equals the entropy of the empirical distribution $(0.75,0.25)$ of the correct labels (the KL divergence from the empirical distribution is 0).
(3) For $c=0.5$, the loss is $-\ln0.5=0.6931\ \mathrm{nat}$. In order of size, $0.4389\lt0.5623\lt0.6931$. The value $0.75$, which learns only the proportion of the labels, is better than $0.5$, which learns nothing, and the classifier of (1), which uses the input, is better still. The value of a model that uses the input is best measured by how much it can lower the loss below $0.5623$, the loss of the “proportion-only model.”
Exercise 5.5: Probability 0 and the blow-up of the KL divergence
Solution
(1) For $\KL(p\,\|\,q)$: the third value has $p=0$, so its term is 0. The remainder is $2\times0.5\ln\frac{0.5}{0.45}=\ln\frac{10}{9}\approx0.1054\ \mathrm{nat}$.
For $\KL(q\,\|\,p)$: at the third value, $q=0.1\gt0$ but $p=0$, so the term $0.1\ln(0.1/0)$ becomes $+\infty$, and $\KL(q\,\|\,p)=+\infty$.
(2) The cross-entropy loss is $H[\hat{p},q]=H[\hat{p}]+\KL(\hat{p}\,\|\,q)$ with respect to the empirical distribution $\hat{p}$. If the model $q$ assigns probability 0 to some class and even one sample of that class is in the data, the loss of that sample is $-\ln0=+\infty$, and the mean loss is also $+\infty$. This has the same structure as $\KL(q\,\|\,p)$ in (1) (the right-hand distribution is 0 where the left-hand distribution places probability). In numerical computation, $\ln0$ becomes $-\infty$ or NaN, and the gradient can no longer be computed either.
(3) Examples of countermeasures: (a) Clip the output probabilities to $[\varepsilon,1-\varepsilon]$ (with $\varepsilon$ about $10^{-7}$) before taking the logarithm. (b) Instead of computing the probabilities first and then taking the logarithm, compute the log-softmax directly from the logits using log-sum-exp (the logarithm stays finite even if a probability is rounded to 0). (c) Mix the one-hot target slightly with the uniform distribution (label smoothing). (a) and (b) are numerical measures to keep the loss finite, and the optimal model hardly changes. (c) changes the target distribution itself, so the learned model no longer assigns probability 1 to the correct class (its degree of confidence decreases).
Exercise 5.6: A non-equimolar high-entropy alloy
Solution
(1) The mole fractions are $x_{\mathrm{Al}}=0.5/4.5=1/9$, and $1/4.5=2/9$ for each of Co, Cr, Fe, and Ni. The terms are
$$ \begin{aligned} -\tfrac19\ln\tfrac19&=\tfrac{\ln9}{9}=0.2441,\\ -\tfrac29\ln\tfrac29&=\tfrac29\ln4.5=0.3342 . \end{aligned} $$Hence $\Delta S_{\mathrm{conf}}/R=0.2441+4\times0.3342=1.5811$, and $\Delta S_{\mathrm{conf}}$ $=1.5811\times8.314$ $\approx13.15\ \mathrm{J\,mol^{-1}\,K^{-1}}$.
(2) Equimolar quaternary system: $R\ln4=1.3863R\approx11.53\ \mathrm{J\,mol^{-1}\,K^{-1}}$. Equimolar quinary system: $R\ln5=1.6094R\approx13.38\ \mathrm{J\,mol^{-1}\,K^{-1}}$. $\mathrm{Al_{0.5}CoCrFeNi}$ is larger than the quaternary system and slightly smaller than the equimolar quinary system (the difference is about $0.24\ \mathrm{J\,mol^{-1}\,K^{-1}}$).
(3) The equimolar composition $x_i=1/5$. This is because the configurational entropy is $R\,H[\bm{x}]$ ($R$ times the entropy obtained by regarding the composition as a probability distribution), and by Theorem 5.2 (a) the entropy of a distribution taking five values attains its maximum value $\ln5$ only for the uniform distribution. However, this concerns only the configurational entropy under the assumption of ideal random mixing, and the phase stability of a real alloy also depends on the enthalpy of mixing and on short-range order.
Exercise 5.7: Spin entropy of a paramagnet
Solution
(1) The energies of the two states are $\mp\mu_{\mathrm B}B$, so in the canonical distribution (Chapter 5, Section 5.8.2), $\beta E=\mp\xi$. The partition function is $Z=e^{\xi}+e^{-\xi}=2\cosh\xi$, and the probabilities are
$$ p_{\text{parallel}}=\frac{e^{\xi}}{2\cosh\xi},\qquad p_{\text{antiparallel}}=\frac{e^{-\xi}}{2\cosh\xi}. $$The mean energy is $\bar{E}=-\mu_{\mathrm B}B\,(p_{\text{parallel}}-p_{\text{antiparallel}})=-\mu_{\mathrm B}B\tanh\xi$, so $\beta\bar{E}=-\xi\tanh\xi$. The entropy of the canonical distribution is $H=\beta\bar{E}+\ln Z$ (Chapter 5, Section 5.8.2), so
$$ H=\ln(2\cosh\xi)-\xi\tanh\xi . $$The moments are independent of one another, so for 1 mol we multiply by $N_{\mathrm A}$ to get $S=N_{\mathrm A}k_{\mathrm B}H=RH$, that is, $S/R=\ln(2\cosh\xi)-\xi\tanh\xi$.
(2) $\xi=0.5$: $\ln(2\cosh0.5)=\ln2.2553=0.8133$ and $0.5\tanh0.5=0.2311$, so $S/R=0.5822$ and $S\approx4.84\ \mathrm{J\,mol^{-1}\,K^{-1}}$.
$\xi=1$: $\ln(2\cosh1)=\ln3.0862=1.1269$ and $\tanh1=0.7616$, so $S/R=0.3653$ and $S\approx3.04\ \mathrm{J\,mol^{-1}\,K^{-1}}$.
$\xi=2$: $\ln(2\cosh2)=\ln7.5244=2.0182$ and $2\tanh2=1.9281$, so $S/R=0.0901$ and $S\approx0.75\ \mathrm{J\,mol^{-1}\,K^{-1}}$.
(3) For $\xi\to0$ (high temperature or weak field): $\cosh\xi\to1$ and $\xi\tanh\xi\to0$, so $S\to R\ln2\approx5.76\ \mathrm{J\,mol^{-1}\,K^{-1}}$. The two directions are equally probable, and each moment carries 1 bit of uncertainty. For $\xi\to\infty$ (low temperature or strong field): $\ln(2\cosh\xi)=\xi+\ln(1+e^{-2\xi})\to\xi$ and $\xi\tanh\xi\to\xi$, so $S\to0$. All the moments align with the direction of the field, and the uncertainty disappears.
(4) $S$ is a function only of $\xi=\mu_{\mathrm B}B/(k_{\mathrm B}T)$, so keeping $S$ constant keeps $\xi$ constant, that is, $B/T$ constant. Therefore, when the field is weakened adiabatically, the temperature falls in proportion to the field. This is the principle of cooling by adiabatic demagnetization (in practice, lattice-vibration entropy and interactions between the moments exist, so this is limited to the range in which this idealized model holds).
Exercise 5.8: Mutual information between a descriptor and the phase formed
Solution
(1) In both tables the marginal distributions are $(0.5,0.5)$ for the descriptor and $(0.5,0.5)$ for the phase, so $p(\cdot)p(\cdot)=0.25$.
Descriptor $a$: the joint probabilities are $0.40,\,0.10,\,0.10,\,0.40$.
Descriptor $b$: the joint probabilities are $0.30,\,0.20,\,0.20,\,0.30$.
$$ \begin{aligned} I[b;y]&=2\times0.30\ln\frac{0.30}{0.25}\\ &\quad+2\times0.20\ln\frac{0.20}{0.25}\\ &=0.6\times0.1823+0.4\times(-0.2231)\\ &=0.1094-0.0893=0.0201\ \mathrm{nat}. \end{aligned} $$(2) $H[y]=\ln2=0.6931\ \mathrm{nat}$. Knowing descriptor $a$ reduces the uncertainty by $0.1927/0.6931\approx27.8\%$, and knowing descriptor $b$ reduces it by $0.0201/0.6931\approx2.9\%$. Descriptor $a$ is far more useful.
(3) We cannot say so. Mutual information measures only the strength of dependence; it does not distinguish the direction (which is the cause) or whether the dependence is only apparent because of a third factor. For example, if the compositions with a large $a$ are concentrated in the lineage of a particular element, and that lineage happens to form the perovskite type easily, then changing $a$ may not change the structure. If many compositions from the same lineage are included, the data are not independent, and the dependence looks spuriously strong. Moreover, mutual information computed from about 100 samples tends to be positive even when the true value is 0. To claim causation, we need syntheses that change only $a$ with the lineage held fixed (interventions) or support from a physical mechanism (Chapter 6, Section 6.11).
Chapter 6 Generalization, Model Selection, and Regularization — Models That Predict Unseen Data
Exercise 6.1: Size of the optimism of the training error (derivation and computation)
Solution
(0) Properties of $\bm{H}$. Since the columns of $\bm{\Phi}$ are linearly independent, $\bm{\Phi}^{\tp}\bm{\Phi}\in\R^{M\times M}$ is invertible.
- $\bm{H}\bm{\Phi}=\bm{\Phi}(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}(\bm{\Phi}^{\tp}\bm{\Phi})=\bm{\Phi}$.
- $\bm{H}^{\tp}=\bm{\Phi}\bigl((\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bigr)^{\tp}\bm{\Phi}^{\tp}$ $=\bm{\Phi}(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bm{\Phi}^{\tp}=\bm{H}$ (the inverse of a symmetric matrix is symmetric).
- $\bm{H}^{2}=\bm{H}\bm{\Phi}(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bm{\Phi}^{\tp}$ $=\bm{\Phi}(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bm{\Phi}^{\tp}=\bm{H}$ (we used the first property).
- $\tr\bm{H}=\tr\bigl(\bm{\Phi}\,[(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bm{\Phi}^{\tp}]\bigr)$ $=\tr\bigl([(\bm{\Phi}^{\tp}\bm{\Phi})^{-1}\bm{\Phi}^{\tp}]\,\bm{\Phi}\bigr)$ $=\tr\bm{I}_M=M$ ($\tr(\bm{A}\bm{B})=\tr(\bm{B}\bm{A})$).
Expectation of a quadratic form. For a constant matrix $\bm{A}\in\R^{N\times N}$, $\bm{\varepsilon}^{\tp}\bm{A}\bm{\varepsilon}=\sum_{i,j}A_{ij}\varepsilon_i\varepsilon_j$. Since $\Cov[\bm{\varepsilon}]=\sigma^{2}\bm{I}$ and $\Ex[\bm{\varepsilon}]=\bm{0}$, we have $\Ex[\varepsilon_i\varepsilon_j]=\sigma^{2}$ ($i=j$) and $0$ ($i\ne j$), so $\Ex[\bm{\varepsilon}^{\tp}\bm{A}\bm{\varepsilon}]=\sigma^{2}\sum_iA_{ii}=\sigma^{2}\tr\bm{A}$.
Training error. $\bm{y}-\hat{\bm{y}}=(\bm{I}-\bm{H})(\bm{\Phi}\bm{w}_0+\bm{\varepsilon})=(\bm{I}-\bm{H})\bm{\varepsilon}$ ($\bm{H}\bm{\Phi}=\bm{\Phi}$). Since $(\bm{I}-\bm{H})^{\tp}(\bm{I}-\bm{H})=\bm{I}-2\bm{H}+\bm{H}^{2}=\bm{I}-\bm{H}$,
$$ \begin{aligned} \Ex\bigl[\norm{\bm{y}-\hat{\bm{y}}}^{2}\bigr]&=\Ex\bigl[\bm{\varepsilon}^{\tp}(\bm{I}-\bm{H})\bm{\varepsilon}\bigr]\\ &=\sigma^{2}\tr(\bm{I}-\bm{H})=\sigma^{2}(N-M) . \end{aligned} $$A new measurement at the same inputs. Let $\bm{y}'=\bm{\Phi}\bm{w}_0+\bm{\varepsilon}'$ ($\bm{\varepsilon}'$ is independent of $\bm{\varepsilon}$ and has the same distribution). Then $\bm{y}'-\hat{\bm{y}}=\bm{\varepsilon}'-\bm{H}\bm{\varepsilon}$. The expectation of the cross term, $-2\,\Ex[\bm{\varepsilon}'^{\tp}\bm{H}\bm{\varepsilon}]$, is 0 by independence and zero mean. Hence
$$ \begin{aligned} &\Ex\bigl[\norm{\bm{y}'-\hat{\bm{y}}}^{2}\bigr]\\ &\quad=N\sigma^{2}+\Ex\bigl[\bm{\varepsilon}^{\tp}\bm{H}^{\tp}\bm{H}\bm{\varepsilon}\bigr]\\ &\quad=N\sigma^{2}+\sigma^{2}\tr\bm{H}=\sigma^{2}(N+M) . \end{aligned} $$(From the second line to the third we used $\bm{H}^{\tp}\bm{H}=\bm{H}^{2}=\bm{H}$ and the expectation of a quadratic form.)
Dividing both by $N$ gives $\sigma^{2}(1-M/N)$ and $\sigma^{2}(1+M/N)$ in Eq. (6.3) of Chapter 6.
(1) With $\sigma^{2}=0.25\ \%^{2}$, $M=4$, and $N=20$, the expectation of the mean squared training error is $0.25\times(1-4/20)=0.25\times0.8=0.20\ \%^{2}$, and for a new measurement it is $0.25\times(1+0.2)=0.30\ \%^{2}$.
(2) For $M=10$: $0.25\times(1-0.5)=0.125\ \%^{2}$ and $0.25\times1.5=0.375\ \%^{2}$. The difference (the size of the optimism) is $0.10$ for $M=4$ and $0.25\ \%^{2}$ for $M=10$, so it grows in proportion to $M$.
(3) By (0), the expectation of the residual sum of squares is $\sigma^{2}(N-M)$, so $\hat\sigma^{2}=\norm{\bm{y}-\hat{\bm{y}}}^{2}/(N-M)$ is an unbiased estimate of $\sigma^{2}$. We get $\hat\sigma^{2}=3.2/(20-4)=0.20\ \%^{2}$ and $\hat\sigma=\sqrt{0.20}\approx0.447\ \%$. Dividing by $N$ gives $3.2/20=0.16\ \%^{2}$, whose square root is $0.40\ \%$, which underestimates the noise by about 10 %.
Exercise 6.2: Shrinkage estimation and one-dimensional ridge regression
Solution
(1) As in Example 6.4 of Chapter 6, $\Ex[\hat\mu_c]=r+c(\mu-r)$, so the bias is $-(1-c)\Delta$ and the variance is $c^{2}\sigma^{2}/N$; thus
$$ m(c)\equiv\Ex[(\hat\mu_c-\mu)^{2}]=(1-c)^{2}\Delta^{2}+c^{2}\frac{\sigma^{2}}{N} . $$Differentiate with respect to $c$ and set the result to 0: $-2(1-c)\Delta^{2}+2c\,\sigma^{2}/N=0$, which gives
$$ c^{\ast}=\frac{\Delta^{2}}{\Delta^{2}+\sigma^{2}/N} . $$The second derivative $2\Delta^{2}+2\sigma^{2}/N\gt0$, so this is a minimum. Writing $v=\sigma^{2}/N$, we have $1-c^{\ast}=v/(\Delta^{2}+v)$, and
$$ \begin{aligned} m(c^{\ast})&=\frac{v^{2}\Delta^{2}+\Delta^{4}v}{(\Delta^{2}+v)^{2}}=\frac{v\Delta^{2}(v+\Delta^{2})}{(\Delta^{2}+v)^{2}}\\ &=\frac{\Delta^{2}}{\Delta^{2}+v}\,v=c^{\ast}\,\frac{\sigma^{2}}{N} . \end{aligned} $$This is always smaller than the squared error $\sigma^{2}/N$ of the sample mean ($c=1$) (if $\sigma^{2}/N\gt0$, then $c^{\ast}\lt1$). For $\Delta=1$ and $v=0.25$ in Example 6.4, we get $c^{\ast}=0.8$ and minimum value $0.2$, which agrees. However, $c^{\ast}$ contains the unknown $\Delta$, so in practice the strength of the shrinkage must be chosen using validation data or the like.
(2) Let $z=\sum_nx_ny_n$. Substituting $y_n=w^{\ast}x_n+\varepsilon_n$ gives $z=w^{\ast}S+\sum_nx_n\varepsilon_n$, so $\Ex[z]=w^{\ast}S$ and $\Var[z]=\sum_nx_n^{2}\sigma^{2}=\sigma^{2}S$ (the $\varepsilon_n$ are independent). Since $w_\lambda=z/(S+\lambda)$,
$$ \begin{aligned} \Ex[w_\lambda]-w^{\ast}&=\frac{w^{\ast}S}{S+\lambda}-w^{\ast}=-\frac{w^{\ast}\lambda}{S+\lambda},\\ \Var[w_\lambda]&=\frac{\sigma^{2}S}{(S+\lambda)^{2}} . \end{aligned} $$The expectation of the squared error is (bias)² + variance:
$$ m(\lambda)=\frac{(w^{\ast})^{2}\lambda^{2}+\sigma^{2}S}{(S+\lambda)^{2}} . $$By the quotient rule,
$$ \begin{aligned} m'(\lambda)&=\frac{2(w^{\ast})^{2}\lambda(S+\lambda)}{(S+\lambda)^{3}}\\ &\qquad-\frac{2\bigl((w^{\ast})^{2}\lambda^{2}+\sigma^{2}S\bigr)}{(S+\lambda)^{3}}\\ &=\frac{2S\bigl((w^{\ast})^{2}\lambda-\sigma^{2}\bigr)}{(S+\lambda)^{3}} . \end{aligned} $$It is negative for $\lambda\lt\sigma^{2}/(w^{\ast})^{2}$ and positive for larger values, so the minimum is at $\lambda^{\ast}=\sigma^{2}/(w^{\ast})^{2}$. The larger the noise and the smaller the true coefficient, the stronger the regularization that is best. The $\lambda=\sigma^{2}/\sigma_w^{2}$ of Bayesian linear regression, derived in Chapter 8, can be read as putting the anticipated size $\sigma_w^{2}$ of the coefficient in place of $(w^{\ast})^{2}$.
Exercise 6.3: Three-fold cross-validation and leave-one-out
Solution
The data are $y=(2.1,\ 2.5,\ 1.8,\ 2.9,\ 2.2,\ 2.6)$ eV.
(1) Leaving out pair 1 (2.1, 2.5), the training mean is $(1.8+2.9+2.2+2.6)/4=9.5/4=2.375$. The residuals are $2.1-2.375=-0.275$ and $2.5-2.375=0.125$. Leaving out pair 2 (1.8, 2.9), the mean is $(2.1+2.5+2.2+2.6)/4=9.4/4=2.350$, with residuals $-0.550$ and $0.550$. Leaving out pair 3 (2.2, 2.6), the mean is $(2.1+2.5+1.8+2.9)/4=9.3/4=2.325$, with residuals $-0.125$ and $0.275$. The squares are $0.075625,\ 0.015625,\ 0.3025,$ $0.3025,\ 0.015625,\ 0.075625$, and their sum is $0.7875$. The mean squared error of the three-fold cross-validation is $0.7875/6=0.131\ \mathrm{eV}^{2}$ (RMSE 0.362 eV).
(2) The overall mean is $14.1/6=2.35$. The training residuals are $-0.25,\ 0.15,\ -0.55,\ 0.55,\ -0.15,\ 0.25$, the sum of squares is $0.0625+0.0225+0.3025$ $+0.3025+0.0225+0.0625$ $=0.775$, and the mean is $0.775/6=0.1292\ \mathrm{eV}^{2}$. The LOO residuals are $\frac{N}{N-1}=\frac65=1.2$ times these: $-0.30,\ 0.18,\ -0.66,\ 0.66,\ -0.18,\ 0.30$. For example, the mean with the first point left out is $(2.5+1.8+2.9+2.2+2.6)/5$ $=12.0/5=2.40$, and the residual $2.1-2.40=-0.30$ agrees. The sum of squares is $0.09+0.0324+0.4356$ $+0.4356+0.0324+0.09$ $=1.116$, and the mean is $1.116/6=0.186\ \mathrm{eV}^{2}$. This agrees with $(6/5)^{2}\times0.1292=1.44\times0.1292=0.186$.
That LOO (0.186) is larger than the three-fold value (0.131) is because, in this example, the residuals happened to cancel for the particular way the pairs were split; in general it is not determined which is larger. With only six data points, the cross-validation value changes greatly with the way the data are split.
Exercise 6.4: Duplicates in a database and splitting
Solution
(1) For each of the 120 duplicated rows, the probability that the row falls on the validation side is $40/200=0.2$. Given that, the probability that its partner (a specific one of the remaining 199 rows) falls in the 160 training slots is $160/199$. By the linearity of expectation, the expected number of validation rows whose partner is in the training data is
$$ 120\times\frac{40}{200}\times\frac{160}{199}=24\times0.804=19.3\ \text{rows} $$which is about 48 % of the 40 validation rows ($19.3/40=0.482$).
(2) For a row that has a partner, the predicted value is the partner’s measured value, so the error is the difference of two independent measurements, and the expectation of the squared error is $2\times0.04^{2}=0.0032\ \mathrm{eV}^{2}$. For the other rows it is $0.35^{2}=0.1225\ \mathrm{eV}^{2}$. The expectation of the mean squared validation error is $0.518\times0.1225+0.482\times0.0032$ $=0.0634+0.0015$ $=0.0650\ \mathrm{eV}^{2}$, and its square root is $0.255\ \mathrm{eV}$. This looks about 27 % smaller than the true 0.35 eV.
(3) (a) Find the duplicates before splitting, and combine them into one row per composition, for example by averaging the measurements of the same composition. (b) Perform a group split with composition as the group, so that rows of the same composition do not straddle training and validation. In either case, decide and record beforehand the criterion for finding duplicates (variations in how compositions are written, and whether polymorphs are distinguished).
Exercise 6.5: Extrapolating the band gap of a mixed crystal from half of the composition range
Solution
(1) $E_g(x)=1.20-1.20x+2.40x$ $-0.80x+0.80x^{2}$ $=1.20+0.40x+0.80x^{2}$ eV.
(2) First find the straight line $\alpha+\beta x$ that approximates $x^{2}$ on $[0,h]$. Differentiate $J(\alpha,\beta)=\int_0^{h}(x^{2}-\alpha-\beta x)^{2}\dd x$ partially with respect to $\alpha,\beta$ and set the results to 0 (the integral version of the normal equations):
$$ \begin{aligned} \int_0^{h}(x^{2}-\alpha-\beta x)\,\dd x&=0,\\ \int_0^{h}x\,(x^{2}-\alpha-\beta x)\,\dd x&=0 . \end{aligned} $$Integrating gives $\dfrac{h^{3}}{3}=\alpha h+\beta\dfrac{h^{2}}{2}$ and $\dfrac{h^{4}}{4}=\alpha\dfrac{h^{2}}{2}+\beta\dfrac{h^{3}}{3}$. Dividing the first equation by $h$ and the second by $h^{2}/2$ gives $\dfrac{h^{2}}{3}=\alpha+\dfrac{\beta h}{2}$ and $\dfrac{h^{2}}{2}=\alpha+\dfrac{2\beta h}{3}$. Taking the difference, $\dfrac{h^{2}}{6}=\dfrac{\beta h}{6}$, so $\beta=h$ and $\alpha=\dfrac{h^{2}}{3}-\dfrac{h^{2}}{2}=-\dfrac{h^{2}}{6}$.
The constant and $x$ terms can be represented exactly by a straight line, so the best straight line for $E_g$ is $1.20+0.40x+0.80(hx-h^{2}/6)$. Substituting $h=0.5$,
$$ \begin{aligned} a+bx&=1.20-\frac{0.80\times0.25}{6}\\ &\qquad+(0.40+0.80\times0.5)\,x\\ &=1.1667+0.80\,x\ \ \mathrm{eV}. \end{aligned} $$(3) The error (line − true value) is, at $x=0$: $1.1667-1.20=-0.033$ eV; at $x=0.25$: $1.3667-1.35=+0.017$ eV; at $x=0.5$: $1.5667-1.60=-0.033$ eV. Within the range the error is at most 0.033 eV, comparable to the noise standard deviation of 0.03 eV, so it is hard to notice from the measurements that “a straight line is not enough.” On the other hand, at $x=1$ the line gives $1.967$ eV while the true value is $2.40$ eV, so the error is $-0.433$ eV, more than 14 times the noise.
(4) That the error within the range was at the noise level does not guarantee correctness outside the range. A term such as the curvature (bowing) of $x(1-x)$, which looks weak inside the range, has a large effect outside. When predicting beyond the composition range, (a) state explicitly that this is extrapolation, (b) use a physically reasonable functional form (such as Vegard’s law plus a bowing term; Chapter 8), and (c) if possible, measure even one point at the end of the range (BC at $x=1$) to check the model.
Exercise 6.6: Negative coefficient of determination
Solution
The mean of the test data is $\bar{y}=(3.0+3.4+2.8+3.6)/4=3.2$ eV, and $\sum_n(y_n-\bar{y})^{2}$ $=0.04+0.04+0.16+0.16$ $=0.40\ \mathrm{eV}^{2}$.
(1) The errors $y-\hat{y}$ of model A are $(-0.3,\ 0.1,\ -0.5,\ 0.3)$. MAE $=(0.3+0.1+0.5+0.3)/4=0.30$ eV. The sum of squares is $0.09+0.01+0.25+0.09=0.44$, and RMSE $=\sqrt{0.44/4}=\sqrt{0.11}=0.332$ eV. $R^{2}=1-0.44/0.40=-0.10$.
(2) The errors of model B are $(-0.1,\ 0.1,\ -0.1,\ 0.2)$. MAE $=0.5/4=0.125$ eV. The sum of squares is $0.01+0.01+0.01+0.04=0.07$, and RMSE $=\sqrt{0.0175}=0.132$ eV. $R^{2}=1-0.07/0.40=0.825$.
(3) The denominator $\sum_n(y_n-\bar{y})^{2}$ of $R^{2}$ is “the sum of squared errors when all points are predicted by the test data’s own mean, 3.2 eV.” The prediction 3.3 eV of model A is farther from the data than this mean, so its sum of squares, 0.44, is larger than the denominator 0.40, and $R^{2}\lt0$. The mean of the test data is a value that is not known at the time of prediction, so $R^{2}\lt0$ means “we could have won if we had known the mean of the test data.” It tends to occur when the mean of the training data and the mean of the test data are shifted (the distribution has changed).
Exercise 6.7: Surface color and density
Solution
(1) The variance of a sum of independent quantities is the sum of the variances, and the covariance of independent quantities is 0, so
$$ \begin{aligned} \Var[x]&=0.8^{2}\times1+0.36=1.00,\\ \Cov[x,y]&=0.8\times1.5\times\Var[z]=1.20,\\ \Var[y]&=1.5^{2}+0.75=3.00 . \end{aligned} $$The regression slope is $\Cov[x,y]/\Var[x]=1.20$, and the correlation coefficient is $1.20/\sqrt{1.00\times3.00}=0.693$.
(2) We have $y=1.5z+n_y$, and $n_y$ is independent of both $x$ and $z$ ($x$ is determined only by $z$ and $n_x$), so $\Ex[y\mid x,z]=1.5z$. The regression that includes both $x$ and $z$ (least squares over the population) coincides with the conditional expectation, so the coefficient of $x$ is 0 and the coefficient of $z$ is 1.5. The whole correlation between $x$ and $y$ passes through $z$, so once $z$ is fixed, $x$ tells us nothing about $y$.
(3) An example experiment: split samples fired in the same furnace and at the same position (the same $z$) randomly into two groups, polish or paint the surface of only one group to change its lightness, and compare the densities. If there is no difference in density, lightness is not the cause. As another design, assign the position in the furnace to each sample at random, measure the actual temperature with a thermocouple, record $z$, and carry out the regression of (2).
(4) As long as the samples are made in the same furnace, in the same atmosphere, and from the same raw materials, the relation between lightness and density (the correlation through $z$) is preserved, so lightness can be useful as an inexpensive test for estimating density. However, it is useful only as long as “the data arise by the same mechanism.” If the relation $z\to x$ changes, for example by changing the furnace, by changing the atmosphere so that the way the color changes is different, or by finishing the surface, the prediction breaks down (the distribution shift of Section 6.9). It cannot be used by manipulating lightness in order to raise the density.
Exercise 6.8: The expectation of the smaller of two candidates
Solution
For any real numbers $a,b$, $\min(a,b)=\dfrac{a+b}{2}-\dfrac{\abs{a-b}}{2}$ (if $a\le b$, the right-hand side $=\frac{a+b}{2}-\frac{b-a}{2}=a$, and similarly for $a\gt b$). By the linearity of expectation,
$$ \begin{aligned} \Ex[\min(a,b)]&=\frac{\Ex[a]+\Ex[b]}{2}-\frac{\Ex\abs{a-b}}{2}\\ &=\mu-\frac{\Ex\abs{a-b}}{2} . \end{aligned} $$Since $a,b$ are independent Gaussian random variables, $u=a-b$ is also Gaussian, with mean 0 and variance $s^{2}+s^{2}=2s^{2}$. For $u\sim\Normal(0,\sigma_u^{2})$ ($\sigma_u$ is the standard deviation of $u$), using the fact that the integrand is an even function, $\Ex\abs{u}$ is
$$ \begin{aligned} \Ex\abs{u}&=2\int_0^{\infty}u\,\frac{1}{\sqrt{2\pi}\,\sigma_u}e^{-u^{2}/(2\sigma_u^{2})}\,\dd u\\ &=\frac{2}{\sqrt{2\pi}\,\sigma_u}\Bigl[-\sigma_u^{2}e^{-u^{2}/(2\sigma_u^{2})}\Bigr]_0^{\infty}\\ &=\frac{2\sigma_u^{2}}{\sqrt{2\pi}\,\sigma_u}=\sigma_u\sqrt{\frac{2}{\pi}} . \end{aligned} $$Substituting $\sigma_u=\sqrt2\,s$ gives $\Ex\abs{a-b}=\sqrt2\,s\sqrt{2/\pi}=2s/\sqrt{\pi}$. Therefore
$$ \Ex[\min(a,b)]=\mu-\frac{s}{\sqrt{\pi}} . $$The bias $s/\sqrt\pi$ is proportional to the spread $s$ of the estimate of the validation error. The less validation data there is, the larger $s$ is, and the more optimistic the validation error of the selected model becomes. Conversely, if we increase the validation data and make $s$ smaller, the bias due to selection also becomes smaller.
Chapter 7 Fundamentals of Optimization — Descending the Valley of the Loss
Exercise 7.1: Tracing two-dimensional gradient descent by hand
Solution
(1) From $\det(\bm{H}-\lambda\bm{I})=(3-\lambda)^{2}-1=0$ we get $3-\lambda=\pm1$, so the eigenvalues are $\lambda=2$ and $\lambda=4$. For $\lambda=4$: $(\bm{H}-4\bm{I})\bm{q}=\bm{0}$ reads $-q_1+q_2=0$, so $\bm{q}_2=(1,1)^{\tp}/\sqrt2$. For $\lambda=2$: $q_1+q_2=0$, so $\bm{q}_1=(1,-1)^{\tp}/\sqrt2$. The two eigenvectors are orthogonal.
(2) The condition for convergence is $0\lt\eta\lt2/\lambda_{\max}=2/4=0.5$. We have $\eta_{\mathrm{opt}}=2/(4+2)=1/3$, $\kappa=4/2=2$, and $\rho_{\mathrm{opt}}=(2-1)/(2+1)=1/3$.
(3) Since $\bm{H}\bm{w}_0=(3\cdot2+1\cdot0,\ 1\cdot2+3\cdot0)^{\tp}=(6,2)^{\tp}$,
$$ \begin{aligned} \bm{w}_1&=\bm{w}_0-\tfrac13\bm{H}\bm{w}_0\\ &=(2,0)^{\tp}-(2,\tfrac23)^{\tp}=\bigl(0,\ -\tfrac23\bigr)^{\tp}. \end{aligned} $$Since $\bm{H}\bm{w}_1=(-\tfrac23,\ -2)^{\tp}$,
$$ \begin{aligned} \bm{w}_2&=\bm{w}_1-\tfrac13\bm{H}\bm{w}_1\\ &=\bigl(0+\tfrac29,\ -\tfrac23+\tfrac23\bigr)^{\tp}=\bigl(\tfrac29,\ 0\bigr)^{\tp}. \end{aligned} $$The norms are $\norm{\bm{w}_0}=2$, $\norm{\bm{w}_1}=2/3$, and $\norm{\bm{w}_2}=2/9$, so the norm shrinks by exactly a factor of $1/3$ at each step. The losses are $L(\bm{w}_0)=\tfrac12\bm{w}_0^{\tp}\bm{H}\bm{w}_0=\tfrac12(2\cdot6)=6$, $L(\bm{w}_1)=\tfrac12\cdot\tfrac23\cdot2=\tfrac23$, and $L(\bm{w}_2)=\tfrac12\cdot\tfrac29\cdot\tfrac23=\tfrac{2}{27}\approx0.0741$, so the loss shrinks by a factor of $1/9$ at each step.
(Intuition) We have $\bm{w}_0=(2,0)^{\tp}=\sqrt2\,\bm{q}_1+\sqrt2\,\bm{q}_2$. With $\eta=1/3$, the $\bm{q}_1$ component is multiplied by $1-\tfrac13\cdot2=\tfrac13$ and the $\bm{q}_2$ component by $1-\tfrac13\cdot4=-\tfrac13$. Both factors have absolute value $1/3$, so the norm shrinks by exactly a factor of $1/3$, and only the sign of the $\bm{q}_2$ component flips at every step (this is why $\bm{w}$ moves alternately on the $w_1$ axis and the $w_2$ axis).
Exercise 7.2: The optimal constant learning rate
Solution
(1) For a fixed $\eta\gt0$, $\phi(\lambda)=1-\eta\lambda$ is a linear (decreasing) function of $\lambda$. For every $\lambda$ in the interval $[\lambda_{\min},\lambda_{\max}]$ we have $\phi(\lambda_{\max})\le\phi(\lambda)\le\phi(\lambda_{\min})$, so $\abs{\phi(\lambda)}\le\max\bigl(\abs{\phi(\lambda_{\min})},\abs{\phi(\lambda_{\max})}\bigr)$. All the eigenvalues lie in this interval, and its two endpoints are themselves eigenvalues, so $\rho(\eta)=\max\bigl(\abs{1-\eta\lambda_{\min}},\abs{1-\eta\lambda_{\max}}\bigr)$.
(2) Let $a(\eta)=\abs{1-\eta\lambda_{\min}}$ and $b(\eta)=\abs{1-\eta\lambda_{\max}}$. For $0\lt\eta\le1/\lambda_{\max}$, both are of the form $1-\eta\lambda$ and $a\ge b$, so $\rho=a=1-\eta\lambda_{\min}$ decreases in $\eta$. For $\eta\ge1/\lambda_{\min}$, $b=\eta\lambda_{\max}-1\ge a=\eta\lambda_{\min}-1$, so $\rho=b$ increases. In between, for $1/\lambda_{\max}\le\eta\le1/\lambda_{\min}$, we have $a=1-\eta\lambda_{\min}$ (decreasing) and $b=\eta\lambda_{\max}-1$ (increasing), so $\rho=\max(a,b)$ is smallest at the point where $a=b$.
$$ \begin{aligned} &1-\eta\lambda_{\min}=\eta\lambda_{\max}-1\\ &\Longrightarrow\quad \eta_{\mathrm{opt}}=\frac{2}{\lambda_{\max}+\lambda_{\min}} . \end{aligned} $$Then
$$ \begin{aligned} \rho_{\mathrm{opt}}&=1-\frac{2\lambda_{\min}}{\lambda_{\max}+\lambda_{\min}}\\ &=\frac{\lambda_{\max}-\lambda_{\min}}{\lambda_{\max}+\lambda_{\min}}=\frac{\kappa-1}{\kappa+1} \end{aligned} $$(in the last step we divided the numerator and denominator by $\lambda_{\min}$). That $\eta_{\mathrm{opt}}$ lies in $[1/\lambda_{\max},1/\lambda_{\min}]$ can be checked from $\lambda_{\min}\le\lambda_{\max}$, which gives $\lambda_{\max}+\lambda_{\min}\le2\lambda_{\max}$ and $\lambda_{\max}+\lambda_{\min}\ge2\lambda_{\min}$.
(3) After $k$ iterations the error is at most $\rho^{k}$ times the initial error, so from $\rho^{k}=\epsilon$ we get $k=\ln\epsilon/\ln\rho=\ln(1/\epsilon)/\bigl(-\ln\rho\bigr)$. Here $\rho=(\kappa-1)/(\kappa+1)=1-2/(\kappa+1)$, and for $\kappa\gg1$ the quantity $2/(\kappa+1)\approx2/\kappa$ is small, so $\ln(1-x)\approx-x$ gives $-\ln\rho\approx2/\kappa$. Hence $k\approx\tfrac{\kappa}{2}\ln(1/\epsilon)$. For example, for $\kappa=1000$ and $\epsilon=10^{-6}$, this is about $500\times13.8\approx6900$ iterations.
Exercise 7.3: Standardizing the firing temperature and the holding time
Solution
(1) Take the averages over $N=5$ samples. We have $\overline{1}=1$, $\overline{T}=6500/5=1300$, $\overline{t_{\mathrm h}}=(1+4+2+3+2)/5=2.4$, $\overline{T^{2}}=8.55\times10^{6}/5=1.71\times10^{6}$ (the numerator is $(1.21+1.44+1.69+1.96+2.25)\times10^{6}$), $\overline{Tt_{\mathrm h}}=15700/5=3140$ (the numerator is $1100+4800+2600+4200+3000$), and $\overline{t_{\mathrm h}^{2}}=(1+16+4+9+4)/5=6.8$. Therefore
$$ \bm{H}=\begin{pmatrix}1&1300&2.4\\1300&1.71\times10^{6}&3140\\2.4&3140&6.8\end{pmatrix}. $$(2) $s_T^{2}=1.71\times10^{6}-1300^{2}=20000$, so $s_T=141.42\ ^{\circ}\mathrm{C}$. $s_t^{2}=6.8-2.4^{2}=1.04$, so $s_t=1.0198\ \mathrm{h}$. The covariance is $3140-1300\times2.4=20$, and the correlation coefficient is $r=20/(141.42\times1.0198)=0.1387$. After standardization, $\bm{H}$ takes the form given in the main text, $\begin{pmatrix}1&0&0\\0&1&r\\0&r&1\end{pmatrix}$, with eigenvalues $1,\ 1+r=1.1387,\ 1-r=0.8613$. The condition number is $1.1387/0.8613=1.322$.
(3) The upper limit of the learning rate is $2/(1.710\times10^{6})=1.17\times10^{-6}$, and the condition number is $1.710\times10^{6}/1.15\times10^{-2}\approx1.48\times10^{8}$. By Exercise 7.2 (3), the number of iterations with the optimal constant learning rate is about $\tfrac{\kappa}{2}\ln10^{6}=0.74\times10^{8}\times13.8\approx1.0\times10^{9}$. After standardization, $\rho=(1.322-1)/(1.322+1)=0.1387$ (which is $=r$), so $\ln10^{-6}/\ln0.1387=13.8/1.975\approx7.0$, and seven iterations suffice.
(4) It does not change. Expressing the time in minutes multiplies the values of $t_{\mathrm h}$ by 60, but the mean and the standard deviation are also multiplied by 60, so the standardized value $(t_{\mathrm h}-m)/s$ is the same. The correlation coefficient also does not depend on the units. Standardization removes the choice of unit and origin of each feature, so the standardized $\bm{H}$ does not depend on how the units are chosen. (The condition number before standardization does change when the unit is changed to minutes.)
Exercise 7.4: Variance of the minibatch gradient under sampling without replacement
Solution
(1) Even under sampling without replacement, by symmetry the index $i$ that enters a given position in the minibatch (say, the first) is any element of $\{1,\dots,N\}$ with probability $1/N$. Hence $\Ex[\bm{d}_i]=\frac1N\sum_n\bm{d}_n=\bm{0}$. Since $\bm{g}_{\mathcal{B}}-\nabla L=\frac1B\sum_{b=1}^{B}\bm{d}_{i_b}$, the linearity of expectation gives $\Ex[\bm{g}_{\mathcal{B}}]=\nabla L$ (unbiased).
(2) The pair of indices $(i,j)$ entering two different positions is equally likely, with probability $1/\{N(N-1)\}$, to be any of the $N(N-1)$ ordered pairs of distinct indices. On the other hand, since $\sum_n\bm{d}_n=\bm{0}$,
$$ \begin{aligned} 0=\Bigl\|\sum_n\bm{d}_n\Bigr\|^{2}&=\sum_n\norm{\bm{d}_n}^{2}+\sum_{n\ne n'}\bm{d}_n^{\tp}\bm{d}_{n'}\\ &=Ns^{2}+\sum_{n\ne n'}\bm{d}_n^{\tp}\bm{d}_{n'} . \end{aligned} $$Hence $\sum_{n\ne n'}\bm{d}_n^{\tp}\bm{d}_{n'}=-Ns^{2}$, and
$$ \Ex[\bm{d}_i^{\tp}\bm{d}_j]=\frac{1}{N(N-1)}\sum_{n\ne n'}\bm{d}_n^{\tp}\bm{d}_{n'}=-\frac{s^{2}}{N-1}. $$(3) Expanding as in the proof in the main text, we obtain
$$ \begin{aligned} &\Ex\Bigl[\norm{\bm{g}_{\mathcal{B}}-\nabla L}^{2}\Bigr]\\ &=\frac1{B^{2}}\Bigl(\sum_{b}\Ex\norm{\bm{d}_{i_b}}^{2}+\sum_{b\ne b'}\Ex[\bm{d}_{i_b}^{\tp}\bm{d}_{i_{b'}}]\Bigr)\\ &=\frac1{B^{2}}\Bigl(Bs^{2}-B(B-1)\frac{s^{2}}{N-1}\Bigr)\\ &=\frac{s^{2}}{B}\Bigl(1-\frac{B-1}{N-1}\Bigr)=\frac{s^{2}}{B}\cdot\frac{N-B}{N-1}. \end{aligned} $$In Example 7.6, $s^{2}=6.6875$, $N=4$, and $B=2$, so $\frac{6.6875}{2}\cdot\frac{2}{3}=2.229$, which agrees with the variance $13.375/6=2.229$ obtained by enumerating all six cases. This is also consistent with the fact that for $B=N$ we have $(N-B)=0$, so the variance is 0 and the minibatch gradient coincides with the gradient over all the data.
Exercise 7.5: How much does momentum reduce the number of iterations?
Solution
(1) The eigenvalues are $100$ and $1$, so $\kappa=100$. We have $\eta_{\mathrm{opt}}=2/(100+1)=0.0198$ and $\rho_{\mathrm{opt}}=99/101=0.9802$. The number of iterations is $\ln10^{-6}/\ln0.9802$ $=-13.816/(-0.02000)\approx691$.
(2) $\eta=4/(\sqrt{100}+\sqrt1)^{2}=4/121=0.0331$ and $\beta_1=\bigl((10-1)/(10+1)\bigr)^{2}=(9/11)^{2}=0.669$. The contraction factor is $9/11=0.818$, and the number of iterations is $\ln10^{-6}/\ln0.818$ $=-13.816/(-0.2007)\approx69$. This is about 1/10 of that of gradient descent. (With these $\eta,\beta_1$, the eigenvalues of the iteration in each direction are double roots, and the error decreases as $\rho^{k}$ times a linear polynomial in $k$. As a result, the actual number of iterations is larger than this estimate: starting from $\bm{w}_0=(1,1)^{\tp}$, it takes 93 iterations to reduce $\norm{\bm{w}_k}$ by a factor of $10^{-6}$. This is still about 1/7 of that of gradient descent.) Since $\kappa$ has been replaced by $\sqrt{\kappa}$, for $\kappa=100$ the number of iterations is reduced to about one-tenth, since $\sqrt{100}=10$.
(3) For $\kappa=1$, the optimum is $\beta_1=\bigl((1-1)/(1+1)\bigr)^{2}=0$, so not using momentum at all (plain gradient descent) is the best. Since gradient descent with $\eta=1/\lambda$ already reaches the minimum in one step for this problem, carrying over the past velocity only produces overshoot ($w_3=-0.25$ in Example 7.8). Momentum is effective for problems with a large condition number, where the gradient accumulates and accelerates in the gentle direction while the oscillations in the steep direction cancel each other.
Exercise 7.6: Three inequality constraints
Solution
Write the constraints as $g_1=w_1+w_2-2\le0$, $g_2=-w_1\le0$, and $g_3=-w_2\le0$. Then $\nabla g_1=(1,1)^{\tp}$, $\nabla g_2=(-1,0)^{\tp}$, and $\nabla g_3=(0,-1)^{\tp}$.
(1) $\nabla f=(2(w_1-1),\ 2(w_2-2))^{\tp}$. The unconstrained minimum $(1,2)$ satisfies $w_1+w_2=3\gt2$, so it lies outside the hypotenuse, while it satisfies $w_1,w_2\gt0$. So we assume that only $g_1$ is active ($\alpha_2=\alpha_3=0$). From the stationarity conditions $2(w_1-1)+\alpha_1=0$ and $2(w_2-2)+\alpha_1=0$, we get $w_1=1-\alpha_1/2$ and $w_2=2-\alpha_1/2$. Substituting into $g_1=0$ gives $3-\alpha_1=2$, so $\alpha_1=1$. Hence $\bm{w}^{*}=(0.5,\ 1.5)$ and $f^{*}=0.25+0.25=0.5$. Check: 1. $\nabla f+\alpha_1\nabla g_1=(-1,-1)+(1,1)=\bm{0}$. 2. $g_1=0$, $g_2=-0.5$, and $g_3=-1.5$ are all $\le0$. 3. $\alpha=(1,0,0)\ge\bm{0}$. 4. $\alpha_1g_1=0$, $\alpha_2g_2=0\cdot(-0.5)=0$, and $\alpha_3g_3=0$. All the conditions are satisfied.
(2) $\nabla f=(2(w_1+1),\ 2(w_2-3))^{\tp}$. The unconstrained minimum $(-1,3)$ has $w_1\lt0$ and lies on the line $w_1+w_2=2$, outside the upper-left vertex $(0,2)$ of the triangle. First assume that only $g_1$ is active. Then $w_1=-1-\alpha_1/2$ and $w_2=3-\alpha_1/2$, and $g_1=0$ gives $2-\alpha_1=2$, so $\alpha_1=0$ and $\bm{w}=(-1,3)$; but $g_2=1\gt0$, which violates condition 2. Next assume that only $g_2$ is active. Then $w_1=0$, and $2(0+1)-\alpha_2=0$ gives $\alpha_2=2$ and $w_2=3$, but $g_1=1\gt0$, which is a violation. So we assume that both $g_1$ and $g_2$ are active (the vertex $(0,2)$). The stationarity conditions are
$$ \begin{aligned} 2(0+1)+\alpha_1-\alpha_2&=0,\\ 2(2-3)+\alpha_1&=0 . \end{aligned} $$The second equation gives $\alpha_1=2$, and the first gives $\alpha_2=4$. Hence $\bm{w}^{*}=(0,2)$ and $f^{*}=1+1=2$. Check: 1. Adding $2(1,1)+4(-1,0)=(-2,2)$ to $\nabla f=(2,-2)$ gives $\bm{0}$. 2. $g_1=0$, $g_2=0$, and $g_3=-2$. 3. $\alpha=(2,4,0)\ge\bm{0}$. 4. $\alpha_1g_1=\alpha_2g_2=0$ and $\alpha_3=0$. All the conditions are satisfied. Since $f$ and all the $g_j$ are convex, this is the minimum.
Exercise 7.7: Relaxing a structure with stiff and soft bonds
Solution
Since $\bm{F}=(-k_1u_1,\ -k_2u_2)^{\tp}$, the update is $u_i\leftarrow(1-\eta k_i)u_i$ component by component, which is gradient descent with the Hessian matrix $\diag(k_1,k_2)$.
(1) $\eta\lt2/k_1=2/20=0.1\ \text{Å}^{2}/\mathrm{eV}$ (since $\eta F$ is a length in Å, the unit of $\eta$ is Å divided by eV/Å, that is, $\text{Å}^{2}/\mathrm{eV}$).
(2) $\eta_{\mathrm{opt}}=2/(20+0.5)=0.0976\ \text{Å}^{2}/\mathrm{eV}$. $\kappa=20/0.5=40$, and the contraction factor is $(40-1)/(40+1)=0.951$. Then $\ln10^{-3}/\ln0.951$ $=-6.908/(-0.0500)\approx138$ iterations.
(3) With $\eta=0.05$, $1-0.05\times20=0$, so the stiff direction relaxes in one step, but the soft direction shrinks only by a factor of $1-0.05\times0.5=0.975$ per step, which takes $\ln10^{-3}/\ln0.975\approx273$ iterations. With a learning rate equal to half the upper limit, the number of iterations in the slow direction is about twice as large.
(4) If $\eta_i=1/k_i$, then $1-\eta_ik_i=0$, and both directions reach $u_i=0$ in one iteration. This is $\bm{\Delta}=-\bm{H}^{-1}\nabla E$, obtained by multiplying by the inverse of the Hessian matrix $\diag(k_1,k_2)$, that is, Newton’s method (Section 7.9). It cannot be used as it is for real structures, for the following reasons: (i) the coordinates of the normal modes (the eigenvectors of the force-constant matrix) are not known in advance, and in atomic coordinates stiff bonds and soft deformations are mixed; (ii) computing the $3N_{\mathrm a}\times3N_{\mathrm a}$ force-constant matrix requires many energy and force calculations and is expensive; (iii) far from a stable point the energy is not quadratic, and the matrix changes from place to place. Therefore BFGS or L-BFGS is used, which gradually approximates the Hessian matrix (or its inverse) from the changes in the forces.
Exercise 7.8: Newton’s method does not depend on scale
Solution
(1) The components of $\bm{w}=\bm{A}\bm{w}'$ are $w_i=\sum_jA_{ij}w'_j$, so $\partial w_i/\partial w'_j=A_{ij}$. By the chain rule,
$$ \begin{aligned} \pdiff{L'}{w'_j}&=\sum_i\pdiff{L}{w_i}\pdiff{w_i}{w'_j}\\ &=\sum_iA_{ij}\pdiff{L}{w_i}=\bigl(\bm{A}^{\tp}\nabla_{\bm{w}}L\bigr)_j . \end{aligned} $$Differentiating once more with respect to $w'_l$, in the same way,
$$ \begin{aligned} \frac{\partial^{2}L'}{\partial w'_j\partial w'_l}&=\sum_i\sum_mA_{ij}\,\frac{\partial^{2}L}{\partial w_i\partial w_m}\,A_{ml}\\ &=(\bm{A}^{\tp}\bm{H}\bm{A})_{jl}. \end{aligned} $$Hence $\bm{H}'=\bm{A}^{\tp}\bm{H}\bm{A}$.
(2) One step of Newton’s method on the $\bm{w}'$ side is $\bm{H}'\bm{\Delta}'=-\nabla_{\bm{w}'}L'$, that is, $\bm{A}^{\tp}\bm{H}\bm{A}\bm{\Delta}'=-\bm{A}^{\tp}\nabla_{\bm{w}}L$. Since $\bm{A}^{\tp}$ is invertible, multiplying both sides from the left by $(\bm{A}^{\tp})^{-1}$ gives $\bm{H}(\bm{A}\bm{\Delta}')=-\nabla_{\bm{w}}L$. This is the same as the Newton equation $\bm{H}\bm{\Delta}=-\nabla_{\bm{w}}L$ on the $\bm{w}$ side, so if $\bm{H}$ is invertible, $\bm{A}\bm{\Delta}'=\bm{\Delta}$. Therefore $\bm{A}\bm{w}'_{k+1}=\bm{A}\bm{w}'_k+\bm{A}\bm{\Delta}'=\bm{w}_k+\bm{\Delta}=\bm{w}_{k+1}$. Whichever coordinates we compute in, we pass through the same points.
(3) Mapping one step of gradient descent on the $\bm{w}'$ side back to the $\bm{w}$ side gives
$$ \bm{A}\bigl(\bm{w}'_k-\eta\bm{A}^{\tp}\nabla_{\bm{w}}L\bigr)=\bm{w}_k-\eta\,\bm{A}\bm{A}^{\tp}\nabla_{\bm{w}}L $$which does not coincide with $\bm{w}_k-\eta\nabla_{\bm{w}}L$ unless $\bm{A}\bm{A}^{\tp}=\bm{I}$ (a rotation, for example). That is, the path taken by gradient descent depends on the choice of coordinates (the units of the features). Standardization amounts to a coordinate change of the form $\bm{w}=\bm{A}\bm{w}'$ (dividing a feature by $s_j$ gives $w_j=w'_j/s_j$, so the diagonal entries of $\bm{A}$ are the reciprocals of the standard deviations, $1/s_j$; the part that subtracts the mean mixes the other components into the intercept component), and it makes the shape of the valley, $\bm{A}^{\tp}\bm{H}\bm{A}$, rounder for gradient descent. In Newton’s method this transformation is built in automatically, so the sequence of points does not change whether or not we standardize (though, as far as rounding errors are concerned, standardization is also beneficial for Newton’s method). Gradient descent with $\bm{A}\bm{A}^{\tp}$ multiplied in, of the form $\bm{w}_k-\eta\bm{P}\nabla L$ ($\bm{P}$ positive definite), is called preconditioned gradient descent; $\bm{P}=\bm{H}^{-1}$ gives Newton’s method, and taking $\bm{P}$ to be diagonal is close to the idea behind RMSProp and Adam.
← Back to Chapter 7, “Fundamentals of Optimization — Descending the Valley of the Loss”
Chapter 8 Linear Regression Models — Basis Functions and Least Squares
Exercise 8.1: The formulas for fitting a straight line (derivation)
Solution
For the basis $(1,x)$ the normal equations are
$$ \begin{aligned} Nw_0+w_1\sum_n x_n&=\sum_n y_n,\\ w_0\sum_n x_n+w_1\sum_n x_n^{2}&=\sum_n x_ny_n . \end{aligned} $$Eliminating $w_0$. Dividing the first equation by $N$ gives $w_0+w_1\bar{x}=\bar{y}$, that is, $w_0=\bar{y}-w_1\bar{x}$. This says that “the line $w_0+w_1x$ takes the value $\bar{y}$ at $x=\bar{x}$,” in other words, that the line passes through the point $(\bar{x},\bar{y})$.
The expression for $w_1$. Substitute $w_0=\bar{y}-w_1\bar{x}$ into the second equation and use $\sum_nx_n=N\bar{x}$.
$$ \begin{aligned} (\bar{y}-w_1\bar{x})N\bar{x}+w_1\sum_n x_n^{2}&=\sum_n x_ny_n\\ w_1\Bigl(\sum_n x_n^{2}-N\bar{x}^{2}\Bigr)&=\sum_n x_ny_n-N\bar{x}\bar{y}. \end{aligned} $$Rewrite the right-hand side and the parenthesis on the left in terms of deviations.
$$ \begin{aligned}&\sum_n(x_n-\bar{x})(y_n-\bar{y})\\&=\sum_nx_ny_n-\bar{y}\sum_nx_n-\bar{x}\sum_ny_n+N\bar{x}\bar{y}\\&=\sum_nx_ny_n-N\bar{x}\bar{y}\end{aligned} $$Hence the right-hand side is $S_{xy}$. Similarly (replacing $y$ by $x$), the parenthesis on the left is $S_{xx}$. Therefore $w_1=S_{xy}/S_{xx}$ (Eq. (8.7) of Chapter 8).
Properties of the residuals. For the residuals $r_n=y_n-w_0-w_1x_n$, the first normal equation is equivalent to $\sum_n r_n=0$ and the second to $\sum_n x_nr_n=0$ (they are merely the rewritten forms of $\sum_n y_n-Nw_0-w_1\sum_nx_n=0$ and $\sum_nx_ny_n-w_0\sum_nx_n-w_1\sum_nx_n^{2}=0$, respectively). This is nothing other than the statement that “the residuals are orthogonal to the two columns $(1,\dots,1)^{\tp}$ and $(x_1,\dots,x_N)^{\tp}$ of the design matrix.”
Exercise 8.2: The hat matrix and the bias of $\sigma^{2}_{\mathrm{ML}}$ (derivation)
Solution
(1) $\bm{A}\equiv\bm{\Phi}^{\tp}\bm{\Phi}$ is symmetric and nonsingular, so its inverse matrix is also symmetric.
- $\bm{H}^{\tp}=(\bm{\Phi}^{\tp})^{\tp}(\bm{A}^{-1})^{\tp}\bm{\Phi}^{\tp}=\bm{\Phi}\bm{A}^{-1}\bm{\Phi}^{\tp}=\bm{H}$.
- $\bm{H}^{2}=\bm{\Phi}\bm{A}^{-1}(\bm{\Phi}^{\tp}\bm{\Phi})\bm{A}^{-1}\bm{\Phi}^{\tp}$ $=\bm{\Phi}\bm{A}^{-1}\bm{\Phi}^{\tp}=\bm{H}$.
- $\tr\bm{H}=\tr\bigl(\bm{\Phi}\,\bm{A}^{-1}\bm{\Phi}^{\tp}\bigr)$ $=\tr\bigl(\bm{A}^{-1}\bm{\Phi}^{\tp}\bm{\Phi}\bigr)=\tr\bm{I}_M=M$.
Similarly, $\bm{I}-\bm{H}$ is also symmetric, $(\bm{I}-\bm{H})^{2}=\bm{I}-2\bm{H}+\bm{H}^{2}=\bm{I}-\bm{H}$, and $\tr(\bm{I}-\bm{H})=N-M$.
(2) The least-squares predicted value is $\hat{\bm{y}}=\bm{H}\bm{y}$, so the residual is $\bm{r}=(\bm{I}-\bm{H})\bm{y}$. From $\bm{H}\bm{\Phi}=\bm{\Phi}\bm{A}^{-1}\bm{A}=\bm{\Phi}$ we get $(\bm{I}-\bm{H})\bm{\Phi}\bm{w}_{\mathrm{true}}=\bm{0}$, so $\bm{r}=(\bm{I}-\bm{H})\bm{\varepsilon}$. Therefore
$$ \begin{aligned}\norm{\bm{r}}^{2}&=\bm{\varepsilon}^{\tp}(\bm{I}-\bm{H})^{\tp}(\bm{I}-\bm{H})\bm{\varepsilon}\\&=\bm{\varepsilon}^{\tp}(\bm{I}-\bm{H})\bm{\varepsilon}.\end{aligned} $$A scalar equals its own trace, and the trace may be cycled in the order of a product, so
$$ \begin{aligned} \Ex\bigl[\norm{\bm{r}}^{2}\bigr]&=\Ex\bigl[\tr\bigl((\bm{I}-\bm{H})\bm{\varepsilon}\bm{\varepsilon}^{\tp}\bigr)\bigr]\\&=\tr\bigl((\bm{I}-\bm{H})\Ex[\bm{\varepsilon}\bm{\varepsilon}^{\tp}]\bigr)\\ &=\sigma^{2}\tr(\bm{I}-\bm{H})=\sigma^{2}(N-M). \end{aligned} $$Since $\sigma^{2}_{\mathrm{ML}}=\norm{\bm{r}}^{2}/N$, we have $\Ex[\sigma^{2}_{\mathrm{ML}}]=\frac{N-M}{N}\sigma^{2}$. The quantity $\norm{\bm{r}}^{2}/(N-M)$ is an unbiased estimate. The same property was also used in Exercise 6.1 of Chapter 6.
(3) In Example 8.2, $\bm{\Phi}^{\tp}\bm{\Phi}=\begin{pmatrix}3&3\\3&5\end{pmatrix}$, and its inverse matrix is $\frac16\begin{pmatrix}5&-3\\-3&3\end{pmatrix}$. Since the $n$th row is $(1,x_n)$, $H_{nm}=\frac16(5-3x_n-3x_m+3x_nx_m)$. Substituting $x=0,1,2$ gives
$$ \bm{H}=\frac16\begin{pmatrix}5&2&-1\\2&2&2\\-1&2&5\end{pmatrix}. $$It is symmetric, and its trace is $(5+2+5)/6=2=M$. The (1,1) component of $\bm{H}^{2}$ is $(25+4+1)/36=30/36=5/6$, which agrees with $H_{11}$ (the other components work out the same way). $\bm{H}\bm{y}=\frac16(5+2-4,\ 2+2+8,$ $-1+2+20)^{\tp}$ $=(0.5,\ 2.0,\ 3.5)^{\tp}$ agrees with $\hat{\bm{y}}$ in Example 8.2.
Exercise 8.3: The bowing parameter when the end members are known (a materials topic)
Solution
(1) Rearranging Eq. (8.23) of Chapter 8 gives $E_g-[(1-x)E_{\mathrm{A}}+xE_{\mathrm{B}}]=b\cdot\{-x(1-x)\}$. The target value is $z_n=E_{g,n}-[(1-x_n)1.20+x_n2.40]$, the basis function is $\psi(x)=-x(1-x)$, and the model is a linear model with a single coefficient $b$, namely $z=b\,\psi(x)$ (no constant term).
(2) The linear part $1.20+1.20x_n$ takes the values $1.44,\ 1.68,\ 1.80,\ 1.92,\ 2.16$. The targets are $z_n=-0.11,\ -0.21,\ -0.19,\ -0.22,\ -0.11$. The basis values are $\psi_n=-0.16,\ -0.24,\ -0.25,$ $-0.24,\ -0.16$. From the normal equation for a single coefficient, $b\sum_n\psi_n^{2}=\sum_n\psi_nz_n$,
$$ \begin{aligned} \sum_n\psi_nz_n&=0.0176+0.0504+0.0475\\&\quad+0.0528+0.0176=0.1859,\\ \sum_n\psi_n^{2}&=0.0256+0.0576+0.0625\\&\quad+0.0576+0.0256=0.2289,\\ b&=0.1859/0.2289=0.812\ \mathrm{eV}. \end{aligned} $$(3) For a flat prior distribution ($\sigma_w\to\infty$), $S_N=\sigma^{2}/\sum_n\psi_n^{2}=0.03^{2}/0.2289$, and the standard deviation is $0.03/\sqrt{0.2289}=0.03/0.4784=0.063$ eV. Thus $b=0.81\pm0.06$ eV.
(4) At $x=0.3$, the linear part is $1.20+1.20\times0.3=1.56$ and $\psi=-0.3\times0.7=-0.21$. The predictive mean is $1.56+0.812\times(-0.21)=1.389$ eV. The standard deviation due to lack of knowledge is $\abs{\psi}\sqrt{S_N}=0.21\times0.063=0.013$ eV (the standard deviation of an observed value is $\sqrt{0.013^{2}+0.03^{2}}=0.033$ eV). Because we treated the end members as known and reduced the number of coefficients to one, the uncertainty is much smaller than in the three-coefficient fit of Chapter 8, Section 8.10 (standard deviation of $b$ equal to 0.14 eV, 12 data points). Note, however, that if the values of the end members contain errors, $b$ is biased by that amount.
Exercise 8.4: An Arrhenius plot at four temperatures (a materials topic)
Solution
(1) $u=1000/T=2.0000,\ 1.6667,\ 1.4286,\ 1.2500$ (1000 times K$^{-1}$), $\bar{u}=1.5863$, $\bar{l}=-6.00$ (with $l=\ln\sigma_{\mathrm{ion}}$). The deviations are $u_n-\bar{u}=0.4137,\ 0.0804,$ $-0.1577,\ -0.3363$ and $l_n-\bar{l}=-2.14,\ -0.37,\ 0.82,\ 1.69$.
$$ \begin{aligned} S_{uu}&=0.1711+0.0065+0.0249+0.1131\\&=0.3156,\\ S_{ul}&=-0.8853-0.0297-0.1294-0.5684\\&=-1.6127,\\ w_1&=S_{ul}/S_{uu}=-5.110,\\ w_0&=\bar{l}-w_1\bar{u}=2.107. \end{aligned} $$$E_a=-1000\,k_{\mathrm B}w_1$ $=1000\times8.617\times10^{-5}\times5.110$ $=0.440$ eV.
(2) $\sigma/\sqrt{S_{uu}}=0.10/\sqrt{0.3156}=0.178$. The standard deviation of $E_a$ is $1000\,k_{\mathrm B}\times0.178=0.0862\times0.178=0.015$ eV. Thus $E_a=0.440\pm0.015$ eV.
(3) $u_*=1000/900=1.1111$. The predictive mean is $2.107-5.110\times1.1111=-3.572$ ($\sigma_{\mathrm{ion}}\approx e^{-3.572}=0.028$ S/cm). The variance due to lack of knowledge is
$$ \begin{aligned}&0.10^{2}\bigl[1/4+(1.1111-1.5863)^{2}/0.3156\bigr]\\&=0.01\times(0.25+0.716)=0.00966,\end{aligned} $$so its standard deviation is 0.098. The standard deviation of an observed value is $\sqrt{0.00966+0.01}=0.140$. Since 900 K lies outside the measurement range (500–800 K), the contribution from lack of knowledge has grown to the same order as the noise.
This expression is obtained by using the centered basis $(1,\ u-\bar{u})$, for which $\bm{\Phi}^{\tp}\bm{\Phi}=\diag(N,\ S_{uu})$ (the cross term vanishes, $\sum_n(u_n-\bar{u})=0$) and, for a flat prior distribution, $\bm{S}_N=\sigma^{2}\diag(1/N,\ 1/S_{uu})$, and then sandwiching this between $\bm{\phi}_*=(1,\ u_*-\bar{u})^{\tp}$.
(4) If the error $\delta$ is constant in absolute value, the error in $\ln\sigma_{\mathrm{ion}}$ is approximately $\delta/\sigma_{\mathrm{ion},n}$, which is larger for the low-temperature points (where the conductivity is small). Weight each point by its variance $\sigma_n^{2}=(\delta/\sigma_{\mathrm{ion},n})^{2}$ and minimize $\sum_n r_n^{2}/\sigma_n^{2}$ (weighted least squares). In this example the conductivity at 500 K is about $e^{3.8}\approx45$ times smaller than at 800 K, so the error in the logarithm is about 45 times larger and the weight is about $45^{2}\approx2000$ times smaller; the 500 K point then hardly affects the slope. Alternatively, do not take the logarithm and fit $\sigma_{\mathrm{ion}}=\sigma_0e^{-E_a/(k_{\mathrm B}T)}$ directly by nonlinear least squares (the methods of Chapter 7).
Exercise 8.5: The ridge coefficients shrink as $\lambda$ increases (derivation)
Solution
(1) From Eq. (8.14) of Chapter 8, $\hat{\bm{w}}_\lambda=\sum_ic_i(\lambda)\bm{v}_i$ with $c_i(\lambda)=\dfrac{s_i}{s_i^{2}+\lambda}\bm{u}_i^{\tp}\bm{y}$. Since $\bm{v}_i^{\tp}\bm{v}_j=\delta_{ij}$,
$$ \norm{\hat{\bm{w}}_\lambda}^{2}=\sum_i c_i(\lambda)^{2}=\sum_i\frac{s_i^{2}}{(s_i^{2}+\lambda)^{2}}(\bm{u}_i^{\tp}\bm{y})^{2}. $$Differentiating with respect to $\lambda$, each term becomes $-\dfrac{2s_i^{2}}{(s_i^{2}+\lambda)^{3}}(\bm{u}_i^{\tp}\bm{y})^{2}\le0$. Therefore $\norm{\hat{\bm{w}}_\lambda}^{2}$ decreases monotonically for $\lambda\ge0$ (strictly if there is a term with $\bm{u}_i^{\tp}\bm{y}\ne0$). It approaches 0 as $\lambda\to\infty$.
(2) Since $\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I}=\bm{V}(\bm{\Sigma}^{2}+\lambda\bm{I})\bm{V}^{\tp}$, its inverse matrix is $\bm{V}(\bm{\Sigma}^{2}+\lambda\bm{I})^{-1}\bm{V}^{\tp}$. Therefore
$$ \begin{aligned} &\bm{\Phi}(\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I})^{-1}\bm{\Phi}^{\tp}\\&=\bm{U}\bm{\Sigma}\bm{V}^{\tp}\bm{V}(\bm{\Sigma}^{2}+\lambda\bm{I})^{-1}\bm{V}^{\tp}\bm{V}\bm{\Sigma}\bm{U}^{\tp}\\ &=\bm{U}\,\bm{\Sigma}(\bm{\Sigma}^{2}+\lambda\bm{I})^{-1}\bm{\Sigma}\,\bm{U}^{\tp}. \end{aligned} $$Taking the trace and using $\tr(\bm{U}\bm{D}\bm{U}^{\tp})=\tr(\bm{D}\bm{U}^{\tp}\bm{U})=\tr\bm{D}$, we obtain $\tr\bm{D}=\sum_is_i^{2}/(s_i^{2}+\lambda)=\mathrm{df}(\lambda)$. At $\lambda=0$ it agrees with the trace $M$ of the hat matrix (Exercise 8.2).
(3) In Example 8.6, $\bm{\Phi}^{\tp}\bm{\Phi}=\diag(4,\ 0.2)$ and $\bm{\Phi}^{\tp}\bm{y}=(6.0,\ 0.34)^{\tp}$. For $\lambda=1$, $w_0=6.0/5=1.2$ and $w_1=0.34/1.2=0.283$. The effective degrees of freedom are $4/5+0.2/1.2=0.800+0.167=0.967$. $\norm{\bm{w}}^{2}$ decreases monotonically: $1.5^{2}+1.7^{2}=5.14$ for $\lambda=0$, $1.4286^{2}+0.85^{2}=2.76$ for $\lambda=0.2$, and $1.2^{2}+0.283^{2}=1.52$ for $\lambda=1$.
Exercise 8.6: Sequential updating and batch updating (derivation and computation)
Solution
(1) First update with $\data_1$. From the prior distribution $\Normal(\bm{0},\sigma_w^{2}\bm{I})$, Eq. (8.20) of Chapter 8 gives
$$ \begin{aligned}\bm{S}_1^{-1}&=\sigma_w^{-2}\bm{I}+\sigma^{-2}\bm{\Phi}_1^{\tp}\bm{\Phi}_1,\\ \bm{S}_1^{-1}\bm{m}_1&=\sigma^{-2}\bm{\Phi}_1^{\tp}\bm{y}_1 .\end{aligned} $$Taking this as the prior distribution ($\bm{m}_0\to\bm{m}_1$, $\bm{S}_0\to\bm{S}_1$) and updating with $\data_2$, we obtain
$$ \begin{aligned} \bm{S}_2^{-1}&=\bm{S}_1^{-1}+\sigma^{-2}\bm{\Phi}_2^{\tp}\bm{\Phi}_2\\&=\sigma_w^{-2}\bm{I}+\sigma^{-2}(\bm{\Phi}_1^{\tp}\bm{\Phi}_1+\bm{\Phi}_2^{\tp}\bm{\Phi}_2),\\ \bm{S}_2^{-1}\bm{m}_2&=\bm{S}_1^{-1}\bm{m}_1+\sigma^{-2}\bm{\Phi}_2^{\tp}\bm{y}_2\\&=\sigma^{-2}(\bm{\Phi}_1^{\tp}\bm{y}_1+\bm{\Phi}_2^{\tp}\bm{y}_2). \end{aligned} $$The design matrix of the full data is $\bm{\Phi}=\begin{pmatrix}\bm{\Phi}_1\\ \bm{\Phi}_2\end{pmatrix}$ and the target is $\bm{y}=\begin{pmatrix}\bm{y}_1\\ \bm{y}_2\end{pmatrix}$, so $\bm{\Phi}^{\tp}\bm{\Phi}=\bm{\Phi}_1^{\tp}\bm{\Phi}_1+\bm{\Phi}_2^{\tp}\bm{\Phi}_2$ and $\bm{\Phi}^{\tp}\bm{y}=\bm{\Phi}_1^{\tp}\bm{y}_1+\bm{\Phi}_2^{\tp}\bm{y}_2$. Hence $\bm{S}_2,\bm{m}_2$ agree with $\bm{S}_N,\bm{m}_N$ obtained in one batch (Eq. (8.18)). The key point is that the precision matrix and “precision × mean” are sums over the data.
(2) The posterior distribution in Example 8.7 has $m_1=0.90625$ and $S_1^{-1}=16$. For the fourth point $x=4$, $y=4.1$ ($\sigma=1$),
$$ \begin{aligned}S_2^{-1}&=16+\frac{4^{2}}{1}=32,\\ m_2&=\frac{16\times0.90625+4\times4.1}{32}\\&=\frac{14.5+16.4}{32}=0.9656 .\end{aligned} $$In batch form, $\sum x_n^{2}=1+4+9+16=30$, $\sum x_ny_n=14.5+16.4=30.9$, $S^{-1}=1/0.5+30=32$, and $m=30.9/32=0.9656$, which agrees. The posterior standard deviation is $1/\sqrt{32}=0.177$ (it has shrunk from 0.25 with three points).
Exercise 8.7: The predictive variance of a line determined by two points (computation)
Solution
(1) $\bm{\Phi}=\begin{pmatrix}1&-1\\1&1\end{pmatrix}$ and $\bm{\Phi}^{\tp}\bm{\Phi}=\begin{pmatrix}2&0\\0&2\end{pmatrix}$. Therefore
$$ \begin{aligned}\bm{S}_N^{-1}&=\Bigl(\frac{1}{\sigma_w^{2}}+\frac{2}{\sigma^{2}}\Bigr)\bm{I}=\frac{\sigma^{2}+2\sigma_w^{2}}{\sigma^{2}\sigma_w^{2}}\bm{I},\\ \bm{S}_N&=\frac{\sigma^{2}\sigma_w^{2}}{\sigma^{2}+2\sigma_w^{2}}\bm{I}.\end{aligned} $$(2) Since $\bm{\phi}_*=(1,x_*)^{\tp}$,
$$ \bm{\phi}_*^{\tp}\bm{S}_N\bm{\phi}_*=\frac{\sigma^{2}\sigma_w^{2}}{\sigma^{2}+2\sigma_w^{2}}\,(1+x_*^{2}). $$It is smallest at $x_*=0$ (the midpoint of the two points) and grows in proportion to $x_*^{2}$.
(3) For $\sigma_w=1$ and $\sigma=0.5$, the coefficient is $0.25/(0.25+2)=1/9$. For $x_*=0,1,2,3$ the values are $1/9=0.111$, $2/9=0.222$, $5/9=0.556$, $10/9=1.111$. At $x_*=3$ it exceeds four times the noise variance $\sigma^{2}=0.25$.
$\bm{y}$ does not enter $\bm{S}_N$ (Eq. (8.18) of Chapter 8). Therefore the variance due to lack of knowledge is determined only by “where we measured” (the design matrix), not by the measured values. For this reason, before carrying out any measurement, we can compute at which inputs measuring would reduce the predictive uncertainty the most. This is the foundation of the idea of experimental design (Chapter 13). Note, however, that this holds when $\sigma^{2}$ and $\sigma_w^{2}$ are fixed; if they are chosen by the marginal likelihood (the Advanced Topic box in Chapter 8, Section 8.7), the variance also depends on $\bm{y}$.
Exercise 8.8: Extrapolation with Gaussian basis functions (discussion and a materials topic)
Solution
(1) $\phi_j(s)=\exp[-(s-c_j)^{2}/(2\times0.25^{2})]$ $=\exp[-(s-c_j)^{2}/0.125]$.
- $s=1.2$: for $c=1$, $\exp(-0.04/0.125)=\exp(-0.32)=0.726$; for $c=0.75$, $\exp(-0.2025/0.125)=\exp(-1.62)=0.198$; for $c=0.5$, $\exp(-3.92)=0.020$. $\bm{\phi}^{\tp}\bm{\phi}\approx0.527+0.039+0.0004=0.567$. The variance from the prior distribution alone is $100\times0.567=56.7$ (standard deviation 7.5 %).
- $s=1.4$: for $c=1$, $\exp(-0.16/0.125)=\exp(-1.28)=0.278$; for $c=0.75$, $\exp(-3.38)=0.034$. $\bm{\phi}^{\tp}\bm{\phi}\approx0.0773+0.0012=0.0785$, and the variance is $7.85$ (standard deviation 2.8 %).
- $s=2.0$: for $c=1$, $\exp(-1/0.125)=\exp(-8)=3.4\times10^{-4}$, and the others are even smaller. $\bm{\phi}^{\tp}\bm{\phi}\approx1.1\times10^{-7}$, and the variance is $1.1\times10^{-5}$ (standard deviation 0.003 %).
(At $s=0$, $1+2\times0.6065^{2}+2\times0.1353^{2}+\dots=1.77$ and the variance is 177, so the prior variance is larger inside the range of the data.)
(2) At 1700 °C ($s=2.0$), regardless of whether there are data, the variance due to lack of knowledge becomes almost 0, and the predictive mean is $\bm{m}_N^{\tp}\bm{\phi}\approx0$, that is, it returns to the baseline value of 88 %. The band on the screen is only the band of the observed value, ±2σ = ±2 %, but this does not mean that “the relative density at 1700 °C is well known to be 88 ± 2 %.” It is a value that comes out mechanically from the model assumption that the basis functions vanish at this temperature, and it says nothing about the reliability of the extrapolation. For a real sintered body, neither the data nor the basis functions tell us whether densification continues at still higher temperatures or whether the density decreases because of grain growth or decomposition.
(3) Examples: (a) Add a constant and linear basis (the basis $1,s$) or polynomial basis functions so that the model can express that “some form continues” outside the data (the band of a polynomial widens outside). (b) Place the centers of the basis functions out to the range where we want to predict (for example $[-2,2]$), or increase the width $r$. (c) Use the Gaussian process (Chapter 12), the limit of an infinite number of basis functions, so that far from the data the variance returns to the prior variance $\sigma_f^{2}$. (d) Use a functional form based on the physics of sintering (for example a rate equation for densification) as the basis. In every case, the band remains the width under the model’s assumptions, so predictions outside the range should be checked by confirmation experiments.
← Back to Chapter 8, “Linear Regression Models — Basis Functions and Least Squares”
Chapter 9 Linear Classification Models — Decision Boundaries and Probabilities
Exercise 9.1: Distance to the boundary
Solution
(1) Since $f(\bm{x})=3x_1-4x_2+5$, the decision boundary is $3x_1-4x_2+5=0$, that is, the line $x_2=\tfrac34x_1+\tfrac54$.
(2) $\norm{\bm{w}}=\sqrt{3^{2}+(-4)^{2}}=5$. The signed distance is $r=f(\bm{x})/\norm{\bm{w}}$ (Eq. (9.2) of Chapter 9).
- Point $(1,2)$: $f=3-8+5=0$. Since $r=0$, this point lies on the boundary. By the convention that $f\ge0$ means class 1, it is predicted to be class 1, but it is a point that cannot be said to belong to either class.
- Point $(-1,1)$: $f=-3-4+5=-2$. Since $r=-2/5=-0.4$, it is class 0.
- Origin: $f=b=5$. Since $r=5/5=1$, it is class 1.
(3) The required point is the foot of the perpendicular dropped from the origin to the boundary. The origin is at distance 1 on the side in the direction of $\bm{w}$, so we need only move from it by 1 in the direction of $-\bm{w}$.
$$ \begin{aligned} \bm{x}_{\perp}&=\bm{0}-1\times\frac{\bm{w}}{\norm{\bm{w}}}\\ &=-\frac{(3,-4)}{5}=(-0.6,\ 0.8). \end{aligned} $$Check: $3\times(-0.6)-4\times0.8+5$ $=-1.8-3.2+5=0$, so the point lies on the boundary, and its distance from the origin is $\sqrt{0.36+0.64}=1$.
Exercise 9.2: Sigmoid and tanh
Solution
(1) Let $u=a/2$. Then $\tanh u=\dfrac{e^{u}-e^{-u}}{e^{u}+e^{-u}}$. Multiplying the numerator and denominator by $e^{-u}$ gives $\tanh u=\dfrac{1-e^{-2u}}{1+e^{-2u}}=\dfrac{1-e^{-a}}{1+e^{-a}}$. Hence
$$ \begin{aligned} &\tfrac12\{1+\tanh(a/2)\}\\ &=\frac12\cdot\frac{(1+e^{-a})+(1-e^{-a})}{1+e^{-a}}\\ &=\frac{1}{1+e^{-a}}=\sigma(a). \end{aligned} $$The sigmoid is tanh stretched horizontally by a factor of 2, with the range of values moved from $(-1,1)$ to $(0,1)$.
(2) Let $p=\sigma(a)$. Then $1-p=e^{-a}/(1+e^{-a})$, so $p/(1-p)=1/e^{-a}=e^{a}$, and taking the logarithm of both sides gives $a=\ln\{p/(1-p)\}=\ell(p)$. Conversely, if $\ell(p)=a$, solving $p/(1-p)=e^{a}$ gives $p=\sigma(a)$. Hence $\ell$ and $\sigma$ are inverse functions of each other. The derivative is
$$ \begin{aligned} \diff{\ell}{p}&=\diff{}{p}\bigl\{\ln p-\ln(1-p)\bigr\}\\ &=\frac1p+\frac{1}{1-p}=\frac{1}{p(1-p)} . \end{aligned} $$This also agrees with the derivative of the inverse function, $1/\sigma'(a)=1/\{\sigma(1-\sigma)\}$.
(3) We use Eq. (9.9) of Chapter 9, $\sigma'=\sigma(1-\sigma)$.
$$ \begin{aligned} \diff{}{a}\ln\sigma(a)&=\frac{\sigma'(a)}{\sigma(a)}=1-\sigma(a),\\ \frac{\dd^{2}}{\dd a^{2}}\ln\sigma(a)&=-\sigma'(a)\\ &=-\sigma(a)\bigl(1-\sigma(a)\bigr). \end{aligned} $$Hence $\dfrac{\dd^{2}}{\dd a^{2}}\{-\ln\sigma(a)\}=\sigma(a)(1-\sigma(a))\gt0$, and $-\ln\sigma(a)$ is a convex function. Likewise $-\ln(1-\sigma(a))=-\ln\sigma(-a)$ is convex, so the cross-entropy loss for a single point is convex in $a$. Since $a$ is a linear (first-degree) expression in $(\bm{w},b)$, the loss, being the composition of a convex function with a linear expression, is also convex in $(\bm{w},b)$.
Exercise 9.3: Conditions for the Hessian matrix to be positive definite
Solution
(1) Let $s_n=\hat{y}_n(1-\hat{y}_n)$. Then $0\lt s_n\le1/4$ (since $0\lt\hat{y}_n\lt1$). For any $\bm{v}\in\R^{M+1}$,
$$ \bm{v}^{\tp}\bm{H}\bm{v}=\sum_{n=1}^{N}s_n(\bm{v}^{\tp}\tilde{\bm{\phi}}_n)^{2}\ge0 . $$Suppose equality holds. Since $s_n\gt0$, every term is 0; that is, $\bm{v}^{\tp}\tilde{\bm{\phi}}_n=0$ for all $n$, which in matrix form reads $\tilde{\bm{\Phi}}\bm{v}=\bm{0}$. If the rank of $\tilde{\bm{\Phi}}$ is $M+1$ (the columns are linearly independent), the only solution of $\tilde{\bm{\Phi}}\bm{v}=\bm{0}$ is $\bm{v}=\bm{0}$. Therefore, if $\bm{v}\ne\bm{0}$, then $\bm{v}^{\tp}\bm{H}\bm{v}\gt0$, and $\bm{H}$ is positive definite.
(2) The Hessian matrix of the regularization term $\tfrac{\lambda}{2}\norm{\bm{w}}^{2}$ with respect to $\bm{w}$ is $\lambda\bm{I}_M$. Writing the block for the $\bm{w}$ part as $\bm{H}_{ww}+\lambda\bm{I}_M$, for any $\bm{u}\in\R^{M}$ with $\bm{u}\ne\bm{0}$ we have
$$ \begin{aligned} \bm{u}^{\tp}(\bm{H}_{ww}+\lambda\bm{I}_M)\bm{u}&=\bm{u}^{\tp}\bm{H}_{ww}\bm{u}+\lambda\norm{\bm{u}}^{2}\\ &\ge\lambda\norm{\bm{u}}^{2}\gt0 \end{aligned} $$($\bm{H}_{ww}$ is positive semidefinite for the same reason as in (1)). It is positive definite regardless of the rank of the data.
(3) A positive definite Hessian matrix guarantees that “the loss is strictly convex” and implies that a minimum point, if it exists, is unique. However, it does not guarantee that “a minimum point exists.” For example, $g(w)=e^{-w}$ is strictly convex because $g''=e^{-w}\gt0$, but it only approaches 0 as $w\to\infty$ and has no minimum. The loss for linearly separable data is the same: moving in a certain direction keeps lowering the loss, and the curvature $s_n$ in that direction approaches 0 ($\hat{y}_n\to0$ or 1). The Hessian is positive definite at every finite point, but the minimum point lies infinitely far away. When regularization is added, the lower bound $\lambda$ in (2) keeps the curvature from approaching 0, and in addition the loss grows without bound as $\norm{\bm{w}}\to\infty$, so the minimum point comes to lie at a finite position.
Exercise 9.4: One step of Newton’s method
Solution
The data are $x=(-1.5,-0.5,0.5,1.5)$ and $y=(0,1,0,1)$. Let $\tilde{\bm{\phi}}_n=(x_n,1)^{\tp}$ and $\tilde{\bm{w}}=(w,b)^{\tp}$.
(1) At $w=b=0$, $\hat{y}_n=0.5$ and $s_n=\hat{y}_n(1-\hat{y}_n)=0.25$.
$$ \begin{aligned} \bm{H}&=0.25\sum_n\begin{pmatrix}x_n^{2}&x_n\\x_n&1\end{pmatrix}\\ &=0.25\begin{pmatrix}5&0\\0&4\end{pmatrix}=\begin{pmatrix}1.25&0\\0&1\end{pmatrix}. \end{aligned} $$($\sum x_n^{2}=2.25+0.25+0.25+2.25=5$, $\sum x_n=0$.) By Example 9.4 (2), the gradient is $\nabla L=(-1.0,\ 0)^{\tp}$.
(2) Solving $\bm{H}\bm{d}=\nabla L$ gives $\bm{d}=(-1.0/1.25,\ 0/1)^{\tp}=(-0.8,\ 0)^{\tp}$. The update $\tilde{\bm{w}}\leftarrow\tilde{\bm{w}}-\bm{d}$ gives $(w,b)=(0.8,\ 0)$. Then $a_n=0.8x_n=(-1.2,\ -0.4,\ 0.4,\ 1.2)$ and $\hat{y}_n=(0.2315,\ 0.4013,\ 0.5987,\ 0.7685)$, and the loss is
$$ \begin{aligned} L&=-2\ln0.7685-2\ln0.4013\\ &=2\times0.2633+2\times0.9130\\ &\approx2.3526 . \end{aligned} $$Gradient descent ($\eta=0.5$) gave $w=0.5$ and $L=2.4256$ after one step, and $w=0.700$ and $L=2.3669$ after two steps. So one step of Newton’s method ($L=2.3526$) gets closer to the minimum $L^{*}\approx2.3475$ than two steps of gradient descent do. This is because Newton’s method uses the curvature $\bm{H}$ to decide the size of each step direction by direction.
(3) Second step: at $(w,b)=(0.8,0)$, $s_n=(0.1779,\ 0.2403,\ 0.2403,\ 0.1779)$, $\bm{H}=\begin{pmatrix}0.9207&0\\0&0.8363\end{pmatrix}$, $\partial L/\partial w=-0.0957$, and $\partial L/\partial b=0$. Then $w\leftarrow0.8+0.0957/0.9207=0.9040$. At the third step $w=0.90818$, which agrees with the minimum point $w^{*}=0.90818$ to more than three digits (the 0.904 of the second step differs in the third digit). Near the minimum point, the error shrinks by roughly squaring at each step (quadratic convergence).
Exercise 9.5: A two-class softmax is logistic regression
Solution
(1) Dividing the numerator and denominator of $\hat{y}_1=\dfrac{e^{a_1}}{e^{a_1}+e^{a_2}}$ by $e^{a_1}$ gives $\hat{y}_1=\dfrac{1}{1+e^{-(a_1-a_2)}}=\sigma(a_1-a_2)$. Here
$$ \begin{aligned} a_1-a_2&=(\bm{w}_1-\bm{w}_2)^{\tp}\bm{\phi}+(b_1-b_2)\\ &=\bm{w}^{\tp}\bm{\phi}+b \end{aligned} $$so $\hat{y}_1$ equals the output of logistic regression with $\bm{w}=\bm{w}_1-\bm{w}_2$ and $b=b_1-b_2$. $\hat{y}_2=1-\hat{y}_1$ agrees as well.
(2) By Eq. (9.19) of Chapter 9, $\nabla_{\bm{w}_k}L=\sum_n(\hat{y}_{nk}-y_{nk})\bm{\phi}_n$. The sum over $k=1,2$ is
$$ \begin{aligned} &\sum_n\bigl\{(\hat{y}_{n1}+\hat{y}_{n2})-(y_{n1}+y_{n2})\bigr\}\bm{\phi}_n\\ &=\sum_n(1-1)\bm{\phi}_n=\bm{0} \end{aligned} $$(the probabilities sum to 1, and so does the one-hot vector). Meaning: even if the same vector $\bm{c}$ is added to both $\bm{w}_1$ and $\bm{w}_2$, $a_1-a_2$ does not change, and neither does the loss. The component of the gradient in the direction $(\bm{c},\bm{c})$, along which the loss does not change, is 0, and this appears as “the sum is 0.” For this reason the solution of $K$-class softmax regression is not uniquely determined, and it is fixed either by setting the weights of one class to $\bm{0}$ or by adding regularization.
(3) Let $\hat{y}_k=e^{a_k}/Z$ and $Z=\sum_je^{a_j}$. Then $\partial Z/\partial a_j=e^{a_j}$. By the quotient rule,
$$ \begin{aligned} \pdiff{\hat{y}_k}{a_j}&=\frac{\delta_{kj}e^{a_k}Z-e^{a_k}e^{a_j}}{Z^{2}}\\ &=\frac{e^{a_k}}{Z}\Bigl(\delta_{kj}-\frac{e^{a_j}}{Z}\Bigr)\\ &=\hat{y}_k(\delta_{kj}-\hat{y}_j). \end{aligned} $$For $K=2$ and $k=j=1$ this becomes $\hat{y}_1(1-\hat{y}_1)$, which agrees with the derivative of the sigmoid.
Exercise 9.6: Inspection threshold for sintered parts
Solution
There are $5000\times0.02=100$ defective parts and 4900 good parts.
(1) $t=1.0$: recall $=1-\Phi(1-2)=\Phi(1)=0.8413$ and false positive rate $=1-\Phi(1)=0.1587$. TP $=100\times0.8413=84.1$, FN $=15.9$, FP $=4900\times0.1587=777.4$, TN $=4122.6$. Precision $=84.1/(84.1+777.4)=0.0977$, F1 $=2\times0.0977\times0.8413$ $/(0.0977+0.8413)=0.175$, accuracy $=(84.1+4122.6)/5000=0.841$.
$t=2.0$: recall $=1-\Phi(0)=0.5$ and false positive rate $=1-\Phi(2)=0.02275$. TP $=50$, FN $=50$, FP $=111.5$, TN $=4788.5$. Precision $=50/161.5=0.310$, F1 $=2\times0.310\times0.5/0.810=0.382$, accuracy $=4838.5/5000=0.968$.
(2) Expected cost $=20\times\mathrm{FN}+1\times\mathrm{FP}$. For $t=1.0$: $20\times15.9+777.4=1094.7$. For $t=2.0$: $20\times50+111.5=1111.5$. For “everything is good”: FN $=100$ and FP $=0$, giving $2000$. Although $t=2.0$ is better than $t=1.0$ in accuracy and F1, it is slightly worse in cost. The conclusion changes depending on which metric is used to choose.
(3) The class-conditional densities of the score are Gaussian distributions with variance 1 and means 0 and 2, so by the same calculation as Example 9.2 of Chapter 9 the log-odds are $a(s)=2s-2+\ln(0.02/0.98)$ $=2s-2-3.892$. The probability at the threshold is $p^{*}=1/(1+20)=1/21$, and in log-odds this is $\ln\{(1/21)/(20/21)\}=-\ln20=-2.996$. Solving $a(s)=-2.996$ gives
$$ \begin{aligned} 2s&=2+3.892-2.996=2.896,\\ t^{*}&=1.448 . \end{aligned} $$Then recall $=\Phi(0.552)=0.710$, false positive rate $=1-\Phi(1.448)=0.0738$, FN $=29.0$, FP $=361.6$, and the expected cost is $20\times29.0+361.6=942.6$. This is smaller than that for either of $t=1.0$ and $2.0$, and the same $t\approx1.448$ is obtained even if we vary $t$ finely and minimize the cost numerically.
Exercise 9.7: Expressing the range of the tolerance factor with a discriminant function
Solution
(1) $a(t)=-200t^{2}+376.8t-174.735$. By the quadratic formula, the solutions of the quadratic equation $a(t)=0$ are
$$ \begin{aligned} t&=\frac{376.8\pm\sqrt{376.8^{2}-4\times200\times174.735}}{2\times200}\\ &=\frac{376.8\pm\sqrt{141978.24-139788}}{400}\\ &=\frac{376.8\pm46.8}{400}, \end{aligned} $$$t_1=0.825$ and $t_2=1.059$. Since the coefficient of $t^{2}$ is negative, $a(t)\gt0$ ($\hat{y}\gt0.5$) holds for $0.825\lt t\lt1.059$. We can write $a(t)=-200(t-0.825)(t-1.059)$.
(2) $t=0.94$: $a=-200\times0.115\times(-0.119)=2.737$ and $\hat{y}=\sigma(2.737)=0.939$. $t=0.80$: $a=-200\times(-0.025)\times(-0.259)=-1.295$ and $\hat{y}=0.215$. $t=1.10$: $a=-200\times0.275\times0.041=-2.255$ and $\hat{y}=0.095$.
(3) Since $a=wt+b$ is a linear function of $t$, if $w\ne0$ the sign changes at only one point, $t=-b/w$, and the region where $a\gt0$ is a half-line on one side, either “$t\gt-b/w$” or “$t\lt-b/w$.” If $w=0$, the sign is the same everywhere. In either case, $a\gt0$ cannot hold on only a bounded interval $(t_1,t_2)$. In the plane of the features $(t,t^{2})$, $a=w_1t+w_2t^{2}+b=0$ is a line, and the data points $(t,t^{2})$ lie on a parabola. That line cuts the parabola at two points, so on the $t$ axis it becomes a test for an interval.
(4) Since $\tau\lt4.18$ is class 1 (perovskite), we can write $f(\tau)=4.18-\tau\gt0$. Then $w=-1$ and $b=4.18$ (a positive multiple of these gives the same boundary). The Platt scaling that the paper used to obtain probabilities from $\tau$ amounts to fitting $A\gt0$ and $B$ in $1/\{1+\exp(A\tau+B)\}$ (the form in Section 9.8), and the boundary is $\tau=-B/A$.
Exercise 9.8: Choosing between generative and discriminative
Solution
(1) Generative classification with a shared covariance: the means take $2\times20=40$ parameters, the covariance takes $20\times21/2=210$, and the prior probability takes 1, for a total of 251. With a separate covariance for each class, the total is $40+2\times210+1=461$. Logistic regression: $\bm{w}$ has 20 parameters and $b$ has 1, for a total of 21. A generative model estimates even “the shape of the distribution of the inputs,” which is not used directly for classification, so it has far more parameters. With little data, the estimate of the covariance matrix becomes unstable (if $N_k\lt D$, the sample covariance matrix is singular and has no inverse matrix).
(2) The generative model is easier to handle. If $p(\bm{x}\mid C_k)$ is a multivariate Gaussian distribution, the marginal distribution obtained by integrating out the missing components is also Gaussian, and it is obtained simply by extracting the submatrices of the mean and covariance for the observed components (Chapter 3, Section 3.6). Therefore the posterior probability $p(C_k\mid\bm{x}_{\text{observed}})$ can be computed from the observed descriptors alone. Logistic regression presupposes an $\bm{x}$ with all components present, so one must either impute the missing values (which itself requires assumptions) or discard that sample.
(3) Representing a variable that takes only 0 or 1 with a Gaussian distribution is an incorrect assumption about the shape of the distribution (it places density on values that are never taken, and treats the relationship between the two values as a continuous quantity). That error enters $\bm{w}$ through $\bm{\Sigma}$ and $\bm{\mu}_k$. Logistic regression assumes nothing about the distribution of the inputs and makes only the assumption that “the log-odds are a linear expression in the features,” so binary descriptors can be put into the features as they are (the coefficient can be read as “how much the log-odds increase when that element is contained”). Because it makes fewer assumptions, if there is enough data it tends to give a boundary with less bias.
← Back to Chapter 9, “Linear Classification Models — Decision Boundaries and Probabilities”
Chapter 10 Kernel Methods — Learning from Similarity
Exercise 10.1: Feature map of the nonhomogeneous polynomial kernel (computation)
Solution
(1) Let $t\equiv\bm{x}^{\tp}\bm{x}'=x_1x_1'+x_2x_2'$. Then $(t+c)^{2}=t^{2}+2ct+c^{2}$. We expand each term.
$$ \begin{aligned} t^{2}&=x_1^{2}x_1'^{2}+x_2^{2}x_2'^{2}\\ &\quad+(\sqrt2x_1x_2)(\sqrt2x_1'x_2')\\ 2ct&=(\sqrt{2c}\,x_1)(\sqrt{2c}\,x_1')\\ &\quad+(\sqrt{2c}\,x_2)(\sqrt{2c}\,x_2')\\ c^{2}&=c\cdot c \end{aligned} $$Hence $(\bm{x}^{\tp}\bm{x}'+c)^{2}=\bm{\phi}(\bm{x})^{\tp}\bm{\phi}(\bm{x}')$, where
$$ \begin{aligned} \bm{\phi}(\bm{x})=\bigl(&c,\ \sqrt{2c}\,x_1,\ \sqrt{2c}\,x_2,\\ &x_1^{2},\ x_2^{2},\ \sqrt2x_1x_2\bigr)^{\tp} \end{aligned} $$(2) The contributions to the dot product are $c^{2}$ from the constant term, $2c\,t$ from the first-degree term, and $t^{2}$ from the second-degree term. As $c$ grows, the first-degree term (ratio $2c$) and the constant term (ratio $c^{2}$) carry more weight relative to the second-degree term. As $c\to0$ we return to the homogeneous kernel $(\bm{x}^{\tp}\bm{x}')^{2}$.
(3) We have $t=1\times3+2\times(-1)=1$ and $c=2$, so $(1+2)^{2}=9$. Using $\sqrt{2c}=2$, the feature vectors are
$$ \begin{aligned} \bm{\phi}(\bm{x})&=(2,\ 2,\ 4,\ 1,\ 4,\ 2\sqrt2)^{\tp}\\ \bm{\phi}(\bm{x}')&=(2,\ 6,\ -2,\ 9,\ 1,\ -3\sqrt2)^{\tp} \end{aligned} $$Their dot product is $4+12-8+9+4-12=9$, which agrees.
(4) By $\binom{D+d}{d}$, for $D=5$ and $d=3$ we get $\binom{8}{3}=56$, and for $D=20$ and $d=3$ we get $\binom{23}{3}=1771$. Computing the kernel needs only a dot product ($D$ multiplications) and a cube.
Exercise 10.2: An identity linking the primal and dual problems (derivation)
Solution
(1) For any $\bm{v}\in\R^{M}$ with $\bm{v}\ne\bm{0}$,
$$ \begin{aligned} \bm{v}^{\tp}(\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I}_M)\bm{v}&=\norm{\bm{\Phi}\bm{v}}^{2}+\lambda\norm{\bm{v}}^{2}\\ &\ge\lambda\norm{\bm{v}}^{2}\gt0 \end{aligned} $$so the matrix is positive definite; hence all its eigenvalues are positive and it is invertible. Similarly, for $\bm{u}\in\R^{N}$ with $\bm{u}\ne\bm{0}$,
$$ \bm{u}^{\tp}(\bm{\Phi}\bm{\Phi}^{\tp}+\lambda\bm{I}_N)\bm{u}=\norm{\bm{\Phi}^{\tp}\bm{u}}^{2}+\lambda\norm{\bm{u}}^{2}\gt0 $$(2) Expanding the matrix product gives
$$ \begin{aligned} \bm{\Phi}^{\tp}(\bm{\Phi}\bm{\Phi}^{\tp}+\lambda\bm{I}_N)&=\bm{\Phi}^{\tp}\bm{\Phi}\bm{\Phi}^{\tp}+\lambda\bm{\Phi}^{\tp}\\ &=(\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I}_M)\bm{\Phi}^{\tp} \end{aligned} $$Multiplying both sides by $(\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I}_M)^{-1}$ from the left and by $(\bm{\Phi}\bm{\Phi}^{\tp}+\lambda\bm{I}_N)^{-1}$ from the right (both exist by (1)), we obtain
$$ (\bm{\Phi}^{\tp}\bm{\Phi}+\lambda\bm{I}_M)^{-1}\bm{\Phi}^{\tp}=\bm{\Phi}^{\tp}(\bm{\Phi}\bm{\Phi}^{\tp}+\lambda\bm{I}_N)^{-1} $$Multiplying by $\bm{y}$ from the right, the solution $\bm{w}$ of the primal problem coincides with $\bm{\Phi}^{\tp}\bm{a}$, built from the solution of the dual problem.
(3) We compare the number of operations, counting multiplications and additions together. For the primal problem, factorizing the $M\times M=10^{4}\times10^{4}$ matrix takes about $M^{3}/3=3.3\times10^{11}$ operations; for the dual problem, factorizing the $50\times50$ matrix takes about $50^{3}/3=4.2\times10^{4}$ operations (counting multiplications alone, both are half of this). The cost of forming the matrices is likewise $NM^{2}=5\times10^{9}$ operations for $\bm{\Phi}^{\tp}\bm{\Phi}$ and $N^{2}M=2.5\times10^{7}$ operations for $\bm{K}=\bm{\Phi}\bm{\Phi}^{\tp}$; in both respects the dual problem is far cheaper.
Exercise 10.3: Building up kernels (derivation)
Solution
(1) Let $\bm{K}_1$ and $\bm{K}_2$ be the Gram matrices of the two kernels on the same set of points. The Gram matrix of the product kernel is the componentwise product $\bm{K}_1\odot\bm{K}_2$ (that is, $(\bm{K}_1\odot\bm{K}_2)_{nm}=(K_1)_{nm}(K_2)_{nm}$). Since $\bm{K}_2$ is symmetric and positive semidefinite, we can write $\bm{K}_2=\sum_i\mu_i\bm{u}_i\bm{u}_i^{\tp}$ with $\mu_i\ge0$ (Section A.3 of Appendix A). In components, $(K_2)_{nm}=\sum_i\mu_iu_{in}u_{im}$. Therefore
$$ \begin{aligned} &\bm{c}^{\tp}(\bm{K}_1\odot\bm{K}_2)\bm{c}\\ &=\sum_{n,m}c_nc_m(K_1)_{nm}\sum_i\mu_iu_{in}u_{im}\\ &=\sum_i\mu_i\sum_{n,m}(c_nu_{in})(K_1)_{nm}(c_mu_{im})\\ &=\sum_i\mu_i\,\bm{b}_i^{\tp}\bm{K}_1\bm{b}_i\ \ge\ 0 \end{aligned} $$Here $\bm{b}_i=\bm{c}\odot\bm{u}_i$ (with components $c_nu_{in}$). Since $\mu_i\ge0$ and $\bm{b}_i^{\tp}\bm{K}_1\bm{b}_i\ge0$, each term is nonnegative. Symmetry is also preserved ($(K_1)_{nm}(K_2)_{nm}=(K_1)_{mn}(K_2)_{mn}$).
(2) Since $\bm{x}^{\tp}\bm{x}'/\ell^{2}$ is the dot product of the features $\bm{x}/\ell$, it is a positive definite kernel. The coefficients of $\exp(t)=\sum_{j\ge0}t^{j}/j!$ are all positive, so by (6) of Theorem 10.2 in the main text, $\exp(\bm{x}^{\tp}\bm{x}'/\ell^{2})$ is also a positive definite kernel.
(3) From $\norm{\bm{x}-\bm{x}'}^{2}=\norm{\bm{x}}^{2}-2\bm{x}^{\tp}\bm{x}'+\norm{\bm{x}'}^{2}$ we get
$$ \begin{aligned} &\sigma_f^{2}\exp\!\left(-\frac{\norm{\bm{x}-\bm{x}'}^{2}}{2\ell^{2}}\right)\\ &=\sigma_f^{2}\,g(\bm{x})\exp\!\left(\frac{\bm{x}^{\tp}\bm{x}'}{\ell^{2}}\right)g(\bm{x}') \end{aligned} $$where $g(\bm{x})=e^{-\norm{\bm{x}}^{2}/(2\ell^{2})}$. Applying (4) of Theorem 10.2 (weighting by a function) and (2) (multiplication by the positive constant $\sigma_f^{2}$) to the kernel in (2), we see that the RBF kernel is positive definite.
(4) From $e^{-1}=0.36788$, $e^{-3}=0.04979$, and $e^{-2}=0.13534$,
$$ \bm{K}=\begin{pmatrix}1&0.36788&0.04979\\0.36788&1&0.13534\\0.04979&0.13534&1\end{pmatrix} $$The eigenvalues are $0.6218$, $0.9680$, and $1.4101$, all positive (their sum agrees with $\tr\bm{K}=3$). The Laplace kernel is also a positive definite kernel (the case $\nu=1/2$ of the Matérn family).
Exercise 10.4: Kernel ridge regression on three points (computation)
Solution
(1) Let $c_1=e^{-1/2}=0.60653$ (distance 1) and $c_2=e^{-2}=0.13534$ (distance 2). Then
$$ \bm{K}+0.5\bm{I}=\begin{pmatrix}1.5&c_1&c_2\\c_1&1.5&c_1\\c_2&c_1&1.5\end{pmatrix} $$The data are symmetric under $x\to-x$ ($y(-1)=y(1)$), and this matrix is also unchanged when the first and third indices are swapped. Since the solution is unique, the swapped solution is the same solution, so $a_1=a_3$. Substituting $\bm{a}=(p,q,p)^{\tp}$, the first and third rows give the same equation, and we obtain
$$ \begin{aligned} (1.5+c_2)\,p+c_1q&=1\\ 2c_1\,p+1.5\,q&=0 \end{aligned} $$From the second equation, $q=-\dfrac{2c_1}{1.5}p=-0.80871\,p$. Substituting into the first,
$$ \begin{aligned} &(1.63534-0.60653\times0.80871)\,p\\ &=1.14483\,p=1 \end{aligned} $$Hence $p=0.87349$ and $q=-0.70640$.
(2) The prediction is $f(x)=p\,k(-1,x)+q\,k(0,x)+p\,k(1,x)$.
$$ \begin{aligned} f(0)&=2c_1p+q\\ &=1.05961-0.70640=0.3532\\ f(1)&=c_2p+c_1q+p\\ &=0.11822-0.42845+0.87349\\ &=0.5633\\ f(3)&=e^{-8}p+e^{-4.5}q+e^{-2}p\\ &=0.00029-0.00785+0.11822\\ &=0.1107 \end{aligned} $$By symmetry, $f(-1)$ is the same as $f(1)$.
(3) The value $\lambda=0.5$ is large compared with the diagonal entries 1 of the Gram matrix and shrinks the fine components strongly, so the predictions at the training points are pulled from the observed values (0 and 1) toward the mean ($0.353$ and $0.563$). The point $x=3$ is $2\ell$ away even from the nearest point $x=1$, and the kernel values are small, so the prediction approaches 0. Since we solved without subtracting the mean, the value it returns to is 0.
Exercise 10.5: Interpolating the band gap of a mixed crystal with kernel ridge regression (a materials topic)
Solution
(1) $E_g(0)=1.20$, $E_g(0.5)=0.60+1.20$ $-0.80\times0.25=1.60$, and $E_g(1)=2.40$ eV. The mean is $\bar{y}=(1.20+1.60+2.40)/3=1.7333$ eV. The target values with the mean subtracted are $(-0.5333,\ -0.1333,\ 0.6667)$ eV.
(2) The spacing 0.5 between points equals $\ell$, so the entries of $\bm{K}$ are $e^{-1/2}=0.60653$ (neighbors) and $e^{-2}=0.13534$ (the two ends), the same pattern as in Exercise 10.4. Solving $(\bm{K}+10^{-3}\bm{I})\bm{a}=\bm{y}-\bar{y}\bm{1}$ gives $\bm{a}=(-0.3257,\ -0.5785,\ 1.0605)$ eV.
At $x=0.25$, $\bm{k}_*=(e^{-0.125},\ e^{-0.125},\ e^{-1.125})^{\tp}$ $=(0.8825,\ 0.8825,\ 0.3247)^{\tp}$, so
$$ \begin{aligned} f(0.25)&=1.7333\\ &\quad+0.8825\times(-0.9042)\\ &\quad+0.3247\times1.0605\\ &=1.7333-0.7980+0.3443\\ &=1.280\ \mathrm{eV} \end{aligned} $$The true value is $E_g(0.25)=0.90+0.60$ $-0.80\times0.1875=1.350$ eV. Similarly, at $x=0.75$ we get $f=2.053$ eV, while the true value is $E_g(0.75)=0.30+1.80-0.15$ $=1.950$ eV.
Because $\lambda$ is small, the fit passes almost exactly through the observed values at the training points ($f(0)=1.2003$, $f(1)=2.3989$).
(3) Linear interpolation gives $1.40$ eV at $x=0.25$ and $2.00$ eV at $x=0.75$, with an error of $0.05$ eV in both cases. The errors of kernel ridge regression are $-0.07$ eV and $+0.10$ eV, so in this example linear interpolation is closer. The true function is a downward-convex parabola (bowing), but the RBF kernel ($\ell=0.5$) makes the assumption that “between the points the function is a superposition of bumps that return toward the mean of 1.733 eV,” so three points alone cannot reproduce the shape of the parabola. A linear regression that includes the basis function $x(1-x)$, as in Chapter 8, can determine the true function exactly from three points. When a physically reasonable functional form is known, it is better to use it as the mean function or basis and let the kernel account only for the deviation from it.
(4) The prediction at $x=1.3$ is $2.447$ eV, a value on the way back toward the mean of 1.733 eV as we move away from the end point. In the first place, the composition $x$ is a quantity between 0 and 1, so $x=1.3$ has no physical meaning, and neither the extrapolated formula value of $3.07$ eV nor the model’s prediction is a “value of a material.” The correct answer is: do not predict outside the domain.
Exercise 10.6: Similarity of atomic configurations and invariance (a materials topic, discussion)
Solution
(1) Under the 90° rotation $(x,y)\mapsto(-y,x)$, atom 1 moves to $(0,0)$, atom 2 to $(0,1.0)$, and atom 3 to $(-1.2,0)$. Swapping the labels of atoms 2 and 3 gives Q: atom 1 at $(0,0)$, atom 2 at $(-1.2,0)$, atom 3 at $(0,1.0)$.
(2) The vectors listing the coordinates are P $=(0,0,\ 1.0,0,\ 0,1.2)$ and Q $=(0,0,\ -1.2,0,\ 0,1.0)$. The sum of squared differences is $(1.0+1.2)^{2}+(1.2-1.0)^{2}$ $=4.84+0.04=4.88$ Å$^{2}$. The similarity is $\exp\bigl(-4.88/(2\times0.25)\bigr)$ $=e^{-9.76}=5.8\times10^{-5}$, so although the two arrangements are physically the same, they are judged to be “not similar at all.”
(3) The interatomic distances of P are $\abs{12}=1.0$, $\abs{13}=1.2$, and $\abs{23}=\sqrt{1.0^{2}+1.2^{2}}=1.562$ Å. For Q as well, the rotation does not change the distances and the relabeling only changes their order, so sorting them in increasing order gives the same $(1.0,\ 1.2,\ 1.562)$. The similarity is $e^{0}=1$.
(4) The distances of P′ are $(1.0,\ 1.3,\ \sqrt{1+1.69}=1.640)$. The sum of squared differences from P is $0+0.01+0.0061=0.0161$ Å$^{2}$, and the similarity is $\exp(-0.0161/0.5)=0.968$. If we move the atoms slightly, the similarity drops only slightly.
(5) Examples of weaknesses: ① when there are more atoms, the set of pairwise distances alone does not determine the arrangement uniquely (different arrangements can have the same set of distances), so different structures may be judged to be “the same.” ② Where the order of two distances is exchanged, the components of the sorted result change with a kink, so the derivative of the similarity (the quantity corresponding to the force) becomes discontinuous. ③ When the number of nearby atoms changes, the length of the descriptor changes, and descriptors cannot be compared as they are. SOAP is a method that integrates the overlap of atomic densities over rotations; it avoids these problems while maintaining invariance and smoothness (Section 10.10 of the main text).
Exercise 10.7: The Nadaraya–Watson limits and attention (computation, discussion)
Solution
(1) The distances from $x_*=1.5$ to the three points are 1.5, 0.5, and 0.5. As $\ell\to0$, the ratio of window values $e^{-(d_n^{2}-d_m^{2})/(2\ell^{2})}$ tends to 0 for every point other than the one with the shortest distance. The points at the shortest distance are the two points $x=1$ and $x=2$, which are equally distant, so the weights are $(0,\ \tfrac12,\ \tfrac12)$ and the prediction is $(3+2)/2=2.5$. As $\ell\to\infty$, all the window values tend to 1, the weights are $(\tfrac13,\tfrac13,\tfrac13)$, and the prediction is the mean $(1+3+2)/3=2.0$.
(2) For $\ell=1$ and $x_*=4$, the exponents are $-(4-0)^{2}/2=-8$, $-(4-1)^{2}/2=-4.5$, and $-(4-2)^{2}/2=-2$. To avoid overflow, we subtract the maximum $-2$ before exponentiating, which gives $(e^{-6},\ e^{-2.5},\ 1)=(0.00248,\ 0.08208,\ 1)$, with sum $1.08456$. The weights are $(0.0023,\ 0.0757,\ 0.9220)$, and the prediction is $0.0023\times1+0.0757\times3$ $+0.9220\times2=2.073$. Outside the data, the prediction approaches the value at the nearest point ($x=2$, value 2).
(3) With $s_n=x_*x_n-x_n^{2}/2$ ($\ell=1$), we get $(0,\ 3.5,\ 6)$.
$$ \begin{aligned} -\frac{(x_*-x_n)^{2}}{2}&=-\frac{x_*^{2}}{2}+x_*x_n-\frac{x_n^{2}}{2}\\ &=-8+s_n \end{aligned} $$so the two differ only by the constant $-8$, which is common to all $n$. The softmax does not change when the same constant is added to all the scores, so the weights coincide. Indeed, subtracting the maximum 6 from $s_n$ gives $(-6,\ -2.5,\ 0)$, the same numbers as in (2).
(4) The scale $1/\ell^{2}$ of the score corresponds to $1/\sqrt{d_k}$ in attention. Increasing the scale corresponds to decreasing $\ell$, and the weights concentrate on the key with the highest score (the limit $\ell\to0$ selects only the nearest point). Decreasing the scale makes the weights approach uniform, and the prediction approaches the simple average of the values.
Exercise 10.8: A periodic kernel for crystal orientation (a materials topic, derivation)
Solution
(1) Let $\Delta=\theta-\theta'$ and $\omega=2\pi/p$. Since $\bm{u}$ is a point on the unit circle, $\norm{\bm{u}}=\norm{\bm{u}'}=1$, and
$$ \begin{aligned} &\norm{\bm{u}-\bm{u}'}^{2}\\ &=2-2\bigl(\cos\omega\theta\cos\omega\theta'+\sin\omega\theta\sin\omega\theta'\bigr)\\ &=2-2\cos(\omega\Delta)=4\sin^{2}(\omega\Delta/2) \end{aligned} $$(the last step uses the half-angle formula $1-\cos t=2\sin^{2}(t/2)$). Since $\omega\Delta/2=\pi\Delta/p$, the RBF kernel in the space of $\bm{u}$ is
$$ \begin{aligned} \exp\!\left(-\frac{\norm{\bm{u}-\bm{u}'}^{2}}{2\ell^{2}}\right)&\\ =\exp\!\left(-\frac{2\sin^{2}(\pi\Delta/p)}{\ell^{2}}\right)& \end{aligned} $$The RBF kernel is positive definite, and positive definiteness is preserved when the input is transformed by a map $\bm{u}(\theta)$ ((5) of Theorem 10.2 in the main text), so this kernel is positive definite.
(2) For $\ell=1$ and $p=90°$:
- $\Delta=15°$: $\sin^{2}(30°)=0.25$, $k=e^{-0.5}=0.607$
- $\Delta=45°$: $\sin^{2}(90°)=1$, $k=e^{-2}=0.135$
- $\Delta=90°$: $\sin^{2}(180°)=0$, $k=1$
(3) If we use the RBF kernel ($\ell=20°$) directly on $\theta$, then $k=\exp(-\Delta^{2}/800)$, which is $0.755$ for $\Delta=15°$, $0.080$ for $45°$, and $4.0\times10^{-5}$ for $90°$. The directions 0° and 90°, which should take the same value by symmetry, are regarded as “unrelated.” The periodic kernel treats 0° and 90° as the same point, so, for example, measurements over 0–45° can also predict the values over 45–90°, and symmetry compensates for the small amount of data. Conversely, if the sample orientation has errors or the crystal symmetry is lower than assumed (twinning, strain caused by stress, and so on), the assumed period does not hold and the predictions are wrong. Building symmetry into the kernel also means making an assumption about the symmetry.
← Back to Chapter 10, “Kernel Methods — Learning from Similarity”
Chapter 11 Support Vector Machines — Maximizing the Margin
Exercise 11.1: Checking whether a given line is the maximum-margin line
Solution
(1) The line $x_1+x_2-2=0$ has $\bm{w}=(1,1)^{\tp}$, $b=-2$, and $\norm{\bm{w}}=\sqrt2$. At each point, $y_nf(\bm{x}_n)$ is
$$ \begin{aligned} \bm{x}_1&:\ (+1)(2+2-2)=2,\\ \bm{x}_2&:\ (+1)(4+3-2)=5,\\ \bm{x}_3&:\ (-1)(0+0-2)=2,\\ \bm{x}_4&:\ (-1)(1-2-2)=3 . \end{aligned} $$The signed distances $r_n=y_nf/\norm{\bm{w}}$ are $2/\sqrt2=1.414$, $5/\sqrt2=3.536$, $1.414$, and $3/\sqrt2=2.121$, all positive (every point is on the correct side). The margin is the smallest of these, $\sqrt2\approx1.414$. Since $\min_ny_nf=2$, multiplying $(\bm{w},b)$ by $1/2$ gives the canonical form $\bm{w}=(0.5,\ 0.5)^{\tp}$, $b=-1$ (the boundary is the same line). Then $y_nf=1,\ 2.5,\ 1,\ 1.5$.
(2) The points on the margin ($y_nf=1$) are $\bm{x}_1$ and $\bm{x}_3$, so we assume $\mathcal{S}=\{1,3\}$ and $\alpha_2=\alpha_4=0$. The stationarity condition $\bm{w}=\sum_n\alpha_ny_n\bm{x}_n$ reads
$$ \begin{aligned} (0.5,\ 0.5)^{\tp}&=\alpha_1(+1)(2,2)^{\tp}+\alpha_3(-1)(0,0)^{\tp}\\ &=(2\alpha_1,\ 2\alpha_1)^{\tp} \end{aligned} $$so $\alpha_1=\tfrac14$. From $\sum_n\alpha_ny_n=\alpha_1-\alpha_3=0$ we get $\alpha_3=\tfrac14$. We now check the KKT conditions. Stationarity: satisfied above. Primal feasibility: $y_nf=1,\ 2.5,\ 1,\ 1.5\ge1$. Dual feasibility: $\bm{\alpha}=(\tfrac14,\ 0,\ \tfrac14,\ 0)\ge\bm{0}$. Complementarity: $\alpha_2=\alpha_4=0$, and $y_nf-1=0$ at $\bm{x}_1,\bm{x}_3$. Since the primal problem is convex, this point, which satisfies the KKT conditions, is the optimal solution. That is, the given line is the maximum-margin line (geometrically, it is the perpendicular bisector of the segment joining $\bm{x}_1$ and $\bm{x}_3$).
(3) The width is $2/\norm{\bm{w}}=2/\sqrt{0.5}=2\sqrt2\approx2.83$ (equal to the distance $\sqrt{8}$ between $\bm{x}_1$ and $\bm{x}_3$). The dual value $D=\sum_n\alpha_n-\tfrac12\norm{\bm{w}}^{2}=\tfrac12-\tfrac14=\tfrac14$ equals the primal value $\tfrac12\norm{\bm{w}}^{2}=\tfrac14$.
Exercise 11.2: Changing the penalty for each class
Solution
(1) Write the penalty of point $n$ as $C_n\equiv C_{y_n}$ (that is, $C_{+}$ if $y_n=+1$ and $C_{-}$ if $-1$). The objective function is then $\tfrac12\norm{\bm{w}}^{2}+\sum_nC_n\xi_n$. Introducing $\alpha_n\ge0$ for the constraint $1-\xi_n-y_nf(\bm{x}_n)\le0$ and $\mu_n\ge0$ for $-\xi_n\le0$, we obtain
$$ \begin{aligned} \Lambda={}&\frac12\norm{\bm{w}}^{2}+\sum_nC_n\xi_n-\sum_n\mu_n\xi_n\\ &-\sum_n\alpha_n\bigl\{y_n(\bm{w}^{\tp}\bm{\phi}_n+b)-1+\xi_n\bigr\}. \end{aligned} $$The stationarity conditions for $\bm{w}$ and $b$ are the same as Eqs. (11.6) and (11.7) of Chapter 11: $\bm{w}=\sum_n\alpha_ny_n\bm{\phi}_n$ and $\sum_n\alpha_ny_n=0$. The stationarity condition for $\xi_n$ is $\partial\Lambda/\partial\xi_n=C_n-\alpha_n-\mu_n=0$, that is, $\mu_n=C_n-\alpha_n$. The terms containing $\xi_n$ vanish because $\sum_n(C_n-\alpha_n-\mu_n)\xi_n=0$, and the rest is the same calculation as in the hard-margin case, giving
$$ D(\bm{\alpha})=\sum_n\alpha_n-\frac12\sum_{n,m}\alpha_n\alpha_my_ny_mk(\bm{x}_n,\bm{x}_m) $$From $\mu_n\ge0$ we obtain $\alpha_n\le C_n$. Therefore the constraints are $0\le\alpha_n\le C_{y_n}$ and $\sum_n\alpha_ny_n=0$.
(2) Take $C_{+}\gt C_{-}$. If we impose a large penalty on the slack of points with $y=+1$ (defective items), the boundary is less willing to place a defective item inside the margin or on the wrong side, so misses (judging a defective item to be good) decrease. In return, false alarms, in which a good item is judged defective, may increase. A class that makes up only 2 % contributes almost nothing to the total penalty when the same $C$ is used, so the boundary tends to fit the majority class. A commonly used rule of thumb is to make the ratio of the penalties the inverse ratio of the class sizes ($C_{+}/C_{-}\approx98/2$), but in the end we decide by looking at the costs of misses and false alarms and at the recall and precision on the validation data (Chapter 9, Section 9.7).
Exercise 11.3: A one-dimensional SVM and adding a point
Solution
(1) The closest points of different classes are $x=-2$ ($-1$) and $x=0$ ($+1$), and the boundary is their midpoint $x=-1$. Let $f(x)=w(x+1)$. The canonical-form condition $f(0)=1$ gives $w=1$ and $b=1$. For the other points, $y_nf=-(-3+1)=2$ and $2+1=3$, both at least 1. Taking $\mathcal{S}=\{-2,0\}$, the stationarity condition $w=\sum_n\alpha_ny_nx_n$ reads
$$ 1=\alpha_{-2}(-1)(-2)+\alpha_{0}(+1)(0)=2\alpha_{-2} $$so $\alpha_{-2}=\tfrac12$. From $\sum_n\alpha_ny_n=-\alpha_{-2}+\alpha_0=0$ we get $\alpha_0=\tfrac12$. Thus $\bm{\alpha}=(0,\ \tfrac12,\ \tfrac12,\ 0)$ (the points in the order $-3,-2,0,2$). Since the point $x=0$ has $x_n=0$, we have $\alpha_ny_nx_n=0$, so it does not contribute to $w$; however, to satisfy the equality constraint $\sum_n\alpha_ny_n=0$ (the stationarity condition for $b$), $\alpha_0=\alpha_{-2}$ is required. It is this point that determines $b$. The width is $2/w=2$.
(2) For the new point $x=-1.2$ ($y=-1$), $y f=-(-1.2+1)=0.2\lt1$, which violates the constraint, so the solution changes. The new closest pair is $x=-1.2$ and $x=0$, the boundary is their midpoint $x=-0.6$, and the width is $1.2$. Imposing $f(0)=1$ on $f(x)=w(x+0.6)$ gives $w=1/0.6=5/3$ and $b=5/3\times0.6=1$. Check: $f(-1.2)=\tfrac53(-0.6)=-1$, $f(-2)=\tfrac53(-1.4)=-2.33$, $f(-3)=-4$, and $f(2)=\tfrac53(2.6)=4.33$, so every point has $y_nf\ge1$. The stationarity condition $\tfrac53=\alpha_{-1.2}(-1)(-1.2)+\alpha_0\cdot0=1.2\,\alpha_{-1.2}$ gives $\alpha_{-1.2}=\tfrac{25}{18}\approx1.389$, $\alpha_0=\tfrac{25}{18}$, and all the others are 0. The point $x=-2$, which was a support vector originally, now has $\alpha=0$.
Exercise 11.4: A two-point SVM with an RBF kernel and γ
Solution
(1) We have $k_{11}=k_{22}=1$ and $k_{12}=q=e^{-\gamma d^{2}}$. From $\sum_n\alpha_ny_n=0$, $\alpha_1=\alpha_2=\alpha$.
$$ \begin{aligned} D(\alpha)&=2\alpha-\frac12\alpha^{2}(1+1-2q)\\ &=2\alpha-\alpha^{2}(1-q). \end{aligned} $$From $\mathrm{d}D/\mathrm{d}\alpha=2-2\alpha(1-q)=0$ we get $\alpha=1/(1-q)$. Then $b=y_2-\alpha y_1k_{12}-\alpha y_2k_{22}$ $=1+\alpha q-\alpha$ $=1-\alpha(1-q)=0$. Since $\norm{\bm{w}}^{2}=\alpha^{2}(2-2q)=2\alpha$, the width is $2/\norm{\bm{w}}=\sqrt{2/\alpha}=\sqrt{2(1-q)}$.
(2) For $d=1$: with $\gamma=0.05$, $q=e^{-0.05}=0.9512$, $\alpha=1/0.04877=20.50$, and the width is $\sqrt{2\times0.04877}=0.312$. With $\gamma=1$, $q=0.3679$, $\alpha=1.582$, and the width is $1.124$. With $\gamma=20$, $q=e^{-20}=2.06\times10^{-9}$, $\alpha=1.000$, and the width is $\sqrt2=1.414$.
(3) As $\gamma\to\infty$, $q\to0$, the feature vectors of the two points become orthogonal (dissimilar), $\alpha\to1$, and the width $\to\sqrt2$. The score equals $\pm1$ only very close to each point and returns to 0 a little away from the two points (the limit of surrounding each point with a narrow peak). As $\gamma\to0$, $q\to1$ and the feature vectors of the two points become almost identical, the width $\sqrt{2(1-q)}\approx d\sqrt{2\gamma}\to0$, and $\alpha\approx1/(\gamma d^{2})\to\infty$. Because two points that cannot be distinguished in the feature space are forcibly separated, $\alpha$ diverges. With a soft margin, the multiplier is capped by $\alpha\le C$, and both points have $\alpha=C$ and lie inside the margin.
Exercise 11.5: Reading the glass-formation boundary in the original units
Solution
(1) Setting $f=0$ at $\delta=8$: $1.087\,u_1=5.718-0.2691\times8$ $=5.718-2.153=3.565$, so $u_1=3.565/1.087=3.280$. Then $R=10^{3.280}\approx1.9\times10^{3}\ \mathrm{K\,s^{-1}}$. If the material is cooled faster than this, the model judges that it “forms a glass.”
(2) The values $f=\pm1$ correspond to positions shifted by $\pm1/1.087=\pm0.920$ in $u_1$, so the margin band is about $2\times0.92=1.84$ decades in $\log_{10}R$ (at $\delta=8\ \%$, $R\approx2.3\times10^{2}$–$1.6\times10^{4}\ \mathrm{K\,s^{-1}}$). For cooling rates in this range the judgment is uncertain.
(3) On the boundary, $1.087\,\Delta u_1+0.2691\,\Delta u_2=0$. If $\Delta u_2=1$, then $\Delta u_1=-0.2691/1.087=-0.248$. When the atomic-radius difference is larger by 1 %, the cooling rate on the boundary falls by about 0.25 decades (to about 1/1.8). For the rule that generated the data, $(u_1-3.5)+0.30(u_2-9.0)=0$, the value is 0.30 decades, so as an estimate from 30 points it is close but not identical.
(4) It must not be used. These data are synthetic data for teaching purposes, not measured values of real alloys. The coefficients merely reflect the rule and the noise that we built in under the assumption that “ease of glass formation is determined by a linear function of two descriptors.” In real systems, other factors such as the heat of mixing, the number of components, and the liquidus temperature matter, and the boundary is not necessarily a straight line. Moreover, there is no guarantee for extrapolation outside the range of the data ($\log_{10}R\in[1,6]$, $\delta\in[2,16]\ \%$). We take away only the way of thinking (make samples near the boundary, and read the coefficients in the original units).
Exercise 11.6: Classifying phases by the tolerance factor
Solution
(1) The closest points of different classes are $t=0.78$ ($-1$) and $t=0.86$ ($+1$). The threshold is their midpoint $t=0.82$. Imposing the canonical-form condition $f(0.86)=1$ on $f(t)=w(t-0.82)$ gives $w=1/0.04=25$ and $b=-25\times0.82=-20.5$. The width is $2/w=0.08$ (the distance between the two points). For the other points, $y_nf$ is $-25(0.72-0.82)=2.5$ at $t=0.72$, $2.25$ at $0.91$, $3.25$ at $0.95$, and $4.25$ at $0.99$, all at least 1. From the stationarity condition $w=\alpha_{0.78}(-1)(0.78)+\alpha_{0.86}(+1)(0.86)$ and $\alpha_{0.78}=\alpha_{0.86}\equiv\alpha$ (the equality constraint), we get $25=\alpha(0.86-0.78)=0.08\alpha$, so $\alpha=312.5$. The other points have $\alpha=0$. The reason $\alpha$ is large is that the range of $t$ is narrow and $\norm{\bm{w}}$ is large; if we standardize the input, $\alpha$ becomes a value of about 1.
(2) If we add a sample at $t=1.06$ that “did not form,” the $+1$ samples ($0.86\le t\le0.99$) are sandwiched on both sides by $-1$ samples. A one-dimensional linear discriminant function $f=wt+b$ is monotone, so the region $f\gt0$ is a half-line $t\gt-b/w$ (or $t\lt-b/w$), and it cannot make the $-1$ samples on both sides negative at the same time. Therefore they cannot be separated by a linear boundary. Since “only the inside of the right range is $+1$,” it suffices to add $t^{2}$ to the features, $\bm{\phi}(t)=(t,\ t^{2})$ ($f=w_2t^{2}+w_1t+b$ is an upward-convex parabola for $w_2\lt0$, positive between the two thresholds), that is, to use the quadratic polynomial kernel $(tt'+1)^{2}$ or the RBF kernel. The stability of an actual phase is not determined by the tolerance factor alone, so we should also consider increasing the number of descriptors.
Exercise 11.7: Which added sample moves the boundary?
Solution
The original solution is $\bm{w}=(1,1)^{\tp}$, $b=-1$, and $\bm{\alpha}=(1,\tfrac12,\tfrac12)$.
(1) At $(3,3)$ ($y=+1$), $yf=3+3-1=5\ge1$. If we assign $\alpha=0$ to the new point, the sum in the stationarity condition does not change, the constraint of the new point is satisfied, and complementarity also holds, since $\alpha\cdot(5-1)=0$. All the KKT conditions are satisfied, so the solution does not change.
(2) At $(0.4,0.4)$ ($y=+1$), $yf=0.8-1=-0.2\lt1$ (misclassified), which violates the constraint, so the solution changes. The closest points of different classes are $(0,0)$ and $(0.4,0.4)$ (distance $0.4\sqrt2=0.566$), so we can expect the boundary to be their perpendicular bisector $x_1+x_2=0.4$. Let $\bm{w}=c(1,1)^{\tp}$. From $f(0,0)=b=-1$ and $f(0.4,0.4)=0.8c-1=1$, we get $c=2.5$. Thus $\bm{w}=(2.5,\ 2.5)^{\tp}$ and $b=-1$. For the other points, $f(2,0)=f(0,2)=5-1=4\ge1$. The stationarity condition $\bm{w}=\alpha_4(0.4,0.4)^{\tp}$ gives $\alpha_4=6.25$, and the equality constraint gives $\alpha_1=6.25$ and $\alpha_2=\alpha_3=0$. The width shrinks to $2/\norm{\bm{w}}=2/(2.5\sqrt2)=0.566$. The original support vectors $(2,0)$ and $(0,2)$ no longer take part in determining the boundary.
(3) Adding a sample under conditions where it is correctly classified outside the margin (conditions where $yf\ge1$ is expected) does not move the boundary and carries little information. What can move the boundary is a sample with $yf\lt1$, that is, a condition inside the margin. The actual label is not known until we make the sample, so it is efficient to make the next sample at a condition where the predicted score $\abs{f}$ is smaller than 1 (the point P of Example 11.9). However, as in (2), a single point can move the boundary a great deal, so we check that the label of that point is not a mistake and, if necessary, suppress the influence of outliers with a soft margin (finite $C$).
Exercise 11.8: Platt scaling
Solution
(1) $p=0.5$ occurs when $\exp(Af+B)=1$, that is, $Af+B=0$. Then $f=-B/A=-(-0.22)/(-2.18)=-0.101$. The score boundary $f=0$ and the point with probability 0.5 do not coincide (at $f=0$, $p=0.555$).
(2) For $f=-0.5$: $Af+B=1.09-0.22=0.87$ and $p=1/(1+e^{0.87})=1/(1+2.387)=0.295$. For $f=2$: $Af+B=-4.36-0.22=-4.58$ and $p=1/(1+e^{-4.58})$ $=1/(1+0.0103)=0.990$.
(3) Differentiating $p(f)=1/\{1+\exp(Af+B)\}$ gives
$$ \frac{\mathrm{d}p}{\mathrm{d}f}=\frac{-A\exp(Af+B)}{\{1+\exp(Af+B)\}^{2}} $$which is always positive if $A\lt0$. Since $p$ is a strictly increasing function of $f$, the ranking by score and the ranking by probability are the same. Even so, converting to probabilities is meaningful because (i) the threshold can be chosen from costs (for example, if the cost of a miss is 9 times that of a false alarm, judge “defective” when $p\gt0.1$), (ii) the probabilities can be combined with those of other models and with prior probabilities, and (iii) the result can be reported as a meaningful number, such as “$+1$ with probability 80 %.”
(4) The training points are points that the SVM learned to “push out of the margin,” and their scores come out systematically larger (overconfident) than the scores of new data. In particular, points with $\alpha=0$ gather at $\abs{f}\ge1$. If $A,B$ are determined from the scores of the training data, $\abs{A}$ becomes large and the probabilities are pushed too close to 0 and 1 (in the example of Chapter 11, $A=-3.08$ and $B=0.80$, determined from the 60 training points, estimated the probability at $f=-1$ as 0.020, far smaller than the 0.123 determined from the calibration data). For calibration we use data not used in training (validation data, or the scores of the held-out points of each cross-validation split).
← Back to Chapter 11, “Support Vector Machines — Maximizing the Margin”
Chapter 12 Gaussian Process Regression — Placing a Distribution on Functions
Exercise 12.1: Writing the prediction from a single observation in general
Solution
(1) Since there is one observation, $\bm{K}_y=\sigma_f^{2}+\sigma^{2}$ (a $1\times1$ matrix), $\bm{k}_*=k(x_1,x_*)=\sigma_f^{2}e^{-r^{2}/(2\ell^{2})}$, and $k_{**}=\sigma_f^{2}$. Substituting into the mean and variance expressions of Formula 12.1 in Chapter 12 gives
$$ \begin{aligned} \mu_*(x_*)&=m+\frac{\sigma_f^{2}e^{-r^{2}/(2\ell^{2})}}{\sigma_f^{2}+\sigma^{2}}\,(y_1-m),\\ \sigma_*^{2}(x_*)&=\sigma_f^{2}-\frac{\sigma_f^{4}e^{-r^{2}/\ell^{2}}}{\sigma_f^{2}+\sigma^{2}}. \end{aligned} $$The exponent in the variance expression is $-r^{2}/\ell^{2}$ because the exponent doubles in $k(x_1,x_*)^{2}$.
(2) We have $y_1-m=-3.40+4.47=1.07$, $\sigma_f^{2}+\sigma^{2}=0.64+0.0025=0.6425$, $\sigma_f^{2}/(\sigma_f^{2}+\sigma^{2})=0.99611$, and $\sigma_f^{4}/(\sigma_f^{2}+\sigma^{2})=0.4096/0.6425=0.63751$.
- $x_*=7.0$ ($r=0$): $\mu_*=-4.47+0.99611\times1.07$ $=-4.47+1.06584$ $=-3.4042$. $\sigma_*^{2}=0.64-0.63751=0.00249$, $\sigma_*=0.0499$.
- $x_*=8.0$ ($r=1$): from $e^{-1/2}=0.60653$, $\mu_*=-4.47+0.99611\times0.60653\times1.07$ $=-4.47+0.64646$ $=-3.8235$. From $e^{-1}=0.36788$, $\sigma_*^{2}=0.64-0.63751\times0.36788=0.40547$, $\sigma_*=0.6368$.
- $x_*=9.0$ ($r=2$): from $e^{-2}=0.13534$, $\mu_*=-4.47+0.99611\times0.13534\times1.07$ $=-4.3258$. From $e^{-4}=0.018316$, $\sigma_*^{2}=0.64-0.63751\times0.018316=0.62832$, $\sigma_*=0.7927$.
(3) As $\sigma\to0$, at $x_*=x_1$ we get $\mu_*=m+(y_1-m)=y_1$ and $\sigma_*^{2}=\sigma_f^{2}-\sigma_f^{2}=0$, so the predictive mean passes exactly through the observation point (interpolation). If $\sigma\gt0$, then even at the observation point $\mu_*$ is shrunk from $y_1$ toward $m$ by the fraction $\sigma^{2}/(\sigma_f^{2}+\sigma^{2})$. As $r\to\infty$ the exponential factor goes to 0, so $\mu_*\to m$ and $\sigma_*^{2}\to\sigma_f^{2}$: the prediction returns to the prior distribution.
Exercise 12.2: The linear kernel and Bayesian linear regression
Solution
(1) With $f(x)=wx$, $\Ex[w]=0$, and $\Ex[w^{2}]=\sigma_w^{2}$, we have $k(x,x')=\Cov[wx,wx']=xx'\,\Ex[w^{2}]=\sigma_w^{2}xx'$.
(2) The Gram matrix is $\bm{K}=\sigma_w^{2}\bm{x}\bm{x}^{\tp}$, with $\bm{K}_y=\sigma^{2}\bm{I}+\sigma_w^{2}\bm{x}\bm{x}^{\tp}$ and $\bm{k}_*=\sigma_w^{2}x_*\bm{x}$. Let $S\equiv\bm{x}^{\tp}\bm{x}=\sum_nx_n^{2}$. Apply the Sherman–Morrison formula with $\bm{A}=\sigma^{2}\bm{I}$ and $\bm{u}=\sigma_w\bm{x}$. Then $\bm{A}^{-1}=\bm{I}/\sigma^{2}$ and $\bm{u}^{\tp}\bm{A}^{-1}\bm{u}=\sigma_w^{2}S/\sigma^{2}$, so
$$ \bm{K}_y^{-1}=\frac{1}{\sigma^{2}}\bm{I}-\frac{\sigma_w^{2}/\sigma^{4}}{1+\sigma_w^{2}S/\sigma^{2}}\,\bm{x}\bm{x}^{\tp}. $$Substituting this into $\mu_*=\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{y}$ and using $\bm{x}^{\tp}\bm{x}=S$ gives
$$ \begin{aligned} \mu_*&=\sigma_w^{2}x_*\left[\frac{\bm{x}^{\tp}\bm{y}}{\sigma^{2}}-\frac{\sigma_w^{2}/\sigma^{4}}{1+\sigma_w^{2}S/\sigma^{2}}\,S\,\bm{x}^{\tp}\bm{y}\right]\\ &=\frac{\sigma_w^{2}x_*\,\bm{x}^{\tp}\bm{y}}{\sigma^{2}}\left[1-\frac{\sigma_w^{2}S/\sigma^{2}}{1+\sigma_w^{2}S/\sigma^{2}}\right]\\ &=\frac{\sigma_w^{2}x_*\,\bm{x}^{\tp}\bm{y}}{\sigma^{2}}\cdot\frac{1}{1+\sigma_w^{2}S/\sigma^{2}}\\ &=\frac{\sigma_w^{2}x_*\,\bm{x}^{\tp}\bm{y}}{\sigma^{2}+\sigma_w^{2}S}=x_*\,\frac{\sum_nx_ny_n}{\sum_nx_n^{2}+\sigma^{2}/\sigma_w^{2}}. \end{aligned} $$In the last step we divided the numerator and the denominator by $\sigma_w^{2}$.
(3) Differentiate the one-weight ridge regression $L(w)=\tfrac12\sum_n(y_n-wx_n)^{2}+\tfrac{\lambda}{2}w^{2}$ with respect to $w$ and set the result to 0: $-\sum_nx_n(y_n-wx_n)+\lambda w=0$, hence $w=\dfrac{\sum_nx_ny_n}{\sum_nx_n^{2}+\lambda}$. If we take $\lambda=\sigma^{2}/\sigma_w^{2}$, then $\mu_*$ in (2) is this $w$ multiplied by $x_*$. The same calculation gives the variance $\sigma_*^{2}=x_*^{2}\,\sigma^{2}/(S+\sigma^{2}/\sigma_w^{2})$, which agrees with the posterior variance of the weight in the Bayesian linear regression of Chapter 8, $(S/\sigma^{2}+1/\sigma_w^{2})^{-1}$, multiplied by $x_*^{2}$. This is the simplest example of the fact that computations in weight space and in function space give the same prediction.
Exercise 12.3: Adding an observation does not increase the predictive variance
Solution
(1) Upper bound: since $\bm{K}_y$ is positive definite, $\bm{K}_y^{-1}$ is also positive definite (its eigenvalues are the reciprocals of positive numbers), so $\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{k}_*\ge0$ for any vector $\bm{k}_*$. Hence $\sigma_*^{2}=k_{**}-\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{k}_*\le k_{**}$.
Lower bound: compute the variance of the random variable $e=f_*-\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{y}$. Using $\Var[f_*]=k_{**}$, $\Cov[\bm{y},f_*]=\bm{k}_*$, and $\Cov[\bm{y}]=\bm{K}_y$, and letting $\bm{b}=\bm{K}_y^{-1}\bm{k}_*$, we obtain
$$ \begin{aligned} \Var[e]&=\Var[f_*]-2\bm{b}^{\tp}\Cov[\bm{y},f_*]\\ &\quad+\bm{b}^{\tp}\Cov[\bm{y}]\bm{b}\\ &=k_{**}-2\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{k}_*\\ &\quad+\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{K}_y\bm{K}_y^{-1}\bm{k}_*\\ &=k_{**}-\bm{k}_*^{\tp}\bm{K}_y^{-1}\bm{k}_*=\sigma_*^{2}. \end{aligned} $$A variance is at least 0, so $\sigma_*^{2}\ge0$.
(2) Conditioning on $N+1$ points is the same as first conditioning on $N$ points and then conditioning on $y_{N+1}$ with the resulting posterior distribution as the new prior distribution (sequential updating with Bayes’s theorem; Chapter 4, Section 4.4). In the posterior distribution after $N$ points, $(f_*,f_{N+1})$ follows a Gaussian distribution with variances $\sigma_{*,N}^{2}$ and $s^{2}$ and covariance $c$. Since the noise $\varepsilon_{N+1}$ in $y_{N+1}=f_{N+1}+\varepsilon_{N+1}$ is independent of the earlier data and of $f$, the covariance matrix of $(f_*,y_{N+1})$ after $N$ points is
$$ \begin{pmatrix}\sigma_{*,N}^{2}&c\\ c&s^{2}+\sigma^{2}\end{pmatrix} $$Applying the formula for the conditional distribution in Chapter 3 (the scalar case) gives
$$ \sigma_{*,N+1}^{2}=\sigma_{*,N}^{2}-\frac{c\cdot c}{s^{2}+\sigma^{2}}=\sigma_{*,N}^{2}-\frac{c^{2}}{s^{2}+\sigma^{2}}. $$(3) The subtracted quantity $c^{2}/(s^{2}+\sigma^{2})$ is at least 0, so adding an observation does not increase the predictive variance. The reduction is larger the larger the posterior covariance $c$ between the value at the new point and the value we want to predict, and if $c=0$ (a distant point, or a point already well known from the $N$ points), the variance does not decrease. Moreover, the observed value $y_{N+1}$ does not appear in this expression, so once we decide where to measure, we can know how much the variance will decrease before measuring. This is the basis, in the next chapter, for asking “where should we measure to reduce the uncertainty the most?”
Exercise 12.4: Computing the prediction and the marginal likelihood with the Cholesky decomposition
Solution
Since $k(0,2)=e^{-2}=0.13534$, we have $\bm{K}_y=\begin{pmatrix}1.01&0.13534\\0.13534&1.01\end{pmatrix}$.
(1) $L_{11}=\sqrt{1.01}=1.00499$, $L_{21}=0.13534/1.00499=0.13466$, $L_{22}=\sqrt{1.01-0.13466^{2}}$ $=\sqrt{1.01-0.01813}$ $=0.99592$.
(2) Forward substitution $\bm{L}\bm{u}=\bm{y}$:
$$ \begin{aligned} u_1&=1.0/1.00499=0.99504,\\ u_2&=\frac{0.2-0.13466\times0.99504}{0.99592}\\ &=0.06627. \end{aligned} $$Back substitution $\bm{L}^{\tp}\bm{a}=\bm{u}$:
$$ \begin{aligned} a_2&=0.06627/0.99592=0.06655,\\ a_1&=\frac{0.99504-0.13466\times0.06655}{1.00499}\\ &=0.98118. \end{aligned} $$(3) $\bm{k}_*=(e^{-1/2},e^{-1/2})^{\tp}=(0.60653,\,0.60653)^{\tp}$.
$$ \begin{aligned} \mu_*&=0.60653\times(0.98118+0.06655)\\ &=0.6355,\\ v_1&=0.60653/1.00499=0.60352,\\ v_2&=\frac{0.60653-0.13466\times0.60352}{0.99592}\\ &=0.52741,\\ \bm{v}^{\tp}\bm{v}&=0.36424+0.27816=0.64240,\\ \sigma_*^{2}&=1-0.64240=0.35760,\\ \sigma_*&=0.5980. \end{aligned} $$Even exactly midway between the two observation points, the distance to each observation point is 1 ($=\ell$), so $\sigma_*$ decreases only from the prior value 1 to about 0.6.
(4) The data-fit term is $-\tfrac12\bm{y}^{\tp}\bm{a}=-\tfrac12\bm{u}^{\tp}\bm{u}$ $=-\tfrac12(0.99010+0.00439)$ $=-0.49725$. The complexity-penalty term is $-\sum_i\ln L_{ii}$ $=-(\ln1.00499+\ln0.99592)$ $=-(0.00498-0.00409)$ $=-0.00089$. The constant term is $-\tfrac22\ln2\pi=-1.83788$. Adding them up, $\ln p(\bm{y}\mid\bm{\theta})=-2.3360$.
Exercise 12.5: How to report a prediction of ionic conductivity
Solution
(1) From Table 12.3 of Chapter 12, at $x_*=7.0$ we have $\mu_*=-3.5124$ and $\sqrt{\sigma_*^{2}+\sigma^{2}}=0.2940$. The range into which the next observed value falls with about 95% probability is
$$ -3.5124\pm2\times0.2940=[-4.100,\ -2.925]. $$The band for the latent function is $-3.5124\pm2\times0.2897=[-4.092,\ -2.933]$, and the difference between the two bands is only 0.008 at each end. This is because, away from the observation points, $\sigma_*=0.29$ is much larger than $\sigma=0.05$, so almost all of the uncertainty comes from lack of knowledge.
(2) Examples of information to add: ① The uncertainty. State that $\sigma_*=0.29$ (in $\log_{10}$), that the approximately 95% band of the latent function is $10^{-4.09}$ to $10^{-2.93}\ \mathrm{S\,cm^{-1}}$, which corresponds to 0.26 to 3.8 times the central value in terms of the conductivity ratio, and whether it is the band of the latent function or the band of the observed value. ② That 7.0 mol% itself was not measured, and that the prediction interpolates between the observations at 6.4 mol% and 8.2 mol%. ③ The dependence on the hyperparameters. With $\ell=1$ mol% the result is $-3.51\pm0.29$, but with $\ell=1.585$ mol%, which maximizes the marginal likelihood, it is $-3.47\pm0.08$, so both the predicted value and the width of the band change (Table 12.1). It is also good to state which kernel (RBF), noise assumption, and mean function were used, and that there are only 8 data points.
(3) It is better to measure 7.0 mol%. The predictive variance is determined only by the arrangement of the inputs, not by the values of the data (Section 12.4.4), so we can compute the effect before measuring. If a ninth point is added, with $\ell=1$, $\sigma_f=0.8$, and $\sigma=0.05$, then at $x_*=7.0$ the value of $\sigma_*$ decreases only from 0.290 to 0.288 when the point is added at 6.4 mol%, but it decreases to 0.049 when the point is added at 7.0 mol%. Since 6.4 mol% has already been measured ($\sigma_*=0.050$), measuring it once more reduces $\sigma_*$ only to about 0.035, and we learn almost nothing about the height near the top of the peak (near 7.0 mol%). In terms of the formula in Exercise 12.3 (2), this is because the posterior covariance $c$ between the new observed value at 6.4 mol% and $f(7.0)$ is small.
Exercise 12.6: Two inputs, firing temperature and dopant amount
Solution
(1) If we keep the inputs as $(T,x)$ and use $\ell=1$, the correlation coefficient between two points with $\Delta T=50$ (°C) and $\Delta x=0$ is $\exp(-50^{2}/2)=e^{-1250}$, which is effectively 0 (about $10^{-543}$). That is, samples whose temperatures differ by 50 °C are regarded as “completely unrelated,” and a measurement at one temperature gives no information about the prediction at a neighboring temperature. At points far from every observation point the prediction returns to the mean function, so there is almost no interpolation in the temperature direction. On the other hand, if the dopant amount differs by only 0.5 mol%, the correlation is as high as $e^{-0.125}=0.88$. The magnitudes of the numbers are determined merely by the units and do not express physical “closeness.”
(2) With the ARD kernel,
$$ \begin{aligned} \rho&=\exp\!\left[-\frac12\left(\frac{50}{100}\right)^{2}-\frac12\left(\frac{0.5}{1}\right)^{2}\right]\\ &=\exp(-0.25)=0.779 . \end{aligned} $$The difference in each direction is “half a length scale,” so each weakens the correlation to the same degree.
(3) The distance in the kernel is measured by differences in the numerical values of the inputs, so if inputs with different units or orders of magnitude are simply placed side by side, the input with the larger magnitude (the temperature in °C) dominates the distance. Just as we standardized the inputs for gradient descent in Chapter 7, Section 7.3, it is good either to standardize each input to mean 0 and standard deviation 1 and then use an isotropic kernel, or to use an ARD kernel with a length scale $\ell_i$ (with units) for each input and choose the $\ell_i$ by the marginal likelihood. With ARD, an input whose chosen $\ell_i$ is large can be read as “having little effect on the prediction.” However, the mean and standard deviation used for standardization must be computed from the training data only (data leakage, Chapter 6).
Exercise 12.7: When the same point is measured twice
Solution
(1) Since the two inputs are the same, $\bm{K}=\sigma_f^{2}\begin{pmatrix}1&1\\1&1\end{pmatrix}$, whose two rows are equal, so $\det\bm{K}=\sigma_f^{4}(1-1)=0$ (the eigenvalues are $0$ and $2\sigma_f^{2}=1.28$). If $\sigma=0$, then $\bm{K}_y=\bm{K}$ is also singular, and neither the inverse matrix nor the Cholesky decomposition exists. In terms of meaning, the noiseless model assumes that “$f(7.0)$ is a single value and the observations reproduce it exactly,” so it cannot simultaneously explain two different observed values, $-3.40$ and $-3.30$. The data and the model contradict each other.
(2) If $\sigma=0.05$, then $\bm{K}_y=\sigma^{2}\bm{I}+\sigma_f^{2}\bm{1}\bm{1}^{\tp}$. Since $\bm{K}_y\bm{1}=(\sigma^{2}+2\sigma_f^{2})\bm{1}$, we have $\bm{K}_y^{-1}\bm{1}=\bm{1}/(\sigma^{2}+2\sigma_f^{2})$. Because $\bm{k}_*=\sigma_f^{2}\bm{1}$, using the symmetry of $\bm{K}_y^{-1}$ we get
$$ \begin{aligned} \mu_*&=m+\sigma_f^{2}\bm{1}^{\tp}\bm{K}_y^{-1}(\bm{y}-m\bm{1})\\ &=m+\frac{\sigma_f^{2}\sum_n(y_n-m)}{2\sigma_f^{2}+\sigma^{2}}\\ &=m+\frac{2\sigma_f^{2}}{2\sigma_f^{2}+\sigma^{2}}(\bar{y}-m), \end{aligned} $$where $\bar{y}=(y_1+y_2)/2=-3.35$. Substituting the numbers, $\mu_*=-4.47+\dfrac{1.28}{1.2825}\times1.12$ $=-4.47+1.11782$ $=-3.3522$. The variance has the same form as in Example 12.7: $\sigma_*^{2}=\dfrac{\sigma_f^{2}\sigma^{2}}{2\sigma_f^{2}+\sigma^{2}}=\dfrac{0.0016}{1.2825}=0.00125$ ($\sigma_*=0.035$). The predictive mean is the average of the two observed values, $-3.35$, shrunk toward the mean function $m$ by only $\sigma^{2}/(2\sigma_f^{2}+\sigma^{2})=0.2$%, so it is almost exactly that average.
(3) If we add jitter $\epsilon$, then computationally this amounts to replacing $\sigma^{2}$ by $\epsilon$ in (2), and the computation goes through. However, if $\epsilon$ is small, then $\sigma_*^{2}\approx\epsilon/2$ is also nearly 0, and we reach the overconfident conclusion that “$f(7.0)$ is almost certainly $-3.35$.” In reality the two measured values differ by as much as 0.1, so we should consider that there is measurement scatter (about $0.1/\sqrt2\approx0.07$ in standard deviation), and its magnitude must be put into the model as the noise variance. Jitter is a remedy for numerical computation and cannot replace an estimate of the noise.
← Back to Chapter 12, “Gaussian Process Regression — Placing a Distribution on Functions”
Chapter 13 Bayesian Optimization and Experimental Design — Where to Measure Next
Exercise 13.1: Comparing acquisition functions on three candidates
Solution
Since $f_{\mathrm{best}}=-4.1059$ and $\xi=0$, we have $d=\mu_*-f_{\mathrm{best}}=\mu_*+4.1059$ and $z=d/\sigma_*$. PI $=\Phi(z)$ and EI $=d\,\Phi(z)+\sigma_*\Normal(z\mid0,1)$ (Eqs. (13.6)–(13.8) of Chapter 13).
For $x=2.3$ mol%: $d=-4.1015+4.1059=0.0044$ and $z=0.0044/0.0708=0.0621$. $\Phi(0.0621)=0.5248$ and $\Normal(0.0621\mid0,1)=0.3982$.
$$ \begin{aligned} \mathrm{EI}&=0.0044\times0.5248+0.0708\times0.3982\\ &=0.0023+0.0282=0.0305 . \end{aligned} $$For $x=7.0$ mol%: $d=-4.6462+4.1059=-0.5403$ and $z=-0.5403/0.7831=-0.690$. $\Phi(-0.690)=0.2451$ and $\Normal(0.690\mid0,1)=0.3144$.
$$ \begin{aligned} \mathrm{EI}&=-0.5403\times0.2451+0.7831\times0.3144\\ &=-0.1324+0.2462=0.1138 . \end{aligned} $$For $x=10.0$ mol%: $d=-4.7301+4.1059=-0.6242$ and $z=-0.6242/0.6368=-0.980$. $\Phi(-0.980)=0.1635$ and $\Normal(0.980\mid0,1)=0.2468$.
$$ \begin{aligned} \mathrm{EI}&=-0.6242\times0.1635+0.6368\times0.2468\\ &=-0.1021+0.1572=0.0551 . \end{aligned} $$UCB $=\mu_*+\kappa\sigma_*$:
| $x$ / mol% | PI | EI | UCB ($\kappa=1$) | UCB ($\kappa=2$) |
|---|---|---|---|---|
| 2.3 | 0.525 | 0.0305 | $-4.031$ | $-3.960$ |
| 7.0 | 0.245 | 0.1138 | $-3.863$ | $-3.080$ |
| 10.0 | 0.164 | 0.0551 | $-4.093$ | $-3.457$ |
(2) PI selects 2.3 mol% (right next to the best point, 2.4 mol%), EI selects 7.0 mol%, and UCB selects 7.0 mol% for both $\kappa=1$ and $\kappa=2$. This agrees with Figure 13.4 of Chapter 13, where the maximum of PI lies at 2.300 mol% and the maxima of EI and UCB lie near 7 mol% (at 6.800 and 6.875). The maximum on the grid is not exactly 7.0 because here we compared only three candidates. At 10.0 mol% as well, which is at the edge of the range and far from the observations so that $\sigma_*$ is large, the EI is larger than at 2.3 mol%.
Exercise 13.2: Deriving the EI for minimization from the integral
Solution
Suppose $\sigma_*\gt0$. Since $I=\max(f_{\mathrm{best}}-f-\xi,0)$ is positive only when $f\lt f_{\mathrm{best}}-\xi$,
$$ \begin{aligned} \Ex[I]=\int_{-\infty}^{f_{\mathrm{best}}-\xi}&\bigl(f_{\mathrm{best}}-f-\xi\bigr)\\ &\times\Normal(f\mid\mu_*,\sigma_*^{2})\,\dd f . \end{aligned} $$Let $u=(\mu_*-f)/\sigma_*$. Then $f=\mu_*-\sigma_*u$ and $\dd f=-\sigma_*\,\dd u$, and as $f$ runs from $-\infty$ to $f_{\mathrm{best}}-\xi$, $u$ runs from $+\infty$ to $(\mu_*-f_{\mathrm{best}}+\xi)/\sigma_*=-d/\sigma_*=-z$ (where $d=f_{\mathrm{best}}-\mu_*-\xi$). Since the Gaussian density is symmetric in $u$, $\Normal(f\mid\mu_*,\sigma_*^{2})\,\abs{\dd f}=\Normal(u\mid0,1)\,\dd u$, and by reversing the orientation we can take the range of integration to be $[-z,\infty)$. The improvement in the integrand is
$$ \begin{aligned} f_{\mathrm{best}}-f-\xi&=f_{\mathrm{best}}-\mu_*+\sigma_*u-\xi\\ &=d+\sigma_*u . \end{aligned} $$Therefore
$$ \begin{aligned} \Ex[I]&=\int_{-z}^{\infty}(d+\sigma_*u)\,\Normal(u\mid0,1)\,\dd u\\ &=d\int_{-z}^{\infty}\Normal(u\mid0,1)\,\dd u\\ &\quad+\sigma_*\int_{-z}^{\infty}u\,\Normal(u\mid0,1)\,\dd u . \end{aligned} $$The integral in the first term is $1-\Phi(-z)=\Phi(z)$. For the second term, from $\diff{}{u}\Normal(u\mid0,1)=-u\,\Normal(u\mid0,1)$ we get
$$ \begin{aligned} &\int_{-z}^{\infty}u\,\Normal(u\mid0,1)\,\dd u\\ &=\Bigl[-\Normal(u\mid0,1)\Bigr]_{-z}^{\infty}\\ &=\Normal(-z\mid0,1)=\Normal(z\mid0,1) . \end{aligned} $$Hence $\Ex[I]=d\,\Phi(z)+\sigma_*\Normal(z\mid0,1)$, with $d=f_{\mathrm{best}}-\mu_*-\xi$ and $z=d/\sigma_*$. This has the same form as the formula for maximization; only the direction of the improvement is reversed (Table 13.1 of Chapter 13).
Exercise 13.3: EI increases in both the mean and the width
Solution
Regard $\mathrm{EI}=d\,\Phi(z)+\sigma_*\Normal(z\mid0,1)$ (with $d=\mu_*-f_{\mathrm{best}}-\xi$ and $z=d/\sigma_*$) as a function of $\mu_*$ and $\sigma_*$. Below we abbreviate $\Normal(z\mid0,1)$ to $\Normal(z)$. The relations we use are $\diff{\Phi(z)}{z}=\Normal(z)$, $\diff{\Normal(z)}{z}=-z\,\Normal(z)$, and
$$ \begin{aligned} &\pdiff{d}{\mu_*}=1,\qquad \pdiff{z}{\mu_*}=\frac{1}{\sigma_*},\\ &\pdiff{z}{\sigma_*}=-\frac{d}{\sigma_*^{2}}=-\frac{z}{\sigma_*} . \end{aligned} $$Derivative with respect to $\mu_*$: by the product rule and the chain rule,
$$ \begin{aligned} \pdiff{\mathrm{EI}}{\mu_*}&=\Phi(z)+d\,\Normal(z)\cdot\frac{1}{\sigma_*}\\ &\quad+\sigma_*\cdot\bigl(-z\,\Normal(z)\bigr)\cdot\frac{1}{\sigma_*}\\ &=\Phi(z)+z\,\Normal(z)-z\,\Normal(z)=\Phi(z) . \end{aligned} $$(We used $d/\sigma_*=z$.)
Derivative with respect to $\sigma_*$: since $d$ does not depend on $\sigma_*$,
$$ \begin{aligned} \pdiff{\mathrm{EI}}{\sigma_*}&=d\,\Normal(z)\cdot\Bigl(-\frac{z}{\sigma_*}\Bigr)+\Normal(z)\\ &\quad+\sigma_*\cdot\bigl(-z\,\Normal(z)\bigr)\cdot\Bigl(-\frac{z}{\sigma_*}\Bigr)\\ &=-z^{2}\Normal(z)+\Normal(z)+z^{2}\Normal(z)\\ &=\Normal(z) . \end{aligned} $$Since $\Phi(z)\gt0$ and $\Normal(z)\gt0$, EI is a strictly increasing function of both $\mu_*$ and $\sigma_*$. The higher the predicted mean (exploitation) and the wider the predictive width (exploration), the larger the EI. This is why the contour lines in Figure 13.5 of Chapter 13 increase in value toward the right and toward the top. The ratio of the two partial derivatives, $\Normal(z)/\Phi(z)$, is larger the smaller $z$ is (that is, the more the mean falls short), and at such points increasing the width raises EI more.
Exercise 13.4: The next point for the firing temperature
Solution
(1) From $s=(T-1300)/200$: at 1250 °C, $s=-0.25$; at 1380 °C, $s=0.40$; at 1460 °C, $s=0.80$.
(2) $f_{\mathrm{best}}=92.0$ %, $d=\mu_*-92.0$, and $z=d/\sigma_*$.
- 1250 °C: $d=-7.0$ and $z=-7.0/0.6=-11.7$. Both $\Phi(-11.7)$ and $\Normal(11.7\mid0,1)$ are at most $10^{-30}$, so PI and EI are effectively 0. UCB $=85.0+1.2=86.2$ %.
- 1380 °C: $d=-0.2$ and $z=-0.4$. $\mathrm{PI}=\Phi(-0.4)=0.345$. $\mathrm{EI}=-0.2\times0.3446$ $+0.5\times0.3683$ $=-0.0689+0.1842$ $=0.115$ %. UCB $=91.8+1.0=92.8$ %.
- 1460 °C: $d=-1.0$ and $z=-0.667$. $\mathrm{PI}=\Phi(-0.667)=0.253$. $\mathrm{EI}=-1.0\times0.2525$ $+1.5\times0.3194$ $=-0.2525+0.4792$ $=0.227$ %. UCB $=91.0+3.0=94.0$ %.
PI selects 1380 °C, and EI and UCB select 1460 °C. PI favors points whose mean is close to $f_{\mathrm{best}}$, whereas EI and UCB evaluate the possible upside of 1460 °C, where the width is large.
(3) Solving $g'(s)=8-10s+6\cos3s=0$ numerically gives $s\approx0.623$, that is, $T=1300+200\times0.623\approx1425$ °C, with $g\approx92.96$ % (this is a maximum because $g''(s)=-10-18\sin3s\lt0$). The true values are $g(1380\ ^{\circ}\mathrm{C})=92.26$ % and $g(1460\ ^{\circ}\mathrm{C})=92.55$ %, and the true maximum lies between the two candidates. Each candidate is only 0.4–0.7 % below the true maximum, a difference smaller than the noise standard deviation of 1.0 %. At this stage, a single observation cannot decide which of the two candidates is better; it makes sense to measure between the candidates (1400–1450 °C) and to repeat the same condition and average (Section 13.7 of Chapter 13). The choice of acquisition function is a judgment made on the model at that point in time, and it is not a guarantee of hitting the location of the true maximum.
Exercise 13.5: Random search and the guarantee of a grid
Solution
(1) The probability of landing in $[6.75,7.25]$ in a single trial is $0.5/10=0.05$. The probability of missing in all $n$ trials is $0.95^{n}$, so $1-0.95^{n}\ge0.9$, that is, $0.95^{n}\le0.1$. Taking the natural logarithm of both sides gives $n\ln0.95\le\ln0.1$. Dividing by $\ln0.95\lt0$ reverses the inequality, and
$$ n\ge\frac{\ln0.1}{\ln0.95}=\frac{-2.3026}{-0.051293}\approx44.9 . $$The minimum is $n=45$ trials ($1-0.95^{45}=0.9006$ and $1-0.95^{44}=0.8953$).
(2) For $n=20$, the grid points are $x_k=10(k-\frac12)/20=0.5k-0.25$ ($k=1,\dots,20$), that is, $0.25,0.75,\dots,9.75$, with spacing 0.5 mol%. For $k=14$ this gives $6.75$ and for $k=15$ it gives $7.25$, and both lie 0.25 mol% from the peak at 7.0. Hence the grid with $n=20$ is certain to satisfy the condition (in fact, wherever the peak lies in $[0.25,9.75]$, the distance to the nearest grid point is at most 0.25).
(3) In two dimensions, the probability that random search lands in the square in a single trial is $0.05\times0.05=0.0025$. For $1-0.9975^{n}\ge0.9$ we need $n\ge\ln0.1/\ln0.9975\approx919.9$, that is, 920 trials. The grid has 20 points in each direction, so $20^{2}=400$ trials. As the dimension increases, the number of trials needed grows exponentially for both (in $D$ dimensions the grid needs $20^{D}$). The grid is certain but spends the budget with “the same fineness everywhere,” whereas random search guarantees only in a probabilistic sense. Bayesian optimization is a method that tries to greatly reduce this number by using the assumption that the function is smooth and that only a few directions matter.
Exercise 13.6: Repeated measurements and the recommended point
Solution
(1) The maximum of the six observed values is $-3.3635$ at $x=7.125$ mol%, so the recommended point is 7.125 mol%.
(2) The means are
$$ \begin{aligned} \bar{y}(6.900)&=\tfrac13(-3.3908-3.4539-3.4994)\\ &=-3.4480,\\ \bar{y}(7.125)&=\tfrac13(-3.4051-3.4229-3.3635)\\ &=-3.3972 . \end{aligned} $$The standard deviation of each mean is $0.05/\sqrt3=0.0289$, and the standard deviation of the difference of the means is $\sqrt{0.0289^{2}+0.0289^{2}}$ $=\sqrt{2/3}\times0.05=0.0408$. The difference is $-3.3972-(-3.4480)=0.0509$, which is a mere $0.0509/0.0408\approx1.25$ times the standard deviation of the difference.
(3) The true value $f(6.900)=-3.4066$ is higher than $f(7.125)=-3.4103$ by 0.0037, so both the maximum of the observed values and the means of three repetitions chose the wrong point. The true difference of 0.0037 is one fourteenth of the noise 0.05, and it cannot possibly be distinguished with means of three repetitions each (following the idea of Example 13.8 of Chapter 13, to make the probability of mistaking the two below 5 % we need $n\gt(1.645\times0.0707/0.0037)^{2}\approx988$ at each point, that is, about 990 repetitions). What we can say is the following. (i) If we recommend the maximum of the observed values, the point with the luckiest noise tends to be chosen. It is better to recommend by the mean or the posterior mean. (ii) Two conditions whose true difference is far smaller than the measurement noise should be regarded as equivalent in practice, and it is better not to spend the budget on telling them apart. Both are within 0.01 of the true maximum, $-3.400$. (iii) The recommended condition should be reported together with a check of reproducibility by remaking the samples.
Exercise 13.7: UCB is a quantile of the predictive distribution
Solution
(1) $u=(f_*-\mu_*)/\sigma_*$ follows the standard Gaussian distribution. Since $\sigma_*\gt0$,
$$ \begin{aligned} f_*\le\mu_*+\kappa\sigma_*&\iff\frac{f_*-\mu_*}{\sigma_*}\le\kappa\\ &\iff u\le\kappa , \end{aligned} $$and therefore $P(f_*\le\mu_*+\kappa\sigma_*)=P(u\le\kappa)=\Phi(\kappa)$.
(2) For $\kappa=1$: $\Phi(1)=0.841$. For $\kappa=2$: $\Phi(2)=0.977$. UCB ($\kappa=2$) is an optimistic estimate in the sense that “the probability that the true value exceeds it is only about 2.3 %.”
(3) The value satisfying $\Phi(\kappa)=0.95$ is $\kappa=1.645$. The upper 5 % point is $\mu_*+1.645\sigma_*$.
(4) Increasing $\kappa$ means comparing at a higher quantile (a more optimistic estimate). In the quantile location $\mu_*+\kappa\sigma_*$, the contribution of $\sigma_*$ grows in proportion to $\kappa$, so points with a somewhat lower mean but a large width rise to the top. That is, the search leans toward exploration. $\kappa=0$ means comparing at the center of the distribution (mean = median), which gives pure exploitation.
Exercise 13.8: Planning a two-week search with four furnaces
Solution
The following is one reasonable example of a plan (there is not just one answer).
(1) Initial points: since the input is two-dimensional, place eight points (two days’ worth; several times the input dimension) in an arrangement that fills the range 1100–1450 °C × 1–10 h without bias (a Latin hypercube, or a slightly perturbed grid). If there are results for similar materials from the past, include one or two of those conditions or add them as initial data. Including one set of repetitions of the same condition gives a rough estimate of the noise magnitude $\sigma$.
(2) Kernel and scales: use an ARD kernel, which has a length scale for each input (Example 13.12 of Chapter 13). Either give the temperature its own $\ell_T$ in °C as it is, or normalize both inputs to $[0,1]$. Since the effect of holding time is often logarithmic, taking $\ln t$ as the input is also one option. Re-select the hyperparameters ($\ell_T$, $\ell_t$, $\sigma_f$, $\sigma$) every day by the marginal likelihood. The objective is the relative density in % (the range is 0–100 %, so when it is close to 100 % also consider a transformation).
(3) Four conditions per day: choose one maximum point of EI, tentatively assume that it was “observed at the value of the predicted mean,” update the model, and choose the next maximum point of EI; repeat this four times. Alternatively, draw four functions from the posterior distribution and choose the maximum point of each (Thompson sampling). Check that the four points are not too close to one another.
(4) Constraints: exclude conditions above 1450 °C from the search range (a known constraint). Record conditions where the sample cracks and cannot be measured as “failures,” predict whether cracking occurs with a separate classification model (the logistic regression of Chapter 9, or classification with a Gaussian process), and choose by the value of EI multiplied by the “probability of not cracking.” If the density of cracked samples is discarded as missing values, a dangerous region will be chosen over and over.
(5) When to stop, and the recommendation: stop when all 40 runs have been used, or when the maximum of EI stays below about 1/10 of the measurement noise (for example, the standard deviation of repeated relative-density measurements) for many days and the recommended point no longer changes. The recommended point is not the maximum of the observed values but the already-observed condition at which the predicted mean of the surrogate model is largest; on the final day, repeat that condition and the runner-up condition 2–4 times each to check reproducibility and the difference. In the report, write the search range, the initial arrangement, the acquisition function, and how the hyperparameters were chosen, and state clearly that nothing can be said about the outside of the range.
← Back to Chapter 13, “Bayesian Optimization and Experimental Design — Where to Measure Next”
Chapter 14 Representations in Neural Networks — Learning the Basis Functions
Exercise 14.1: Forward propagation in a 2–2–1 network
Solution
(1) The activations of the first layer are $\bm{a}^{(1)}=\bm{W}^{(1)}\bm{x}+\bm{b}^{(1)}$, so
$$ \begin{aligned} a^{(1)}_1&=1\times0.5+1\times1.0+0=1.5,\\ a^{(1)}_2&=1\times0.5+(-1)\times1.0-0.5=-1.0 . \end{aligned} $$Passing these through tanh gives $\bm{z}^{(1)}=(\tanh1.5,\ \tanh(-1.0))$ $=(0.905148,\ -0.761594)$. The activation of the output layer is
$$ \begin{aligned} a^{(2)}&=2\times0.905148\\ &\quad+(-1)\times(-0.761594)+(-1)\\ &=1.810296+0.761594-1=1.571890, \end{aligned} $$and $\hat{y}=\sigma(1.571890)=1/(1+e^{-1.571890})$ $=1/(1+0.207652)=0.828053$.
(2) Since $y=1$, $\ell=-\ln\hat{y}=-\ln0.828053=0.188678$. Since the output layer pairs a sigmoid with the cross-entropy, the error at the output layer is $\delta^{(2)}=\hat{y}-y=0.828053-1=-0.171947$. Because it is negative, learning proceeds in the direction that increases $a^{(2)}$ (that is, brings $\hat{y}$ closer to 1).
(3) With ReLU, $\bm{z}^{(1)}=(\max(0,1.5),\ \max(0,-1.0))=(1.5,\ 0)$. Then $a^{(2)}=2\times1.5+(-1)\times0-1=2$ and $\hat{y}=\sigma(2)=0.880797$.
(4) The first layer has $2\times(2+1)=6$ parameters and the second layer has $1\times(2+1)=3$, for a total of 9.
Exercise 14.2: The relation between tanh and sigmoid
Solution
(1) Since $\sigma(2a)=\dfrac{1}{1+e^{-2a}}$,
$$ \begin{aligned} 2\sigma(2a)-1&=\frac{2-(1+e^{-2a})}{1+e^{-2a}}=\frac{1-e^{-2a}}{1+e^{-2a}}\\ &=\frac{e^{a}-e^{-a}}{e^{a}+e^{-a}}=\tanh a . \end{aligned} $$In the third equality we multiplied the numerator and the denominator by $e^{a}$.
(2) Applying (1) to $a_j=\bm{w}_j^{\tp}\bm{x}+b_j$ gives
$$ \begin{aligned} f(\bm{x})&=\sum_jW^{(2)}_j\bigl\{2\sigma(2\bm{w}_j^{\tp}\bm{x}+2b_j)-1\bigr\}+b^{(2)}\\ &=\sum_j\bigl(2W^{(2)}_j\bigr)\,\sigma\bigl((2\bm{w}_j)^{\tp}\bm{x}+2b_j\bigr)\\ &\quad+\Bigl(b^{(2)}-\sum_jW^{(2)}_j\Bigr). \end{aligned} $$Therefore, in a network with sigmoid hidden layers, if we replace the weights and biases by
$$ \begin{aligned} &\bm{w}_j\to2\bm{w}_j,\quad b_j\to2b_j,\quad W^{(2)}_j\to2W^{(2)}_j,\\ &b^{(2)}\to b^{(2)}-\sum_jW^{(2)}_j \end{aligned} $$then exactly the same function is represented. The reverse direction (from sigmoid to tanh) can be converted in the same way. As a numerical example, with the weights of Exercise 14.1 and $\bm{x}=(0.3,-0.7)^{\tp}$, both the tanh version and the converted sigmoid version give $f=-2.22202$ (here $f$ is $a^{(2)}$, before passing through the sigmoid).
(3) The set of representable functions does not change. However, how easy the network is to train can differ. tanh has slope 1 at the origin and its outputs are distributed around 0, so the initial gradients are large and the inputs to the next layer are not biased. Sigmoid has slope 1/4 at the origin and its outputs are always positive, so with the same initialization and the same learning rate, learning tends to be slow. Even for the same set of functions, a different way of parametrizing it (the scale) changes the behavior of gradient methods.
Exercise 14.3: What goes wrong when squared error is used on a sigmoid output
Solution
(1) By the chain rule and $\sigma'(a)=\hat{y}(1-\hat{y})$,
$$ \pdiff{\ell_{\mathrm{SE}}}{a}=\pdiff{\ell_{\mathrm{SE}}}{\hat{y}}\,\diff{\hat{y}}{a}=(\hat{y}-y)\,\hat{y}(1-\hat{y}). $$(2) $\hat{y}=\sigma(-5)=1/(1+e^{5})$ $=1/149.413159=0.0066929$. With the cross-entropy, $\delta=\hat{y}-y=-0.993307$. With squared error, $(-0.993307)\times0.0066929\times(1-0.0066929)$ $=(-0.993307)\times0.0066481$ $=-0.0066036$. The ratio of the magnitudes is about 150 times, and the squared-error gradient is far smaller.
(3) With squared error, the more badly the prediction misses so that the sigmoid is saturated ($\hat{y}$ close to 0 or 1), the closer $\hat{y}(1-\hat{y})$ gets to 0, and the gradient vanishes. The learning signal from exactly the data that most need correcting, the “confidently wrong” ones, becomes weak, and learning makes little progress. With the cross-entropy, the steep growth of $-\ln\hat{y}$ cancels the saturation of the sigmoid, and the error becomes exactly the size of the miss, $\hat{y}-y$. Moreover, squared error does not arise from the likelihood of the Bernoulli distribution, so it also has no justification as an estimate of a probability.
Exercise 14.4: One hidden unit cannot separate XOR
Solution
(1) Let $u=\bm{w}^{\tp}\bm{x}+b$. Since $\sigma$ is monotonically increasing and $\sigma(0)=1/2$, we have $\hat{y}\gt1/2\iff vh(u)+c\gt0$.
- If $v=0$: the condition is $c\gt0$, which does not depend on $\bm{x}$. It holds for all $\bm{x}$ or for none (the empty set).
- If $v\gt0$: the condition is $h(u)\gt-c/v$. Since $h$ is monotone nondecreasing, the set $S=\{u:h(u)\gt-c/v\}$ has the property that “if some $u$ lies in $S$, then every larger $u$ does too.” Hence $S$ is one of $\R$ itself, the empty set, $\{u\gt t\}$, or $\{u\ge t\}$ (with $t=\inf S$).
- If $v\lt0$: the condition is $h(u)\lt-c/v$, and in the same way it is one of $\R$ itself, the empty set, $\{u\lt t\}$, or $\{u\le t\}$.
In every case, the set of $\bm{x}$ with $\hat{y}\gt1/2$ is either a half-plane bounded by the line $\bm{w}^{\tp}\bm{x}+b=t$ (with or without the boundary), or the whole plane, or the empty set.
(2) Suppose the four points were separated correctly. Then the two points $(1,0)$ and $(0,1)$ with $y=1$ lie inside the half-plane, and the two points $(0,0)$ and $(1,1)$ with $y=0$ lie outside. The whole plane and the empty set do not split the data into two classes, so we consider only the half-plane case. In the case “$u\gt t$” (the others are similar), $u$ is a linear function of $\bm{x}$ plus a constant, so $u(1,0)+u(0,1)=u(0,0)+u(1,1)$ holds (both sides equal $w_1+w_2+2b$). The two terms on the left are greater than $t$ and the two terms on the right are at most $t$, so left side $\gt2t\ge$ right side, a contradiction. For “$u\ge t$,” “$u\lt t$,” and “$u\le t$,” only the direction of the inequalities and whether equality is allowed change, and the same contradiction arises. Therefore no weights exist that correctly separate the four XOR points.
(3) The XOR data in Simulator 14.1 consist of four clusters, and a single straight line can correctly separate at most three of them (about 75 % of the whole). With $H=1$, by (1) the decision boundary is a single straight line; together with the fact that the clusters are spread out by noise, the accuracy is bounded above by roughly 75 % (since noise makes some points in the tails of the clusters spill over to the other side of the boundary, with a finite amount of data it fluctuates around 75 %), and in practice it stayed at 73 %. This differs from the case in which the solution is not found by training even with more hidden units ($H=2$, default seed): with $H=1$, the expressive power itself is insufficient.
Exercise 14.5: Representing the band gap of a mixed crystal with ReLU
Solution
(1) $E_g(0)=1.20$ eV, $E_g(1)=2.40$ eV, and $E_g(0.5)=0.5\times1.20+0.5\times2.40$ $-0.80\times0.25$ $=0.60+1.20-0.20=1.60$ eV.
(2) The slopes are $m_1=(1.60-1.20)/0.5=0.8$ eV on $[0,0.5]$ and $m_2=(2.40-1.60)/0.5=1.6$ eV on $[0.5,1]$. For $0\le x$ we have $\relu(x)=x$, so
$$ \begin{aligned} f(x)={}&1.20+0.8\,\relu(x)\\ &+0.8\,\relu(x-0.5)\quad(\mathrm{eV}), \end{aligned} $$that is, $c=1.20$ eV, $v_1=m_1=0.8$ eV, and $v_2=m_2-m_1=0.8$ eV.
(3) $E_g(x)=1.20+1.20x-0.80x+0.80x^{2}$ $=1.20+0.40x+0.80x^{2}$, so $E_g''(x)=1.6$ eV (constant). The error of the piecewise linear function is largest at the midpoint of each interval, and its magnitude is $E_g''h_s^{2}/8=1.6\times0.5^{2}/8=0.05$ eV (since $g''$ is constant within each interval, this matches the upper limit in Eq. (14.18) of Chapter 14 with equality). It occurs at $x=0.25$ and $x=0.75$. For example, at $x=0.25$, $E_g=1.20+0.10+0.05=1.35$ eV and $f=1.20+0.8\times0.25=1.40$ eV, a difference of 0.05 eV. This is larger than the noise standard deviation of 0.03 eV, so a three-point piecewise linear function cannot fully capture the structure of the data.
(4) From $1.6\,h_s^{2}/8\le0.01$ we get $h_s^{2}\le0.05$, so $h_s\le0.2236$. Since $h_s=1/K$, $K\ge4.47$; that is, $K=5$ intervals are needed (for $K=4$ the maximum error is 0.0125 eV, and for $K=5$ it is 0.008 eV). Constructing it as in (2), there are $K=5$ hidden units. (However, for $x\ge0$ the first unit $\relu(x)$ is just $x$ itself, so if there is a direct linear term from the input to the output, 4 units suffice.)
(5) The true function of data set B is exactly a linear combination of $1,\ x,\ x(1-x)$ (the Vegard’s law line plus the bowing term), so linear regression with the basis functions of Chapter 8 can represent it without error using 3 parameters. The solution is uniquely determined by the normal equations, the coefficients (such as the bowing parameter $-0.80$ eV) have physical meaning, and Bayesian linear regression can also give the uncertainty. A network does not know the form, so it needs correspondingly more units and data, and its learning also depends on the initial values. If the form of the function is known from physics, it is better to use that form as the basis.
Exercise 14.6: Properties of a sum of per-atom energies
Solution
(1) In the dimer each atom has one partner, so $G_1=G_2=\exp\{-(2.5/2.5)^{2}\}$ $=e^{-1}=0.367879$. Then $2G-1=-0.264241$, $\tanh(-0.264241)=-0.258258$, and $E_i=0.5\times(-0.258258)-3.0=-3.129129$ eV. Hence $E=2\times(-3.129129)=-6.258258$ eV.
(2) The coordinates of the four atoms are $0,\ 2.5,\ 20,\ 22.5$ Å. For example, the descriptor of the atom at $x=2.5$ receives, in addition to the $e^{-1}$ from its dimer partner, the contributions $\exp\{-(17.5/2.5)^{2}\}=e^{-49}\approx5.2\times10^{-22}$ and $\exp\{-(20/2.5)^{2}\}=e^{-64}\approx1.6\times10^{-28}$ from the two distant atoms. Even for the atom at $x=0$, only $e^{-64}$ and $e^{-81}$ are added. The slope of $E_i$ with respect to $G$ is $\diff{E_i}{G}=0.5\times2\times(1-\tanh^{2})$ $=1-0.258258^{2}=0.933303$ eV, so the deviation of the four-atom sum from twice the result of (1) is $0.933303\times2$ $\times(e^{-49}+e^{-64}+e^{-64}+e^{-81})$ $\approx9.8\times10^{-22}$ eV. This is far smaller than the rounding size (about $10^{-15}$ eV) when an energy of about 12.5 eV is represented in double-precision floating point, so numerically it cannot be distinguished from $E=-12.516516$ eV $=2\times(-6.258258)$ eV. In a model that includes a cutoff function $f_{\mathrm c}$, the contribution of atoms beyond the cutoff radius is exactly 0, and the energy is exactly doubled (extensivity).
(3) There are $10!=3628800$ ways of numbering the atoms, so for the same structure (if all atoms are of the same element) $3628800$ different input vectors arise. In addition, translations and rotations also change the input. The problems are the following two: (i) the same structure can yield different energies (invariance under permutation, translation, and rotation is not guaranteed, and it is also impractical to show all the orderings in the training data); (ii) the dimension of the input is determined by the number of atoms, so the same network cannot be used for structures with different numbers of atoms (surfaces, cells containing defects, cells of different sizes), and extensivity does not hold either. The construction by per-atom descriptors and a sum solves these problems by design.
Exercise 14.7: Symmetries of the weight space
Solution
(1) There are $3!=6$ permutations and $2^{3}=8$ choices of whether or not to flip the sign of each unit, giving $6\times8=48$ (including the original weights).
(2) Flipping the sign of all the incoming weights, the bias, and the outgoing weight of hidden unit 1 gives $(0.7,\,0.2,\,1.5)\to(-0.7,\,-0.2,\,-1.5)$, and
$$ \begin{aligned} \tilde{f}(s)={}&-1.5\tanh(-0.7s-0.2)\\ &-0.8\tanh(-1.3s+0.4)+0.1 . \end{aligned} $$At $s=0.37$: $0.7\times0.37+0.2=0.459$, $\tanh0.459=0.429269$, $-1.3\times0.37+0.4=-0.081$, and $\tanh(-0.081)=-0.080823$. The original expression is $1.5\times0.429269-0.8\times(-0.080823)+0.1$ $=0.643903+0.064659+0.1$ $=0.808562$. For the flipped expression, $-1.5\times\tanh(-0.459)$ $=-1.5\times(-0.429269)=0.643903$, so it also gives $0.808562$.
(3) For $a=1$, $\relu(-1)=0$ and $-\relu(1)=-1$, so $\relu(-a)\ne-\relu(a)$. Therefore, replacing $v\,\relu(wa+b)$ by $(-v)\,\relu(-wa-b)$ generally changes the value (example: $v=1,\ w=1,\ b=0$, input 1, giving 1 and 0). Instead, for $c\gt0$ we have $\relu(ca)=c\,\relu(a)$. Using $c=4$ for $f(s)=2\relu(s-0.5)$ gives
$$ f(s)=\frac{2}{4}\,\relu\bigl(4s-2\bigr)=0.5\,\relu(4s-2). $$Checking: at $s=0.2$ both are 0; at $s=0.9$ they are $2\times0.4=0.8$ and $0.5\times1.6=0.8$; at $s=1.4$ they are $2\times0.9=1.8$ and $0.5\times3.6=1.8$. Since $c$ may be any positive number, there is a continuum of weights representing the same function. For this reason, in a ReLU network, comparing the magnitudes of the weights themselves (for example, only $\norm{\bm{W}^{(1)}}$) is of limited meaning, and weight decay also affects the balance of the weight magnitudes across layers.
Exercise 14.8: Linear networks and narrow layers
Solution
(1) By Eq. (14.8) of Chapter 14 (composition of linear layers), $\bm{W}=\bm{W}^{(2)}\bm{W}^{(1)}$ and $\bm{b}=\bm{W}^{(2)}\bm{b}^{(1)}+b^{(2)}$.
$$ \begin{aligned} \bm{W}&=\begin{pmatrix}1&-1&2\end{pmatrix}\begin{pmatrix}1&2\\0&1\\-1&1\end{pmatrix}\\ &=\bigl(1\cdot1+(-1)\cdot0+2\cdot(-1),\\ &\qquad 1\cdot2+(-1)\cdot1+2\cdot1\bigr)\\ &=\begin{pmatrix}-1&3\end{pmatrix}, \end{aligned} $$ $$ \bm{b}=1\cdot1+(-1)\cdot0+2\cdot(-1)+0.5=-0.5 . $$Hence $\hat{y}=-x_1+3x_2-0.5$. For example, for $\bm{x}=(0.3,-1.2)^{\tp}$, both the step-by-step computation through the two layers and the single-layer formula give $-4.4$.
(2) Since $\bm{W}^{(1)}\in\R^{1\times3}$ (a row vector $\bm{p}^{\tp}$) and $\bm{W}^{(2)}\in\R^{3\times1}$ (a column vector $\bm{q}$), $\bm{W}^{(2)}\bm{W}^{(1)}=\bm{q}\bm{p}^{\tp}$. For any $\bm{x}$, $\bm{q}\bm{p}^{\tp}\bm{x}=(\bm{p}^{\tp}\bm{x})\,\bm{q}$ is a constant multiple of $\bm{q}$, so the image (column space) is a subspace of dimension at most 1 spanned by $\bm{q}$. Hence the rank is at most 1. In general, $\rank(\bm{A}\bm{B})\le\min(\rank\bm{A},\rank\bm{B})$, and if the width of an intermediate layer is $r$, the rank of the whole is at most $r$.
(3) If a network that passes the input through a narrow layer (of width $r$) and returns it to the original dimension is trained so that its output reproduces its input, it becomes a method of representing the data compressed into $r$ dimensions. This is called an autoencoder. When the activation function is the identity map and squared error is used, the $r$-dimensional subspace obtained by training coincides with the space spanned by the top $r$ principal components of principal component analysis (PCA) (Chapter 18, Section 18.8). If nonlinear activation functions are introduced, curved low-dimensional structures can also be represented.
← Back to Chapter 14, “Representations in Neural Networks — Learning the Basis Functions”
Chapter 15 Backpropagation and Learning — Distributing Gradients with the Chain Rule
Exercise 15.1: A 1–1–1 ReLU network
Solution
(1) Forward propagation: $a^{(1)}=W^{(1)}x+b^{(1)}=0.8\times1.5-0.2=1.0$. Since $a^{(1)}\gt0$, $z^{(1)}=\relu(1.0)=1.0$. Then $\hat{y}=a^{(2)}=W^{(2)}z^{(1)}+b^{(2)}$ $=1.5\times1.0+0.1=1.6$. The loss is $\ell=\tfrac12(1.6-2.0)^{2}=0.08$.
Backward propagation: because the output is the identity and the loss is half the squared error, $\delta^{(2)}=\hat{y}-y=-0.4$. The derivative of the ReLU is 1 since $a^{(1)}=1.0\gt0$, so $\delta^{(1)}=1\times W^{(2)}\delta^{(2)}=1.5\times(-0.4)=-0.6$. The gradients are
$$ \begin{aligned} \pdiff{\ell}{W^{(2)}}&=\delta^{(2)}z^{(1)}=-0.4,\\ \pdiff{\ell}{b^{(2)}}&=\delta^{(2)}=-0.4,\\ \pdiff{\ell}{W^{(1)}}&=\delta^{(1)}x=-0.6\times1.5=-0.9,\\ \pdiff{\ell}{b^{(1)}}&=\delta^{(1)}=-0.6 . \end{aligned} $$(2) Updating with $\eta=0.1$ gives $W^{(1)}=0.8+0.09=0.89$, $b^{(1)}=-0.2+0.06=-0.14$, $W^{(2)}=1.5+0.04=1.54$, and $b^{(2)}=0.1+0.04=0.14$. After the update, $a^{(1)}=0.89\times1.5-0.14=1.195$, $z^{(1)}=1.195$, $\hat{y}=1.54\times1.195+0.14=1.9803$, and $\ell=\tfrac12(1.9803-2.0)^{2}$ $=\tfrac12\times0.000388=1.94\times10^{-4}$. The loss dropped from 0.08 to about 1/400 of its value.
(3) For $x=-1.0$, $a^{(1)}=0.8\times(-1.0)-0.2=-1.0\lt0$, so $z^{(1)}=0$, $\hat{y}=b^{(2)}=0.1$, and $\ell=\tfrac12(0.1-2.0)^{2}=1.805$. Here $\delta^{(2)}=-1.9$, but the derivative of the ReLU is 0, so $\delta^{(1)}=0$. Therefore $\partial\ell/\partial W^{(1)}=\partial\ell/\partial b^{(1)}=0$. Also, since $z^{(1)}=0$, $\partial\ell/\partial W^{(2)}=\delta^{(2)}z^{(1)}=0$. The only parameter that moves is $b^{(2)}$, with $\partial\ell/\partial b^{(2)}=-1.9$; after the update $b^{(2)}=0.1+0.19=0.29$ (the loss becomes 1.462). For data on which the hidden unit is not active, the weights of the hidden layer learn nothing.
Exercise 15.2: Combining a sigmoid output with the squared error
Solution
(1) By the chain rule, $\delta=\pdiff{\ell}{\hat{y}}\diff{\hat{y}}{a}$. Since $\pdiff{\ell}{\hat{y}}=\hat{y}-y$ and $\diff{\hat{y}}{a}=\sigma'(a)=\sigma(a)(1-\sigma(a))=\hat{y}(1-\hat{y})$, we obtain $\delta=(\hat{y}-y)\hat{y}(1-\hat{y})$.
(2) For $y=1$ and $\hat{y}=0.01$, the squared error gives $\delta=(0.01-1)\times0.01\times0.99=-0.009801$. The cross-entropy gives $\delta=0.01-1=-0.99$. The $\delta$ of the squared error is about 1/100 as large. (For $\hat{y}=0.5$ the values are $-0.125$ and $-0.5$, and for $\hat{y}=0.99$ they are $-0.000099$ and $-0.01$.)
(3) With the squared error the factor $\hat{y}(1-\hat{y})$ is multiplied in. So when the sigmoid saturates and $\hat{y}$ is close to 0 or 1, $\delta$ is small even if the prediction is badly wrong, all of the gradients in Eqs. (15.6)–(15.8) of Chapter 15 become small, and learning hardly progresses. With the cross-entropy, the derivative $1/\hat{y}$ of $\ln\hat{y}$ cancels this factor, and $\delta=\hat{y}-y$ is proportional to how far the prediction misses. Moreover, the cross-entropy is the negative log-likelihood of the Bernoulli distribution, so it is also consistent with maximum likelihood estimation (Chapter 5, Section 5.5; Chapter 14, Section 14.6).
Exercise 15.3: The second update
Solution
The parameters after the update are $\bm{W}^{(1)}=((0.709829,-0.195085),$ $(0.657292,0.128646))$, $\bm{b}^{(1)}=(0.309829,-0.242708)$, $\bm{W}^{(2)}=(1.10770,-0.830494)$, and $b^{(2)}=0.455266$, and the forward-propagation values are $\bm{a}^{(1)}=(0.922116,\,0.478907)$, $\bm{z}^{(1)}=(0.726897,\,0.445368)$, $a^{(2)}=0.890573$, $\hat{y}=0.709008$, and $L=-\ln0.709008=0.343888$.
(1) $\delta^{(2)}=\hat{y}-y=0.709008-1=-0.290992$. Also $h'(a^{(1)}_1)=1-0.726897^{2}=0.471621$ and $h'(a^{(1)}_2)=1-0.445368^{2}=0.801648$. The vector $\bm{W}^{(2)\tp}\delta^{(2)}$ is
$$ \begin{aligned} \bm{W}^{(2)\tp}\delta^{(2)}&=\bigl(1.10770\times(-0.290992),\\ &\qquad -0.830494\times(-0.290992)\bigr)\\ &=(-0.322331,\ 0.241667). \end{aligned} $$Multiplying component by component gives
$$ \begin{aligned} \bm{\delta}^{(1)}&=\bigl(0.471621\times(-0.322331),\\ &\qquad 0.801648\times0.241667\bigr)\\ &=(-0.152018,\ 0.193732). \end{aligned} $$(2) For the output layer,
$$ \begin{aligned} \pdiff{L}{\bm{W}^{(2)}}&=\delta^{(2)}\bm{z}^{(1)\tp}\\ &=(-0.290992\times0.726897,\\ &\qquad -0.290992\times0.445368)\\ &=(-0.211521,\ -0.129598), \end{aligned} $$and $\partial L/\partial b^{(2)}=-0.290992$. For the hidden layer, $\partial L/\partial\bm{W}^{(1)}=\bm{\delta}^{(1)}\bm{x}^{\tp}$ $=((-0.152018,\ -0.0760089),$ $(0.193732,\ 0.0968658))$ and $\partial L/\partial\bm{b}^{(1)}=(-0.152018,\ 0.193732)$. The sum of squares of the nine components is $\norm{\bm{g}}^{2}=0.282656$.
(3) Updating with $\eta=0.5$ gives $\bm{W}^{(1)}=((0.785838,-0.157081),$ $(0.560426,0.0802131))$, $\bm{b}^{(1)}=(0.385838,-0.339574)$, $\bm{W}^{(2)}=(1.21346,-0.765695)$, and $b^{(2)}=0.600762$. Forward propagation gives $\bm{a}^{(1)}=(1.093136,\,0.260959)$, $\bm{z}^{(1)}=(0.798020,\,0.255192)$,
$$ \begin{aligned} a^{(2)}&=1.21346\times0.798020\\ &\quad-0.765695\times0.255192+0.600762\\ &=1.373726, \end{aligned} $$$\hat{y}=\sigma(1.373726)=0.797981$, and $L=-\ln0.797981=0.225670$.
The second decrease is $0.343888-0.225670=0.118218$, which is smaller than the first one, 0.370550. This is because $\hat{y}$ approached 1, so $\abs{\delta^{(2)}}$ fell from 0.510533 to 0.290992, and the sum of squares of the gradient also fell from 1.00151 to 0.282656. The difference from the first-order approximation of the decrease, $\eta\norm{\bm{g}}^{2}=0.141328$, is smaller than for the first update: the smaller the gradient, the better the first-order approximation holds.
Exercise 15.4: The optimal step size for finite differences
Solution
(1) Differentiate $E(\epsilon)=\dfrac{\epsilon^{2}}{6}\abs{L'''}+\dfrac{\epsilon_{\mathrm{mach}}\abs{L}}{\epsilon}$ with respect to $\epsilon$ and set the result equal to 0.
$$ \diff{E}{\epsilon}=\frac{\epsilon}{3}\abs{L'''}-\frac{\epsilon_{\mathrm{mach}}\abs{L}}{\epsilon^{2}}=0 $$gives
$$ \epsilon^{*}=\Bigl(\frac{3\epsilon_{\mathrm{mach}}\abs{L}}{\abs{L'''}}\Bigr)^{1/3}. $$Using $(\epsilon^{*})^{3}\abs{L'''}=3\epsilon_{\mathrm{mach}}\abs{L}$, we have $\epsilon_{\mathrm{mach}}\abs{L}/\epsilon^{*}=(\epsilon^{*})^{2}\abs{L'''}/3$, so
$$ \begin{aligned} E(\epsilon^{*})&=\frac{(\epsilon^{*})^{2}\abs{L'''}}{6}+\frac{(\epsilon^{*})^{2}\abs{L'''}}{3}\\ &=\frac{(\epsilon^{*})^{2}\abs{L'''}}{2}\\ &=\frac12\abs{L'''}^{1/3}\bigl(3\epsilon_{\mathrm{mach}}\abs{L}\bigr)^{2/3}, \end{aligned} $$that is, the minimum error is proportional to $\epsilon_{\mathrm{mach}}^{2/3}$.
(2) For the forward difference, we minimize the sum $E_{\mathrm{f}}(\epsilon)$ of the truncation error $\tfrac{\epsilon}{2}\abs{L''}$ and the rounding error $2\epsilon_{\mathrm{mach}}\abs{L}/\epsilon$. From $\diff{E_{\mathrm{f}}}{\epsilon}=\tfrac12\abs{L''}-2\epsilon_{\mathrm{mach}}\abs{L}/\epsilon^{2}=0$ we get $\epsilon^{2}=4\epsilon_{\mathrm{mach}}\abs{L}/\abs{L''}$, that is, $\epsilon^{*}=2\sqrt{\epsilon_{\mathrm{mach}}\abs{L}/\abs{L''}}$. The error at this step size is $2\sqrt{\epsilon_{\mathrm{mach}}\abs{L}\abs{L''}}$, which is proportional to $\epsilon_{\mathrm{mach}}^{1/2}$ (larger than the $\epsilon_{\mathrm{mach}}^{2/3}$ of the central difference).
(3) The optimal step sizes for the central difference and the forward difference are
$$ \begin{aligned} \epsilon^{*}_{\mathrm{c}}&=\Bigl(\frac{3\times1.11\times10^{-16}\times0.714438}{0.0334}\Bigr)^{1/3}\\ &=(7.1\times10^{-15})^{1/3}=1.9\times10^{-5},\\ \epsilon^{*}_{\mathrm{fwd}}&=2\sqrt{\frac{1.11\times10^{-16}\times0.714438}{0.5230}}\\ &=2\sqrt{1.52\times10^{-16}}=2.5\times10^{-8} \end{aligned} $$In Figure 15.5 of Chapter 15, the bottom of the valley for the central difference is near $\epsilon=10^{-5}$ and that for the forward difference is near $10^{-8}$–$3\times10^{-8}$, which agree to within an order of magnitude. The figure shows the largest error over the nine parameters, so the coefficients differ slightly from the estimate for a single parameter.
Exercise 15.5: He initialization
Solution
(1) Suppose the density $p(a)$ of $a$ satisfies $p(-a)=p(a)$. Since $\relu(a)^{2}$ equals $a^{2}$ for $a\gt0$ and 0 for $a\le0$, $\Ex[\relu(a)^{2}]=\int_{0}^{\infty}a^{2}p(a)\,\dd a$. By symmetry, $\int_{-\infty}^{0}a^{2}p(a)\,\dd a=\int_{0}^{\infty}a^{2}p(a)\,\dd a$, so this is exactly half of $\int_{-\infty}^{\infty}a^{2}p(a)\,\dd a$. The mean of a symmetric distribution is 0, so $\int a^{2}p(a)\,\dd a=\Ex[a^{2}]=\Var[a]$. Hence $\Ex[\relu(a)^{2}]=\tfrac12\Var[a]$.
(2) From the derivation in Section 15.6.2, $\Var[a^{(l)}_j]=D_{l-1}\sigma_{\mathrm{init}}^{2}\Ex[(z^{(l-1)})^{2}]$. If $z^{(l-1)}=\relu(a^{(l-1)})$ and $a^{(l-1)}$ is symmetric about 0, then by (1) $\Ex[(z^{(l-1)})^{2}]=\tfrac12\Var[a^{(l-1)}]$. Therefore $\Var[a^{(l)}]=\tfrac12D_{l-1}\sigma_{\mathrm{init}}^{2}\Var[a^{(l-1)}]$, and the condition for this to equal $\Var[a^{(l-1)}]$ is $\tfrac12D_{l-1}\sigma_{\mathrm{init}}^{2}=1$, that is, $\sigma_{\mathrm{init}}^{2}=2/D_{l-1}$. ($a^{(l-1)}$ is symmetric because the weights are drawn independently from a symmetric distribution with mean 0, so the signs of the terms of $a^{(l-1)}=\sum_iW_{ji}z_i$ are interchanged with equal probability.)
(3) He: $\sigma_{\mathrm{init}}=\sqrt{2/64}=0.1768$. Xavier (64 inputs and 64 outputs): $\sigma_{\mathrm{init}}^{2}=2/(64+64)=1/64$, so the factor per layer is $\tfrac12\times64\times\tfrac{1}{64}=\tfrac12$. After 10 layers the variance is multiplied by $(1/2)^{10}=1/1024\approx9.8\times10^{-4}$, so the signal becomes three orders of magnitude smaller (the same tendency as the dashed line in Figure 15.7(b) of Chapter 15).
Exercise 15.6: Per-atom energies and forces
Solution
The interatomic distances are $\abs{x_1-x_2}=1.0$, $\abs{x_2-x_3}=1.2$, and $\abs{x_1-x_3}=2.2$ Å, so $e^{-1.0}=0.367879$, $e^{-1.44}=0.236928$, and $e^{-4.84}=0.007907$.
(1) $G_1=0.367879+0.007907=0.375787$, $G_2=0.367879+0.236928=0.604807$, and $G_3=0.007907+0.236928=0.244835$. The per-atom energies are $\varepsilon(G_i)=-\tanh G_i$, that is, $(-0.359043,\ -0.540461,\ -0.240057)$ eV, and the total is $E=-1.139561$ eV.
(2) By the chain rule (Theorem 15.1), we take the sum over all the $G_i$ that $x_2$ affects.
$$ \begin{aligned} F_2&=-\pdiff{E}{x_2}=-\sum_{i=1}^{3}\varepsilon'(G_i)\,\pdiff{G_i}{x_2},\\ \varepsilon'(G)&=v\bigl(1-\tanh^{2}G\bigr). \end{aligned} $$We have $\varepsilon'(G_1)=-0.871088$, $\varepsilon'(G_2)=-0.707901$, and $\varepsilon'(G_3)=-0.942373$ eV. Using $\pdiff{}{x_2}e^{-(x_i-x_2)^{2}}=2(x_i-x_2)e^{-(x_i-x_2)^{2}}$ ($i\ne2$), the partial derivatives of $G_i$ are
$$ \begin{aligned} \pdiff{G_1}{x_2}&=2(0-1.0)\times0.367879\\ &=-0.735759,\\ \pdiff{G_3}{x_2}&=2(2.2-1.0)\times0.236928\\ &=0.568627,\\ \pdiff{G_2}{x_2}&=-2(1.0-0)\times0.367879\\ &\quad-2(1.0-2.2)\times0.236928\\ &=-0.735759+0.568627\\ &=-0.167132 \end{aligned} $$(in units of Å$^{-1}$). The contributions $-\varepsilon'(G_i)\,\partial G_i/\partial x_2$ from the energy of each atom are $-0.640911$ from atom 1, $-0.118313$ from atom 2, and $+0.535858$ eV/Å from atom 3, so
$$ \begin{aligned} F_2&=-0.640911-0.118313+0.535858\\ &=-0.223366\ \mathrm{eV/Å}. \end{aligned} $$Most of the force acting on atom 2 comes not from the energy of atom 2 itself but from the fact that the energies of the neighboring atoms depend on $x_2$. Similarly, $F_1=1.224848$ and $F_3=-1.001482$ eV/Å (in this model $v\lt0$, so the atoms attract each other, and the atoms at the two ends are pulled inward).
(3) Since $G_i$ is a function only of the differences $x_i-x_j$ between atoms, $E$ does not change when all the atoms are shifted by the same amount $c$: $E(x_1+c,x_2+c,x_3+c)=E(x_1,x_2,x_3)$. Differentiating both sides with respect to $c$ and setting $c=0$ gives $\sum_k\partial E/\partial x_k=0$, that is, $F_1+F_2+F_3=0$ (indeed $1.224848-0.223366-1.001482=0$). From an energy that is unchanged by translation, only internal forces, whose sum is 0, can arise. This is an example of the “invariance” treated in Chapter 16.
Exercise 15.7: Reading the learning curves of the sintering data
Solution
(1) We adopt the weights at epoch 1187, where the validation RMSE is smallest (1.50 %) (early stopping). Before that, both the training and the validation RMSE are decreasing and the training is insufficient; after that, only the training RMSE decreases while the validation RMSE rises (1.65 % at 2000 and 1.94 % at 5000), which is overfitting.
(2) The observations in data set A contain noise (standard deviation 1.0 %), so even if the true function itself were used for prediction, an RMSE of about 1 % should remain on the training data. The value 0.31 % is far smaller than that, which shows that the model is bending to fit the noise of the individual observations rather than the true function (it has memorized even the noise). With only 8 data points for 49 parameters, one can construct any number of curves that pass through the 8 points.
(3) It is not good. If dozens of choices are made on the validation data, the selected combination has also been fitted to the chance fluctuations of the validation data, so the validation RMSE is an optimistic estimate of the error on future data. Report the value obtained by evaluating only once, at the very end, on test data that were never used for any selection (Chapter 6, Section 6.3).
(4) Choose the stopping epoch and $\lambda$ by cross-validation (Chapter 6, Section 6.5), and finally retrain on all the data. Split the data so that samples from the same firing batch are not divided between training and validation (Chapter 6, Section 6.8). Also, with only 8 data points, first try models with few parameters (regression with basis functions in Chapter 8, Gaussian process regression in Chapter 12), and compare them on the validation data to check whether there is any advantage in using a neural network. Predictions outside the temperature range of the training data (1159–1473 °C) are treated as extrapolation for any model.
Exercise 15.8: Weight decay and MAP estimation
Solution
(1) By Bayes’s theorem, $p(\bm{w}\mid\data)\propto p(\data\mid\bm{w})\,p(\bm{w})$. Since the observations are independent and Gaussian,
$$ p(\data\mid\bm{w})=\prod_{n=1}^{N}\frac{1}{\sqrt{2\pi\sigma^{2}}}\exp\Bigl(-\frac{(y_n-f_n)^{2}}{2\sigma^{2}}\Bigr). $$Here $f_n=f(\bm{x}_n;\bm{w})$.
The prior distribution is $p(\bm{w})\propto\exp\bigl(-\norm{\bm{w}}^{2}/(2\sigma_w^{2})\bigr)$. Taking the negative logarithm and collecting the terms that do not depend on $\bm{w}$ into $C$, we obtain
$$ \begin{aligned} -\ln p(\bm{w}\mid\data)=&\ \frac{1}{\sigma^{2}}\sum_{n=1}^{N}\frac12(f_n-y_n)^{2}\\ &+\frac{1}{2\sigma_w^{2}}\norm{\bm{w}}^{2}+C . \end{aligned} $$(2) Multiplying by the positive constant $\sigma^{2}/N$ does not change the $\bm{w}$ that minimizes the expression.
$$ \begin{aligned} &\frac{\sigma^{2}}{N}\bigl(-\ln p(\bm{w}\mid\data)-C\bigr)\\ &\quad=\frac1N\sum_{n=1}^{N}\frac12(f_n-y_n)^{2}+\frac{\sigma^{2}}{2N\sigma_w^{2}}\norm{\bm{w}}^{2}. \end{aligned} $$This is the mean loss plus $\tfrac{\lambda}{2}\norm{\bm{w}}^{2}$, with $\lambda=\sigma^{2}/(N\sigma_w^{2})$. Therefore, minimizing the loss with weight decay is the same as MAP estimation under a Gaussian prior distribution. The more data there are (the larger $N$ is), the smaller the $\lambda$ of the mean convention becomes. The $\lambda'=\sigma^{2}/\sigma_w^{2}$ of the sum convention (the same correspondence as for Ridge regression in Chapter 8) does not depend on $N$. Not penalizing the bias corresponds to taking a uniform (very broad) prior distribution for the bias.
(3) In standardized units, the noise standard deviation is $1.0/7.15$ and the variance is $(1/7.15)^{2}=0.01955$. For $N=20$ and $\sigma_w=1$, $\lambda=0.01955/20=9.8\times10^{-4}$, which is nearly equal to the choice $10^{-3}$ among the options of Simulator 15.3. Note that the loss of a minibatch is the mean over the minibatch, so the strength of the penalty in one update is the same as for the mean loss over all the data, and this correspondence can be used as it is in minibatch training as well.
← Back to Chapter 15, “Backpropagation and Learning — Distributing Gradients with the Chain Rule”
Chapter 16 Deep Learning That Exploits Structure — Images, Graphs, and Symmetry
Exercise 16.1: One-dimensional convolution and the output length
Solution
(1) Since the padding is “valid”, the window must lie entirely inside the input, which gives four outputs, for $t=1,2,3,4$. From $y_t=x_t-x_{t+1}$,
$$ \begin{aligned} y_1&=1-2=-1,\quad y_2=2-0=2,\\ y_3&=0-(-1)=1,\quad y_4=-1-3=-4 . \end{aligned} $$So $\bm{y}=(-1,2,1,-4)$. This filter takes the difference from the neighbor, so its output is positive where the signal decreases toward the right and negative where it increases. In other words, it detects changes toward the right (steps and edges) together with their sign.
(2) The output length is $\lfloor(T+2P-k)/s\rfloor+1$.
- (a) $\lfloor(100+4-5)/1\rfloor+1=99+1=100$.
- (b) $\lfloor(100+4-5)/2\rfloor+1$ $=\lfloor49.5\rfloor+1=50$.
- (c) $\lfloor(100+0-5)/1\rfloor+1=95+1=96$.
(3) For $s=1$ we have $T_{\mathrm{out}}=T+2P-k+1$, so the condition for $T_{\mathrm{out}}=T$ is $2P=k-1$, that is, $P=(k-1)/2$. For $k=5$ this gives $P=2$, and (a) satisfies exactly this condition. A window of width $k$ sticks out by $(k-1)/2$ entries on each side of its center, so if we pad that many zeros, the window can also be placed at the end positions.
Exercise 16.2: Counting the parameters of a small CNN
Solution
(1) A 3×3 convolution with “same” padding leaves the height and width unchanged, and 2×2 max pooling (stride 2) halves the height and width.
- Input: 128×128×1 → convolution 1: 128×128×8 → pooling: 64×64×8
- → convolution 2: 64×64×16 → pooling: 32×32×16
- → global average: 16 → fully connected: 3 → softmax: 3
(2) We use Eq. (16.5) of Chapter 16, $N_{\mathrm{param}}=C_{\mathrm{out}}(k^{2}C_{\mathrm{in}}+1)$.
$$ \begin{aligned} \text{Convolution 1}&:\ 8\times(9\times1+1)=80,\\ \text{Convolution 2}&:\ 16\times(9\times8+1)=1168,\\ \text{Fully connected}&:\ 3\times(16+1)=51 . \end{aligned} $$Pooling and the global average have no parameters, so the total is $80+1168+51=1299$.
(3) There are $128\times128=16384$ pixels. Connecting them directly to the three classes takes $3\times(16384+1)=49155$ parameters. If we insert 100 hidden units, the first layer has $100\times(16384+1)=1\,638\,500$ parameters and the second layer has $3\times(100+1)=303$, for a total of $1\,638\,803$. The CNN of (2) has about $1/38$ and about $1/1262$ of these numbers of parameters, respectively. Moreover, even if the image size changes, the number of parameters in the convolutional part does not change (and, thanks to the global average, neither does the fully connected part).
Exercise 16.3: A linear map that commutes with the shift is a convolution
Solution
Below, all indices are counted as $0,\dots,T-1$ modulo $T$.
(1) The linear part of a convolution with periodic boundary is $y_t=\sum_{u=-r}^{r}w_ux_{t+u}$. Let $s=t+u$. The coefficient in $y_t=\sum_sC_{ts}x_s$ is $C_{ts}=w_u$ if there is a $u\in\{-r,\dots,r\}$ with $s-t\equiv u$ ($\bmod T$), and $0$ otherwise. This is determined by $s-t$ alone, so if we set $c_m=w_m$ ($0\le m\le r$), $c_{T-m}=w_{-m}$ ($1\le m\le r$), and $c_m=0$ otherwise, we can write $C_{ts}=c_{(s-t)\bmod T}$ (assuming $2r+1\le T$).
(2) From $(\bm{S}\bm{x})_t=x_{t-1}$, we have $S_{qs}=1$ only for $s=q-1$, that is, $q=s+1$, and the entry is 0 otherwise. Therefore
$$ \begin{aligned} (\bm{C}\bm{S})_{ts}&=\sum_qC_{tq}S_{qs}=C_{t,s+1}\\ &=c_{s+1-t},\\ (\bm{S}\bm{C})_{ts}&=\sum_qS_{tq}C_{qs}=C_{t-1,s}\\ &=c_{s-(t-1)}=c_{s+1-t}. \end{aligned} $$The two are equal, so $\bm{C}\bm{S}=\bm{S}\bm{C}$.
(3) The computation in (2) gives $(\bm{C}\bm{S})_{ts}=C_{t,s+1}$ and $(\bm{S}\bm{C})_{ts}=C_{t-1,s}$ without using the form of $\bm{C}$. Hence if $\bm{C}\bm{S}=\bm{S}\bm{C}$, then $C_{t,s+1}=C_{t-1,s}$ for all $t,s$. Replacing $t$ by $t+1$ gives $C_{t+1,s+1}=C_{t,s}$; that is, the entries of $\bm{C}$ do not change as we move diagonally toward the lower right. Repeating this $t$ times gives
$$ C_{t,s}=C_{t-1,s-1}=\cdots=C_{0,\,s-t} $$and if we set $c_m\equiv C_{0,m}$, then $C_{ts}=c_{(s-t)\bmod T}$, which is the form in (1) (a circulant matrix).
(4) Commuting with $\bm{S}$ means “shifting by one and then mapping gives the same result as mapping and then shifting,” which is the same as translation equivariance (since $\bm{S}^{\tau}=S_\tau$, a shift by one is enough). Therefore, under periodic boundary conditions, a translation-equivariant linear layer is necessarily a convolution with some filter. However, the filter width can be as large as $T$. That the filter is small (local) is an additional assumption, separate from translation equivariance.
Exercise 16.4: Magnification and the receptive field
Solution
(1) At the end of Example 16.4, $r=32$ and $j=4$. For 2×2 max pooling ($k=2$, $s=2$), $r=32+(2-1)\times4=36$ and $j=4\times2=8$. For the 3×3 convolution, $r=36+(3-1)\times8=52$. The receptive field is 52 pixels.
(2) At 0.1 μm/pixel, one grain is $5/0.1=50$ pixels, and the receptive field is $52\times0.1=5.2$ μm, about the size of one grain. At 0.5 μm/pixel, one grain is $5/0.5=10$ pixels, and the receptive field is $52\times0.5=26$ μm, a range that spans about five grains.
(3) A filter learned at 0.1 μm/pixel is fitted to the patterns of “grains about 50 pixels across” (how the grain boundaries curve, how uniform the brightness inside a grain is). In an image at 0.5 μm/pixel, a grain of the same microstructure is only 10 pixels across, which looks like an entirely different pattern to the filter, so the prediction cannot be trusted (a difference between the training and test distributions). Example countermeasures: (i) before predicting, enlarge or shrink the image so that the pixel size becomes 0.1 μm/pixel (however, enlarging a 0.5 μm/pixel image does not bring back the details that were lost, so it may be safer to match the training side to 0.5 μm/pixel). (ii) Include images at both magnifications in the training data, or apply data augmentation by enlarging and shrinking. (iii) Report the evaluation separately for each magnification, and check whether the model can be used on images at a different magnification.
Exercise 16.5: The graph of a simple cubic lattice
Solution
Taking the position of the atom as the origin, the periodic images lie at $a\bm{n}$ ($\bm{n}\in\mathbb{Z}^{3}$, $\bm{n}\ne\bm{0}$), at distance $a\norm{\bm{n}}$.
(1) The condition $a\norm{\bm{n}}\lt4.5$ Å, that is, $\norm{\bm{n}}\lt1.5$, is satisfied by $\norm{\bm{n}}=1$ (6 images such as $(\pm1,0,0)$, at distance 3.0 Å) and $\norm{\bm{n}}=\sqrt2\approx1.414$ (12 images such as $(\pm1,\pm1,0)$, at distance $3\sqrt2=4.243$ Å). $\norm{\bm{n}}=\sqrt3\approx1.732$ is not included. There are $6+12=18$ edges, of two lengths: 3.0 Å and 4.243 Å.
(2) Since $\norm{\bm{n}}\lt5.5/3=1.833$, $\norm{\bm{n}}=\sqrt3$ (8 images $(\pm1,\pm1,\pm1)$, at distance $3\sqrt3=5.196$ Å) is added, giving $18+8=26$ edges of three lengths. $\norm{\bm{n}}=2$ is 6.0 Å and is not included.
(3) The unit cell contains only one atom, so the partner of every edge is a periodic image of the atom itself (a self-loop). In a graph that places one edge for each pair of atoms inside the unit cell, there is no pair at all, so there are 0 edges and the graph cannot be distinguished from a single isolated atom. All the information on the coordination number (18 or 26), the nearest-neighbor distance, and the lattice constant is lost. We need a multigraph that distinguishes edges by periodic image.
(4) Even for a 2×2×2 supercell (6.0 Å on a side, 8 atoms), the arrangement of atoms around each atom is exactly the same, so the number of edges leaving each atom is still 18 ($r_{\mathrm c}=4.5$ Å). However, the partners are now other atoms in the supercell or their periodic images, and there can be two edges to the same partner (for example, from $(0,0,0)$ to $(3,0,0)$ there are two edges: to the atom itself and to its periodic image shifted by $-6$ Å). The features of all the atoms take the same values as in the original one-atom case, so the output of a mean readout does not change (with a sum readout it becomes 8 times larger).
Exercise 16.6: Aggregating by sum does not depend on the labeling
Solution
(1) We mark the quantities after relabeling with a tilde. The new vertex $i$ is the original vertex $\pi(i)$, so $\tilde{\bm{h}}_i=\bm{h}_{\pi(i)}$, the edge features are $\tilde{\bm{e}}_{ij}=\bm{e}_{\pi(i)\pi(j)}$, and the neighborhood satisfies “$\tilde{j}\in\tilde{\mathcal{A}}(i)$ ⇔ $\pi(\tilde{j})\in\mathcal{A}(\pi(i))$.” The sum of messages at the new vertex $i$ is
$$ \begin{aligned} \tilde{\bm{m}}_i&=\sum_{\tilde{j}\in\tilde{\mathcal{A}}(i)}M\bigl(\tilde{\bm{h}}_i,\tilde{\bm{h}}_{\tilde{j}},\tilde{\bm{e}}_{i\tilde{j}}\bigr)\\ &=\sum_{\tilde{j}\in\tilde{\mathcal{A}}(i)}M\bigl(\bm{h}_{\pi(i)},\bm{h}_{\pi(\tilde{j})},\bm{e}_{\pi(i)\pi(\tilde{j})}\bigr). \end{aligned} $$If we substitute $j=\pi(\tilde{j})$, then as $\tilde{j}$ runs over $\tilde{\mathcal{A}}(i)$, $j$ runs over $\mathcal{A}(\pi(i))$ exactly once each ($\pi$ is one-to-one). A sum does not depend on the order of addition, so
$$ \tilde{\bm{m}}_i=\sum_{j\in\mathcal{A}(\pi(i))}M\bigl(\bm{h}_{\pi(i)},\bm{h}_j,\bm{e}_{\pi(i)j}\bigr)=\bm{m}_{\pi(i)} . $$Therefore $\tilde{\bm{h}}'_i=U(\tilde{\bm{h}}_i,\tilde{\bm{m}}_i)=U(\bm{h}_{\pi(i)},\bm{m}_{\pi(i)})=\bm{h}'_{\pi(i)}$. After one step, “the feature of the new vertex $i$ equals the feature of the original vertex $\pi(i)$” still holds, so by repeating the same argument it holds after any number of steps (mathematical induction).
(2) We have $\sum_ig(\tilde{\bm{h}}_i)=\sum_ig(\bm{h}_{\pi(i)})$, and substituting $k=\pi(i)$, as $i$ runs over $1,\dots,N_{\mathrm{at}}$, $k$ also runs over each value exactly once, so the sum is unchanged: $=\sum_kg(\bm{h}_k)$. Multiplying by $R$ does not change this, so the readout is invariant. The mean only multiplies by $1/N_{\mathrm{at}}$, so it is also invariant.
(3) For the output not to change when atoms 1 and 2 are swapped, we need $w_1h_2+w_2h_1+w_3h_3=w_1h_1+w_2h_2+w_3h_3$ for all $h_1,h_2,h_3$, that is, $(w_1-w_2)(h_2-h_1)=0$. There are inputs with $h_1\ne h_2$, so $w_1=w_2$. Similarly, from swapping 1 and 3 and swapping 2 and 3, $w_1=w_3$. Therefore the output is invariant only when $w_1=w_2=w_3=w$, and in that case $\hat{y}=w(h_1+h_2+h_3)$ is exactly the sum readout. If the three atoms are of different elements and we only need to consider swaps between atoms of the same element, the only condition is that the weights of atoms of the same element are equal.
Exercise 16.7: Rotating the forces on two atoms
Solution
(1) The distance is $r=\sqrt{0.6^{2}+0.8^{2}}=1.0$ Å, which is shorter than $r_0=1.2$ Å, so the spring is compressed.
$$ \begin{aligned} E&=\tfrac{4}{2}(1.0-1.2)^{2}\\ &=2\times0.04=0.08\ \text{eV},\\ V'(r)&=k(r-r_0)=4\times(-0.2)=-0.8\ \text{eV/Å}. \end{aligned} $$From Eq. (16.17) of Chapter 16 (the force from a pair potential),
$$ \begin{aligned} \bm{F}_1&=V'(r)\frac{\bm{r}_2-\bm{r}_1}{r}\\ &=-0.8\times(0.6,0.8)\\ &=(-0.48,\,-0.64),\\ \bm{F}_2&=V'(r)\frac{\bm{r}_1-\bm{r}_2}{r}\\ &=(0.48,\,0.64) \end{aligned} $$(in eV/Å). Since the spring is compressed, atom 1 is pushed away from atom 2, and atom 2 is also pushed away from atom 1.
(2) Rotating with $\bm{Q}=\begin{pmatrix}0&-1\\1&0\end{pmatrix}$ gives $\bm{r}'_1=(0,0)$ and $\bm{r}'_2=(-0.8,0.6)$. The distance remains 1.0 Å, so $E=0.08$ eV.
$$ \begin{aligned} \bm{F}'_1&=-0.8\times(-0.8,0.6)=(0.64,\,-0.48),\\ \bm{F}'_2&=(-0.64,\,0.48). \end{aligned} $$On the other hand, $\bm{Q}\bm{F}_1=\bm{Q}(-0.48,-0.64)^{\tp}=(0.64,-0.48)^{\tp}$ and $\bm{Q}\bm{F}_2=(-0.64,0.48)^{\tp}$, which agree.
(3) Let the positions after the rotation and translation be $\bm{r}'_i=\bm{Q}\bm{r}_i+\bm{t}$. Then $\bm{r}'_2-\bm{r}'_1=\bm{Q}(\bm{r}_2-\bm{r}_1)$, and its length is $\norm{\bm{Q}(\bm{r}_2-\bm{r}_1)}=r$ (because $\bm{Q}^{\tp}\bm{Q}=\bm{I}$). Therefore
$$ \begin{aligned} \bm{F}_1(\bm{\mathcal{R}}')&=V'(r)\frac{\bm{Q}(\bm{r}_2-\bm{r}_1)}{r}\\ &=\bm{Q}\Bigl(V'(r)\frac{\bm{r}_2-\bm{r}_1}{r}\Bigr)=\bm{Q}\bm{F}_1(\bm{\mathcal{R}}). \end{aligned} $$The same holds for $\bm{F}_2$. The vector $\bm{t}$ cancels when we take the difference, so the forces do not change under translation. Also, $\bm{F}_1+\bm{F}_2$ is $V'(r)/r$ times $(\bm{r}_2-\bm{r}_1)+(\bm{r}_1-\bm{r}_2)=\bm{0}$, so it is $\bm{0}$. This confirms the two properties of Theorem 16.2 (rotation equivariance and zero net force).
Exercise 16.8: Designing a model that predicts the band gap
Solution
The following is one example of a solution.
(1) Input: the crystal structure (lattice vectors, and the positions and elements of the atoms in the unit cell). Convert it to the periodic multigraph of Chapter 16, Section 16.5, with the vertex features given by information on the element and the edge features by the distance (expanded in radial basis functions). Output: the band gap (a scalar, in eV, nonnegative). Using a softplus or similar in the output layer ensures that no negative values are produced. Invariance: invariant under translation, rotation, and permutation of atoms of the same element. In addition, the prediction should not depend on the choice of unit cell (the position of the origin, or whether it is a primitive cell, a conventional cell, or a supercell). Readout: the band gap is an intensive quantity that does not depend on the size of the crystal, so we use the mean. With a sum, simply entering the same crystal as a supercell would multiply the prediction by the number of atoms.
(2) Things that cause leakage in a random split: structures with the same composition but slightly different structures (polymorphs, slightly distorted structures), structures of the same type in which a chemically similar element is substituted (for example, substitution by an element of the same group), and duplicate data in which the same material was computed under different calculation conditions. If these are divided between training and test, the test becomes a problem of “guessing something almost identical.” Countermeasures: put all structures of the same composition on the same side (split by composition), split by groups according to the combination of elements (chemical system) or the structure type, or send everything containing a particular element to the test set (evaluating extrapolation to unknown elements).
(3) Values from first-principles calculations inherit the properties of the approximation used. For example, in density functional theory calculations with the widely used local density approximation (LDA), it is known that the band gaps of semiconductors and insulators come out smaller than the experimental values (J. P. Perdew, M. Levy, Phys. Rev. Lett. 51, 1884 (1983)). The model learns not the experimental values but “the values of that calculation method.” If we want to predict experimental values, we need, for example, to relearn the deviation from the computed values using a small number of experimental values (learning the difference; Chapter 27, Section 27.8), or to evaluate the correspondence between computed and experimental values separately on the test set. Also, if the data contain many metals (gap 0), the mean error looks small, so we also report the error on the nonzero cases only.
(4) If the new element has never appeared in the training data, the feature (embedding) of that element has not been learned, and the prediction has no basis. Ways to check: count how many entries in the training data contain that element or similar elements; estimate the magnitude of the extrapolation error with a test in which a particular element is left out of training and evaluation; use the spread of the predictions of several models trained with different random-number seeds as a rough measure of uncertainty; and send only promising candidates to experiment after checking them with first-principles calculations.
← Back to Chapter 16, “Deep Learning That Exploits Structure — Images, Graphs, and Symmetry”
Chapter 17 Clustering, Mixture Distributions, and the EM Algorithm — Estimating Unseen Labels
Exercise 17.1: k-means with $K=3$ and how $J$ decreases
Solution
(1) Assignment (representatives $1,6,11$): the point $x=1$ is at distance 0 from 1, and $x=2$ is at distance 1 from 1 and 4 from 6, so it goes to cluster 1. The point $x=6$ is at distance 0 from 6, so it goes to cluster 2. The point $x=9$ is at distance 3 from 6 and 2 from 11, so it goes to cluster 3. The points $x=10,11$ also go to cluster 3. Update: $\mu_1=(1+2)/2=1.5$, $\mu_2=6$, $\mu_3=(9+10+11)/3=10$. Assignment: $x=2$ is at distance 0.5 from 1.5 and 4 from 6, $x=6$ is at distance 0 from 6, and $x=9$ is at distance 3 from 6 and 1 from 10, so the assignment does not change. At convergence,
$$ \begin{aligned} J&=(0.5^{2}+0.5^{2})+0^{2}+(1^{2}+0^{2}+1^{2})\\ &=0.5+0+2=2.5\ \mu\mathrm{m}^{2}. \end{aligned} $$(2) For $K=1$: the representative is the mean of all the data, $(1+2+6+9+10+11)/6=39/6=6.5$, and
$$ \begin{aligned} J^{*}_1&=5.5^{2}+4.5^{2}+0.5^{2}\\ &\quad+2.5^{2}+3.5^{2}+4.5^{2}\\ &=30.25+20.25+0.25\\ &\quad+6.25+12.25+20.25\\ &=89.5 . \end{aligned} $$For $K=2$: as found in Example 17.3, $J^{*}_2=14.5$. For $K=3$: in one dimension it suffices to examine the ways of splitting the points into three consecutive groups ($\binom{5}{2}=10$ ways). From the smallest, $\{1,2\}\{6\}\{9,10,11\}$ gives $0.5+0+2=2.5$, $\{1,2\}\{6,9\}\{10,11\}$ gives $0.5+4.5+0.5=5.5$, $\{1,2\}\{6,9,10\}\{11\}$ gives $0.5+8.67+0=9.17$, and $\{1\}\{2,6\}\{9,10,11\}$ gives $0+8+2=10$; the others are larger still. Thus $J^{*}_3=2.5$, and the answer to (1) is the optimal solution.
(3) $J^{*}_K$ decreases as $89.5\to14.5\to2.5$. In terms of differences, the drop is 75 from $K=1\to2$ and 12 from $2\to3$, so there seems to be an elbow at $K=2$. In terms of ratios, however, both steps reduce it to about $1/6$, and the elbow is not clear. For $K=3$, the point $x=6$ forms a cluster by itself. Whether this is a “third group” or an “outlier” cannot be decided from six data points. The judgment of an elbow also depends on whether we look at $J$ through differences or through ratios, and it is especially risky when there are few data.
Exercise 17.2: A Gaussian mixture with a variance shared by all components
Solution
(1) The log-likelihood is $\ln p=\sum_n\ln\sum_k\pi_k\Normal(x_n\mid\mu_k,\sigma^{2})$, and $\sigma^{2}$ enters every component. As in Chapter 17, Section 17.5.2, we use $\partial f/\partial\sigma^{2}=f\,\partial\ln f/\partial\sigma^{2}$ to obtain
$$ \pdiff{\ln p}{\sigma^{2}}=\sum_{n}\sum_{k}\gamma_{nk}\,\pdiff{\ln\Normal(x_n\mid\mu_k,\sigma^{2})}{\sigma^{2}} . $$Since $\ln\Normal(x\mid\mu,\sigma^{2})=-\tfrac12\ln2\pi$ $-\tfrac12\ln\sigma^{2}-\dfrac{(x-\mu)^{2}}{2\sigma^{2}}$, the derivative with respect to $\sigma^{2}$ is $-\dfrac{1}{2\sigma^{2}}+\dfrac{(x-\mu)^{2}}{2\sigma^{4}}$. Substituting and using $\sum_k\gamma_{nk}=1$ gives
$$ \begin{aligned} \pdiff{\ln p}{\sigma^{2}}&=-\frac{N}{2\sigma^{2}}\\ &\quad+\frac{1}{2\sigma^{4}}\sum_n\sum_k\gamma_{nk}(x_n-\mu_k)^{2}=0 . \end{aligned} $$Multiplying both sides by $2\sigma^{4}$ and solving for $\sigma^{2}$ gives
$$ \sigma^{2}=\frac{1}{N}\sum_{n=1}^{N}\sum_{k=1}^{K}\gamma_{nk}(x_n-\mu_k)^{2}. $$The update formulas for $\mu_k$ and $\pi_k$ are the same as in the case of component-wise variances (in the stationarity condition for $\mu_k$, $\sigma^{2}$ comes out as a common factor and cancels).
(2) In Example 17.7, the weighted sums of squares around the new means were $\sum_n\gamma_{n1}(x_n-\mu_1)^{2}=1.92348$ and $\sum_n\gamma_{n2}(x_n-\mu_2)^{2}=11.71107$. Therefore
$$ \begin{aligned} \sigma^{2}&=\frac{1.92348+11.71107}{4}\\ &=\frac{13.63455}{4}=3.40864 . \end{aligned} $$This is the same value as the average $(1.60126\times1.20123+2.39874\times4.88218)/4$ of the component-wise values 1.20123 and 4.88218, weighted by the effective numbers of points $N_1=1.60126$ and $N_2=2.39874$.
(3) Degeneration does not occur. For the variance to shrink onto a single point we would need $\sigma^{2}\to0$, but since the variance is shared, all components shrink at the same time. If the number of distinct values in the data is larger than $K$, there is always at least one point at a distance $\delta\gt0$ or more from every mean, and the density at that point tends to 0 as $\sigma^{2}\to0$, like $e^{-\delta^{2}/(2\sigma^{2})}/\sigma$. The logarithm of this factor, $-\delta^{2}/(2\sigma^{2})-\ln\sigma$, tends to $-\infty$ far faster than the term in which a mean sits on a single point increases through $-\ln\sigma$, so the log-likelihood does not diverge.
Exercise 17.3: The EM algorithm with a prior distribution (MAP estimation)
Solution
In the decomposition for the EM algorithm, consider $\ln p(\bm{X}\mid\bm{\theta})+\ln p(\bm{\theta})$ in place of $\ln p(\bm{X}\mid\bm{\theta})$. Since $\ln p(\bm{\theta})$ does not depend on $\bm{Z}$, the E step is unchanged, and the M step becomes the maximization of $\mathcal{Q}+\ln p(\bm{\theta})$. The log posterior distribution also does not decrease over the iterations.
(1) In $\mathcal{Q}$ of Chapter 17, Section 17.7.3, write the logarithm of the Gaussian distribution of component $k$ with precision $\tau_k=1/\sigma_k^{2}$: $\ln\Normal(x\mid\mu_k,1/\tau_k)=-\tfrac12\ln2\pi$ $+\tfrac12\ln\tau_k-\tfrac12\tau_k(x-\mu_k)^{2}$. Collecting the terms that contain $\tau_k$ gives
$$ \begin{aligned} F(\tau_k)&=\sum_n\gamma_{nk}\Bigl[\tfrac12\ln\tau_k-\tfrac12\tau_k(x_n-\mu_k)^{2}\Bigr]\\ &\quad+(a-1)\ln\tau_k-b\tau_k\\ &=\Bigl(\tfrac{N_k}{2}+a-1\Bigr)\ln\tau_k\\ &\quad-\Bigl(\tfrac{S_k}{2}+b\Bigr)\tau_k . \end{aligned} $$Differentiating and setting the result to 0 gives
$$ \frac{N_k/2+a-1}{\tau_k}-\frac{S_k}{2}-b=0 . $$Multiplying both sides by $2\tau_k$ and solving for $\tau_k$ gives
$$ \tau_k=\frac{N_k+2a-2}{S_k+2b},\qquad \sigma_k^{2}=\frac{S_k+2b}{N_k+2a-2}. $$Since $F''(\tau_k)=-(N_k/2+a-1)/\tau_k^{2}\lt0$ (for $a\gt1$), this is a maximum point. Because $\mu_k$ does not appear in the prior distribution, its update formula remains the weighted average ($S_k$ is computed with this new $\mu_k$). With $a=1$ and $b=0$ we recover the formula for maximum likelihood estimation.
(2) The terms containing $\pi_k$ are $\sum_k N_k\ln\pi_k+(\alpha-1)\sum_k\ln\pi_k$ $=\sum_k(N_k+\alpha-1)\ln\pi_k$. Under the constraint $\sum_k\pi_k=1$, differentiate the Lagrangian $\Lambda=\sum_k(N_k+\alpha-1)\ln\pi_k+\nu\bigl(\sum_k\pi_k-1\bigr)$ with respect to $\pi_k$ and set the result to 0:
$$ \frac{N_k+\alpha-1}{\pi_k}+\nu=0, $$that is, $\pi_k=-(N_k+\alpha-1)/\nu$.
Summing over $k$ gives $1=-\bigl(N+K(\alpha-1)\bigr)/\nu$, hence $\nu=-\bigl(N+K(\alpha-1)\bigr)$, and
$$ \pi_k=\frac{N_k+\alpha-1}{N+K(\alpha-1)} . $$If $\alpha\gt1$, then $\pi_k\gt0$ remains even for a component that is responsible for no point ($N_k=0$). If $\alpha=1$ (a uniform prior distribution), we recover the maximum likelihood value $N_k/N$.
(3) $\sigma_k^{2}=(0+2\times0.1)/(1+2\times2-2)$ $=0.2/3=0.0667$. In general, since $S_k\ge0$, we have $\sigma_k^{2}\ge2b/(N_k+2a-2)\gt0$, so the variance never becomes 0. In the log posterior distribution, the term $-b\tau_k$ tends to $-\infty$ as $\tau_k\to\infty$ ($\sigma_k\to0$) and cancels the increase of $\tfrac12\ln\tau_k$ due to the density at a single point, so degeneration does not occur. This can be read as “the prior distribution adds virtual data (a sum of squares $2b$ and a count of $2a-2$ points) to each component.”
Exercise 17.4: Identifying grains with abnormal grain growth
Solution
(1) $u=\ln4=1.38629$. The standardized distances are $z_1=(1.38629-0.718)/0.282=2.36984$ and $z_2=(1.38629-2.122)/0.255=-2.88512$.
$$ \begin{aligned} \pi_1\Normal(u\mid\mu_1,\sigma_1^{2})&=0.866\times\frac{e^{-2.36984^{2}/2}}{\sqrt{2\pi}\times0.282}\\ &=0.866\times\frac{0.060322}{0.70687}\\ &=0.073902,\\ \pi_2\Normal(u\mid\mu_2,\sigma_2^{2})&=0.134\times\frac{e^{-2.88512^{2}/2}}{\sqrt{2\pi}\times0.255}\\ &=0.134\times\frac{0.015577}{0.63919}\\ &=0.0032656 . \end{aligned} $$$\gamma_2=0.0032656/(0.073902+0.0032656)$ $=0.0423$. A grain with diameter 4 μm is assigned only 4 % responsibility by the component of large grains.
(2) We solve $\ln\bigl[\pi_1\Normal(u\mid\mu_1,\sigma_1^{2})\bigr]=\ln\bigl[\pi_2\Normal(u\mid\mu_2,\sigma_2^{2})\bigr]$, that is,
$$ \ln\frac{\pi_1}{\sigma_1}-\frac{(u-\mu_1)^{2}}{2\sigma_1^{2}}=\ln\frac{\pi_2}{\sigma_2}-\frac{(u-\mu_2)^{2}}{2\sigma_2^{2}} $$($\sqrt{2\pi}$ cancels on both sides). Expanding into the form $Au^{2}+Bu+C=0$ gives
$$ \begin{aligned} A&=\frac{1}{2\sigma_2^{2}}-\frac{1}{2\sigma_1^{2}}\\ &=7.68935-6.28741=1.40194,\\ B&=\frac{\mu_1}{\sigma_1^{2}}-\frac{\mu_2}{\sigma_2^{2}}\\ &=9.02872-32.63360=-23.60488,\\ C&=\frac{\mu_2^{2}}{2\sigma_2^{2}}-\frac{\mu_1^{2}}{2\sigma_1^{2}}+\ln\frac{\pi_1\sigma_2}{\pi_2\sigma_1}\\ &=34.62425-3.24131+1.76540\\ &=33.14834 . \end{aligned} $$By the quadratic formula,
$$ \begin{aligned} u&=\frac{23.60488\pm\sqrt{557.19-185.89}}{2.80388}\\ &=\frac{23.60488\pm19.26921}{2.80388}, \end{aligned} $$that is, $u=1.5463$ and $u=15.291$. The former corresponds to $d=e^{1.5463}=4.69\ \mu\mathrm{m}$; for grains larger than this, the responsibility of component 2 exceeds 0.5. The latter ($d\approx4\times10^{6}\ \mu\mathrm{m}$) is a solution that appears because the tail of component 1, which has the larger variance, wins again far away, and it has no physical meaning (when the variances differ, the boundary is the solution of a quadratic equation, and two of them can appear).
(3) In a converged EM algorithm, $\pi_2=N_2/N$, so $N_2=0.134\times300=40.2$. Of the 45 “large grains” used in the generation, 6 are pulled toward small values, with $u\lt1.546$ ($d\lt4.7\ \mu\mathrm{m}$), and are mixed into the peak of small grains. The Gaussian mixture judges “a value like this looks like the component of small grains,” so these are assigned to component 1. The count obtained from the responsibilities is not the number by origin itself but an estimate seen from the values.
(4) What the mixture model shows is only that “the distribution of the logarithm of the grain size has two peaks.” To call it abnormal grain growth, we need to confirm, through microstructure observation, things such as the shape of the large grains (straight grain boundaries, facets), how the fraction and the diameter of the large grains change with sintering time, the presence of compositional segregation or a second phase, and differences depending on the position of the observed cross section (the diameter seen on a cross section appears smaller than the three-dimensional diameter). A similar second peak can also arise from lumps of agglomerated powder, or from a measurement error in which two grains are counted as one because a grain boundary was overlooked.
Exercise 17.5: Patterns in a two-phase region lie on a line segment
Solution
(1) Since $\bm{y}(f)=\bm{a}+f(\bm{b}-\bm{a})$, we have $\bm{y}(f)-\bm{y}(f')=(f-f')(\bm{b}-\bm{a})$. From the property of the norm $\norm{c\bm{v}}=\abs{c}\norm{\bm{v}}$, we get $\norm{\bm{y}(f)-\bm{y}(f')}=\abs{f-f'}\norm{\bm{a}-\bm{b}}$. The patterns lie on the line segment $\bm{a}\to\bm{b}$ in $\R^{D}$, at positions proportional to $f$.
(2) By (1), the $J$ of k-means is the same as that of k-means on the one-dimensional values $t=f\norm{\bm{a}-\bm{b}}$, and $J$ is $\norm{\bm{a}-\bm{b}}^{2}$ times the sum of squares of $f$. For the five ways of splitting into the smallest $s$ points and the rest, we compute the sum of squares of $f$ (around the mean of each group).
- $s=1$: $\{0\}$ gives 0, and $\{0.2,\dots,1\}$ gives $0.16+0.04+0+0.04+0.16=0.40$ around the mean 0.6. The total is 0.40.
- $s=2$: $\{0,0.2\}$ gives $0.02$, and $\{0.4,\dots,1\}$ gives $0.09+0.01+0.01+0.09=0.20$ around the mean 0.7. The total is 0.22.
- $s=3$: $\{0,0.2,0.4\}$ gives $0.04+0+0.04=0.08$ around the mean 0.2, and the rest gives 0.08 in the same way. The total is 0.16.
- $s=4,5$: by symmetry, 0.22 and 0.40.
The minimum is at $s=3$, with $J=0.16\norm{\bm{a}-\bm{b}}^{2}$. The clusters split into $f\le0.4$ and $f\ge0.6$. Since $x=0.35+0.30f$, $f=0.4$ corresponds to $x=0.47$ and $f=0.6$ to $x=0.53$, so the boundary falls at the middle of the two-phase region, $x\approx0.50$.
(3) There is no phase boundary at $x=0.50$. In a two-phase region the peak positions do not move; only the ratio of the amounts of the two phases changes smoothly. Since k-means can express this continuous change only in the language of “discrete groups,” it creates an artificial boundary at a position that divides the line segment equally. Reading from this that “there is a phase boundary at $x=0.5$” would be an error. To represent a two-phase region correctly, it is better to use a model that expresses each pattern as “a sum, with nonnegative weights, of the end patterns (patterns of the pure phases)” (linear mixing, nonnegative matrix factorization, and so on), together with the physical constraint that the weights change linearly with the composition (the lever rule). Note also that if each pattern is normalized to length 1, the points lie not on a line segment but on a circular arc; however, the order in which they lie does not change, so the conclusion is the same.
Exercise 17.6: BIC and AIC
Solution
(1) $P=3K-1=2,5,8,11$, and $-2\ln\hat{L}=496.34,\ 311.08,\ 299.16,\ 290.90$.
$$ \begin{aligned} \mathrm{BIC}_1&=496.34+2\times5.7038=507.75,\\ \mathrm{BIC}_2&=311.08+5\times5.7038=339.60,\\ \mathrm{BIC}_3&=299.16+8\times5.7038=344.79,\\ \mathrm{BIC}_4&=290.90+11\times5.7038=353.64 . \end{aligned} $$BIC is smallest at $K=2$.
(2) For AIC the penalty is 2 per parameter.
Among $K=1,\dots,4$, AIC is smallest at $K=4$, and it keeps decreasing as $K$ increases. BIC and AIC chose different values of $K$.
(3) The difference is the size of the penalty. BIC imposes $\ln N$ (here 5.70) per parameter, and AIC imposes 2. If $N\ge8$, then $\ln N\gt2$, so BIC tends to choose fewer components. The aims also differ. BIC is an approximation to the marginal likelihood of the model and aims at “identifying the model that generated the data.” AIC estimates the expectation of the log-likelihood of predictions for new data and aims at “a model with good prediction.” In this data set, the additional components at $K=3,4$ are narrow components fitted to a small number of points, with mixing coefficients of about 0.02 and standard deviations of about 0.04, and it is hard to interpret them as groups of grains. Whichever criterion is used, one should check what the added components represent.
Exercise 17.7: Adding components always improves the data fit
Solution
(1) Let the maximum point for $K$ components be $\bm{\theta}^{*}_K=\{\pi_k,\bm{\mu}_k,\bm{\Sigma}_k\}_{k=1}^{K}$. Add to it a component with mixing coefficient $\pi_{K+1}=0$ (its mean and covariance may be anything), and let $\bm{\theta}'$ be the resulting parameters of $K+1$ components. Then for every $\bm{x}$,
$$ \begin{aligned} p(\bm{x}\mid\bm{\theta}')&=\sum_{k=1}^{K}\pi_k\Normal(\bm{x}\mid\bm{\mu}_k,\bm{\Sigma}_k)+0\\ &=p(\bm{x}\mid\bm{\theta}^{*}_K) \end{aligned} $$so the log-likelihood is the same. The maximum for $K+1$ components is the maximum over all parameters of $K+1$ components, including $\bm{\theta}'$, so $\ln\hat{L}_{K+1}\ge\ln p(\bm{X}\mid\bm{\theta}')=\ln\hat{L}_K$. (If $\pi_k\gt0$ is required, set $\pi_{K+1}=\varepsilon$, multiply the other $\pi_k$ by $1-\varepsilon$, and let $\varepsilon\to0$; the log-likelihood then approaches $\ln\hat{L}_K$ arbitrarily closely, so the same conclusion is obtained for the supremum.) Under the same variance floor, the same argument holds if the covariance of the added component is chosen to satisfy the floor.
(2) To the optimal set $\{\bm{\mu}_k\}$ of $K$ representatives, add an arbitrary single point $\bm{\mu}_{K+1}$. If we reassign each point to the nearest of the $K+1$ representatives, the “squared distance to the nearest representative” of each point does not increase, because only the candidates have increased. Therefore $J$ for these $K+1$ representatives is at most $J^{*}_K$, and its minimum $J^{*}_{K+1}$ is also at most $J^{*}_K$. If $K=N$ and all points are distinct, making each point a cluster with itself as the representative gives all distances 0, so $J^{*}_N=0$.
(3) Parts (1) and (2) show that the data fit to the training data (the log-likelihood and $J$) always improves merely by making the model more complex. This is the same structure as in Chapter 6, where the training error kept decreasing as the polynomial degree was raised, and became 0 for a polynomial passing through $N$ points. If $K$ is chosen by the data fit to the training data, the largest $K$ (or $K=N$) is chosen, and the result is an “overfitted” model tuned to the accidental positions of individual points. The number of components must be chosen by a criterion that penalizes complexity (such as BIC), by the log-likelihood on validation data (cross-validation), or by the physical interpretation of the components.
Chapter 18 Continuous Latent Variables — PCA and Low-Dimensional Representations
Exercise 18.1: PCA of a 3-dimensional covariance matrix
Solution
(1) Since the third variable has covariance 0 with the other two, $\bm{S}$ splits into the upper-left $2\times2$ block $\begin{pmatrix}3&1\\1&3\end{pmatrix}$ and the lower-right entry $1$. The characteristic equation of the upper-left block is $(3-\lambda)^{2}-1=0$, and $3-\lambda=\pm1$ gives $\lambda=4,\,2$.
- $\lambda=4$: from $(3-4)v_1+v_2=0$ we get $v_1=v_2$. $\bm{v}_1=\frac{1}{\sqrt2}(1,1,0)^{\tp}$.
- $\lambda=2$: from $(3-2)v_1+v_2=0$ we get $v_2=-v_1$. $\bm{v}_2=\frac{1}{\sqrt2}(-1,1,0)^{\tp}$ (the sign is arbitrary).
- $\lambda=1$: $\bm{v}_3=(0,0,1)^{\tp}$.
Check: $\bm{S}\bm{v}_1=\frac{1}{\sqrt2}(3+1,\,1+3,\,0)^{\tp}=4\bm{v}_1$. The sum of the eigenvalues, $4+2+1=7$, equals $\tr\bm{S}=3+3+1$.
(2) The proportions of variance are $4/7=57.1\ \%$, $2/7=28.6\ \%$, $1/7=14.3\ \%$. The cumulative proportions of variance are $57.1\ \%$, $6/7=85.7\ \%$, $100\ \%$.
(3) By Theorem 18.2 (Eq. (18.6) of Chapter 18), the reconstruction error is the sum of the discarded eigenvalues. For $M=1$ it is $2+1=3$, and for $M=2$ it is $1$.
(4) The covariance matrix with $1/(N-1)$ is $\frac{N}{N-1}\bm{S}=\frac{10}{9}\bm{S}$, so the eigenvectors are the same and the eigenvalues are multiplied by $\frac{10}{9}$, giving $4.444$, $2.222$, $1.111$. The proportions of variance do not change.
Exercise 18.2: The optimal plane passes through the mean
Solution
(1) With $\bm{c}$ fixed, $J$ is a sum of separate sums of squares $\norm{(\bm{x}_n-\bm{c})-\bm{B}\bm{a}_n}^{2}$, one for each $\bm{a}_n$. Differentiating with respect to $\bm{a}_n$ and setting the result to 0 gives
$$ \begin{aligned}&-2\bm{B}^{\tp}\bigl\{(\bm{x}_n-\bm{c})-\bm{B}\bm{a}_n\bigr\}=\bm{0}\\ &\Longrightarrow\ \bm{B}^{\tp}\bm{B}\,\bm{a}_n=\bm{B}^{\tp}(\bm{x}_n-\bm{c}).\end{aligned} $$Since $\bm{B}^{\tp}\bm{B}=\bm{I}_M$, we get $\bm{a}_n=\bm{B}^{\tp}(\bm{x}_n-\bm{c})$ (the coordinates of the orthogonal projection onto the plane).
(2) Substituting, we obtain $\bm{x}_n-\bm{c}-\bm{B}\bm{a}_n$ $=(\bm{I}-\bm{B}\bm{B}^{\tp})(\bm{x}_n-\bm{c})$ $=\bm{P}_{\perp}(\bm{x}_n-\bm{c})$. Since $\bm{P}_{\perp}$ is symmetric and $\bm{P}_{\perp}^{2}=\bm{P}_{\perp}$ (from $\bm{B}\bm{B}^{\tp}\bm{B}\bm{B}^{\tp}=\bm{B}\bm{B}^{\tp}$),
$$ J(\bm{c})=\frac1N\sum_{n}(\bm{x}_n-\bm{c})^{\tp}\bm{P}_{\perp}(\bm{x}_n-\bm{c}). $$Differentiating with respect to $\bm{c}$ gives
$$ \pdiff{J}{\bm{c}}=-\frac2N\sum_{n}\bm{P}_{\perp}(\bm{x}_n-\bm{c})=-2\bm{P}_{\perp}(\bar{\bm{x}}-\bm{c}). $$$J$ is a quadratic function of $\bm{c}$ and its second derivative $2\bm{P}_{\perp}$ is positive semidefinite, so a point where the gradient is 0 is a minimum. The condition is $\bm{P}_{\perp}(\bar{\bm{x}}-\bm{c})=\bm{0}$, and $\bm{c}=\bar{\bm{x}}$ satisfies it. Therefore the plane through the mean is optimal.
(3) The condition $\bm{P}_{\perp}(\bar{\bm{x}}-\bm{c})=\bm{0}$ is equivalent to “$\bar{\bm{x}}-\bm{c}$ lies in the column space of $\bm{B}$,” so every $\bm{c}=\bar{\bm{x}}+\bm{B}\bm{b}$ ($\bm{b}\in\R^{M}$ arbitrary) is optimal. Moving $\bm{c}$ along the plane does not change the plane itself, and the $\bm{a}_n$ absorb the shift ($\bm{a}_n\to\bm{a}_n-\bm{b}$). The choice of the reference point on the plane is free, and PCA chooses $\bm{c}=\bar{\bm{x}}$ (in which case $\sum_n\bm{a}_n=\bm{0}$).
Exercise 18.3: SVD of four points
Solution
(1) The sum of the first column is $4-4+1-1=0$ and the sum of the second column is $2-2-2+2=0$, so the data are centered.
$$ \begin{aligned} (\bm{X}^{\tp}\bm{X})_{11}&=16+16+1+1=34,\\ (\bm{X}^{\tp}\bm{X})_{12}&=8+8-2-2=12,\\ (\bm{X}^{\tp}\bm{X})_{22}&=4+4+4+4=16 . \end{aligned} $$From the characteristic equation $\lambda^{2}-50\lambda+(34\times16-144)$ $=\lambda^{2}-50\lambda+400=0$ we get $\lambda=(50\pm\sqrt{2500-1600})/2$ $=(50\pm30)/2=40,\,10$. The singular values are $s_1=\sqrt{40}=2\sqrt{10}\approx6.325$ and $s_2=\sqrt{10}\approx3.162$.
(2) For $40$, $(34-40)v_1+12v_2=0$ gives $v_2=v_1/2$, so $\bm{v}_1=\frac{1}{\sqrt5}(2,1)^{\tp}$. For $10$, $(34-10)v_1+12v_2=0$ gives $v_2=-2v_1$, so $\bm{v}_2=\frac{1}{\sqrt5}(-1,2)^{\tp}$. The scores $z_{ni}=\bm{v}_i^{\tp}\bm{x}_n$ ($\bm{x}_n$ is the centered row) are
$$ \begin{aligned} z_{n1}&=\tfrac{1}{\sqrt5}(10,\,-10,\,0,\,0)\\&=(2\sqrt5,\,-2\sqrt5,\,0,\,0),\\ z_{n2}&=\tfrac{1}{\sqrt5}(0,\,0,\,-5,\,5)\\&=(0,\,0,\,-\sqrt5,\,\sqrt5). \end{aligned} $$Here $2\sqrt5\approx4.472$ and $\sqrt5\approx2.236$. For example, $z_{11}=(4\times2+2\times1)/\sqrt5=10/\sqrt5$ and $z_{32}=(1\times(-1)+(-2)\times2)/\sqrt5=-5/\sqrt5$. Check: $\sum_nz_{n1}^{2}=20+20=40=s_1^{2}$ and $\sum_nz_{n2}^{2}=5+5=10=s_2^{2}$ (consistent with Eq. (18.10) of Chapter 18, $z_{ni}=s_iU_{ni}$, and with the columns of $\bm{U}$ having length 1).
(3) With $1/N$ ($N=4$): $\lambda_1=40/4=10$ and $\lambda_2=10/4=2.5$. With $1/(N-1)$: $40/3\approx13.33$ and $10/3\approx3.33$. In both cases the proportions of variance are $40/50=0.8$ and $10/50=0.2$.
Exercise 18.4: Peak shifts increase the number of principal components
Solution
(1) Let $g_0(\nu)=g(\nu-\nu_0)$; then $x_n(\nu)=I_n\,g_0(\nu-\delta_n)$. Expanding to first order in $\delta_n$ by Taylor’s theorem,
$$ \begin{aligned}g_0(\nu-\delta_n)&=g_0(\nu)-\delta_n\,g_0'(\nu)\\&\quad+\tfrac12\delta_n^{2}g_0''(\nu)-\cdots\end{aligned} $$so if $\delta_n$ is sufficiently smaller than the peak width, $x_n(\nu)\approx I_n\,g_0(\nu)-I_n\delta_n\,g_0'(\nu)$. Every spectrum is a sum of two functions $g_0$ and $g_0'$, which do not depend on the sample, multiplied by the coefficients $I_n$ and $-I_n\delta_n$. In other words, a spectrum measured at 200 points lies near a 2-dimensional subspace of $\R^{200}$ (spanned by $g_0$ and $g_0'$).
(2) By the product rule, $\diff{}{\nu}\bigl(g_0^{2}\bigr)=2g_0g_0'$, so
$$ \int_{-\infty}^{\infty}g_0g_0'\,\dd\nu=\frac12\Bigl[g_0^{2}\Bigr]_{-\infty}^{\infty}=0 , $$because the peak vanishes at both ends. (For a symmetric $g_0$, $g_0'$ is antisymmetric, so one may also see this as the integrand being an odd function.)
(3) If $I_n=I$ (constant), then $x_n\approx Ig_0-I\delta_ng_0'$ and the mean is $\bar{x}\approx Ig_0-I\bar{\delta}g_0'$, so after centering $x_n-\bar{x}\approx-I(\delta_n-\bar{\delta})\,g_0'$. Everything is a constant multiple of $g_0'$, so there is approximately one principal component (its shape is $g_0'$, a “derivative shape” whose sign differs on the two sides of the peak position). The second-order term $\tfrac12(\delta_n^{2}-\overline{\delta^{2}})g_0''$ produces a small second principal component. Computing under the same conditions with $I_n$ held constant, the eigenvalues were $0.0825$, $0.00061$, …, the first principal component accounted for 99.3 %, and its direction nearly coincided with $g_0'$ ($|\cos|=0.9999$).
(4) If $I_n$ also fluctuates, the centered data become $(I_n-\bar{I})g_0-(I_n\delta_n-\overline{I\delta})g_0'$, which spread in the two directions $g_0$ and $g_0'$. By (2) the two are orthogonal, so the principal components are roughly the direction of $g_0$ (intensity fluctuation) and the direction of $g_0'$ (position fluctuation). A rough guide to the magnitudes of the eigenvalues is $\Var[I_n]\norm{g_0}^{2}$ for the former and $\Var[I_n\delta_n]\norm{g_0'}^{2}$ for the latter; for this sample of 60 spectra these are $0.0249\times7.84=0.195$ and $8.44\times0.0098=0.083$. They agree well with the actual eigenvalues $0.1976$ and $0.0789$, and the directions of the first and second principal components coincide with $g_0$ and $g_0'$ with $|\cos|=0.991$. The third eigenvalue, $0.00039$, is a small component due to the second-order term. Thus even with a single phase, two principal components are needed if the peak moves. The number of principal components is “the number of independently varying factors,” not the number of phases. If one counts phases from the number of principal components in a series of solid solutions, one overestimates the number of phases. One should either analyze after aligning the peak positions (or with a model that has the peak position as a parameter), or judge together with physical information such as the indexing of the diffraction pattern.
Exercise 18.5: The number of components of noisy spectra
Solution
(1) The cumulative proportions of variance are
$$ \begin{aligned} &\frac{1.738}{3.8329}=45.3\ \%,\\ &\frac{1.738+0.2276}{3.8329}=\frac{1.9656}{3.8329}=51.3\ \%,\\ &\frac{1.9656+0.07457}{3.8329}=\frac{2.0402}{3.8329}=53.2\ \%. \end{aligned} $$The eigenvalues from the third onward decrease slowly around $0.07$, so to reach 90 % we must add several tens of principal components (36 for these data). Most of them are directions of noise, and the “90 % rule” makes us take in even the noise as signal.
(2) $D\sigma^{2}/N=200\times0.01/60=0.0333$. The band is
$$ \begin{aligned} \sigma^{2}\frac{(\sqrt{D}-\sqrt{N})^{2}}{N}&=0.01\times\frac{(14.142-7.746)^{2}}{60}\\&=0.0068,\\ \sigma^{2}\frac{(\sqrt{D}+\sqrt{N})^{2}}{N}&=0.01\times\frac{(14.142+7.746)^{2}}{60}\\&=0.0799 . \end{aligned} $$(This is $(0.1/0.02)^{2}=25$ times the band $0.00027$–$0.0032$ for $\sigma=0.02$.) The third eigenvalue $0.07457$ and those after it are smaller than the upper end of the band, $0.0799$, so they lie in the noise range. The second eigenvalue $0.2276$ stands out at about 2.8 times the upper end. Therefore we conclude that the signal has two components.
(3) $\sigma_{\mathrm{ML}}^{2}=1.86728/(200-2)=0.009431$, so $\sigma_{\mathrm{ML}}=0.0971$. This is close to the value $0.100$ used to generate the data (the reason it is slightly smaller is the same as in Example 18.10 (3) of Chapter 18).
Exercise 18.6: The maximum likelihood solution of probabilistic PCA
Solution
(1) $\sigma_{\mathrm{ML}}^{2}=\frac{1}{4-2}(0.6+0.4)=0.5$. Since $\bm{L}_M-\sigma^{2}\bm{I}=\diag(5-0.5,\,2-0.5)$ $=\diag(4.5,\,1.5)$, taking $\bm{Q}=\bm{I}$ we have
$$ \begin{aligned}\bm{W}_{\mathrm{ML}}&=\bigl(\sqrt{4.5}\,\bm{v}_1,\ \sqrt{1.5}\,\bm{v}_2\bigr)\\&\approx\bigl(2.121\,\bm{v}_1,\ 1.225\,\bm{v}_2\bigr)\in\R^{4\times2}.\end{aligned} $$(2) Adding $\bm{W}\bm{W}^{\tp}=4.5\,\bm{v}_1\bm{v}_1^{\tp}+1.5\,\bm{v}_2\bm{v}_2^{\tp}$ and $\sigma^{2}\bm{I}=0.5\sum_{i=1}^{4}\bm{v}_i\bm{v}_i^{\tp}$ gives
$$ \bm{C}=5\,\bm{v}_1\bm{v}_1^{\tp}+2\,\bm{v}_2\bm{v}_2^{\tp}+0.5\,\bm{v}_3\bm{v}_3^{\tp}+0.5\,\bm{v}_4\bm{v}_4^{\tp}. $$The eigenvalues are $5,\,2,\,0.5,\,0.5$. In the first and second directions they agree with the data eigenvalues $5,\,2$, and in the third and fourth directions the data values $0.6,\,0.4$ are replaced by their average $0.5$. The total variance $8=5+2+0.6+0.4$ is preserved.
(3) Since $\bm{W}^{\tp}\bm{W}=\diag(4.5,\,1.5)$ ($\bm{v}_1,\bm{v}_2$ are orthonormal), $\bm{B}=\bm{W}^{\tp}\bm{W}+\sigma^{2}\bm{I}=\diag(5,\,2)$, and the posterior covariance is $\sigma^{2}\bm{B}^{-1}=\diag(0.5/5,\ 0.5/2)$ $=\diag(0.1,\ 0.25)$. The latent variable in the first direction, which has the larger variance, is better determined by the observation.
(4) For the 90° rotation $\bm{Q}=\begin{pmatrix}0&-1\\1&0\end{pmatrix}$, the first column of $\bm{W}\bm{Q}$ $=0\cdot(\sqrt{4.5}\bm{v}_1)+1\cdot(\sqrt{1.5}\bm{v}_2)=\sqrt{1.5}\,\bm{v}_2$ and the second column $=-\sqrt{4.5}\,\bm{v}_1$. The order and signs of the columns have been exchanged, but $\bm{W}\bm{Q}(\bm{W}\bm{Q})^{\tp}=\bm{W}\bm{Q}\bm{Q}^{\tp}\bm{W}^{\tp}=\bm{W}\bm{W}^{\tp}$, so $\bm{C}$ does not change and neither does the likelihood. From the data alone we cannot tell which $\bm{W}$ is the right one.
Exercise 18.7: Reading a t-SNE map of a materials database
Solution
(1) It is not valid. t-SNE adjusts the per-point width $\sigma_i$ by the perplexity, so a cluster that is spread out in the original space and one that is tightly packed are drawn at similar sizes if their neighborhood relations are the same (Example 18.9 of Chapter 18). The size of a cluster on the map is also affected by the number of compounds and by differences in density. Instead: in the original 100-dimensional space, compute and compare the variance of the descriptors of each group (the trace of the covariance matrix) or the mean distance within each group.
(2) One cannot conclude this merely from the fact that they look far apart on the map. The KL divergence of t-SNE hardly penalizes the placement of distant points relative to each other, so distances between clusters do not necessarily reflect the original distances, and they also change with the perplexity and the random-number seed. Instead: in the original space (or in the space after removing noise by PCA), compare the distributions of distances between the perovskite-type oxides and the other oxides. Draw the map several times while changing the seed and the perplexity, and check whether the separation always appears. Compare it with external information such as differences in crystal structure.
(3) It should be avoided. The coordinates of the map are quantities distorted so as to preserve neighborhood relations, they change with the random numbers, and they discard much of the information in the original descriptors. The regression result would then depend on the distortion of the map and on the seed. Instead: regress with the original descriptors (or, if necessary, the PCA scores computed from the training data only) as the input, and evaluate by cross-validation (Chapter 6, Section 6.5).
(4) Standard t-SNE has no mapping that places a new point on the same map. If we add the new point and recompute, the placement of the existing points changes as well. Instead: find nearby known compounds by computing distances in the original descriptor space (or in the PCA space). When we want to overlay it on the map, we limit ourselves to showing the positions of the nearby known points as a rough guide.
To summarize, a t-SNE map is useful as a tool for looking at “which compounds are in the neighborhood of which compound,” but its sizes, distances, and coordinates themselves must not be used for quantitative conclusions.
← Back to Chapter 18, “Continuous Latent Variables — PCA and Low-Dimensional Representations”
Chapter 19 Graphical Models — Factorizing a Joint Distribution with Diagrams
Exercise 19.1: Counting parameters from a graph
Solution
(1) Place one “distribution conditioned on the parents” on each variable. Since $x_1$ and $x_2$ have no parents, the parents of $x_3$ are $x_1,x_2$, and the parent of $x_4$ and $x_5$ is $x_3$,
$$ \begin{aligned} &p(x_1,\dots,x_5)\\ &\quad=p(x_1)\,p(x_2)\,p(x_3\mid x_1,x_2)\\ &\qquad\times p(x_4\mid x_3)\,p(x_5\mid x_3). \end{aligned} $$(2) Let $K_k$ be the number of values. The table of $p(x_k\mid\mathrm{pa}_k)$ has $K_k-1$ free numbers for each of the “number of combinations of parent values” $\prod_{j\in\mathrm{pa}_k}K_j$.
- $x_1$ (3 values, no parents): $3-1=2$.
- $x_2$ (2 values, no parents): $2-1=1$.
- $x_3$ (2 values; the parents $x_1,x_2$ have $3\times2=6$ combinations): $(2-1)\times6=6$.
- $x_4$ (4 values; the parent $x_3$ has 2 values): $(4-1)\times2=6$.
- $x_5$ (2 values; the parent $x_3$ has 2 values): $(2-1)\times2=2$.
The total is $2+1+6+6+2=17$ parameters. If we kept the full table as it is, the number of combinations would be $3\times2\times2\times4\times2=96$, so there would be $96-1=95$ parameters.
(3) $x_4\leftarrow x_3\to x_5$ is a tail-to-tail pattern. When $x_3$ is not observed, $x_4$ and $x_5$ are connected through $x_3$ and are in general not independent ($p(x_4,x_5)=\sum_{x_3}p(x_3)\,p(x_4\mid x_3)\,p(x_5\mid x_3)$ does not split into a product). When $x_3$ is observed, $p(x_4,x_5\mid x_3)=p(x_4\mid x_3)\,p(x_5\mid x_3)$ holds, so they are conditionally independent.
Exercise 19.2: Reading off d-separation
Solution
The paths of the graph are: one between $a$ and $b$, namely $a\to c\leftarrow b$; one between $a$ and $e$, namely $a\to c\leftarrow b\to e$; and one between $a$ and $d$, namely $a\to c\to d$ (there are no other edges leaving $a$). The only descendant of $c$ is $d$.
(1) $a\perp b$: holds. In the path $a\to c\leftarrow b$, $c$ is head-to-head, and neither $c$ nor its descendant $d$ is in the conditioning set, so the path is blocked.
(2) $a\perp b\mid d$: does not hold. $c$ is head-to-head, but its descendant $d$ is in the conditioning set, so the path is open (explaining away).
(3) $a\perp e$: holds. The path $a\to c\leftarrow b\to e$ is blocked because $c$ is head-to-head and not observed.
(4) $a\perp e\mid c$: does not hold. $c$ is head-to-head and observed, so it is open. $b$ is tail-to-tail ($c\leftarrow b\to e$) and not observed, so it is open. Since the whole path is open, they are not d-separated.
(5) $a\perp e\mid\{b,c\}$: holds. The path is open at $c$, but the tail-to-tail $b$ is observed, so the path is blocked.
(6) $a\perp d\mid c$: holds. In the path $a\to c\to d$, $c$ is head-to-tail and observed, so the path is blocked.
(Supplement) If we put arbitrary numbers into the conditional distribution tables and carry out a full enumeration, we can check that in (1), (3), (5), (6) the equality $p(x,y\mid z)=p(x\mid z)\,p(y\mid z)$ holds for all values, whereas in (2) and (4) there are values for which the equality fails.
Exercise 19.3: Finding a conditional distribution with the Markov blanket
Solution
(1) The parent of $x_2$ is $x_1$, its child is $x_3$, and $x_3$ has no other parents. The Markov blanket is $\{x_1,x_3\}$.
(2) In Eq. (19.8) of Chapter 19, the only factors containing $x_2$ are $p(x_2\mid x_1)$ and $p(x_3\mid x_2)$, so
$$ \begin{aligned} &p(x_2\mid x_1,x_3,x_4)\\ &\quad\propto p(x_2\mid x_1=1)\,p(x_3=1\mid x_2). \end{aligned} $$For $x_2=0$: $0.3\times0.8=0.24$; for $x_2=1$: $0.7\times0.3=0.21$. Normalizing,
$$ \begin{aligned} &p(x_2=1\mid x_1=1,x_3=1,x_4=1)\\ &\quad=\frac{0.21}{0.24+0.21}=\frac{0.21}{0.45}\\ &\quad=\frac{7}{15}\approx0.467 . \end{aligned} $$(3) $x_4$ lies outside the blanket. The path $x_2\to x_3\to x_4$ from $x_2$ to $x_4$ is blocked because $x_3$, which is head-to-tail, is observed. In the equation as well, $p(x_4\mid x_3)$ does not contain $x_2$, so it cancels between the denominator and the numerator.
Exercise 19.4: Diagnosing the cause of low density
Solution
For $d=1$, find the joint probability $p(a)\,p(b)\,p(d=1\mid a,b)$ for each $(a,b)$ (with $p(a=0)=0.7$ and $p(b=0)=0.8$).
$$ \begin{aligned} (a,b)=(0,0)&:\ 0.7\times0.8\times0.05=0.028,\\ (1,0)&:\ 0.3\times0.8\times0.7=0.168,\\ (0,1)&:\ 0.7\times0.2\times0.5=0.070,\\ (1,1)&:\ 0.3\times0.2\times0.9=0.054. \end{aligned} $$The sum is $p(d=1)=0.320$.
(1) Add the two rows with $a=1$ and the two rows with $b=1$ separately, and divide by $p(d=1)$.
$$ \begin{aligned} p(a=1\mid d=1)&=\frac{0.168+0.054}{0.320}\\ &=\frac{0.222}{0.320}\approx0.694,\\ p(b=1\mid d=1)&=\frac{0.070+0.054}{0.320}\\ &=\frac{0.124}{0.320}\approx0.388. \end{aligned} $$(2) Use only the two rows with $b=1$.
$$ \begin{aligned} p(a=1\mid d=1,b=1)&=\frac{0.054}{0.070+0.054}\\ &=\frac{0.054}{0.124}\approx0.435 . \end{aligned} $$(3) Use only the two rows with $b=0$.
$$ \begin{aligned} p(a=1\mid d=1,b=0)&=\frac{0.168}{0.028+0.168}\\ &=\frac{0.168}{0.196}\approx0.857 . \end{aligned} $$(4) $a\to d\leftarrow b$ is head-to-head, and because we observed the low density $d$, $a$ and $b$ became dependent. Once we learn that the raw powder was coarse, the low density is “already explained by that,” so the probability that the temperature was too low drops from 0.694 to 0.435 (explaining away). If the raw powder is normal, the temperature remains as the explanation, so the probability rises to 0.857.
Which one to check first is decided by cost and the magnitude of information. In this setup, the probability of insufficient temperature is high, 0.69, for a low-density sample, and the furnace temperature record can often be checked more easily than a measurement of the particle size distribution, so it is reasonable to look at the temperature record first. If the temperature turns out to have been low, the same explaining-away effect lowers the probability that the raw powder was coarse ($p(b=1\mid d=1,a=1)$ $=0.054/0.222\approx0.243$). However, this is a conclusion under the numbers we set and under the graph’s assumption that “there are only two causes.”
Exercise 19.5: A triangular antiferromagnet and frustration
Solution
(1) For $(+,+,+)$ and $(-,-,-)$, all three edges have $s_is_j=+1$, so $E=3J$. In the other six states, two spins are aligned and one points the opposite way, so one edge is $+1$ and two edges are $-1$, giving $E=J(1-1-1)=-J$. There are six states with the lowest energy $-J$.
(2) The weight is $e^{-\beta E}$, and since $e^{\beta J}=2$, a state with $E=3J$ has weight $e^{-3\beta J}=1/8$, and a state with $E=-J$ has weight $e^{\beta J}=2$.
$$ Z=2\times\frac18+6\times2=0.25+12=12.25 . $$The probability that all three are aligned is $0.25/12.25=1/49\approx0.020$.
(3) In the two states with $E=3J$, $s_1s_2=+1$. Among the six states with $E=-J$, $s_1=s_2$ in two states (only $s_3$ is reversed), and $s_1\ne s_2$ in four states.
$$ \begin{aligned} \langle s_1s_2\rangle&=\frac{1}{12.25}\Bigl[2\times\tfrac18\times(+1)\\ &\qquad+2\times2\times(+1)\\ &\qquad+4\times2\times(-1)\Bigr]\\ &=\frac{0.25+4-8}{12.25}\approx-0.306 . \end{aligned} $$(4) The product of the three edges is $(s_1s_2)(s_2s_3)(s_3s_1)=(s_1s_2s_3)^{2}=+1$, so the number of edges equal to $-1$ is even (0 or 2). It is impossible to make all three edges antiparallel ($-1$), and however we arrange the spins, at least one edge is in the higher-energy “aligned” state. This is called frustration. In an antiferromagnet on a triangular lattice, whose unit is the triangle, this situation arises in every triangle, and the number of lowest-energy configurations becomes very large. For an Ising-type triangular-lattice antiferromagnet with nearest-neighbor interactions only, that number grows exponentially with the number of lattice sites $n$. According to the exact solution of Wannier (1950, including the 1973 erratum), even at temperature 0 an entropy (residual entropy) of about $0.323\,k_{\mathrm B}$ per lattice site remains, and the number of ground states is roughly $e^{0.323n}\approx1.38^{n}$. For this reason, the configuration is not fixed to a single one even when the temperature is lowered.
Exercise 19.6: Message passing on a chain
Solution
Write the values in the order $(x=0,\ x=1)$. $\psi$ is the symmetric $2\times2$ table $\begin{pmatrix}2&1\\1&2\end{pmatrix}$.
(1) Let $m_{\to}(x_1)=\phi=(1,\ 3)$ and compute $m_{\to}(x_{k})=\sum_{x_{k-1}}m_{\to}(x_{k-1})\,\psi(x_{k-1},x_k)$ in turn.
$$ \begin{aligned} m_{\to}(x_2)&=(1\times2+3\times1,\ 1\times1+3\times2)\\ &=(5,\ 7),\\ m_{\to}(x_3)&=(5\times2+7\times1,\ 5\times1+7\times2)\\ &=(17,\ 19),\\ m_{\to}(x_4)&=(17\times2+19\times1,\ 17\times1+19\times2)\\ &=(53,\ 55). \end{aligned} $$Since $x_4$ is the right end of the chain, $m_{\leftarrow}(x_4)=1$, so $Z=53+55=108$ and $p(x_4)=(53/108,\ 55/108)\approx(0.491,\ 0.509)$.
(2) Going backward, $m_{\leftarrow}(x_4)=(1,1)$, $m_{\leftarrow}(x_3)=(2+1,\ 1+2)=(3,\ 3)$, and $m_{\leftarrow}(x_2)=(2\times3+1\times3,$ $1\times3+2\times3)=(9,\ 9)$.
$$ \begin{aligned} p(x_2)&=\frac{m_{\to}(x_2)\,m_{\leftarrow}(x_2)}{Z}\\ &=\frac{(5\times9,\ 7\times9)}{108}\\ &=\Bigl(\frac{45}{108},\ \frac{63}{108}\Bigr)\approx(0.417,\ 0.583). \end{aligned} $$Indeed $45+63=108$ agrees with $Z$.
(3) In full enumeration, each of the 16 terms is a product of four factors $\phi\,\psi\,\psi\,\psi$, so it takes three multiplications each, 48 multiplications in total, and 15 additions (just to find $Z$). In message passing, one message (two values) takes $2\times2=4$ multiplications and 2 additions, so the three forward messages take 12 multiplications.
(4) Finding one marginal distribution by full enumeration requires, for each value of $x_k$, a sum over the remaining 49 variables, that is $3^{49}\approx2.4\times10^{23}$ terms, and $3^{50}\approx7.2\times10^{23}$ terms overall. In message passing, each of the 49 forward and 49 backward messages needs only $K^{2}=9$ multiplications, so all the marginal distributions are obtained with $2\times49\times9=882$ multiplications.
Exercise 19.7: Direction of arrows and equivalent graphs
Solution
(1) Factorization $x\to y$: $p(x=0)=0.3+0.1=0.4$, $p(x=1)=0.6$, $p(y=1\mid x=0)=0.1/0.4=0.25$, $p(y=1\mid x=1)=0.4/0.6=2/3$. Factorization $y\to x$: $p(y=0)=0.3+0.2=0.5$, $p(y=1)=0.5$, $p(x=1\mid y=0)=0.2/0.5=0.4$, $p(x=1\mid y=1)=0.4/0.5=0.8$. For example, $(x,y)=(0,0)$ gives $0.4\times0.75=0.3$ and $0.5\times0.6=0.3$, which agree, and the remaining three cells agree in the same way ($(0,1)$: $0.4\times0.25=0.5\times0.2=0.1$; $(1,0)$: $0.6\times\tfrac13=0.5\times0.4=0.2$; $(1,1)$: $0.6\times\tfrac23=0.5\times0.8=0.4$). Both graphs represent the same joint distribution.
(2) Applying the product rule $p(a)\,p(c\mid a)=p(a,c)=p(c)\,p(a\mid c)$ to the factorization for $a\to c\to b$ gives
$$ p(a)\,p(c\mid a)\,p(b\mid c)=p(c)\,p(a\mid c)\,p(b\mid c) $$and the right-hand side is the factorization for $a\leftarrow c\to b$. The reverse transformation can be done with the same equation, so every distribution that can be written in one form can also be written in the other. The two graphs represent the same set of distributions.
(3) It cannot be decided. As in (1), the joint distribution of two variables can be factorized in the same way as $g\to h$ or $h\to g$, so the direction cannot be distinguished from the distribution of the observed data alone. To decide the direction, information from outside the data is needed. For example, we can look at whether hardness changes in an experiment that varies the grain size while holding the other conditions (porosity, phase fractions, impurities) fixed (changing only the grain size through the heat-treatment temperature and time, and assigning samples at random). Alternatively, we can adopt as assumptions the time order that hardness is a quantity measured after the microstructure has formed, and mechanistic knowledge that grain boundaries impede dislocation motion. However, the latter is an assumption, and we also need to check that there is no confounder (such as porosity) that changes at the same time.
Exercise 19.8: Finding the most probable tuple with max-sum
Solution
(1) Let $\psi_{1,2}=p(x_1)\,p(x_2\mid x_1)$ and $\psi_{2,3}=p(x_3\mid x_2)$, and compute the logarithmic values $\omega$ forward, starting from the front. First, $\omega(x_2)=\max_{x_1}\ln\bigl[p(x_1)\,p(x_2\mid x_1)\bigr]$.
$$ \begin{aligned} \omega(x_2=0)&=\max(\ln0.54,\ \ln0.12)\\ &=\max(-0.616,\ -2.120)\\ &=-0.616\quad(x_1=0),\\ \omega(x_2=1)&=\max(\ln0.06,\ \ln0.28)\\ &=\max(-2.813,\ -1.273)\\ &=-1.273\quad(x_1=1). \end{aligned} $$Here $0.54=0.6\times0.9$, $0.12=0.4\times0.3$, $0.06=0.6\times0.1$, and $0.28=0.4\times0.7$. Next, $\omega(x_3)=\max_{x_2}\bigl[\ln p(x_3\mid x_2)+\omega(x_2)\bigr]$.
$$ \begin{aligned} \omega(x_3=0)&=\max(\ln0.7-0.616,\\ &\qquad\ \ \ln0.1-1.273)\\ &=\max(-0.973,\ -3.576)\\ &=-0.973\quad(x_2=0),\\ \omega(x_3=1)&=\max(\ln0.3-0.616,\\ &\qquad\ \ \ln0.9-1.273)\\ &=\max(-1.820,\ -1.378)\\ &=-1.378\quad(x_2=1). \end{aligned} $$The maximum is $\omega(x_3=0)=-0.973$, so $x_3^{*}=0$. Following the backpointers, $x_2^{*}=0$ and $x_1^{*}=0$. The most probable tuple is $(0,0,0)$, with probability $e^{-0.973}\approx0.378=0.6\times0.9\times0.7$.
(2) The marginal distributions are $p(x_1=1)=0.4$, $p(x_2=1)=0.6\times0.1+0.4\times0.7=0.34$, and $p(x_3=1)=0.66\times0.3+0.34\times0.9$ $=0.198+0.306=0.504$. Lining up the more probable value of each gives $(0,0,1)$, whose probability is $0.6\times0.9\times0.3=0.162$. Looking at $x_3$ alone, 1 is slightly more probable, but that is the result of adding up the probabilities of the tuples passing through $x_2=1$; among the tuples with $x_2=0$, $x_3=0$ is much more probable. The most probable tuple is $(0,0,0)$ (0.378), which is more than twice as probable as $(0,0,1)$.
← Back to Chapter 19, “Graphical Models — Factorizing a Joint Distribution with Diagrams”
Chapter 20 Approximate Inference — Approximating Intractable Integrals
Exercise 20.1: Laplace approximation of the posterior distribution of a count rate
Solution
(1) The likelihood of the five counts $c_1,\dots,c_5$ is $\prod_n\dfrac{\lambda^{c_n}e^{-\lambda}}{c_n!}\propto\lambda^{\sum_nc_n}e^{-5\lambda}$ $=\lambda^{12}e^{-5\lambda}$ (the sum of the counts is $2+4+1+3+2=12$). Multiplying by the prior distribution $\mathrm{Gam}(\lambda\mid1,0.2)\propto\lambda^{0}e^{-0.2\lambda}$ gives
$$ p(\lambda\mid\data)\propto\lambda^{12}e^{-5.2\lambda}=\lambda^{13-1}e^{-5.2\lambda}, $$which is a gamma distribution with shape $a=13$ and rate $b=5.2\ \mathrm{s}$.
(2) $\ln\tilde{p}(\lambda)$ $=12\ln\lambda-5.2\lambda$. Differentiating with $\diff{}{\lambda}$: $12/\lambda-5.2=0$ gives $\lambda^{*}$ $=12/5.2$ $=2.308\ \mathrm{s^{-1}}$. Since $-\dfrac{\dd^{2}}{\dd\lambda^{2}}\ln\tilde{p}$ $=12/\lambda^{2}$,
$$ \Lambda=\frac{12}{(12/5.2)^{2}}=\frac{5.2^{2}}{12}=2.253\ \mathrm{s^{2}}. $$The variance is $1/\Lambda=0.444\ \mathrm{s^{-2}}$, the standard deviation is $0.666\ \mathrm{s^{-1}}$, and the 95 % interval is $2.308\pm1.96\times0.666$ $=[1.00,\ 3.61]\ \mathrm{s^{-1}}$. The true mean is $13/5.2=2.5$, and the variance is $13/5.2^{2}=0.481$ (standard deviation 0.693), so the approximation places the center 0.19 too far to the left and its width is also somewhat too narrow. (The probability that it puts on $\lambda\lt0$ is $\Phi(-2.308/0.666)\approx3\times10^{-4}$, which is small.)
(3) With $\lambda=e^{u}$ and $\dd\lambda/\dd u=\lambda$, the unnormalized density of $u$ is $\lambda^{12}e^{-5.2\lambda}\times\lambda$ $=e^{13u-5.2e^{u}}$. Differentiating with $\diff{}{u}$: $13-5.2e^{u}=0$ gives $\lambda=e^{u^{*}}=13/5.2=2.5$. Since $-\dfrac{\dd^{2}}{\dd u^{2}}$ $=5.2e^{u}$ $=13$, we have $\Lambda_u=13$, and the standard deviation of $u$ is $1/\sqrt{13}=0.277$. Transforming the 95 % interval $\ln2.5\pm1.96\times0.277$ of $u$ back to $\lambda$ gives
$$ \bigl[2.5\,e^{-0.544},\ 2.5\,e^{0.544}\bigr]=[1.45,\ 4.31]\ \mathrm{s^{-1}}. $$Compared with the true interval $[1.33,\ 4.03]$, the approximation $[1.00,\ 3.61]$ in $\lambda$ is lower by 0.3–0.4 at both ends, whereas the approximation in the logarithm is higher by 0.1–0.3. The approximation in the logarithm can represent the long right tail as an asymmetric interval, so its deviation is smaller. For a positive quantity such as a count rate, it is better to approximate in the logarithm.
Exercise 20.2: Laplace approximation expanded in the logit
Solution
(1) The derivative of $x=\sigma(u)=1/(1+e^{-u})$ is $\dd x/\dd u=x(1-x)$. In a change of variables the density is multiplied by the Jacobian determinant $\abs{\dd x/\dd u}$, so
$$ \begin{aligned} \tilde{p}_u(u)&=x^{a-1}(1-x)^{b-1}\cdot x(1-x)\\ &=x^{a}(1-x)^{b}. \end{aligned} $$Since $\int\tilde{p}_u\,\dd u$ $=\int_0^1x^{a-1}(1-x)^{b-1}\,\dd x$ $=B(a,b)$, the normalization constant is $Z=B(a,b)$, the same as when written in terms of $x$.
(2) $\ln\tilde{p}_u$ $=a\ln x+b\ln(1-x)$. We use the chain rule $\diff{}{u}=x(1-x)\diff{}{x}$:
$$ \begin{aligned} \diff{\ln\tilde{p}_u}{u}&=x(1-x)\Bigl(\frac ax-\frac{b}{1-x}\Bigr)\\ &=a(1-x)-bx=a-(a+b)x . \end{aligned} $$Setting this to 0 gives $x^{*}=a/(a+b)$ and $u^{*}$ $=\ln\dfrac{x^{*}}{1-x^{*}}$ $=\ln\dfrac ab$. Differentiating once more with respect to $u$ gives $-(a+b)\,x(1-x)$, so
$$ \Lambda_u=(a+b)\,\frac{a}{a+b}\,\frac{b}{a+b}=\frac{ab}{a+b}. $$(3) For $a=3$ and $b=9$: $x^{*}=0.25$, $u^{*}=\ln(1/3)=-1.0986$, $\Lambda_u=27/12=2.25$.
$$ \begin{aligned} \ln Z&\approx3\ln0.25+9\ln0.75\\ &\quad+\tfrac12\ln\frac{2\pi}{2.25}\\ &=-4.1589-2.5891+0.5135\\ &=-6.2345 . \end{aligned} $$The difference from the true value $-6.2046$ is $-0.030$, which is smaller than the difference $+0.052$ of the approximation in $x$. Note, however, that the mean of the distribution obtained by transforming the logit approximation back to $x$ is 0.268 (true value 0.25), so the mean does not necessarily improve. Which variable is good depends on which quantity we want to approximate.
Exercise 20.3: Deriving the ELBO from Jensen’s inequality
Solution
(1) On the range where $q(\bm{\theta})\gt0$, we can write $p(\data)$ $=\int p(\data,\bm{\theta})\,\dd\bm{\theta}$ $=\int q(\bm{\theta})\dfrac{p(\data,\bm{\theta})}{q(\bm{\theta})}\,\dd\bm{\theta}$ $=\Ex_q[X]$, where $X\equiv p(\data,\bm{\theta})/q(\bm{\theta})$. (If there is a range where $p(\data,\bm{\theta})\gt0$ but $q=0$, the integral is missing that part and $\Ex_q[X]\le p(\data)$, but the direction of the inequality does not change.) Since $\ln$ is a concave function, Jensen’s inequality $\ln\Ex_q[X]\ge\Ex_q[\ln X]$ holds, and
$$ \begin{aligned} \ln p(\data)&\ge\ln\Ex_q[X]\\ &\ge\Ex_q\!\left[\ln\frac{p(\data,\bm{\theta})}{q(\bm{\theta})}\right]=\ELBO(q). \end{aligned} $$(2) Since $\ln$ is strictly concave, equality in Jensen’s inequality holds only when $X$ is almost surely a constant $c$ under $q$. Integrating $p(\data,\bm{\theta})$ $=c\,q(\bm{\theta})$ over $\bm{\theta}$ gives $p(\data)=c$ (when the support of $q$ covers the support of the posterior distribution). Hence $q(\bm{\theta})$ $=p(\data,\bm{\theta})/p(\data)$ $=p(\bm{\theta}\mid\data)$.
(3) Jensen’s inequality tells us only that the ELBO is a lower bound and the condition for equality. The derivation in Section 20.3 shows that the difference $\ln p(\data)-\ELBO(q)$ is exactly $\KL(q\,\|\,p(\bm{\theta}\mid\data))$. For this reason we can say that “maximizing the ELBO” and “minimizing the KL divergence to the posterior distribution” are the same problem, and the properties of the approximation (it concentrates on a peak and its variance tends to be small) can be explained from the properties of the KL divergence.
Exercise 20.4: Mean-field approximation and the product of marginal distributions
Solution
Let $p=\Normal(\bm{0},\bm{\Sigma})$ with $\bm{\Sigma}$ $=\begin{pmatrix}1&\rho\\\rho&1\end{pmatrix}$, $\abs{\bm{\Sigma}}=1-\rho^{2}$, and $\bm{\Sigma}^{-1}$ $=\dfrac{1}{1-\rho^{2}}\begin{pmatrix}1&-\rho\\-\rho&1\end{pmatrix}$. By Section 20.6, $q^{*}$ $=\Normal(\bm{0},(1-\rho^{2})\bm{I})$, and by Section 20.7, $q^{\dagger}$ $=\Normal(\bm{0},\bm{I})$ (the variance of each marginal distribution is 1). Since all the means are $\bm{0}$, the two-dimensional KL formula is $\KL(\Normal_0\,\|\,\Normal_1)$ $=\tfrac12\bigl[\tr(\bm{\Sigma}_1^{-1}\bm{\Sigma}_0)-2+\ln(\abs{\bm{\Sigma}_1}/\abs{\bm{\Sigma}_0})\bigr]$.
(1) $\KL(q^{*}\,\|\,p)$ is $-\tfrac12\ln(1-\rho^{2})$ by Example 20.7 (3). For $\KL(p\,\|\,q^{\dagger})$, let $\bm{\Sigma}_0=\bm{\Sigma}$ and $\bm{\Sigma}_1=\bm{I}$. Then $\tr(\bm{\Sigma})=2$ and $\ln(1/\abs{\bm{\Sigma}})$ $=-\ln(1-\rho^{2})$, so
$$ \begin{aligned} \KL(p\,\|\,q^{\dagger})&=\tfrac12\bigl[2-2-\ln(1-\rho^{2})\bigr]\\ &=-\tfrac12\ln(1-\rho^{2}). \end{aligned} $$$\KL(p(\theta_1,\theta_2)\,\|\,p(\theta_1)p(\theta_2))$ is precisely the definition of the mutual information $I[\theta_1;\theta_2]$ (Chapter 5, Section 5.7).
(2) For $\KL(q^{\dagger}\,\|\,p)$: $\bm{\Sigma}_0=\bm{I}$ and $\bm{\Sigma}_1=\bm{\Sigma}$. We have $\tr(\bm{\Sigma}^{-1})$ $=2/(1-\rho^{2})$ and $\ln\abs{\bm{\Sigma}}$ $=\ln(1-\rho^{2})$. For $\KL(p\,\|\,q^{*})$: $\bm{\Sigma}_0=\bm{\Sigma}$ and $\bm{\Sigma}_1$ $=(1-\rho^{2})\bm{I}$. We have $\tr(\bm{\Sigma}_1^{-1}\bm{\Sigma})$ $=2/(1-\rho^{2})$ and $\ln\bigl[(1-\rho^{2})^{2}/(1-\rho^{2})\bigr]$ $=\ln(1-\rho^{2})$. Both are equal to
$$ \tfrac12\Bigl[\frac{2}{1-\rho^{2}}-2+\ln(1-\rho^{2})\Bigr]. $$For $\rho=0.9$, $1-\rho^{2}=0.19$, so the value in (1) is $-\tfrac12\ln0.19=0.830$ and the value in (2) is $\tfrac12(10.526-2-1.661)$ $=3.433$.
(3) As error bars for the individual parameters, $q^{\dagger}$ gives the correct standard deviation 1, whereas $q^{*}$ shrinks it to $\sqrt{0.19}=0.44$, less than half. If the reported error bars are too narrow, we conclude that values that actually cannot be distinguished are “distinguishable,” so the defect of $q^{*}$ is more serious (overconfidence). However, neither can represent the correlation, so both get the uncertainty of combinations such as sums and differences wrong. For example, the true variance of $\theta_1+\theta_2$ is $2(1+\rho)=3.8$, but it is $0.38$ under $q^{*}$ and 2 under $q^{\dagger}$.
Exercise 20.5: The “phase transition” shown by the mean-field approximation for two spins
Solution
(1) $g(m)=\tanh(\beta Jm)$ is an odd function through $m=0$; for $m\gt0$ it is concave (bulges upward) and approaches 1. Its slope at the origin is $\beta J$. If $\beta J\le1$, then $g(m)\lt m$ for all $m\gt0$, so the only solution is $m=0$. If $\beta J\gt1$, then $g(m)\gt m$ near the origin and $g(m)\lt m$ for large $m$, so a positive solution (and a symmetric negative solution) appears where they cross in between. The condition is $\beta J\gt1$.
(2) Iterating $m=\tanh(1.5m)$ from $m=0.5$ gives $0.635,\ 0.741,\ 0.805,\dots$, which increases and converges to $m=0.8586$. Then $\beta\Ex_q[E]$ $=-1.5\,m^{2}$ $=-1.1057$. For the entropy, from $\tfrac{1+m}{2}=0.9293$ and $\tfrac{1-m}{2}=0.0707$, the entropy per spin is $0.9293\times0.0733+0.0707\times2.6493$ $=0.2555$, and for two spins it is $0.5110$. Hence $\beta A[q]$ $=-1.1057-0.5110$ $=-1.6167$. For the solution $m=0$, $\Ex_q[E]=0$ and the entropy is $2\ln2$, so $\beta A[q]=-1.3863$. Exactly, $Z$ $=2e^{1.5}+2e^{-1.5}$ $=8.96338+0.44626$ $=9.40964$, and $\beta A=-\ln Z=-2.2417$. Both solutions satisfy $\beta A[q]\ge\beta A$, and the solution with $m\ne0$ has the lower free energy (the larger ELBO).
(3) For $h=0$, $E$ is unchanged under flipping all the spins, $s_i\to-s_i$, so $p(s_1,s_2)=p(-s_1,-s_2)$ and $\Ex[s_1]=0$. A system of a finite number of spins has no spontaneous magnetization. Because the mean-field approximation assumes independence, $q(s_1,s_2)=q_1(s_1)q_2(s_2)$, it cannot represent as a correlation the correlation that “the two spins tend to align” (exactly, $\Ex[s_1s_2]$ $=(2e^{1.5}-2e^{-1.5})/Z$ $=0.905$). Instead, it reduces the KL divergence by biasing both spins in the same direction ($\Ex_q[s_1s_2]=m^{2}=0.737$). This is the property of “concentrating on one peak” described in Section 20.7; it is an artifact of the approximation, not a physical phase transition. In an infinitely large lattice, the phase transition predicted by mean-field theory can actually exist (although the value of the critical temperature is off), but confirming it requires methods beyond the mean-field approximation (Chapter 27).
Exercise 20.6: Reparameterization and the score function estimator
Solution
(1) $\Ex_q\Bigl[f\,\pdiff{\ln q}{\mu}\Bigr]$ $=\int f(\theta)\,q(\theta)\,\dfrac{1}{q(\theta)}\pdiff{q(\theta)}{\mu}\,\dd\theta$ $=\int f(\theta)\pdiff{q(\theta)}{\mu}\,\dd\theta$ $=\pdiff{}{\mu}\int f(\theta)q(\theta)\,\dd\theta$ (when differentiation and integration can be interchanged). Hence the estimator is unbiased.
(2) Since $\Ex_q[\theta]=\mu$, the true value is $\partial\mu/\partial\mu=1$. (a) Since $f'(\theta)=1$ and $\partial\theta/\partial\mu=1$, the estimator is always 1, with variance 0. (b) $\ln q$ $=-\tfrac12\ln(2\pi\sigma^{2})-(\theta-\mu)^{2}/(2\sigma^{2})$, and $\partial\ln q/\partial\mu$ $=(\theta-\mu)/\sigma^{2}$. For $\mu=0$ and $\sigma=1$, the estimator is $\theta\cdot\theta$ $=\epsilon^{2}$, with mean $\Ex[\epsilon^{2}]=1$ (unbiased) and variance $\Ex[\epsilon^{4}]-1=3-1=2$.
(3) The true value is $\partial\mu/\partial\sigma=0$. (a) Since $\partial\theta/\partial\sigma$ $=\epsilon$, the estimator is $\epsilon$, with mean 0 and variance 1. (b) Since $\partial\ln q/\partial\sigma$ $=-1/\sigma+(\theta-\mu)^{2}/\sigma^{3}$, the estimator is $\epsilon(\epsilon^{2}-1)$ $=\epsilon^{3}-\epsilon$. The mean is $\Ex[\epsilon^{3}]-\Ex[\epsilon]$ $=0$, and the variance is $\Ex[(\epsilon^{3}-\epsilon)^{2}]$ $=\Ex[\epsilon^{6}]-2\Ex[\epsilon^{4}]+\Ex[\epsilon^{2}]$ $=15-6+1$ $=10$. The reparameterization estimator has 1/10 the variance. The score function estimator has the advantage that it does not need the derivative of $f$ (it can also be used for discrete variables), but its variance is large, so in practice it is used in combination with techniques for reducing the variance.
Exercise 20.7: Posterior distribution of the spread of peak positions
Solution
(1) $\ln\tilde{p}(\sigma_{\mathrm p})$ $=-(N+1)\ln\sigma_{\mathrm p}-\dfrac{S}{2\sigma_{\mathrm p}^{2}}$. Setting the derivative $-\dfrac{N+1}{\sigma_{\mathrm p}}+\dfrac{S}{\sigma_{\mathrm p}^{3}}$ $=0$ gives $\sigma_{\mathrm p}^{*2}$ $=\dfrac{S}{N+1}$ $=\dfrac{0.0032}{9}$ $=3.556\times10^{-4}$ and $\sigma_{\mathrm p}^{*}$ $=0.01886\ \mathrm{deg}$. The second derivative is $\dfrac{N+1}{\sigma_{\mathrm p}^{2}}-\dfrac{3S}{\sigma_{\mathrm p}^{4}}$, and at the mode, substituting $S$ $=(N+1)\sigma_{\mathrm p}^{*2}$, it becomes $-\dfrac{2(N+1)}{\sigma_{\mathrm p}^{*2}}$. Therefore
$$ \begin{aligned} \Lambda&=\frac{2(N+1)}{\sigma_{\mathrm p}^{*2}}=\frac{18}{3.556\times10^{-4}}\\ &=5.06\times10^{4}\ \mathrm{deg^{-2}}, \end{aligned} $$the standard deviation is $1/\sqrt{\Lambda}$ $=0.00444\ \mathrm{deg}$, and the 95 % interval is $0.01886\pm0.00871$ $=[0.0101,\ 0.0276]\ \mathrm{deg}$.
(2) $\ln\tilde{p}_v$ $=-Nv-\dfrac{S}{2}e^{-2v}$. Setting the derivative $-N+Se^{-2v}=0$ gives $\sigma_{\mathrm p}^{2}$ $=e^{2v^{*}}$ $=S/N$ $=4\times10^{-4}$ and $\sigma_{\mathrm p}$ $=0.0200\ \mathrm{deg}$. The second derivative is $-2Se^{-2v}=-2N$, so $\Lambda_v=2N=16$, and the standard deviation of $v$ is 0.25. Transforming back to $\sigma_{\mathrm p}$, $0.0200\,e^{\pm1.96\times0.25}$ $=0.0200\,e^{\pm0.49}$ gives $[0.0123,\ 0.0326]\ \mathrm{deg}$.
(3) Compared with the exact interval $[0.0135,\ 0.0383]$, the approximation in $\sigma_{\mathrm p}$ underestimates the upper end by as much as 0.011 (ignoring the long right tail), and the approximation in the logarithm underestimates it by 0.006. The approximation in the logarithm is better. The posterior distribution drops sharply to 0 as $\sigma_{\mathrm p}\to0$ and has an asymmetric shape with a long tail on the large side. Transforming to $\ln\sigma_{\mathrm p}$ moves the wall at 0 to $-\infty$ and makes the distribution closer to symmetric, so the approximation by a Gaussian distribution fits more easily. With fewer measurements this difference becomes larger (for example, for $N=2$ the Laplace approximation in $\sigma_{\mathrm p}$ puts a probability of 0.7 % on negative values).
Exercise 20.8: Choosing an approximation method
Solution
(1) $M=6$. Laplace approximation: the Hessian matrix requires $2M^{2}+1=73$ evaluations (about 73 minutes). If the optimization takes several hundred evaluations, that is several hours per mode, and about half a day for the two modes. Variational inference: if the reparameterized gradient is estimated with a few samples and several thousand updates are performed, it takes $10^{3}$–$10^{4}$ evaluations (when the gradient is obtained by automatic differentiation), or about 1–7 days. The family with correlations has $6+21=27$ variational parameters, so more updates are needed for convergence. MCMC: $10^{5}$ minutes $\approx69$ days.
(2) Mean-field variational inference: for a pair with correlation coefficient 0.95, the standard deviation of each parameter can shrink by a factor of $\sqrt{1-0.95^{2}}=0.31$ (Eq. (20.9) and the two-dimensional Gaussian example in Section 20.6). Moreover, it concentrates on only one of the modes, so it ignores the probability of the other mode. The error bars can be too narrow by a factor of three or more. Variational inference and Laplace approximation with a correlated Gaussian: they can represent the correlation, so the width within one mode is roughly correct, but they still look at only one mode and ignore the asymmetric tails. The Laplace approximation is centered at the mode. MCMC: given enough time the bias becomes small, but if there is a low-probability valley between the two modes, the chain does not cross the valley, and it may appear to have “converged” while seeing only one of the modes (Chapter 21).
(3) An example of a procedure: ① Find the two modes $\bm{\theta}_1,\bm{\theta}_2$ by many optimization runs from different starting points. ② Convert positive quantities (such as length scales) to logarithms before treating them. ③ Apply the Laplace approximation at each mode, obtain the approximate marginal likelihood of each mode, $Z_k\approx p(\data,\bm{\theta}_k)(2\pi)^{M/2}\abs{\bm{\Lambda}_k}^{-1/2}$, by Eq. (20.4), and mix the two Gaussian distributions with weights $Z_k/\sum_jZ_j$. ④ Derive the error bars from $\bm{\Lambda}_k^{-1}$, which includes the correlations, and do not use the mean-field error bars. ⑤ As far as the computation allows, run a short MCMC from each mode, or build a Gaussian process surrogate model of $\ln p$ (Chapter 12), to check the distortion of the tails of the Gaussian approximation. ⑥ In the report, state clearly which approximation was used and which modes were included.
← Back to Chapter 20, “Approximate Inference — Approximating Intractable Integrals”
Chapter 21 Sampling Methods — Integrating with Random Numbers
Exercise 21.1: The integral of the exponential function and a symmetric variable
Solution
(1) $I=\int_0^1e^{u}\,\dd u=e-1\approx1.71828$. The expectation of the square is $\Ex[f^{2}]=\int_0^1e^{2u}\,\dd u=\dfrac{e^{2}-1}{2}\approx3.19453$, so
$$ \begin{aligned} \Var[f]&=\Ex[f^{2}]-I^{2}\\ &=3.19453-2.95249=0.24204 . \end{aligned} $$(2) The standard error for $S=100$ is $\sqrt{0.24204/100}=0.0492$. From $\sqrt{0.24204/S}\le10^{-3}$ we get $S\ge0.24204/10^{-6}\approx2.42\times10^{5}$.
(3) For $g(u)=\tfrac12(e^{u}+e^{1-u})$, since $1-u$ also follows the uniform distribution, $\Ex[g]=\tfrac12(I+I)=I$ (unbiased). Expanding the square and using $e^{u}e^{1-u}=e$ gives
$$ \begin{aligned} g^{2}&=\tfrac14\bigl(e^{2u}+2e+e^{2-2u}\bigr),\\ \Ex[g^{2}]&=\tfrac14\left(\frac{e^{2}-1}{2}+2e+\frac{e^{2}-1}{2}\right)\\ &=\frac{e^{2}-1}{4}+\frac{e}{2}\approx2.95640 . \end{aligned} $$(We used $\int_0^1e^{2-2u}\,\dd u=\int_0^1e^{2v}\,\dd v$.) Hence $\Var[g]=2.95640-2.95249=0.00391$. Since $g$ evaluates $f$ twice, the fair comparison is the variance of the mean of two independent samples, $\Var[f]/2=0.12102$, and the variance becomes $0.00391/0.12102\approx1/31$ of it. This is because $e^{u}$ is monotonically increasing, so $e^{u}$ and $e^{1-u}$ are negatively correlated: when one is large the other is small, and the fluctuations of the sum cancel.
Exercise 21.2: Generating random numbers for the strength of a ceramic
Solution
(1) Solve $u=1-\exp[-(\sigma_{\mathrm f}/\sigma_0)^{m}]$. We have $1-u=\exp[-(\sigma_{\mathrm f}/\sigma_0)^{m}]$; taking the logarithm of both sides gives $(\sigma_{\mathrm f}/\sigma_0)^{m}=-\ln(1-u)$, and raising to the power $1/m$,
$$ \sigma_{\mathrm f}=\sigma_0\bigl[-\ln(1-u)\bigr]^{1/m} . $$(2) For $u=0.05$: $-\ln0.95=0.05129$, $0.05129^{0.1}=0.7430$, and $\sigma_{\mathrm f}=222.9\ \mathrm{MPa}$. For $u=0.5$: $(\ln2)^{0.1}=0.6931^{0.1}=0.9640$, giving $289.2\ \mathrm{MPa}$. For $u=0.95$: $(-\ln0.05)^{0.1}=2.9957^{0.1}=1.1160$, giving $334.8\ \mathrm{MPa}$. Because $m=10$ is large, the range from the 5% point to the 95% point stays within 223–335 MPa.
(3) $(250/300)^{10}=(5/6)^{10}=0.16151$, and $P(\sigma_{\mathrm f}\lt250)=1-e^{-0.16151}=0.1491$. The number among 1000 specimens follows the binomial distribution $\mathrm{Bin}(1000,\,0.1491)$, with mean $149.1$ and standard deviation $\sqrt{1000\times0.1491\times0.8509}=\sqrt{126.9}\approx11.3$. The count among the 1000 generated random numbers fluctuates roughly within the range $149\pm23$ (two standard deviations).
Exercise 21.3: The best proposal distribution for importance sampling
Solution
(1) With $w=p/q$, the variance of $wf$ for a single sample is $\Var_q[wf]=\Ex_q[(wf)^{2}]-(\Ex_q[wf])^{2}$. The second term is $I^{2}$, since $\Ex_q[wf]=\int\frac{p}{q}fq\,\dd x=I$. The first term is
$$ \Ex_q[(wf)^{2}]=\int\frac{p^{2}}{q^{2}}f^{2}\,q\,\dd x=\int\frac{f^{2}p^{2}}{q}\,\dd x . $$Hence the variance is $\int\frac{f^{2}p^{2}}{q}\,\dd x-I^{2}$.
(2) Substituting $q^{*}=fp/I$, where $f\gt0$ we get $w f=\dfrac{p}{fp/I}\,f=I$, a constant, so the variance is 0. In terms of formulas as well, $\int\frac{f^{2}p^{2}}{fp/I}\,\dd x=I\int fp\,\dd x=I^{2}$, and $I^{2}-I^{2}=0$.
(3) Normalizing $q^{*}$ requires the very quantity $I$ that we want to find, so it cannot actually be used. Still, it gives the guideline that “$q$ should concentrate probability where $f(x)p(x)$ is large.” We should draw samples preferentially not only where $p$ is large but also where $f$ is large (for example, in the tail when we want the probability of the tail). Conversely, if $q$ is small where $fp$ is large, then $f^{2}p^{2}/q$ becomes large and the variance grows (the same as the danger of a light-tailed proposal in Section 21.4).
Exercise 21.4: A chain that is stationary but does not satisfy detailed balance
Solution
(1) For $\bm{\pi}=(\tfrac13,\tfrac13,\tfrac13)$ we have $(\bm{\pi}\bm{T})_j=\tfrac13\sum_iT_{ij}$. The column sums are $0.5+0+0.5=1$, $0.5+0.5+0=1$, and $0+0.5+0.5=1$, so $(\bm{\pi}\bm{T})_j=\tfrac13$, that is, $\bm{\pi}\bm{T}=\bm{\pi}$.
(2) $p_1T_{12}=\tfrac13\times0.5=\tfrac16$ and $p_2T_{21}=\tfrac13\times0=0$, which are not equal. Hence detailed balance does not hold.
(3) The net flows $p_iT_{ij}-p_jT_{ji}$ are $+\tfrac16$ for each of $1\to2$, $2\to3$, and $3\to1$. Probability keeps circulating in the direction $1\to2\to3\to1$, but the amount flowing into each state ($\tfrac16$) equals the amount flowing out ($\tfrac16$), so the distribution does not change. The chain is stationary, but if time is reversed the direction of the flow reverses (it is not symmetric under time reversal).
(4) To check stationarity $\sum_xp(x)T(x'\mid x)=p(x')$ we need a sum over all states, and hence a normalized $p$. Detailed balance is a condition on pairs of states, $\tilde{p}(x)T(x'\mid x)=\tilde{p}(x')T(x\mid x')$, in which $Z$ cancels on both sides, so it can be checked with $\tilde{p}$ alone, and a $T$ satisfying it (the Metropolis–Hastings algorithm) can be constructed mechanically. Note that chains that break detailed balance sometimes mix faster, and such methods are also being studied.
Exercise 21.5: A random walk on the logarithm of a positive quantity
Solution
(1) $y'=\ln x'$ follows $\Normal(y'\mid\ln x,\,s^{2})$. In the change of variables to $x'=e^{y'}$ we have $\dd y'/\dd x'=1/x'$ (Chapter 2, Section 2.6), so
$$ \begin{aligned} &q(x'\mid x)\\ &\quad=\frac{1}{x'\sqrt{2\pi}\,s}\exp\!\left[-\frac{(\ln x'-\ln x)^{2}}{2s^{2}}\right] \end{aligned} $$($x'\gt0$). (2) The exponential-function part is symmetric in $x$ and $x'$, so in the ratio only the prefactors $1/x'$ and $1/x$ remain:
$$ \begin{aligned} \frac{q(x\mid x')}{q(x'\mid x)}&=\frac{1/x}{1/x'}=\frac{x'}{x},\\ r&=\frac{\tilde{p}(x')}{\tilde{p}(x)}\cdot\frac{x'}{x} . \end{aligned} $$(3) $\dfrac{\tilde{p}(1.5)}{\tilde{p}(1.0)}=\dfrac{1.5^{2}e^{-3}}{1^{2}e^{-2}}=2.25\,e^{-1}=0.8277$. The correct ratio is $r=0.8277\times1.5=1.2416$, and the acceptance probability is $\min(1,1.2416)=1$. If we forget $x'/x$, the acceptance probability becomes 0.828. The chain that forgot it has targeted $\tilde{p}(e^{y})$ on $\ln x$, so on $x$ it samples $\tilde{p}(x)/x\propto xe^{-2x}$ (the shape $a$ of the gamma distribution is smaller by 1). One obtains a wrong posterior distribution biased toward small $x$.
Exercise 21.6: Monte Carlo for attracting adsorbed molecules
Solution
(1) Adsorption increases $N$ by 1 and adds the adsorption energy $\varepsilon$ and the $k$ newly formed pair interactions $kw$, so $\Delta(E-\mu N)=(\varepsilon-\mu)+kw$.
(2) $k_{\mathrm B}T=0.02585\ \mathrm{eV}$.
- $k=0$: $0.05\ \mathrm{eV}$, acceptance probability $e^{-0.05/0.02585}=e^{-1.934}=0.145$.
- $k=1$: $0.05-0.03=0.02\ \mathrm{eV}$, $e^{-0.774}=0.461$.
- $k=2$: $0.05-0.06=-0.01\ \mathrm{eV}\lt0$, acceptance probability 1.
- $k=4$: $0.05-0.12=-0.07\ \mathrm{eV}$, acceptance probability 1.
For desorption from a site with $k=4$, the change is $+0.07\ \mathrm{eV}$, so the acceptance probability is $e^{-0.07/0.02585}=e^{-2.708}=0.0667$. A molecule surrounded by others hardly ever leaves.
(3) With interactions, the occupation probability of one site depends on the occupation of its neighbors, and the sites are no longer independent. The Langmuir equation of Section 21.12.2 was derived from detailed balance for independent sites, so it cannot be used (an approximate equation can be built with the mean-field approximation, which replaces the states of the neighbors by their average). Molecules adsorb poorly onto isolated sites (acceptance probability 0.145), but adsorb readily onto sites next to a molecule and then hardly leave, so islands of clustered molecules (a two-dimensional condensed phase) form, and at low temperature the system separates into islands and empty regions. The coverage can change abruptly with a small change in $\mu$. The shapes of the islands and the coverage are computed by Monte Carlo.
Exercise 21.7: Long correlations and thinning
Solution
(1) By the formula of Example 21.8, $\tau_{\mathrm{int}}=(1+0.99)/(1-0.99)=199$. To obtain an effective sample size of 1000 we need $S=1000\times199=1.99\times10^{5}$ steps.
(2) Before thinning: $10^{5}/199=502.5$. The thinned sequence can be regarded as an AR(1) process with $\phi'=0.99^{10}=0.9044$, so $\tau_{\mathrm{int}}'=(1+0.9044)/(1-0.9044)=19.92$, and the effective sample size is $10^{4}/19.92=502.1$. Thinning hardly changes the effective sample size (it decreases slightly) and never increases it. The 90% of the samples that were discarded carried almost no information, but whatever information they did carry is lost.
(3) Thinning does not improve precision. It is meaningful when we want to reduce the memory needed to store the samples or the cost of per-sample post-processing (for example, running a heavy property calculation on each sample). Even then, if the thinning interval is about $\tau_{\mathrm{int}}$, the loss of information is small.
Exercise 21.8: Swapping atoms in an alloy
Solution
(1) A A B B is $\bm{s}=(+1,+1,-1,-1)$, and the products of the three adjacent pairs are $+1,\ -1,\ +1$, so $E=J(1-1+1)=J=0.03\ \mathrm{eV}$. A B A B is $(+1,-1,+1,-1)$ with products $-1,-1,-1$, so $E=-3J=-0.09\ \mathrm{eV}$. Thus $\Delta E=-0.09-0.03=-0.12\ \mathrm{eV}$.
(2) Since $\Delta E\lt0$, the acceptance probability is 1. For the reverse swap, $\Delta E=+0.12\ \mathrm{eV}$ and $e^{-0.12/0.08617}=e^{-1.393}=0.248$.
(3) A swap does not change the numbers of A and B, so the composition is preserved and we sample the canonical distribution with fixed composition. If the proposal is “choose one A site and one B site, each uniformly,” then the probability of choosing a given pair is the same before and after the swap (because the numbers of A and B do not change), so the proposal is symmetric. The procedure is therefore the Metropolis algorithm with acceptance probability $\min(1,e^{-\beta\Delta E})$, which satisfies detailed balance by Theorem 21.6. Unlike real diffusion, a pair of distant sites may be chosen.
(4) For $J\gt0$ the energy decreases when unlike atoms are adjacent ($s_is_{i+1}=-1$), so the system favors an ordered arrangement in which A and B alternate (the same tendency as in Chapter 19, Example 19.11, where the fraction of unlike pairs became larger than 0.5). The lower the temperature, the higher the fraction of the ordered arrangement.
← Back to Chapter 21, “Sampling Methods — Integrating with Random Numbers”
Chapter 22 Sequence Data and Hidden Markov Models — Data with an Order
Exercise 22.1: A two-state Markov chain
Solution
We have $A_{12}=1-A_{11}=0.1$ and $A_{21}=1-A_{22}=0.4$.
(1) By Formula 22.2 of Chapter 22, $p^{*}(1)=A_{21}/(A_{12}+A_{21})=0.4/0.5=0.8$ and $p^{*}(2)=0.1/0.5=0.2$. Check: $0.8\times0.9+0.2\times0.4=0.72+0.08=0.8$.
(2) The mean residence time is $1/(1-A_{ii})$, so it is $1/0.1=10$ time steps for state 1 and $1/0.4=2.5$ time steps for state 2. The ratio $10:2.5=0.8:0.2$ agrees with the stationary distribution.
(3) We have $\lambda=1-A_{12}-A_{21}=0.5$. Since $\pi_2=0$, $p_t(2)-p^{*}(2)=0.5^{t-1}(0-0.2)$, and the magnitude of the difference is $0.2\times0.5^{t-1}$. For $t=1,\dots,6$ it is $0.2,\ 0.1,\ 0.05,\ 0.025,\ 0.0125,\ 0.00625$, so the first $t$ at which it falls below 0.01 is $6$ ($p_6(2)=0.19375$).
(4) The characteristic equation is
$$ \begin{aligned} &\det(\bm{A}-\lambda\bm{I})\\ &=(0.9-\lambda)(0.6-\lambda)-0.1\times0.4\\ &=\lambda^{2}-1.5\lambda+0.5\\ &=(\lambda-1)(\lambda-0.5)=0 . \end{aligned} $$The eigenvalues are 1 and 0.5, and 0.5 agrees with $\lambda=1-A_{12}-A_{21}$ in Formula 22.2. In general, the sum of the eigenvalues of a $2\times2$ stochastic matrix is the trace $A_{11}+A_{22}$, so the eigenvalue other than 1 is $A_{11}+A_{22}-1=1-A_{12}-A_{21}$.
Exercise 22.2: Computing forward, backward, and Viterbi by hand
Solution
The parameters are $\bm{\pi}=(0.6,0.4)$, $A_{11}=0.7$, $A_{12}=0.3$, $A_{21}=0.4$, $A_{22}=0.6$, $B_{1\cdot}=(0.5,0.4,0.1)$, $B_{2\cdot}=(0.1,0.3,0.6)$ (low, medium, high), and the observations are high, high, low.
(1) Forward: $\alpha_1=(0.6\times0.1,\ 0.4\times0.6)=(0.06,\ 0.24)$.
$$ \begin{aligned} \alpha_2(1)&=0.1\times(0.06\times0.7+0.24\times0.4)\\ &=0.1\times0.138=0.0138,\\ \alpha_2(2)&=0.6\times(0.06\times0.3+0.24\times0.6)\\ &=0.6\times0.162=0.0972,\\ \alpha_3(1)&=0.5\times(0.0138\times0.7+0.0972\times0.4)\\ &=0.5\times0.04854=0.02427,\\ \alpha_3(2)&=0.1\times(0.0138\times0.3+0.0972\times0.6)\\ &=0.1\times0.06246=0.006246. \end{aligned} $$$p(x_{1:3})=0.02427+0.006246=0.030516$.
(2) Backward: $\beta_3=(1,1)$. Since $x_3=\text{low}$, $\beta_2(1)=0.7\times0.5+0.3\times0.1=0.38$ and $\beta_2(2)=0.4\times0.5+0.6\times0.1=0.26$. Since $x_2=\text{high}$,
$$ \begin{aligned} \beta_1(1)&=0.7\times0.1\times0.38+0.3\times0.6\times0.26\\ &=0.0266+0.0468=0.0734,\\ \beta_1(2)&=0.4\times0.1\times0.38+0.6\times0.6\times0.26\\ &=0.0152+0.0936=0.1088. \end{aligned} $$Check: at $t=1$, $0.06\times0.0734+0.24\times0.1088$ $=0.004404+0.026112$ $=0.030516$, and at $t=2$, $0.0138\times0.38+0.0972\times0.26$ $=0.005244+0.025272$ $=0.030516$. Both agree with $p(x_{1:3})$. Smoothing gives $\gamma_t(j)=\alpha_t(j)\beta_t(j)/0.030516$:
- $\gamma_1$ $=(0.004404,\ 0.026112)/0.030516$ $=(0.14432,\ 0.85568)$
- $\gamma_2$ $=(0.005244,\ 0.025272)/0.030516$ $=(0.17184,\ 0.82816)$
- $\gamma_3$ $=(0.02427,\ 0.006246)/0.030516$ $=(0.79532,\ 0.20468)$
(3) Viterbi: $\omega_1=(0.06,\ 0.24)$. The quantities inside the $\max$ below are $\omega_{t-1}(1)A_{1j}$ and $\omega_{t-1}(2)A_{2j}$ (for example, $0.06\times0.7=0.042$ and $0.24\times0.4=0.096$).
$$ \begin{aligned} \omega_2(1)&=0.1\times\max(0.042,\ 0.096)\\ &=0.1\times0.096=0.0096,\\ \omega_2(2)&=0.6\times\max(0.018,\ 0.144)\\ &=0.6\times0.144=0.0864,\\ \omega_3(1)&=0.5\times\max(0.00672,\ 0.03456)\\ &=0.5\times0.03456=0.01728,\\ \omega_3(2)&=0.1\times\max(0.00288,\ 0.05184)\\ &=0.1\times0.05184=0.005184. \end{aligned} $$The backpointers are $\psi_2=(2,2)$ and $\psi_3=(2,2)$ (in every case the value coming from state 2 is larger). Since $\omega_3(1)\gt\omega_3(2)$, $z_3^{*}=1$, $z_2^{*}=\psi_3(1)=2$, and $z_1^{*}=\psi_2(2)=2$. The path is degraded, degraded, normal (221), and its joint probability is 0.01728 (posterior probability $0.01728/0.030516=0.56626$). Check: $\pi_2B_{2,\text{high}}\cdot A_{22}B_{2,\text{high}}\cdot A_{21}B_{1,\text{low}}$ $=0.24\times0.36\times0.2=0.01728$.
(4) The states with the largest $\gamma_t$ are 2, 2, 1, which agrees with the Viterbi path 221.
Exercise 22.3: Identities for forward–backward
Solution
We call the conditional independences of Chapter 22, Section 22.3.2 “Property 1 (an observation is determined by the current state alone),” “Property 2 (the Markov property of the states),” and “Property 3 (once the current state is known, future observations are unrelated to the past).”
(1) Split the observations into those up to time $t$ and those after it, and use the product rule.
$$ \begin{aligned} &p(x_{1:T},z_t=j)\\ &=p(x_{1:t},z_t=j)\,p(x_{t+1:T}\mid x_{1:t},z_t=j)\\ &=\alpha_t(j)\,p(x_{t+1:T}\mid z_t=j)\quad(\text{Property 3})\\ &=\alpha_t(j)\,\beta_t(j). \end{aligned} $$Summing over $j$ with the sum rule gives $\sum_j\alpha_t(j)\beta_t(j)=\sum_jp(x_{1:T},z_t=j)=p(x_{1:T})$. The right-hand side does not depend on $t$, so the value is the same for every $t$.
(2) Split the observations into the three pieces $x_{1:t}$, $x_{t+1}$, and $x_{t+2:T}$, and apply the product rule in turn.
$$ \begin{aligned} &p(x_{1:T},z_t=i,z_{t+1}=j)\\ &=p(x_{1:t},z_t=i)\\ &\quad\times p(z_{t+1}=j\mid x_{1:t},z_t=i)\\ &\quad\times p(x_{t+1}\mid x_{1:t},z_t=i,z_{t+1}=j)\\ &\quad\times p(x_{t+2:T}\mid x_{1:t+1},z_t=i,z_{t+1}=j). \end{aligned} $$The first factor is $\alpha_t(i)$. By Property 2, the second factor is $A_{ij}$. By Property 1, the third factor is $B_{jx_{t+1}}$. By Property 3 (applied at time $t+1$), the fourth factor is $p(x_{t+2:T}\mid z_{t+1}=j)=\beta_{t+1}(j)$. Hence $p(x_{1:T},z_t=i,z_{t+1}=j)$ $=\alpha_t(i)A_{ij}B_{jx_{t+1}}\beta_{t+1}(j)$, and dividing both sides by $p(x_{1:T})$ gives
$$ \xi_t(i,j)=\frac{\alpha_t(i)A_{ij}B_{jx_{t+1}}\beta_{t+1}(j)}{p(x_{1:T})}. $$(3) Sum over $j$ and use the recurrence relation of the backward algorithm, $\beta_t(i)=\sum_jA_{ij}B_{jx_{t+1}}\beta_{t+1}(j)$.
$$ \begin{aligned} \sum_j\xi_t(i,j)&=\frac{\alpha_t(i)\sum_jA_{ij}B_{jx_{t+1}}\beta_{t+1}(j)}{p(x_{1:T})}\\ &=\frac{\alpha_t(i)\beta_t(i)}{p(x_{1:T})}=\gamma_t(i). \end{aligned} $$This is also exactly the sum rule $\sum_jp(z_t=i,z_{t+1}=j\mid x_{1:T})=p(z_t=i\mid x_{1:T})$.
Exercise 22.4: An example in which the sequence of γ-maximizers is an impossible sequence
Solution
Because the emission probability of the observation is the same in every state, the joint probability $p(x_{1:2},z_{1:2})$ equals $\pi_{z_1}A_{z_1z_2}$ times a constant that does not depend on the states, and the posterior probability is exactly $\pi_{z_1}A_{z_1z_2}$.
(1) There are four sequences with nonzero probability: $12$: $0.4\times0.5=0.2$, $13$: $0.2$, $21$: $0.3\times1=0.3$, $31$: $0.3$. Their sum is 1. The other five sequences (11, 22, 23, 32, 33) contain a transition probability of 0, so their probability is 0.
(2) $\gamma_1=(0.2+0.2,\ 0.3,\ 0.3)=(0.4,\ 0.3,\ 0.3)$ and $\gamma_2=(0.3+0.3,\ 0.2,\ 0.2)=(0.6,\ 0.2,\ 0.2)$. The state with the largest value at each time is 1 and 1, giving the sequence 11. Since $A_{11}=0$, the probability of this sequence is 0. Each time step’s decision is individually the most probable one, yet putting them side by side gives an impossible sequence.
(3) The maximum probability is 0.3, and 21 and 31 tie. In the Viterbi algorithm, $\omega_2(1)=\max(0.4\times0,\ 0.3\times1,\ 0.3\times1)=0.3$ (omitting the observation factor) and $\omega_2(2)=\omega_2(3)=0.4\times0.5=0.2$, so $z_2^{*}=1$, and $\psi_2(1)$ is a tie between 2 and 3; with the rule of choosing the smaller index it is 2. The path is 21 (probability 0.3). The Viterbi path is always a sequence of maximum probability, so it never contains a pair with transition probability 0.
Exercise 22.5: Alarms in furnace monitoring
Solution
(1) $A_{12}=0.03$ and $A_{22}=1$. The prediction is $p(z_t=2\mid x_{1:t-1})$ $=0.03\times0.98+1\times0.02$ $=0.0494$. The predicted odds are $0.0494/0.9506=0.05197$; multiplying by the likelihood ratio for “high,” $B_{2,\text{high}}/B_{1,\text{high}}=0.5667/0.1=5.667$, gives $0.2945$, and the probability is $0.2945/1.2945=0.2275$. This is slightly larger than the 0.2237 of Example 22.12. The difference comes only from the second term of the prediction (the probability of staying degraded, 1 versus 0.95), and while $\hat\alpha_{t-1}(2)$ is small the difference is small.
(2) The likelihood ratio for “medium” is $(1/3)/(1/3)=1$, so the update changes nothing and filtering equals prediction: $f_t=0.03(1-f_{t-1})+f_{t-1}=0.03+0.97f_{t-1}$. Since $1-f_t=0.97(1-f_{t-1})$, we get $f_t\to1$. That is, even though no observation indicates degradation, the probability of degradation approaches 1 merely as time passes, and eventually an alarm sounds. This is because in a “no return” model the probability of degradation keeps rising unless observations showing that the furnace is “not yet degraded” (“low”) continue. In the model with $A_{22}=0.95$, if only “medium” continues, the probability approaches the stationary value $0.03/(0.03+0.05)=0.375$ and does not exceed 0.5. If a no-return model is used, one must look not only at the threshold but also at whether the rise in the probability of degradation was caused by observations (that is, whether there were observations with a likelihood ratio greater than 1).
(3) In the stationary state, the expected number of transitions from normal to degraded per hour is $p^{*}(1)A_{12}=0.625\times0.03=0.01875$, so in one year it is $8760\times0.01875\approx164$ times. This is the model’s claim that “it degrades and recovers 164 times a year”; if the inspection records show only a few actual degradations per year (cases that required repair), then the “degradation” of this model is not actual degradation but is picking up short temporary disturbances (such as a door being opened and closed). It is meaningful to check against external records whether the values of $\bm{A}$ match the actual state of the process.
Exercise 22.6: Tracking battery capacity with a Kalman filter
Solution
(1) With $z_t=z_{t-1}-d+w_t$, given $x_{1:t-1}$ we have $z_{t-1}\sim\Normal(\mu_{t-1},P_{t-1})$, and $w_t$ is independent, so
$$ \mu_{t\mid t-1}=\mu_{t-1}-d,\qquad P_{t\mid t-1}=P_{t-1}+q. $$The update equations are the same as those of Chapter 22: $K_t=P_{t\mid t-1}/(P_{t\mid t-1}+r)$, $\mu_t=\mu_{t\mid t-1}+K_t(x_t-\mu_{t\mid t-1})$, and $P_t=P_{t\mid t-1}r/(P_{t\mid t-1}+r)$.
(2) $t=1$: $\mu_{1\mid0}=100$ and $P_{1\mid0}=1$. $K_1=1/1.25=0.8$, $\mu_1=100+0.8\times(99.6-100)=99.68$, and $P_1=1\times0.25/1.25=0.2$.
$t=2$: $\mu_{2\mid1}=99.68-0.05=99.63$ and $P_{2\mid1}=0.2+0.01=0.21$. $K_2=0.21/0.46=0.45652$, $\mu_2$ $=99.63+0.45652\times(99.9-99.63)$ $=99.63+0.12326=99.753$, and $P_2=0.21\times0.25/0.46=0.11413$.
$t=3$: $\mu_{3\mid2}=99.753-0.05=99.703$ and $P_{3\mid2}=0.11413+0.01=0.12413$. $K_3=0.12413/0.37413=0.33178$, $\mu_3$ $=99.703+0.33178\times(99.3-99.703)$ $=99.703-0.13380=99.569$, and $P_3=0.12413\times0.25/0.37413=0.082946$.
The standard deviation of the estimate, $\sqrt{P_t}=0.447,\ 0.338,\ 0.288$ %, decreases.
(3) $P^{-}_\infty=(q+\sqrt{q^{2}+4qr})/2$ $=(0.01+\sqrt{0.0001+0.01})/2$ $=(0.01+0.10050)/2$ $=0.055249$, and $K_\infty=0.055249/0.305249=0.18100$. The scatter of a single measurement (standard deviation $\sqrt{r}=0.5$ %) is much larger than the irregular change in capacity per cycle ($\sqrt{q}=0.1$ %), so a single measured value moves the estimate with a weight of only 18 %. In effect, the filter is averaging (with exponential weights) the measurements of roughly the most recent $1/K_\infty\approx5.5$ cycles.
(4) The filter predicts by assuming the mean degradation rate $d=0.05$ %/cycle, so when the actual degradation becomes faster, the prediction is too high every time, and the estimate follows the true capacity from above, with a lag (the innovation $x_t-\mu_{t\mid t-1}$ stays biased toward negative values). Because $K_\infty$ is small, the lag lasts for several cycles or more. Possible remedies include estimating the degradation rate as part of the state as well (a two-dimensional state $(z_t,d_t)$) and monitoring the bias of the innovation to detect a switch from one stage to another.
Exercise 22.7: Designing validation for time series
Solution
(a) It leaks. The records from the hour before and after each validation time enter the training set, and adjacent times are similar, so the validation measures the performance of “interpolation when both sides are known.” Moreover, the target variable is the value 12 hours ahead, so the target variable at a training time $t$ (the deviation at $t+12$) is itself information from around the validation time $t+12$. Fix: split by time (for example, train on the first 1.5 years and validate on the last 0.5 years).
(b) It leaks. The average over the 6 hours before and after includes the values at $t+1,\dots,t+6$. At the time $t$ when the prediction is made, those do not yet exist. Fix: use a moving average of the past only, $\frac{1}{6}\sum_{s=t-5}^{t}x_s$ (which includes the value at time $t$).
(c) It leaks (though to a small degree). The values of the last 0.5 years enter the mean and standard deviation used for standardization. If the furnace state changes in the latter half and the level shifts, that information leaks into training. Fix: compute the standardization coefficients from the training period (the first 1.5 years) only, and apply the same coefficients to the validation period (the same as fitting the preprocessing in Chapter 6, Section 6.7).
(d) The features are correct, but it leaks at the boundary. The target variable for the last 12 hours of the training period is determined by the deviations in the first 12 hours of the validation period. Put a gap of at least 12 hours between training and validation so that the training target variables do not refer to values in the validation period. Since the features use the past 24 hours, it is not a problem that the features at the first validation time contain values from the training period (they are information available at the time of prediction). In addition, if there are two years of data, performing walk-forward validation, in which the end of the training period is shifted and the period immediately after is used for validation, also lets us see seasonal differences.
Exercise 22.8: The stationary value of the Kalman gain
Solution
(1) Combining the update $P_t=P_{t\mid t-1}r/(P_{t\mid t-1}+r)$ and the prediction $P_{t+1\mid t}=P_t+q$ gives the recurrence relation for the predicted variance:
$$ P_{t+1\mid t}=\frac{P_{t\mid t-1}\,r}{P_{t\mid t-1}+r}+q . $$At the stationary value $P^{-}$, $P^{-}=\dfrac{P^{-}r}{P^{-}+r}+q$. Multiplying both sides by $P^{-}+r\gt0$ gives
$$ \begin{aligned} P^{-}(P^{-}+r)&=P^{-}r+q(P^{-}+r),\\ (P^{-})^{2}+P^{-}r&=P^{-}r+qP^{-}+qr,\\ (P^{-})^{2}-qP^{-}-qr&=0 . \end{aligned} $$By the quadratic formula, $P^{-}=\bigl(q\pm\sqrt{q^{2}+4qr}\bigr)/2$. Since a variance is positive, we take $+$, and $P^{-}_\infty=\bigl(q+\sqrt{q^{2}+4qr}\bigr)/2$. $K_\infty=P^{-}_\infty/(P^{-}_\infty+r)$ is exactly the definition of the gain.
(2) $P_t=P_{t\mid t-1}r/(P_{t\mid t-1}+r)=\dfrac{P_{t\mid t-1}}{P_{t\mid t-1}+r}\,r=K_tr$. At the stationary value as well, $P_\infty=K_\infty r$.
(3) $q\to0$: $\sqrt{q^{2}+4qr}\approx2\sqrt{qr}$ is larger than $q$, so $P^{-}_\infty\approx\sqrt{qr}\to0$ and $K_\infty\approx\sqrt{q/r}\to0$. Because the state hardly moves, the weight of a new observation approaches 0, and the filter approaches computing the average of all observations so far (the best estimate when repeatedly measuring a quantity that does not move). $r\to0$: $P^{-}_\infty\to q$ and $K_\infty=q/(q+r)\to1$. Because the observation has no noise, the latest observed value is taken as the estimate as it is.
(4) $q=0.2$, $r=1$: $P^{-}_\infty=(0.2+\sqrt{0.04+0.8})/2$ $=(0.2+0.916515)/2$ $=0.558258$, and $K_\infty=0.558258/1.558258=0.358258$. This agrees with the default display of Simulator 22.3 (0.3583 in the readout, and 0.35826 in the “Putting the current numbers into the formula” panel).
← Back to Chapter 22, “Sequence Data and Hidden Markov Models — Data with an Order”
Chapter 23 RNNs, LSTMs, and Sequence Representations — Networks with Memory
Exercise 23.1: Parameters of a character-level language model for SMILES
Solution
(1) The embedding matrix has $V_{\mathrm{voc}}\times D=40\times32=1280$ entries. In the RNN, $\bm{W}_{xh}$ has $D_h\times D=128\times32=4096$, $\bm{W}_{hh}$ has $128\times128=16384$, and $\bm{b}_h$ has 128, for a total of $20608$. In the output layer, $\bm{W}_{hy}$ has $V_{\mathrm{voc}}\times D_h=40\times128=5120$ and $\bm{b}_y$ has 40, for a total of $5160$. The overall total is
$$ 1280+20608+5160=27048 . $$(2) One LSTM layer has $4D_h(D+D_h+1)$ parameters, that is, $4\times128\times(32+128+1)$ $=512\times161=82432$. The embedding and the output layer are unchanged, so the total is $1280+82432+5160=88872$, about 3.3 times that of the RNN.
(3) If a one-hot vector is fed in directly, the input weights number $D_h\times V_{\mathrm{voc}}=128\times40=5120$. With an embedding, they number $1280+4096=5376$, which is actually slightly more. When the vocabulary is as small as 40, the embedding does not save parameters. Even so, using an embedding is meaningful because (i) the representation of each character is learned as a 32-dimensional continuous-valued vector, so characters with similar properties (for example, the aromatic c and the aliphatic C) can be given nearby representations; (ii) when the vocabulary becomes large (thousands to tens of thousands of tokens), it avoids a weight matrix of size $V_{\mathrm{voc}}\times D_h$; and (iii) the input dimension is decoupled from the vocabulary size, so the shape of the RNN itself does not change when the vocabulary is changed.
Exercise 23.2: Generating greedily
Solution
Since $\bm{W}_{xh}=\bm{I}$ and $\bm{b}_h=\bm{0}$, we have $\bm{h}_t=\tanh(\bm{W}_{hh}\bm{h}_{t-1}+\bm{x}_t)$, where $\bm{x}_t$ is the embedding of the input token (a row of $\bm{W}_E$).
$t=1$ (input “heat up”): as in Examples 23.2 and 23.3, $\bm{h}_1=(0.1974,\ 0.7616)^{\tp}$ and $\bm{p}_1=(0.6565,\ 0.2981,\ 0.0312,\ 0.0142)$. The maximum is “heat up” (0.6565), so we choose it.
$t=2$ (input “heat up”): adding the embedding of “heat up,” $(0.2,\ 1.0)^{\tp}$, to $\bm{W}_{hh}\bm{h}_1=(-0.2821,\ 0.4795)^{\tp}$ gives $\bm{a}_2=(-0.0821,\ 1.4795)^{\tp}$ and $\bm{h}_2=(-0.0819,\ 0.9014)^{\tp}$. From $\bm{o}_2=2(0.8195,\ 0.9833,\ -0.9833,\ -0.8195)$ we get $\bm{p}_2=(0.4077,\ 0.5658,\ 0.0111,\ 0.0154)$. The maximum is “hold.”
$t=3$ (input “hold”): $\bm{h}_3=(-0.7581,\ 0.6105)^{\tp}$ and $\bm{p}_3=(0.0423,\ 0.8777,\ 0.0037,\ 0.0763)$. The maximum is “hold.”
$t=4$ (input “hold”): $\bm{h}_4=(-0.8288,\ 0.2224)^{\tp}$ and $\bm{p}_4=(0.0248,\ 0.6840,\ 0.0102,\ 0.2810)$. The maximum is “hold.”
$t=5$ (input “hold”): $\bm{h}_5=(-0.7721,\ -0.0032)^{\tp}$ and $\bm{p}_5=(0.0217,\ 0.4752,\ 0.0219,\ 0.4813)$. The maximum is “⟨end⟩” (0.4813, a slim margin over “hold” at 0.4752), so generation stops here.
The generated sequence is “heat up, heat up, hold, hold, hold, ⟨end⟩.”
Difference from teacher forcing (Example 23.3): in Example 23.3 the input at $t=2$ was the correct “hold,” and $\bm{h}_2=(-0.6539,\ 0.6524)^{\tp}$. In greedy generation, the “heat up” that the model itself chose at $t=1$ is fed in, so the hidden states from $t=2$ onward all take different values. This untrained model produces a sequence different from the correct one (heat up, hold, cool down, ⟨end⟩), and “cool down” is never chosen. During training the correct past is fed in, so only the quality of each one-step prediction is evaluated; during generation, the consequences of the model’s own choices determine all later inputs.
Exercise 23.3: BPTT for a scalar
Solution
(1) Let $a_t=wh_{t-1}+ux_t$, $h_t=\tanh a_t$, and $L=\tfrac12(h_T-y)^{2}$. The quantity $h_t$ appears only in $L$ when $t=T$, and only in $a_{t+1}=wh_t+ux_{t+1}$ when $t\lt T$. Therefore
$$ \begin{aligned} \pdiff{L}{h_T}&=h_T-y,\\ \pdiff{L}{h_t}&=\pdiff{L}{a_{t+1}}\pdiff{a_{t+1}}{h_t}=w\,\delta_{t+1}\quad(t\lt T). \end{aligned} $$The quantity $a_t$ affects $L$ only through $h_t$, and $\diff{h_t}{a_t}=1-\tanh^{2}a_t=1-h_t^{2}$, so
$$ \begin{aligned} \delta_T&=(1-h_T^{2})(h_T-y),\\ \delta_t&=(1-h_t^{2})\,w\,\delta_{t+1}\quad(t\lt T). \end{aligned} $$The parameters $w$ and $u$ appear in $a_t$ at every time step, with $\partial a_t/\partial w=h_{t-1}$ and $\partial a_t/\partial u=x_t$ (these are partial derivatives obtained by holding $h_{t-1}$ fixed and varying only the $w$ that appears explicitly in the expression for $a_t$; the dependence of $h_{t-1}$ on $w$ is counted as a term from the previous time step within the recursion for $\delta$). Hence
$$ \pdiff{L}{w}=\sum_{t=1}^{T}\delta_t\,h_{t-1},\qquad \pdiff{L}{u}=\sum_{t=1}^{T}\delta_t\,x_t . $$(2) Use $h_2=0.54362$, $h_3=0.40940$, and $w=0.8$ from Example 23.4. In the form of Eq. (23.13),
$$ \begin{aligned} \pdiff{h_3}{h_1}&=w(1-h_3^{2})\cdot w(1-h_2^{2})\\ &=0.8\times0.83239\times0.8\times0.70448\\ &=0.6659\times0.5636=0.3753 . \end{aligned} $$(3) Since $\partial L/\partial u=\sum_t\delta_tx_t$ and $x_2=x_3=0$, only $\delta_1x_1=\delta_1=0.03301$ remains. The value $\delta_1$ is obtained by going back two steps from the error $\delta_3$ at the last time step, and at each step it is multiplied by $w(1-h_t^{2})\lt1$ and becomes smaller. In contrast, $\partial L/\partial w$ contains the product of $\delta_3$ and $h_2$ (0.09476), which has not been propagated back, so it is large. The signal for learning the weight of the first input is determined only by the small error that arrives by backward propagation from a distant time step. This is the smallest example of the mechanism by which the vanishing gradient of Section 23.5 hinders the learning of long-range dependencies.
Exercise 23.4: How many steps does the gradient reach, and what does clipping change?
Solution
(1) If $h_0=0$, then $h_t=0$ at all time steps, so $\partial h_{50}/\partial h_0=w^{50}$. Taking the natural logarithm of both sides of $w^{50}\ge0.01$ gives $50\ln w\ge\ln0.01=-4.6052$, so $\ln w\ge-0.092103$ and $w\ge e^{-0.092103}=0.9120$. Thus $w\ge0.912$ is required.
(2) Eq. (23.14) was obtained by replacing $1-h_i^{2}$ in each factor $w(1-h_i^{2})$ by its upper limit 1. If $h_0\ne0$ and the state moves away from 0, then $1-h_i^{2}\lt1$ and each factor is smaller than $w$. The closer $\abs{h_i}$ gets to 1 through saturation, the closer $1-h_i^{2}$ gets to 0, so the gradient becomes even smaller than the upper limit $w^{t}$. For example, if $w=0.912$ and the state stays around 0.5, each factor is $0.912\times0.75=0.684$, and over 50 steps this gives $0.684^{50}\approx5.6\times10^{-9}$ (the actual state decays toward 0, so the true value is larger than this; here it is only a rough estimate to show why the upper limit is loose).
(3) Since $\norm{\bm{g}}=\sqrt{36+64+0}=10\gt2$, we get $\bm{g}\leftarrow(2/10)\bm{g}=(1.2,\ -1.6,\ 0)$. Its length is $\sqrt{1.44+2.56}=2$, and its direction is the same as the original.
Exercise 23.5: The value of the forget gate and how long memory lasts
Solution
(1) Writing Eq. (23.17) for component $j$ gives $c_{t,j}=f_{t,j}\,c_{t-1,j}+i_{t,j}\,\tilde{c}_{t,j}$. Treating $\bm{f}_t,\bm{i}_t,\tilde{\bm{c}}_t$ as constants, $c_{t,j}$ is a linear function of $c_{t-1,j}$ and does not contain the other components $c_{t-1,m}$ ($m\ne j$). Therefore
$$ \pdiff{c_{t,j}}{c_{t-1,m}}=\begin{cases}f_{t,j}&(m=j)\\0&(m\ne j)\end{cases} $$and written as a matrix, this is a diagonal matrix whose only nonzero entries are the diagonal components $f_{t,j}$, so
$$ \pdiff{\bm{c}_t}{\bm{c}_{t-1}}=\diag(\bm{f}_t). $$(2) The direct path over 50 steps gives $f^{50}=0.95^{50}=0.0769$.
(3) From $f^{100}\ge0.5$ we get $f\ge0.5^{1/100}$, and $0.5^{1/100}=e^{(\ln0.5)/100}$ $=e^{-0.0069315}=0.99309$. Solving $\sigma(b_f)=f$: from $1/(1+e^{-b_f})=f$ we get $e^{-b_f}=(1-f)/f$, so $b_f=\ln\{f/(1-f)\}$. Substituting $f=0.99309$ gives $b_f=\ln(0.99309/0.00691)=\ln143.7=4.97$. The pre-activation must be at least about 5.
(4) A GRU has $3D_h(D+D_h+1)=3\times128\times161=61824$ parameters and an LSTM has $4\times128\times161=82432$, so the GRU has 3/4 as many as the LSTM.
Exercise 23.6: Writing the temperature-history summary as an RNN
Solution
(1) Eq. (23.23) corresponds to an RNN whose hidden state $h_k=\Theta_k$ is one-dimensional, with $W_{hh}=1$, an identity activation (not passed through tanh), and an input given by the temperature $T_k$ passed through the nonlinear function $\phi(T_k)=\Delta t\,T_k^{-1}\exp\{-Q/(RT_k)\}$ (we add $\phi(T_k)$ in place of $\bm{W}_{xh}\bm{x}_t$). The bias is 0. To perform the same computation with the LSTM of Eq. (23.17), it suffices to set the forget gate to $f_k=1$ (keep all of the previous value), the input gate to $i_k=1$, and the candidate to $\tilde{c}_k=\phi(T_k)$. However, since $\tilde{c}_k$ is the output of a tanh, the scale of $\Theta$ must be chosen so that it fits in $(-1,1)$.
(2) As in Example 23.10, the ratio is $\dfrac{T_1}{T_2}\exp\!\left[\dfrac{Q}{R}\Bigl(\dfrac{1}{T_1}-\dfrac{1}{T_2}\Bigr)\right]$, with $T_1=1673.15\ \mathrm{K}$ and $T_2=1723.15\ \mathrm{K}$. We have $1/T_1-1/T_2=5.9767\times10^{-4}-5.8033\times10^{-4}$ $=1.7341\times10^{-5}\ \mathrm{K^{-1}}$ and $Q/R=57734\ \mathrm{K}$, so the exponent is $1.0012$ and $e^{1.0012}=2.7215$. Multiplying by $T_1/T_2=0.97098$ gives a ratio of $2.643$. This corresponds to 30 minutes × 2.643 = 79.3 minutes.
(3) $0.99^{600}=\exp(600\ln0.99)$ $=\exp(600\times(-0.010050))$ $=\exp(-6.030)=0.0024$. Only 0.24 % of the contribution from 600 steps earlier remains. On the other hand, $0.999^{600}=\exp(600\times(-0.0010005))$ $=\exp(-0.6003)=0.549$, so about half remains. To represent the accumulated $\Theta$ correctly, the factor must be almost exactly 1, and it is hard for a tanh RNN to maintain this.
(4) Examples: (i) Do not split fragments of the same run’s record, cut by time, between training and validation (split by run, and further by raw-material lot or furnace; Chapter 6, Section 6.8). (ii) When predicting partway through a run, do not use temperatures after the time being predicted as inputs or features (including statistics such as the mean or standardization statistics computed over the whole interval) (leakage in time series, Chapter 22). (iii) When the temperature conditions of a validation run lie outside the training range, state explicitly that this is extrapolation.
Exercise 23.7: Another way to write the same molecule
Solution
(1) Both C=Cc1ccccc1 and c1ccccc1C=C have 11 characters, so the number of tokens is 11 in both. In the second, the 1 that opens the ring is the second token and the 1 that closes it is the eighth, so they are six tokens apart (in the first as well, they are the fifth and 11th, six tokens apart).
(2) Even though the strings differ, they represent the same molecule, so the property value of a test-set molecule is already contained in the training data as is. If the model learns that these are the same molecule despite the difference in strings, the test error measures “recall of a known molecule” rather than “prediction for an unknown molecule,” and the generalization performance is overestimated (data leakage; Chapter 6, Section 6.7). To prevent this, before splitting, convert all molecules to a unique representation (canonicalized SMILES) or remove duplicates by molecular identifier, and then split into training and test sets by molecule.
(3) Another way of writing the same molecule is an “input transformation” that does not change the property value, so adding such variants to the training data amounts to data augmentation that teaches the model to “return the same answer regardless of how the molecule is written” (the same idea as the augmentation that rotates an image, since the object pictured is the same). However, because of the caution in (2), the augmentation is done after the split, and only within the training data.
(4) Examples: (i) Even a grammatically valid SMILES is not a new candidate if it is a copy of a molecule in the training data (novelty must be checked separately). (ii) That a molecule can exist as a molecule is distinct from its being actually synthesizable and from its being stable. (iii) Whether it has the target property must be confirmed by a prediction separate from the generative model, or by experiment or calculation, and that prediction too cannot be trusted outside the training range.
Exercise 23.8: The bottleneck and rereading
Solution
(1) As in Example 23.8, $c=h_{20}=\sum_{t=1}^{20}a^{20-t}x_t$, so the coefficient of $x_1$ is $a^{19}=0.8^{19}=0.0144$. This is only 1.4 % of the coefficient 1 of the last input.
(2) If the scores are $(3,0,0,0)$, then $A_{i1}=\dfrac{e^{3}}{e^{3}+3e^{0}}=\dfrac{20.086}{23.086}=0.870$ (each of the rest is $1/23.086=0.0433$). When all the scores are equal, the numerators of Eq. (23.21) are all the same, so $A_{ij}=1/4=0.25$, and the context is a simple average of the four states. In either case, the information at position 1 arrives with a single weight, without passing through the stages of the encoder. The higher the score of a position, the more strongly it is read.
(3) In an RNN, computing $\bm{h}_t$ requires $\bm{h}_{t-1}$, so the 512 computations must be performed in sequence. In self-attention, the computation at each position does not wait for the results of the others, so the number of sequential computations is one (all positions are computed at once as a matrix product). On a device such as a GPU that can perform many operations simultaneously, the fewer the sequential waits, the faster a single training step finishes, and the more data can be learned in the same time. However, the computational cost of self-attention grows in proportion to $T^{2}$ (Table 23.3).
← Back to Chapter 23, “RNNs, LSTMs, and Sequence Representations — Networks with Memory”
Chapter 24 How Attention Works — Gathering Relevant Information with Weights
Exercise 24.1: Attention with two queries
Solution
(1) $\bm{Q}$ is $2\times2$, $\bm{K}$ is $3\times2$, and $\bm{V}$ is $3\times1$. Hence $T_q=2$, $T_k=3$, $d_k=2$, and $d_v=1$. The scores and the weights are $2\times3$, and the output is $2\times1$.
(2) The matrix of dot products is
$$ \begin{gathered} \bm{Q}\bm{K}^{\tp}=\begin{pmatrix}1&0&1\\0&2&2\end{pmatrix},\\ \bm{S}=\frac{\bm{Q}\bm{K}^{\tp}}{\sqrt2}=\begin{pmatrix}0.7071&0&0.7071\\0&1.4142&1.4142\end{pmatrix}. \end{gathered} $$Row 1: $\exp$ gives $(2.0281,\ 1,\ 2.0281)$, the sum is $5.0562$, and the weights are $(0.4011,\ 0.1978,\ 0.4011)$. Row 2: $\exp$ gives $(1,\ 4.1133,\ 4.1133)$, the sum is $9.2265$, and the weights are $(0.1084,\ 0.4458,\ 0.4458)$. The output is
$$ \begin{aligned} z_1&=0.4011\times1+0.1978\times2\\ &\quad+0.4011\times3=2.0000,\\ z_2&=0.1084\times1+0.4458\times2\\ &\quad+0.4458\times3=2.3374 . \end{aligned} $$The sum of each row is $1.0000$.
(3) It is not a coincidence. In row 1 we have $A_{11}=A_{13}$, so
$$ \begin{aligned} z_1&=A_{11}(v_1+v_3)+A_{12}v_2\\ &=A_{11}\times4+A_{12}\times2=2\,(2A_{11}+A_{12}). \end{aligned} $$Since the row sums to 1, $2A_{11}+A_{12}=1$, and therefore $z_1=2$ regardless of the values of the weights. This is due to the symmetry that the mean of value 1 and value 3 equals value 2, and that key 1 and key 3 receive equal weights. In row 2 the weights lean toward key 2 and key 3, so the output is $2.3374$, larger than the mean 2.
Exercise 24.2: Properties of softmax and the mask
Solution
(1) If $s_j\to s_j+c$, then
$$ \frac{e^{s_j+c}}{\sum_{j'}e^{s_{j'}+c}}=\frac{e^{c}e^{s_j}}{e^{c}\sum_{j'}e^{s_{j'}}}=\frac{e^{s_j}}{\sum_{j'}e^{s_{j'}}} $$so the result does not change.
(2) If all the keys are equal, $\bm{k}_j=\bm{k}$, then for any query $\bm{q}$ the score $s_j=\bm{q}^{\tp}\bm{k}/\sqrt{d_k}$ takes the same value $s$ for every $j$. Then $a_j=e^{s}/(T_ke^{s})=1/T_k$, so the output is $\bm{z}=\frac{1}{T_k}\sum_j\bm{v}_j$ (the simple mean of the values), which does not depend on the query.
(3) If $s_j\to s_j+b_j$, then
$$ a'_j=\frac{e^{s_j}e^{b_j}}{\sum_{j'}e^{s_{j'}}e^{b_{j'}}}=\frac{a_je^{b_j}}{\sum_{j'}a_{j'}e^{b_{j'}}} $$(for the second equality, we divided the numerator and the denominator by $\sum_{j'}e^{s_{j'}}$). The new weights are obtained by multiplying the original weights by $e^{b_j}$ and then renormalizing so that they sum to 1. Unlike in (1), the weights do change when $b_j$ differs from column to column. The causal mask is the case $b_j=0$ ($j\le i$), $b_j=-\infty$ ($j\gt i$): multiplying by $e^{-\infty}=0$ sets the weights of the positions that must not be seen to 0, and the remaining weights are renormalized.
(4) Let $s_{\max}$ be the largest score among the unmasked positions in the row (at least $j=i$ remains). The ratio of the $\exp$ value at a masked position to $e^{s_{\max}}$ is $e^{s_{ij}-10^{9}-s_{\max}}\le e^{20-10^{9}}$ (since $|s|\le10$, we have $s_{ij}-s_{\max}\le20$), and the weight is at most this. The number $e^{-10^{9}}$ is so small that it is rounded to 0 even in 64-bit floating-point arithmetic, so the result is effectively the same as with $-\infty$.
Exercise 24.3: Variance of the dot product and the Jacobian matrix of softmax
Solution
(1) For each term, independence gives $\Ex[q_lk_l]=\Ex[q_l]\Ex[k_l]=0$ and $\Ex[q_l^{2}k_l^{2}]=\Ex[q_l^{2}]\Ex[k_l^{2}]=\sigma_q^{2}\sigma_k^{2}$ (since the mean is 0, $\Ex[q_l^{2}]=\sigma_q^{2}$). Hence $\Var[q_lk_l]=\sigma_q^{2}\sigma_k^{2}-0^{2}=\sigma_q^{2}\sigma_k^{2}$. Terms with different $l$ are independent, so the variances add:
$$ \Var\bigl[\bm{q}^{\tp}\bm{k}\bigr]=\sum_{l=1}^{d_k}\sigma_q^{2}\sigma_k^{2}=d_k\sigma_q^{2}\sigma_k^{2}. $$With $\sigma_q=\sigma_k=1$ we recover Theorem 24.1 of Chapter 24.
(2) The $(j,l)$ component of the Jacobian matrix is $J_{jl}=\delta_{jl}a_j-a_ja_l$. The sum of the $j$th row is
$$ \sum_lJ_{jl}=a_j-a_j\sum_la_l=a_j-a_j\times1=0 . $$Since $J$ is symmetric ($J_{jl}=J_{lj}$), the column sums are also 0. Meaning: for the change $\Delta\bm{s}=\varepsilon(1,\dots,1)^{\tp}$ that increases all the scores by the same amount $\varepsilon$, the change in the weights is $J\Delta\bm{s}=\bm{0}$. This is the differential version of the statement in Exercise 24.2 (1) that “adding the same number to all components does not change the softmax.”
(3) The diagonal components $a_j(1-a_j)$ are
$$ \begin{aligned} J_{11}&=(1-\varepsilon)\,\varepsilon=\varepsilon-\varepsilon^{2}\approx\varepsilon,\\ J_{22}=J_{33}&=\frac{\varepsilon}{2}\Bigl(1-\frac{\varepsilon}{2}\Bigr)\approx\frac{\varepsilon}{2}. \end{aligned} $$The off-diagonal components are $-a_ja_l$, for example $-(1-\varepsilon)\varepsilon/2\approx-\varepsilon/2$ and $-\varepsilon^{2}/4$, all of which have magnitude of order $\varepsilon$ or smaller. As $\varepsilon\to0$ (the weights concentrate on a single position), the whole Jacobian matrix approaches 0, so moving the scores hardly changes the weights. This is why gradients do not flow when the softmax is saturated.
Exercise 24.4: Number of parameters of multi-head attention
Solution
(1) $\bm{W}_Q^{(j)},\bm{W}_K^{(j)},\bm{W}_V^{(j)}$ are each $512\times64$, so there are $3\times512\times64=98{,}304$ parameters.
(2) $\bm{W}_O$ is $(n_{\mathrm{head}}d_v)\times d_{\mathrm{model}}=512\times512=262{,}144$ parameters.
(3) Without biases: $8\times98{,}304+262{,}144$ $=786{,}432+262{,}144$ $=1{,}048{,}576$ parameters. This equals $4d_{\mathrm{model}}^{2}=4\times512^{2}$. With biases: adding 512 each after $\bm{Q},\bm{K},\bm{V}$ and $\bm{W}_O$ gives $4\times512=2048$ more, for a total of $1{,}050{,}624$ parameters.
(4) $\bm{W}_Q,\bm{W}_K,\bm{W}_V$ are each $512\times512$ and $\bm{W}_O$ is $512\times512$, so there are $4\times512^{2}=1{,}048{,}576$ parameters, the same as in (3). The number of heads does not change the number of parameters; it determines into how many independent attentions the same number of parameters is divided.
Exercise 24.5: Attention with a distance bias on a chain of atoms
Solution
(1) The query of atom 1 is $(1,0)$. The dot products with the features of the atoms are $(1,0,1,0)$, and dividing by $\sqrt2$ gives $(0.7071,\ 0,\ 0.7071,\ 0)$. The distances are $r_{1j}=0,\ 1.5,\ 3.0,\ 4.5$ Å, so the bias $-r_{1j}^{2}/(2\times1.5^{2})$ is $0,\ -0.5,\ -2,\ -4.5$. The scores are
$$ (0.7071,\ -0.5,\ -1.2929,\ -4.5). $$$\exp$ gives $(2.0281,\ 0.6065,\ 0.2745,\ 0.0111)$, with sum $2.9202$. The weights are $(0.6945,\ 0.2077,\ 0.0940,\ 0.0038)$ (sum 1). The weights of atoms 1 and 3 go into the A component of the output, and those of atoms 2 and 4 into the B component, so
$$ \begin{aligned} \bm{z}_1&=(0.6945+0.0940,\ 0.2077+0.0038)\\ &=(0.7885,\ 0.2115). \end{aligned} $$(2) As $\ell\to\infty$ all the biases become 0, and the scores are $(0.7071,0,0.7071,0)$. $\exp$ gives $(2.0281,1,2.0281,1)$, with sum $6.0562$, and the weights are $(0.3349,\ 0.1651,\ 0.3349,\ 0.1651)$. The output is $(0.6698,\ 0.3302)$. Since distance has no effect, atom 1 and atom 3, which are of the same element A, receive the same weight even though their distances differ.
(3) As $\ell\to0$, the bias $-r_{1j}^{2}/(2\ell^{2})$ for $j\ne1$ tends to $-\infty$, so the weights become $(1,0,0,0)$ and the output is the atom’s own feature $(1,0)$. No information is gathered from the surrounding atoms. The quantity $\ell$ is a length scale that determines out to what distance atoms are taken into account, and it plays the same role as the length scale of the kernel in Chapter 10.
(4) The score is determined only by the features (elements) of atoms $i$ and $j$ and the distance $r_{ij}$; the index numbers are not used. Relabeling the atoms changes the order of the components of the weight vector, but “how much weight goes to which atom (which element, at which distance)” does not change. This is for the same reason as the permutation equivariance in Theorem 24.2 of Chapter 24 (the distance bias is also merely rearranged into $\bm{P}\bm{B}\bm{P}^{\tp}$, so the proof carries over as it is).
Exercise 24.6: Aggregating the temperature history of firing with attention
Solution
(1) The dot products $\bm{q}^{\tp}\bm{k}_j$ are $2\times1+1\times0=2$, $1$, $2+1=3$, $1$. Dividing by $\sqrt2$ gives the scores $(1.4142,\ 0.7071,\ 2.1213,\ 0.7071)$. $\exp$ gives $(4.1133,\ 2.0281,\ 8.3421,\ 2.0281)$, with sum $16.5116$. The weights are
$$ \begin{aligned} &(a_1,a_2,a_3,a_4)\\ &\quad=(0.2491,\ 0.1228,\ 0.5052,\ 0.1228). \end{aligned} $$The output is
$$ \begin{aligned} &0.2491\times0.0+0.1228\times1.0\\ &\quad+0.5052\times0.5+0.1228\times0.2\\ &=0+0.1228+0.2526+0.0246=0.4000 . \end{aligned} $$(2) The contributions $a_jv_j$ are $(0,\ 0.1228,\ 0.2526,\ 0.0246)$. The order of the magnitudes of the weights is interval 3 (0.505) > interval 1 (0.249) > interval 2 = interval 4 (0.123), but the order of the magnitudes of the contributions is interval 3 > interval 2 > interval 4 > interval 1. Interval 1, the heating interval, which has the second-largest weight, contributes nothing to the output because its value is 0.
(3) We must not conclude this. Interval 3, which has the largest weight, also has the largest contribution, but (a) the contribution is determined by the product of the weight and the value, so the ranking can change depending on how the values are constructed ($\bm{W}_V$); (b) if the information in interval 3 is strongly correlated with that in other intervals, the same prediction may be obtained even if the weight is moved to another interval (Chapter 24, Section 24.10); and (c) the weight is the proportion in the aggregation of a single layer and does not include the computations in the layers before and after it. Examples of ways to check:
- Change the temperature data of interval 3 (for example, replace it with the values of another sample, or with the mean value) or remove it, and examine how much the prediction changes. Do the same for the other intervals and compare.
- Change the random-number seed or the way the training data are split, retrain, and examine whether the weight pattern is reproduced stably (also check that samples from the same furnace and the same lot have not been split between the training and test sets; see data leakage in Chapter 6).
- Actually prepare samples with different cooling rates and measure the relative density, to check experimentally whether the model’s suggestion holds physically.
The first two of the above are ways of checking “which intervals the model is using” inside the model, while the third is a way of checking the physical question “is the first half of the cooling the cause of the relative density?”; the two are different questions.
Exercise 24.7: The causal mask and permutation equivariance
Solution
(1) The first row of the mask is $M_{11}=0$, $M_{1j}=-\infty$ ($j\ge2$). Since $\exp(-\infty)=0$, the weights at position 1 are $A_{11}=e^{s_{11}}/e^{s_{11}}=1$ and $A_{1j}=0$ ($j\ge2$). The output is $\bm{z}_1^{\tp}=1\times\bm{v}_1^{\tp}=\bm{x}_1^{\tp}\bm{W}_V$, which does not depend on the values of the scores.
(2) With the mask applied to the $\bm{X}$ of Section 24.3 (rows $(1,0)$, $(0,1)$, $(1,1)$, $\bm{W}_V=\bm{I}$), the output is $(1,0)$, $(0.3302,0.6698)$, $(0.7517,0.7517)$. If we feed in $\bm{X}'$ with the first and second rows swapped (rows $(0,1)$, $(1,0)$, $(1,1)$), then by (1) the output at the new position 1 is $\bm{x}'_1=(0,1)$. If it were permutation equivariant, the output would have to equal the second row $(0.3302,0.6698)$ of the original output, so they do not agree. Therefore self-attention with a causal mask is not permutation equivariant in general. (The output at the new position 2 is $(0.6698,0.3302)$, which also does not agree with the original first row $(1,0)$.)
(3) By Theorem 24.2, $\bm{Z}(\bm{P}\bm{X})=\bm{P}\bm{Z}(\bm{X})$. The rows of $\bm{P}\bm{Z}$ are the rows of $\bm{Z}$ rearranged, so
$$ \bar{\bm{z}}(\bm{P}\bm{X})=\frac1T\sum_{i=1}^{T}\bigl(\bm{P}\bm{Z}\bigr)_{i}=\frac1T\sum_{i=1}^{T}\bm{z}_i=\bar{\bm{z}}(\bm{X}) $$(a sum does not depend on the order of addition). The order in which the elements of a composition are listed has no physical meaning (for example, Al$_2$O$_3$ is represented as “Al 0.4, O 0.6”). Listing them in the order “Al, O” or in the order “O, Al” gives the same substance, so the prediction must not change with the way they are listed. Using a permutation-invariant aggregation guarantees this requirement as a structural property of the model.
Exercise 24.8: Computational cost and memory for long sequences
Solution
(1) Dividing both sides of $2T^{2}d\gt4Td^{2}$ by $2Td\ (\gt0)$ gives $T\gt2d$. For $d=1024$, this is $T\gt2048$.
(2) The number of components is $T^{2}n_{\mathrm{head}}=8192^{2}\times16=1{,}073{,}741{,}824$. Multiplying by 4 bytes gives
$$ 4{,}294{,}967{,}296\ \text{byte}=4\ \text{GiB}\ (\approx4.29\ \text{GB}). $$For $T=1024$, $1024^{2}\times16\times4=67{,}108{,}864$ byte $=64$ MiB. The ratio is $(8192/1024)^{2}=8^{2}=64$, so multiplying the length by 8 multiplies the memory by 64. This is the amount per layer and per sequence.
(3) Disadvantage: the computational cost and the memory grow as $T^{2}$. An RNN grows in proportion to $T$, and what it keeps along the way is only the $d$-dimensional hidden state. Advantages: all positions can be computed in parallel in a single step, and positions far apart are connected directly in a single step. An RNN requires $T$ steps of sequential computation, and information from distant positions passes through the product of many matrices, so gradients tend to vanish or explode.
← Back to Chapter 24, “How Attention Works — Gathering Relevant Information with Weights”
Chapter 25 The Structure of the Transformer — Stacking Attention
Exercise 25.1: Shifting the positional encoding and the dot product
Solution
For $d_{\mathrm{model}}=4$ we have $\omega_0=1$ and $\omega_1=1/10000^{2/4}=0.01$, and the components are ordered as $(\sin\omega_0pos,\ \cos\omega_0pos,$ $\sin\omega_1pos,\ \cos\omega_1pos)$.
(1) Substitute $pos=3$.
$$ \begin{aligned} \bm{PE}_3&=(\sin3,\ \cos3,\ \sin0.03,\ \cos0.03)\\ &=(0.1411,\ -0.9900,\ 0.0300,\ 0.9996). \end{aligned} $$(2) Using the angle of each pair, $\omega_0k=2$ and $\omega_1k=0.02$, the rotation matrix for the shift $k=2$ is
$$ \bm{R}_2=\begin{pmatrix}c_2&-s_2&0&0\\ s_2&c_2&0&0\\ 0&0&c'&-s'\\ 0&0&s'&c'\end{pmatrix} $$where $c_2=\cos2$, $s_2=\sin2$, $c'=\cos0.02$, and $s'=\sin0.02$. For the first and second components, multiplying $(\sin1,\cos1)=(0.8415,0.5403)$ of $\bm{PE}_1$ by the upper-left $2\times2$ block gives
$$ \begin{aligned} &\bigl(\sin1\cos2+\cos1\sin2,\\ &\qquad -\sin1\sin2+\cos1\cos2\bigr)\\ &=\bigl(\sin(1+2),\ \cos(1+2)\bigr)\\ &=(0.1411,\ -0.9900) \end{aligned} $$which agrees with the first and second components of $\bm{PE}_3$ (numerically as well: $0.8415\cdot(-0.4161)$ $+0.5403\cdot0.9093$ $=0.1411$ and $-0.8415\cdot0.9093$ $+0.5403\cdot(-0.4161)$ $=-0.9900$). In the same way, the third and fourth components become $(\sin0.03,\cos0.03)$.
(3) By Eq. (25.8) of Chapter 25 (the formula for the dot product of positional encodings), the dot product is determined only by the difference $k$ of the positions and equals $\sum_i\cos(\omega_ik)$. Both $\bm{PE}_0\bm{PE}_3^{\tp}$ and $\bm{PE}_5\bm{PE}_8^{\tp}$ have the difference $k=3$, so they are equal, and
$$ \begin{aligned} \cos3+\cos0.03&=-0.98999+0.99955\\ &=0.0096 . \end{aligned} $$A direct computation also gives $\bm{PE}_0\bm{PE}_3^{\tp}$ $=0\cdot0.1411+1\cdot(-0.9900)$ $+0\cdot0.0300+1\cdot0.9996$ $=0.0096$. The fast hand (the first and second components) turns through 3 rad and points almost in the opposite direction ($\cos3\approx-0.99$), while the slow hand points in almost the same direction ($\cos0.03\approx1$), so the sum is almost 0.
Exercise 25.2: Computing LayerNorm and its properties
Solution
(1) The mean is $\bar{x}=(2+4+6+8)/4=5$. The deviations are $(-3,-1,1,3)$. The variance is $s^{2}=(9+1+1+9)/4=5$, so $s=\sqrt5=2.2361$. For $\bm{g}=\bm{1}$ and $\bm{b}=\bm{0}$,
$$ \begin{aligned} \mathrm{LN}(\bm{x})&=\tfrac{1}{\sqrt5}\,(-3,\ -1,\ 1,\ 3)\\ &=(-1.3416,\ -0.4472,\\ &\qquad 0.4472,\ 1.3416). \end{aligned} $$For $\bm{g}=(1,1,2,2)$ and $\bm{b}=(0,0,0,1)$, multiply componentwise and then add:
$$ \begin{aligned} &(-1.3416,\ -0.4472,\\ &\qquad 2\cdot0.4472,\ 2\cdot1.3416+1)\\ &=(-1.3416,\ -0.4472,\ 0.8944,\ 3.6833). \end{aligned} $$(2) Let $\bm{x}'=-\bm{x}$. The mean is $\bar{x}'=-\bar{x}$, the deviations are $x'_k-\bar{x}'=-(x_k-\bar{x})$, and the variance is $s'^{2}=\frac1d\sum_k(x_k-\bar{x})^{2}=s^{2}$, so $s'=s$. Therefore
$$ \frac{x'_k-\bar{x}'}{s'}=-\frac{x_k-\bar{x}}{s}, $$and if $\bm{b}=\bm{0}$ then $\mathrm{LN}(-\bm{x})=-\mathrm{LN}(\bm{x})$. In general, for $a\bm{x}+c\bm{1}$ the denominator becomes $\sqrt{a^{2}s^{2}}=\abs{a}s$, so the ratio is $\dfrac{a}{\abs{a}}\cdot\dfrac{x_k-\bar{x}}{s}=\sgn(a)\dfrac{x_k-\bar{x}}{s}$. Only for $a\gt0$ does the sign stay unchanged so that the result equals the original, which is why Theorem 25.2 assumes $a\gt0$ (for $a\lt0$ the sign is reversed).
(3) If all components equal $c$, then $\bar{x}=c$, all deviations are 0, and $s^{2}=0$. For $\epsilon=0$ we get $0/0$, which is undefined. For $\epsilon\gt0$ the numerator is 0 and the denominator is $\sqrt{\epsilon}\gt0$, so $\mathrm{LN}(\bm{x})_k=g_k\cdot0+b_k=b_k$; that is, the output is exactly the bias $\bm{b}$. The constant $\epsilon$ is included so that the computation does not break down in such cases.
Exercise 25.3: The number of parameters of the base model in the original paper
Solution
Let $d=512$ and $d_{\mathrm{ff}}=2048$. We count part by part.
- One multi-head attention: $\bm{W}_Q,\bm{W}_K,\bm{W}_V,\bm{W}_O$ are each $512\times512$ and each bias has 512 entries, so $4(512^{2}+512)=4\times262{,}656=1{,}050{,}624$.
- One FFN: $512\cdot2048+2048$ $+2048\cdot512+512$ $=2{,}099{,}712$.
- One LayerNorm: $2\times512=1024$.
(1) One encoder layer has one attention, one FFN, and two LayerNorms, so
$$ 1{,}050{,}624+2{,}099{,}712+2048=3{,}152{,}384 . $$One decoder layer has two attentions (self and cross), one FFN, and three LayerNorms, so
$$ \begin{aligned} &2\times1{,}050{,}624+2{,}099{,}712+3072\\ &=4{,}204{,}032 . \end{aligned} $$(2) The shared embedding matrix has $37000\times512=18{,}944{,}000$ entries (it is the same matrix on the input side, on the output side, and before the softmax, so it is counted only once). The positional encoding has no parameters. The total is
$$ \begin{aligned} &18{,}944{,}000+6\times3{,}152{,}384+6\times4{,}204{,}032\\ &=18{,}944{,}000+18{,}914{,}304+25{,}224{,}192\\ &=63{,}082{,}496\approx6.31\times10^{7}. \end{aligned} $$This is about $1.9\times10^{6}$ (about 3 %) fewer than the $65\times10^{6}$ in the paper’s table. Converted into rows of the embedding matrix, the difference is about 3700 words, and since the paper gives the vocabulary only as “about 37000,” a difference of this size can be explained by the exact vocabulary size or by implementation details (for example, the presence or absence of biases). From the information in the paper alone, the cause of the difference cannot be narrowed down to a single one. The framework of the count (the blocks account for about 70 % of the total and the embedding for about 30 %) is correct, and the order of magnitude agrees.
Exercise 25.4: A Transformer that takes a composition as input
Solution
(1) For the order “A, B,” $\bm{X}=\begin{pmatrix}1&0\\0&1\end{pmatrix}$ and $\bm{Q}=\bm{K}=\bm{V}=\bm{X}$. The scores are $\bm{X}\bm{X}^{\tp}/\sqrt2=\begin{pmatrix}0.7071&0\\0&0.7071\end{pmatrix}$. The exponentials in the first row are $(2.0281,\ 1)$, with sum $3.0281$, so the weights are $(0.6698,\ 0.3302)$. The second row is $(0.3302,\ 0.6698)$.
$$ \bm{A}=\begin{pmatrix}0.6698&0.3302\\0.3302&0.6698\end{pmatrix},\qquad \bm{Z}=\bm{A}\bm{X}=\bm{A}. $$The mean is $(0.5,\ 0.5)$, since each component is $(0.6698+0.3302)/2=0.5$. The order “B, A” is obtained by swapping rows; since self-attention is permutation equivariant, the rows of $\bm{Z}$ are merely swapped, and the mean is the same $(0.5,\ 0.5)$.
(2) “A, B”: $\bm{X}=\begin{pmatrix}1.5&0\\0&1\end{pmatrix}$. The scores are $\bm{X}\bm{X}^{\tp}/\sqrt2=\begin{pmatrix}1.5910&0\\0&0.7071\end{pmatrix}$. The exponentials in the first row are $(4.9086,\ 1)$, giving weights $(0.8308,\ 0.1692)$, and those in the second row are $(1,\ 2.0281)$, giving $(0.3302,\ 0.6698)$.
$$ \begin{aligned} \bm{z}_1&=0.8308\,(1.5,0)+0.1692\,(0,1)\\ &=(1.2461,\ 0.1692),\\ \bm{z}_2&=0.3302\,(1.5,0)+0.6698\,(0,1)\\ &=(0.4954,\ 0.6698), \end{aligned} $$The mean is $(0.8707,\ 0.4195)$.
“B, A”: $\bm{X}=\begin{pmatrix}0.5&1\\1&0\end{pmatrix}$. Dividing $\bm{X}\bm{X}^{\tp}=\begin{pmatrix}1.25&0.5\\0.5&1\end{pmatrix}$ by $\sqrt2$ gives the scores $\begin{pmatrix}0.8839&0.3536\\0.3536&0.7071\end{pmatrix}$. The exponentials in the first row are $(2.4203,\ 1.4241)$, giving weights $(0.6296,\ 0.3704)$, and those in the second row are $(1.4241,\ 2.0281)$, giving $(0.4125,\ 0.5875)$.
$$ \begin{aligned} \bm{z}_1&=0.6296\,(0.5,1)+0.3704\,(1,0)\\ &=(0.6852,\ 0.6296),\\ \bm{z}_2&=0.4125\,(0.5,1)+0.5875\,(1,0)\\ &=(0.7937,\ 0.4125), \end{aligned} $$The mean is $(0.7395,\ 0.5210)$. When positional information is added, the output changes with the ordering even for the same composition.
(3) A composition is a set of elements, and the same substance results whichever order it is written in. If positional information is included, the prediction changes with the ordering as in (2), so the same substance would receive different predictions. If self-attention and the FFN are applied without positional information and the outputs are finally averaged (or summed), the prediction does not depend on the ordering (it is permutation invariant). The composition ratios can be included by attaching a quantity that represents the ratio to the embedding of each token. However, substances with the same composition but different crystal structures (polymorphs) cannot be distinguished by composition alone, so for properties where this matters, structural information is also needed separately.
Exercise 25.5: Turning an XRD pattern into a token sequence
Solution
(1) Since $4000/20=200$, $T=200$.
(2) The weight matrix is $T\times T$.
- $T=4000$: $4000^{2}=1.6\times10^{7}$ entries, $\times4$ bytes $=6.4\times10^{7}$ bytes $=64$ MB.
- $T=200$: $200^{2}=4\times10^{4}$ entries, $\times4$ bytes $=1.6\times10^{5}$ bytes $=160$ kB.
Reducing $T$ by a factor of 20 reduces the weight matrix by a factor of $20^{2}=400$. This is for one layer and one head, so the total is further multiplied by the number of layers and heads.
(3) The ratio is $T/(6d_{\mathrm{model}})$, and $6\times256=1536$. For $T=4000$, $4000/1536=2.60$ (attention is 2.6 times the linear transformations); for $T=200$, $200/1536=0.130$ (the linear transformations dominate).
(4) Advantage: the computation and memory of attention decrease as $T^{2}$, making training and inference lighter. Since one token represents a shape spanning a width of $0.4^{\circ}$ (the rise of a peak, its vertex, and so on) all at once, the connection between neighboring points can be handled by the first linear transformation. Disadvantage: fine differences of position within one token (peak shifts on the order of $0.02^{\circ}$) are not distinguished as token positions and are pushed into the vector that makes up the token’s content. In analyses where fine angular information is important, such as peak shifts due to small changes in the lattice constant or the separation of two closely spaced peaks, some measures are needed, such as narrowing the patch width or supplying the peak positions as a separate feature. How to supply the physical quantity called the diffraction angle as positional information (as a position index, or as a function of the angle itself) is also a design choice.
Exercise 25.6: The crossover point of computational cost
Solution
(1) Solve $12Td^{2}=2T^{2}d$. Dividing both sides by $2Td$ ($\gt0$) gives $6d=T$. Therefore the two are equal at $T=6d$; for $T\lt6d$ the linear transformations dominate, and for $T\gt6d$ attention dominates.
(2) The ratio is $T/(6d)$. The small model of S10: $24/(6\cdot32)=24/192=0.125$. The smallest GPT-2 model: $1024/(6\cdot768)=1024/4608=0.222$. In both cases the linear transformations dominate even at the full context length.
(3) $12\times768^{2}\times12$ $=12\times589{,}824\times12$ $=84{,}934{,}656$ operations. The number of parameters of the 12 blocks of Example 25.10 is $12\times7{,}087{,}872=85{,}054{,}464$, and the difference is only $119{,}808$ (which corresponds to the number of bias and LayerNorm parameters, $12\times(4\cdot768+3072+768+4\cdot768)$). Each individual weight of a linear transformation is used in exactly one multiply–add per token, so “the number of multiply–adds per token ≈ the number of weight parameters.” This is why the computational cost of a large model can be estimated from its number of parameters (the $2Td$ part of attention and the $dV_{\mathrm{voc}}$ part of the output logits are added separately).
Exercise 25.7: The causal mask and “not looking ahead”
Solution
We prove, for $l=0,1,\dots,n_{\mathrm{layer}}$, the proposition $P(l)$: “the $t$th row of the output $\bm{X}^{(l)}$ of the $l$th block is determined only by $x_1,\dots,x_t$ (for all $t$).”
$l=0$: The $t$th row of $\bm{X}^{(0)}$ is $\bm{e}_{x_t}\bm{W}_E+\bm{p}_t$, which is determined only by $x_t$. Hence $P(0)$ holds.
$P(l-1)\Rightarrow P(l)$: Assume $P(l-1)$ and examine each operation of the $l$th pre-LN block in turn.
- $\mathrm{LN}_1$ is applied to each row separately, so the $t$th row of $\mathrm{LN}_1(\bm{X}^{(l-1)})$ is determined only by the $t$th row of $\bm{X}^{(l-1)}$, and by the assumption only by $x_{\le t}$.
- $\bm{Q}_j,\bm{K}_j,\bm{V}_j$ are obtained by multiplying each row by a matrix from the right, so the $s$th row is determined only by $x_{\le s}$.
- The $t$th row of the self-attention output is $\sum_{s}A_{ts}\bm{v}_s$. Because of the causal mask, the weights with $s\gt t$ satisfy $A_{ts}=0$, so the sum runs only over $s\le t$. The weights $A_{ts}$ ($s\le t$) are built from $\bm{q}_t$ and $\bm{k}_1,\dots,\bm{k}_t$, and $\bm{v}_s$ ($s\le t$) is also determined only by $x_{\le t}$. Hence the $t$th row is determined only by $x_{\le t}$. Concatenating the heads and multiplying by $\bm{W}_O$ is a row-wise operation and so changes nothing.
- $\bm{U}=\bm{X}^{(l-1)}+\mathrm{MHA}(\cdot)$ is a row-wise sum, so the $t$th row of $\bm{U}$ is also determined only by $x_{\le t}$.
- $\mathrm{LN}_2$, the FFN, and the residual sum are all row-wise operations, so the $t$th row of $\bm{X}^{(l)}$ is also determined only by $x_{\le t}$.
Hence $P(l)$ holds. By induction $P(n_{\mathrm{layer}})$ holds, and since the final LayerNorm and the multiplication by $\bm{W}_E^{\tp}$ are also row-wise, the $t$th row $\bm{o}_t$ of the logits is determined only by $x_1,\dots,x_t$.
What goes wrong in training: In next-token prediction, the model is trained to predict $x_{t+1}$ from the output at position $t$. If $\bm{o}_t$ could depend on $x_{t+1}$, the model could make the loss almost 0 merely by “copying” $x_{t+1}$ from the input, and would learn no ability to predict the next token at all. At generation time $x_{t+1}$ does not yet exist, so such a model would be useless. Thanks to the causal mask, even when the whole correct sequence is fed in once, the prediction at each position is computed without peeking at the answer, and the losses at all positions can be obtained simultaneously in a single forward propagation.
Exercise 25.8: How much does weight sharing save?
Solution
(1) Keeping a separate $\bm{W}_U\in\R^{768\times50257}$ adds $38{,}597{,}376$ parameters, giving
$$ 124{,}439{,}808+38{,}597{,}376=163{,}037{,}184 . $$The reduction due to sharing is $38{,}597{,}376/163{,}037{,}184=0.237$; that is, 23.7 % of the unshared total.
(2) In the small model of S10, $\bm{W}_U$ has $32\times67=2144$ entries, and without sharing the total would be $28{,}384+2144=30{,}528$. The reduction is $2144/30{,}528=0.070$, or 7.0 %. The vocabulary is small, so the effect is also small.
(3) Writing the $i$th row of $\bm{W}_E$ as $\bm{w}_i$, under weight sharing $o_{t,i}=\bm{h}_t\bm{w}_i^{\tp}$. The difference of the logits of two tokens $i,j$ is
$$ o_{t,i}-o_{t,j}=\bm{h}_t\bm{w}_i^{\tp}-\bm{h}_t\bm{w}_j^{\tp}=\bm{h}_t(\bm{w}_i-\bm{w}_j)^{\tp} $$and by the Cauchy–Schwarz inequality
$$ \abs{o_{t,i}-o_{t,j}}\le\norm{\bm{h}_t}\,\norm{\bm{w}_i-\bm{w}_j} $$holds. Two tokens whose input embeddings are close ($\norm{\bm{w}_i-\bm{w}_j}$ is small) have a small logit difference at every position, and so receive similar probabilities at the output as well. Tokens that tend to appear in the same contexts are learned to have close embeddings, so the learning on the input side and on the output side help each other through a single matrix.
← Back to Chapter 25, “The Structure of the Transformer — Stacking Attention”
Chapter 26 How GPT Learns and Generates Text
Exercise 26.1: Greedy decoding and the most probable sequence
Solution
Each factor is determined by the preceding token alone, so we substitute the values in the table into each factor of the autoregressive decomposition, Eq. (26.1) of Chapter 26, and multiply.
(1)
$$ \begin{aligned} p(\text{A }\langle\text{eos}\rangle)&=0.55\times0.25=0.1375,\\ p(\text{B }\langle\text{eos}\rangle)&=0.45\times0.90=0.405 . \end{aligned} $$(2) There are four sequences with two tokens before <eos>: AA, AB, BA, and BB.
$$ \begin{aligned} p(\text{AA}\langle\text{eos}\rangle)&=0.55\times0.40\times0.25=0.0550,\\ p(\text{AB}\langle\text{eos}\rangle)&=0.55\times0.35\times0.90=0.17325,\\ p(\text{BA}\langle\text{eos}\rangle)&=0.45\times0.05\times0.25=0.005625,\\ p(\text{BB}\langle\text{eos}\rangle)&=0.45\times0.05\times0.90=0.02025 . \end{aligned} $$The sum is $0.0550+0.17325$ $+0.005625+0.02025$ $=0.254125$.
(3) Greedy decoding first chooses A, which has the larger probability (0.55). After A, the largest probability is 0.40 for A, so it chooses A again, and from then on it always chooses A after A. Since <eos> (0.25) is never the largest, greedy decoding keeps generating “A A A …” up to the upper limit of the context length.
On the other hand, the probability of the whole sequence is largest for “B <eos>”, at 0.405. Every sequence that starts with A is the leading factor 0.55 multiplied by numbers less than 1, such as 0.1375 for A <eos> and 0.17325 for AB <eos>, so none of them reaches 0.405 (even the largest continuation among the three after A gives $0.55\times0.35\times0.90=0.173$). Among the sequences starting with B, those that go on to something other than <eos> have probability at most $0.45\times0.05$. Therefore the maximum is B <eos>.
Because greedy decoding chooses at each step the word with the largest immediate probability, it cannot undo a choice that is “advantageous at that moment but followed by a poor continuation,” like the initial A. Maximizing the probability of the whole sequence requires something like beam search, which keeps several partial sequences. Also, as in this example, greedy decoding can fail to escape from repeating the same word.
Exercise 26.2: Segmenting a new word with learned merges
Solution
(1) Split the word into characters, append “_” at the end of the word, and apply the merges in the order n+_, i+o, io+n_, o+x.
- ions: i o n s _ → (n+_ does not apply; n is followed by s) → io n s _ → (io+n_ does not apply) → (o+x does not apply). The result is the four tokens io, n, s, _.
- onion: o n i o n _ → o n i o n_ → o n io n_ → o n ion_ → (o is followed by n, so o+x does not apply). The result is the three tokens o, n, ion_.
- nation: n a t i o n _ → n a t i o n_ → n a t io n_ → n a t ion_. The result is the four tokens n, a, t, ion_.
- oxygen: o x y g e n _ → o x y g e n_ → (no i o) → (no io n_) → ox y g e n_. The result is the five tokens ox, y, g, e, n_.
(2) After four rounds, the symbol sequences are ox i d e _ (once), ion_ (four times), io n s _ (once), and ox y g e n_ (twice). The counts of adjacent pairs are 2 for each of (ox, y), (y, g), (g, e), and (e, n_), all from oxygen occurring twice, and 1 for all the others. The maximum is tied among four pairs, so a rule for deciding which one to merge is needed (for example, choose the pair that appeared first, or choose by character order). Since the rule changes the vocabulary and the segmentation, when implementing BPE one must decide on and record the handling of ties; otherwise the same vocabulary cannot be reproduced from the same text.
(3) For the model, a token is just an ID (the row number of the embedding matrix), and the fact that “ion_” and “io” and “n” contain the same characters is not directly visible from the input. The relation between ion and ions (singular and plural) can only be learned within the embeddings and weights, from the fact that the two appear in similar contexts. The fewer times a word appears in the training data, the more weakly such a relation is learned.
Exercise 26.3: Temperature and entropy
Solution
(1) From $p_i=\exp(o_i/\tau)/Z$ we get $\ln p_i=o_i/\tau-\ln Z$. Substitute this into $H$ and use $\sum_ip_i=1$.
$$ \begin{aligned} H(\tau)&=-\sum_ip_i\Bigl(\frac{o_i}{\tau}-\ln Z\Bigr)\\ &=-\frac{1}{\tau}\sum_ip_io_i+\ln Z\sum_ip_i\\ &=\ln Z(\tau)-\frac{\langle o\rangle}{\tau} . \end{aligned} $$(2) First we find the derivatives of $\ln Z$ and $p_i$. Since $\diff{}{\tau}\exp(o_j/\tau)=-\dfrac{o_j}{\tau^{2}}\exp(o_j/\tau)$,
$$ \diff{\ln Z}{\tau}=\frac{1}{Z}\sum_j\Bigl(-\frac{o_j}{\tau^{2}}\Bigr)e^{o_j/\tau}=-\frac{\langle o\rangle}{\tau^{2}} . $$Differentiating $\ln p_i=o_i/\tau-\ln Z$ gives $\dfrac{1}{p_i}\diff{p_i}{\tau}=-\dfrac{o_i}{\tau^{2}}+\dfrac{\langle o\rangle}{\tau^{2}}$, that is,
$$ \diff{p_i}{\tau}=-\frac{p_i\,(o_i-\langle o\rangle)}{\tau^{2}} . $$Using this,
$$ \begin{aligned} \diff{\langle o\rangle}{\tau}&=\sum_io_i\diff{p_i}{\tau}=-\frac{1}{\tau^{2}}\sum_ip_io_i(o_i-\langle o\rangle)\\ &=-\frac{1}{\tau^{2}}\bigl(\langle o^{2}\rangle-\langle o\rangle^{2}\bigr)=-\frac{\Var_p[o]}{\tau^{2}} . \end{aligned} $$Differentiate the expression in (1) (the derivative of a quotient: $\diff{}{\tau}\dfrac{\langle o\rangle}{\tau}=\dfrac{1}{\tau}\diff{\langle o\rangle}{\tau}-\dfrac{\langle o\rangle}{\tau^{2}}$).
$$ \begin{aligned} \diff{H}{\tau}&=-\frac{\langle o\rangle}{\tau^{2}}-\Bigl(-\frac{\Var_p[o]}{\tau^{3}}-\frac{\langle o\rangle}{\tau^{2}}\Bigr)\\ &=\frac{\Var_p[o]}{\tau^{3}} . \end{aligned} $$The variance is at least 0 and $\tau\gt0$, so $dH/d\tau\ge0$, and $H$ increases monotonically in $\tau$ (only when all the logits are equal is the variance 0, and then $H$ is constant at $\ln V_{\mathrm{voc}}$).
(3) The probabilities at $\tau=1$ are $\bm{p}=(0.46306,\,0.28086,$ $0.17035,\,0.06267,\,0.02305)$.
$$ \begin{aligned} \langle o\rangle&=2.0(0.46306)+1.5(0.28086)\\ &\quad+1.0(0.17035)-1.0(0.02305)\\ &=1.4947,\\ \langle o^{2}\rangle&=4(0.46306)+2.25(0.28086)\\ &\quad+1(0.17035)+1(0.02305)\\ &=2.6776 . \end{aligned} $$$\Var_p[o]=2.6776-1.4947^{2}$ $=2.6776-2.2342=0.4434$. Since $\tau=1$, $dH/d\tau=0.4434$ nat. As a check, by the expression in (1), $\ln Z=\ln15.957=2.7699$ and $H=2.7699-1.4947=1.2752$ nat, which agrees with the value in Example 26.6.
Exercise 26.4: Combining top-k and top-p
Solution
(1) The sum of the exp values is $2.718+2.226+1.221$ $+0.607+0.223=6.995$ (6.9949 without rounding).
$$ \begin{aligned} \bm{p}(1)=(&0.3886,\ 0.3182,\ 0.1746,\\ &0.0867,\ 0.0319) . \end{aligned} $$(2) The cumulative sums in decreasing order are $0.3886$, $0.7068$ ($\lt0.75$), and $0.8814$ ($\ge0.75$). Three words remain, and renormalizing by $0.8814$ gives $(0.4409,\ 0.3610,\ 0.1981,\ 0,\ 0)$.
(3) Dividing the logits by 0.5 gives $(2.0,\,1.6,\,0.4,\,-1.0,\,-3.0)$. The exp values are $7.389$, $4.953$, $1.492$, $0.368$, $0.050$, with sum $14.252$, and $\bm{p}(0.5)=(0.5185,\,0.3475,$ $0.1047,\,0.0258,\,0.0035)$. The cumulative sums are $0.5185$ and $0.8660$ ($\ge0.75$), so two words remain, and the result is $(0.5987,\ 0.4013,\ 0,\ 0,\ 0)$. When the distribution becomes sharper, fewer words remain for the same $p$.
(4) Keeping three words with top-k $=3$ and renormalizing gives $(0.4409,\,0.3610,\,0.1981)$. Taking the cumulative sums with these renormalized probabilities gives $0.4409$ and $0.8019$ ($\ge0.75$), so two words remain, and renormalizing by $0.8019$ gives $(0.5498,\ 0.4502,\ 0,\ 0,\ 0)$. In (2) three words remained, whereas here there are two. This is because renormalizing after cutting the tail with top-k raises the probabilities of the top words, so the cumulative sum reaches $p$ sooner. When top-k and top-p are combined, the result depends on the order of application and on which probabilities the cumulative sum is taken over.
Exercise 26.5: The gradient and the optimal solution of next-token prediction
Solution
(1) $\ell=-\ln p_y(\tau)=-\dfrac{o_y}{\tau}+\ln\sum_j\exp(o_j/\tau)$. The derivative of the first term with respect to $o_i$ is $-[i=y]/\tau$. For the second term, by the chain rule,
$$ \pdiff{}{o_i}\ln\sum_j e^{o_j/\tau}=\frac{1}{\sum_je^{o_j/\tau}}\cdot\frac{1}{\tau}e^{o_i/\tau}=\frac{p_i(\tau)}{\tau} . $$Together, $\pdiff{\ell}{o_i}=\bigl(p_i(\tau)-[i=y]\bigr)/\tau$. For $\tau=1$ this reduces to Eq. (26.5) of Chapter 26.
(2) $\bm{o}/\tau=(0.5,\,0,\,-0.5)$. We have $e^{0.5}=1.6487$, $e^{0}=1$, $e^{-0.5}=0.6065$, with sum $3.2553$, so $\bm{p}=(0.5065,\,0.3072,\,0.1863)$. The gradient is
$$ \begin{aligned} \frac{\bm{p}-\bm{y}}{\tau}&=\frac{(0.5065,\,-0.6928,\,0.1863)}{2}\\ &=(0.2532,\,-0.3464,\,0.0932) . \end{aligned} $$(3) By Eq. (26.4) of Chapter 26, the expected loss is $H[p_{\mathrm{data}}]+\KL(p_{\mathrm{data}}\,\|\,q)$. The first term does not depend on $q$. The second term is at least 0, and it is 0 only when $q=p_{\mathrm{data}}$ (Chapter 5). Therefore the $q$ that minimizes the expected loss is $p_{\mathrm{data}}$ itself, and the minimum value is the entropy $H[p_{\mathrm{data}}]$.
Exercise 26.6: Decomposing the loss of the mercury sentence
Solution
(1) The correct sentence (liquid):
$$ \begin{aligned} \ln p&=-6.859-0.116-2.585\\ &\quad-0.003-8.112-0.007\\ &=-17.682 . \end{aligned} $$The number of tokens is 8, so the perplexity is $\exp(17.682/8)=\exp(2.210)=9.12$. The incorrect sentence (solid): $-6.859-0.116-2.585$ $-0.003-0.002-0.001$ $=-9.566$, and the perplexity is $\exp(9.566/8)=\exp(1.196)=3.31$.
(2) The first four tokens are common to both, so the difference $-9.566-(-17.682)=8.116$ comes from the last four tokens. Among them, the difference at the position of “liquid” and “solid” is $-0.002-(-8.112)=8.110$, which accounts for almost all of it.
(3) The optimal distribution that does not distinguish contexts is $q_{\text{solid}}=590/591$, $q_{\text{liquid}}=1/591$ (Eq. (26.14)). The loss at the 591 positions is $-\ln(590/591)=0.001693$ for each of the 590 solid positions and $\ln591=6.382$ for the one liquid position. The average is
$$ \begin{aligned} \frac{590\times0.001693+6.382}{591}&=\frac{0.999+6.382}{591}\\ &=0.01249\ \text{nat} . \end{aligned} $$The total is $7.381$ nat. For a model that can perfectly distinguish mercury alone (putting 1 on liquid in the mercury context and 1 on solid elsewhere), every position has probability 1, so the average loss is 0.
(4) The total loss over the entire training data is about 0.505 nat per token times about 50,300 predicted tokens (the leading <bos> is not predicted), or about $2.5\times10^{4}$ nat. Even if the mercury exception were learned perfectly, the reduction would be at most about 7.4 nat, only about 0.03 % of the whole. Seen against the total loss, the weight of memorizing a rare exception is extremely small, and learning by gradients does not necessarily give priority to memorizing this exception. The exceptions that matter in materials engineering (metals that are liquid at room temperature, ferromagnetic metals, insulators that conduct heat well, and so on) are often exactly the “rare” ones, so for the answers of a language model, the more exceptional the property, the more it needs to be checked.
Exercise 26.7: A sampling inspection that found no errors
Solution
(1) Of 15 items, 0 are wrong ($m=0$, $l=15$), so the posterior distribution is $\mathrm{Beta}(1+0,\,1+15)=\mathrm{Beta}(1,16)$. The posterior mean is $1/(1+16)=1/17=0.0588$.
(2) The density of $\mathrm{Beta}(1,16)$ is $16(1-\mu)^{15}$, and the cumulative distribution function is $\int_0^u16(1-\mu)^{15}\dd\mu=1-(1-u)^{16}$. Set this equal to 0.95.
$$ \begin{aligned} &(1-u)^{16}=0.05\\ &\Longrightarrow\ u=1-0.05^{1/16}=1-0.8293=0.1707 . \end{aligned} $$Even if there is not a single error, the proportion of errors can be as high as about 17 %.
(3) If there are no errors among $n$ items, the posterior distribution is $\mathrm{Beta}(1,n+1)$, and the 95 % upper limit is $1-0.05^{1/(n+1)}$. The condition for this to be less than 0.05 is $0.05^{1/(n+1)}\gt0.95$; taking logarithms, $\dfrac{\ln0.05}{n+1}\gt\ln0.95$. Dividing by $\ln0.95\lt0$ reverses the inequality, giving $n+1\gt\ln0.05/\ln0.95=58.40$. Hence $n+1\ge59$, that is, $n\ge58$ items (at $n=58$ the upper limit is 0.0495, and at $n=57$ it is 0.0503).
(4) Finding no errors in 15 items does not show that the proportion of errors is 0. As in (2), it is consistent even with an error proportion of about 17 %. Moreover, among 15 randomly chosen items, rare kinds of errors (a particular way of writing a unit, a particular measurement method) are easily missed. A report should state the size of the inspection and the upper limit, for example: “15 items were checked against the source and 0 errors were found; the 95 % upper limit of the error proportion is about 17 %.”
Exercise 26.8: What a small model can tell us
Solution
- (a) Can be said as a mechanism (but not as a number). In S10, the probability of the correct word dropped for the materials that have only 8 sentences in the corpus (training + validation), and the top-ranked errors were also concentrated there (Figure 26.7). This is a mechanism that comes from the form of the model and its objective function, namely that the objective function of next-token prediction reflects frequency (the extreme case of Eq. (26.14)), so a trend in the same direction can occur in larger models of the same form. However, the strength of the trend changes with scale and data, and it cannot be determined from S10.
- (b) Cannot be said. The 9.0 % is a value measured with the small model of S10 and a synthetic corpus for teaching purposes; the actual GPT differs in model size, training data, and tuning (Table 26.1).
- (c) Cannot be said (rather, it is wrong). $\tau\to0$ is the same as greedy decoding and simply chooses the top-ranked word with certainty. In the mercury example the top-ranked word is the incorrect “solid,” so lowering $\tau$ makes the error appear with certainty. Temperature reduces Reason 3 (errors due to sampling), but it does not reduce the errors due to Reasons 1 and 2.
- (d) Cannot be said. In step 5 of Simulator 26.2, the last position of the barium titanate context put a weight of 0.80 on the material name, but the answer was wrong. Attention weights are the proportions in which information is gathered; they do not guarantee that a judgment is correct or give its reasons (Chapter 24, Section 24.10).
- (e) Can be said. The claim is the negation of “if the probability is high, it is correct,” so a single counterexample suffices to show it. In S10, the $\ln p$ of the incorrect “Mercury is solid at room temperature .” is −9.57, which is larger than −17.68 for the correct sentence. This counterexample holds even for a small model, and it is sufficient to negate the claim.
← Back to Chapter 26, “How GPT Learns and Generates Text”
Chapter 27 Connections to Materials Science and Statistical Mechanics — From the Partition Function to Machine-Learning Interatomic Potentials
Exercise 27.1: The energy reference and the free energy
Solution
(1) $k_{\mathrm B}T$ $=8.617\times10^{-5}\times600$ $=0.05170\ \mathrm{eV}$, $\beta$ $=1/0.05170$ $=19.34\ \mathrm{eV^{-1}}$. The weights are
$$ \begin{aligned} e^{-\beta\times0}&=1,\\ e^{-0.05/0.05170}&=e^{-0.9671}=0.3802,\\ e^{-0.10/0.05170}&=e^{-1.9341}=0.1446 . \end{aligned} $$$Z=1+0.3802+0.1446=1.5248$. The probabilities are $p=(0.6558,\ 0.2494,\ 0.0948)$. $A$ $=-0.05170\times\ln1.5248$ $=-0.05170\times0.4218$ $=-0.02181\ \mathrm{eV}$. $U$ $=0.05\times0.2494+0.10\times0.0948$ $=0.01247+0.00948$ $=0.02195\ \mathrm{eV}$.
(2) Each weight is multiplied by $e^{-\beta\times1.00}$ $=e^{-19.34}$ $=3.98\times10^{-9}$.
- Probabilities: the same factor multiplies the numerator and the denominator, so they do not change.
- $Z$: it is multiplied by $3.98\times10^{-9}$, giving $6.08\times10^{-9}$.
- $A$: since $-k_{\mathrm B}T\ln(Ze^{-\beta})$ $=-k_{\mathrm B}T\ln Z+1.00$, it rises by $1.00$ eV to $0.9782\ \mathrm{eV}$.
- $U$: the probabilities are unchanged and each energy is larger by $1.00$, so it rises by $1.00$ eV to $1.0219\ \mathrm{eV}$.
- $S=(U-A)/T$: $U$ and $A$ rise by the same amount, so it does not change. $S$ $=(0.02195+0.02181)/600$ $=7.29\times10^{-5}\ \mathrm{eV\,K^{-1}}$, that is, $S/k_{\mathrm B}=0.846$.
The choice of the energy origin shifts the values of $A$ and $U$, but it does not affect the probabilities or the entropy (a quantity of differences, which can be measured).
Exercise 27.2: Gradient, convexity, and fluctuations of an exponential-family model
Solution
(1) Differentiating $Z_{\bm{\theta}}$ $=\sum_x\exp(\bm{\theta}^{\tp}\bm{f}(x))$ and using $\partial\exp(\bm{\theta}^{\tp}\bm{f})/\partial\bm{\theta}$ $=\bm{f}\exp(\bm{\theta}^{\tp}\bm{f})$, we get
$$ \begin{aligned}\pdiff{\ln Z_{\bm{\theta}}}{\bm{\theta}}&=\frac{1}{Z_{\bm{\theta}}}\sum_x\bm{f}(x)\exp(\bm{\theta}^{\tp}\bm{f}(x))\\ &=\sum_xp_{\bm{\theta}}(x)\bm{f}(x)=\Ex_{p_{\bm{\theta}}}[\bm{f}].\end{aligned} $$(2) Differentiating $\ln p_{\bm{\theta}}(x)$ $=\bm{\theta}^{\tp}\bm{f}(x)-\ln Z_{\bm{\theta}}$ and using (1) gives $\partial\ln p_{\bm{\theta}}(x)/\partial\bm{\theta}$ $=\bm{f}(x)-\Ex[\bm{f}]$, and hence $\partial p_{\bm{\theta}}(x)/\partial\bm{\theta}^{\tp}$ $=p_{\bm{\theta}}(x)(\bm{f}(x)-\Ex[\bm{f}])^{\tp}$. Differentiating the result of (1) once more,
$$ \begin{aligned} \frac{\partial^{2}\ln Z_{\bm{\theta}}}{\partial\bm{\theta}\,\partial\bm{\theta}^{\tp}}&=\sum_x\bm{f}(x)\pdiff{p_{\bm{\theta}}(x)}{\bm{\theta}^{\tp}}\\ &=\sum_xp_{\bm{\theta}}(x)\bm{f}(x)\bigl(\bm{f}(x)-\Ex[\bm{f}]\bigr)^{\tp}\\ &=\Ex[\bm{f}\bm{f}^{\tp}]-\Ex[\bm{f}]\Ex[\bm{f}]^{\tp}=\Cov_{p_{\bm{\theta}}}[\bm{f}]. \end{aligned} $$The mean negative log-likelihood is $-\ell(\bm{\theta})$ $=-\bm{\theta}^{\tp}\bar{\bm{f}}+\ln Z_{\bm{\theta}}$ (with $\bar{\bm{f}}$ $=\frac1N\sum_n\bm{f}(x_n)$). The first term is a linear function of $\bm{\theta}$, so the Hessian matrix equals $\Cov_{p_{\bm{\theta}}}[\bm{f}]$. For any $\bm{a}$, $\bm{a}^{\tp}\Cov[\bm{f}]\bm{a}$ $=\Var[\bm{a}^{\tp}\bm{f}]\ge0$, so the covariance matrix is positive semidefinite, and $-\ell$ is a convex function.
(3) Setting $\bm{\theta}\to-\beta$ (a scalar) and $\bm{f}\to E$, (1) and (2) become
$$ \begin{aligned}&\diff{\ln Z}{(-\beta)}=\Ex[E],\\ &\frac{\dd^{2}\ln Z}{\dd(-\beta)^{2}}=\frac{\dd^{2}\ln Z}{\dd\beta^{2}}=\Var[E].\end{aligned} $$Hence $U=\Ex[E]=-\dd\ln Z/\dd\beta$ and $\dd U/\dd\beta$ $=-\dd^{2}\ln Z/\dd\beta^{2}$ $=-\Var[E]$. From $\beta=1/(k_{\mathrm B}T)$ we have $\dd\beta/\dd T$ $=-1/(k_{\mathrm B}T^{2})$, so
$$ \begin{aligned}C&=\diff{U}{T}=\diff{U}{\beta}\diff{\beta}{T}\\ &=(-\Var[E])\times\Bigl(-\frac{1}{k_{\mathrm B}T^{2}}\Bigr)\\ &=\frac{\Var[E]}{k_{\mathrm B}T^{2}}.\end{aligned} $$Since a variance cannot be negative, we also see that the specific heat of the canonical distribution is never negative.
Exercise 27.3: Antiferromagnetic spins on a triangle
Solution
(1) When all three spins point the same way ($+++$, $---$), the products on the three bonds are all $+1$, so $E=3J$. In the other six states (two spins the same, one opposite), there is one pair pointing the same way (product $+1$) and two pairs pointing oppositely (product $-1$), so $E=J(1-1-1)=-J$. To make all three bonds antiparallel, we would need $s_1=-s_2$, $s_2=-s_3$, and $s_3=-s_1$; but the first two give $s_1=s_3$, which contradicts the third. In every state at least one bond is “unsatisfied” (frustration).
(2) $Z=6e^{\beta J}+2e^{-3\beta J}$.
(3) For $\beta J=1$: $Z$ $=6\times2.7183+2\times0.04979$ $=16.3097+0.0996$ $=16.4093$. The probability of being in one of the six lowest-energy states is $16.3097/16.4093=0.9939$. $\langle E\rangle/J$ $=[(-1)\times16.3097+3\times0.0996]/16.4093$ $=(-16.3097+0.2987)/16.4093$ $=-0.9757$. $S/k_{\mathrm B}$ $=\ln Z+\beta\langle E\rangle$ $=\ln16.4093+1\times(-0.9757)$ $=2.7978-0.9757$ $=1.8221$.
(4) As $T\to0$, only the six lowest-energy states remain, with equal probabilities, so $S/k_{\mathrm B}\to\ln6=1.792$. For a ferromagnet ($J\lt0$), the lowest energy is attained by just two states, $+++$ and $---$, so $S/k_{\mathrm B}\to\ln2=0.693$. In the antiferromagnetic triangle, frustration makes the lowest-energy states numerous, so entropy remains even at low temperature. It is this kind of degeneracy that underlies the entropy that remains even in the limit of absolute zero (residual entropy), which is discussed for antiferromagnets on the triangular and Kagome lattices and for the arrangement of hydrogen atoms in water ice.
Exercise 27.4: Variation with a trial Hamiltonian
Solution
(1) Setting $q=p_0$ in Theorem 27.1 gives $A\le A[p_0]=\Ex_{p_0}[E]-TS[p_0]$. Since $p_0$ itself is the Boltzmann distribution of $E_0$, applying the equality case of Theorem 27.1 to $E_0$ gives $A_0=\Ex_{p_0}[E_0]-TS[p_0]$, that is, $-TS[p_0]=A_0-\Ex_{p_0}[E_0]$. Substituting,
$$ \begin{aligned}A&\le\Ex_{p_0}[E]+A_0-\Ex_{p_0}[E_0]\\ &=A_0+\Ex_{p_0}[E-E_0].\end{aligned} $$(2) For $E_0=-b(s_1+s_2)$ the spins are independent, with $Z_0$ $=(e^{\beta b}+e^{-\beta b})^{2}$ $=(2\cosh\beta b)^{2}$, $A_0$ $=-2k_{\mathrm B}T\ln(2\cosh\beta b)$, and $\Ex_{p_0}[s_i]=\tanh\beta b\equiv m$. By independence, $\Ex_{p_0}[E]$ $=-J\Ex[s_1]\Ex[s_2]$ $=-Jm^{2}$ and $\Ex_{p_0}[E_0]=-2bm$. Hence the right-hand side is
$$ R(m)=-2k_{\mathrm B}T\ln(2\cosh\beta b)-Jm^{2}+2bm . $$Using $\beta b=\operatorname{artanh}m$ and $\cosh(\operatorname{artanh}m)$ $=1/\sqrt{1-m^{2}}$, we write it in terms of $m$.
$$ \begin{aligned} \beta R(m)&=-2\ln2+\ln(1-m^{2})\\ &\quad-\beta Jm^{2}+2m\operatorname{artanh}m . \end{aligned} $$On the other hand, simplifying $\varphi(m)$ $=\tfrac{1+m}{2}\ln\tfrac{1+m}{2}+\tfrac{1-m}{2}\ln\tfrac{1-m}{2}$ gives $\varphi(m)$ $=-\ln2+\tfrac12\ln(1-m^{2})+m\operatorname{artanh}m$, so $\beta R(m)$ $=-\beta Jm^{2}+2\varphi(m)$. This agrees with Eq. (27.12) of the main text (the mean-field variational free energy per spin) with $N=2$, $n_{\mathrm{nn}}=1$, and $h=0$. Differentiating with respect to $m$ and setting the result to 0 gives $-2\beta Jm+2\operatorname{artanh}m$ $=0$, that is, $m=\tanh(\beta Jm)$. “Varying within the distributions of independent spins” and “varying with a trial Hamiltonian with an effective field $b$” are the same thing, and the optimal effective field is $b=Jm$.
Exercise 27.5: The maximum-entropy distribution of a positive quantity
Solution
(1) By the same calculation as in Theorem 27.2 (replacing the sum by an integral over $x\ge0$), $p(x)=e^{-\lambda x}/Z$. For $Z=\int_0^\infty e^{-\lambda x}\dd x$ to be finite we need $\lambda\gt0$, and then $Z=1/\lambda$. The mean is $\Ex[x]$ $=\lambda\int_0^\infty xe^{-\lambda x}\dd x$ $=\lambda\times1/\lambda^{2}$ $=1/\lambda$, so the constraint gives $\lambda=1/\mu$. Therefore $p(x)=\mu^{-1}e^{-x/\mu}$.
(2) Since $-\ln p(x)=\ln\mu+x/\mu$, $H$ $=\Ex[-\ln p]$ $=\ln\mu+\Ex[x]/\mu$ $=\ln\mu+1$. (If the unit of $x$ is changed, $\ln\mu$ changes. The differential entropy depends on the unit.)
(3) For $\mu=2\ \mu\mathrm{m}$, $P(d\gt4)$ $=\int_4^\infty\tfrac12e^{-d/2}\dd d$ $=e^{-4/2}$ $=e^{-2}$ $=0.135$.
(4) The exponential distribution is monotonically decreasing with its maximum density at $d=0$, but the grain-size distribution of an actual sintered body often has a peak at some size and a tail extending to the right (a shape close to a lognormal distribution). If we fix the mean of $\ln d$ and the mean of its square, the maximum-entropy distribution becomes $p(d)\propto\exp(-\lambda_1\ln d-\lambda_2(\ln d)^{2})$ $=d^{-\lambda_1}e^{-\lambda_2(\ln d)^{2}}$, which has the form of a lognormal distribution (with $\lambda_2\gt0$). If we put into the constraints the means of whichever quantities we know, the shape of the distribution changes accordingly. Regarding the maximum-entropy distribution for the mean alone as a “model of the grain-size distribution” leaves information unused.
Exercise 27.6: Estimating atomic energies from the total energy alone
Solution
(1) The kernel values are $k(0,0)=k(1,1)=1$ and $k(0,1)=e^{-0.5}=0.6065$. From Eq. (27.17) (the covariance of the total energies),
$$ \begin{aligned} \Var[E_A]&=4\,k(0,0)=4,\\ \Var[E_B]&=k(0,0)+k(1,1)+2k(0,1)\\ &=2+1.2131=3.2131,\\ \Cov[E_A,E_B]&=\sum_{i\in A}\bigl[k(0,0)+k(0,1)\bigr]\\ &=2\times1.6065=3.2131 \end{aligned} $$(in units of $\mathrm{eV^{2}}$).
(2) By the conditional-distribution formula,
$$ \begin{aligned} \Ex[E_B\mid E_A]&=\frac{3.2131}{4}\times(-8.0)\\ &=-6.426\ \mathrm{eV},\\ \Var[E_B\mid E_A]&=3.2131-\frac{3.2131^{2}}{4}\\ &=3.2131-2.5810\\ &=0.6321\ \mathrm{eV^{2}}. \end{aligned} $$The standard deviation is $0.795\ \mathrm{eV}$.
(3) Since $\Cov[e_{\mathrm{at}}(0),E_A]$ $=2k(0,0)$ $=2$, we have $\Ex[e_{\mathrm{at}}(0)\mid E_A]$ $=2/4\times(-8.0)$ $=-4.0\ \mathrm{eV}$, and the variance is $1-2^{2}/4=0$. The two atoms of structure A have the same environment, so the total energy determines $-4.0$ eV per atom with certainty. On the other hand, for an atom with $G=1$, from $\Cov[e_{\mathrm{at}}(1),E_A]$ $=2e^{-0.5}$ $=1.2131$ we get $\Ex[e_{\mathrm{at}}(1)\mid E_A]$ $=1.2131/4\times(-8.0)$ $=-2.426\ \mathrm{eV}$, with variance $1-1.2131^{2}/4=0.632$ (standard deviation $0.795$ eV). Because we have not observed an environment with $G=1$, only part of the information on $G=0$ is carried over through the kernel similarity, and a large uncertainty remains. The prediction of $E_B$ in (2) is $-4.0+(-2.426)=-6.426$ eV, and all of its uncertainty comes from the atom with $G=1$. Note also that the value $-2.426$ eV depends strongly on the prior mean of 0 and on the kernel assumption, and is not a physically meaningful “atomic energy” (the caution in Section 27.9).
Exercise 27.7: The yardstick for potential errors and the design of training data
Solution
(1) At 300 K: $k_{\mathrm B}T$ $=0.02585\ \mathrm{eV}$ $=25.9\ \mathrm{meV}$, and $3\ \mathrm{meV}$ is $0.116$ times that. At 1500 K: $k_{\mathrm B}T$ $=0.1293\ \mathrm{eV}$ $=129.3\ \mathrm{meV}$, and $3\ \mathrm{meV}$ is $0.023$ times that. Per atom, the error is well below $k_{\mathrm B}T$.
(2) $200\times3\ \mathrm{meV}$ $=0.60\ \mathrm{eV}$. At 1500 K, $0.60/0.1293=4.64$ and $e^{4.64}\approx104$ times. Even if the per-atom error is small, when the errors point in the same direction they can change the ratio of probabilities between configurations by two orders of magnitude (in practice part of the errors cancel, so this is an upper-limit estimate).
(3) Examples:
- Structures to add to the training data: snapshots of molecular dynamics near 1500 K (large thermal vibrations), liquid structures, structures with defects such as vacancies and interstitial atoms and structures in the middle of diffusion (near the saddle point), and structures with changed volume. With low-temperature crystals alone, the high-temperature atomic environments lie outside the training range (Section 27.7, Figure 27.6).
- Active learning: run high-temperature molecular dynamics with the trained potential, and add the structures with large uncertainty (ensemble spread or predictive variance) after computing them from first principles (Figure 27.7).
- Checks after training: besides the RMSE of the energy, compare the force errors and the errors in energy differences between configurations (defect formation energies, diffusion barriers) with $k_{\mathrm B}T$.
- Evaluation on the target properties: compare the melting point, diffusion coefficient, thermal expansion, and so on with first-principles molecular dynamics (small systems) or experimental values. Test on structures not used in training (a different temperature or composition).
- Monitor whether signs of extrapolation appear during molecular dynamics, such as atoms approaching each other abnormally closely.
Exercise 27.8: The transition temperature in the mean-field approximation
Solution
(1) $k_{\mathrm B}T_{\mathrm c}$ $=Jn_{\mathrm{nn}}$ $=0.020\times6$ $=0.120\ \mathrm{eV}$, $T_{\mathrm c}$ $=0.120/(8.617\times10^{-5})$ $=1393\ \mathrm{K}$.
(2) At $T=0.8\,T_{\mathrm c}$, $\beta Jn_{\mathrm{nn}}=1/0.8=1.25$. Iterating,
$$ \begin{aligned} m&:\ 1\to0.8483\to0.7858\to0.7540\\ &\quad\to0.7364\to0.7261\to0.7200\\ &\quad\to\cdots\to0.7104 . \end{aligned} $$To three decimal places, $m=0.710$ (the value in Figure 27.3 (b) of the main text).
(3) The mean-field approximation gives $4J$, and the exact solution is $2J/\ln(1+\sqrt2)=2J/0.8814=2.269J$, so the ratio is $4/2.269=1.76$. As the number $n_{\mathrm{nn}}$ of interacting partners increases, the effective field felt by one spin becomes an average over many spins, and the fluctuation of that average (the part that the mean-field approximation neglects) becomes relatively small (the same idea as the variance of an average of independent quantities decreasing as $1/n$; Chapter 2, Section 2.8). Therefore the mean-field approximation becomes more accurate in three dimensions, and still more so on lattices with more partners. Conversely, in one dimension ($n_{\mathrm{nn}}=2$), fluctuations destroy the order, so the exact solution has no finite-temperature phase transition, whereas the mean-field approximation predicts $k_{\mathrm B}T_{\mathrm c}=2J$.
Chapter 28 A Comprehensive Exercise in Materials Search — From Checking the Data to Proposing Additional Experiments
Exercise 28.1: The second EI
Solution
$d=\mu_*-f_{\mathrm{best}}=-3.371-(-3.426)=0.055$, $z=d/\sigma_*=0.055/0.104=0.529$. Substituting into the formula for expected improvement, $\mathrm{EI}=d\,\Phi(z)+\sigma_*\Normal(z\mid0,1)$, we obtain
$$ \begin{aligned} \mathrm{EI}&=0.055\times0.7015+0.104\times0.3469\\ &=0.0386+0.0361=0.0747. \end{aligned} $$The value 0.074 in Table 28.6 was computed from the values before rounding ($\mu_*=-3.37108$, $\sigma_*=0.10397$, $f_{\mathrm{best}}=-3.42565$), which gives 0.0743. The difference comes from rounding the inputs to three digits.
Although the predicted mean exceeds the best value, the EI is smaller than at the first round, for two reasons. First, the best value itself rose from $-3.912$ to $-3.426$ with the first observation, so the margin $d$ by which the mean exceeds it decreased from 0.191 to 0.055. Second, the width $\sigma_*$ also shrank from 0.147 to 0.104. The EI is determined by both the “improvement measured by the mean” $d$ and the “prospect of luckily exceeding the best value by as much as the width” $\sigma_*$, and both became smaller.
Exercise 28.2: Covariance with a batch term
Solution
(1) Two samples in the same batch $j$ and under the same condition $\bm{x}$ are $y_1=f(\bm{x})+u_j+\varepsilon_1$ and $y_2=f(\bm{x})+u_j+\varepsilon_2$. Since $f$, $u_j$, $\varepsilon_1$, and $\varepsilon_2$ are independent, the bilinearity of covariance leaves only the terms involving the same random variable:
$$ \begin{aligned} \Cov[y_1,y_2]&=\Var[f(\bm{x})]+\Var[u_j]\\ &=\sigma_f^{2}+\sigma_b^{2}. \end{aligned} $$(Since $\varepsilon_1$ and $\varepsilon_2$ are different, independent random variables, their covariance is 0.) Each variance is $\Var[y_i]=\sigma_f^{2}+\sigma_b^{2}+\sigma^{2}$, so the correlation coefficient is
$$ \rho_{\text{same}}=\frac{\sigma_f^{2}+\sigma_b^{2}}{\sigma_f^{2}+\sigma_b^{2}+\sigma^{2}} . $$(2) For different batches $j\ne j'$, $u_j$ and $u_{j'}$ are independent, so $\Cov[y_1,y_2]=\sigma_f^{2}$, and the correlation coefficient is $\rho_{\text{diff}}=\sigma_f^{2}/(\sigma_f^{2}+\sigma_b^{2}+\sigma^{2})$.
With the estimates in the main text, $\sigma_f=0.404$, $\sigma_b=0.097$, $\sigma=0.043$, we have $\sigma_f^{2}=0.1632$, $\sigma_b^{2}=0.0094$, $\sigma^{2}=0.0018$, and the denominator is $0.1745$, so $\rho_{\text{same}}=0.1726/0.1745=0.989$ and $\rho_{\text{diff}}=0.1632/0.1745=0.935$. Two samples in the same batch are more strongly correlated.
(3) For fixed inputs, $\bm{f}\sim\Normal(m\bm{1},\bm{K})$, $\bm{u}=(u_1,\dots,u_J)^{\tp}\sim\Normal(\bm{0},\sigma_b^{2}\bm{I})$, and $\bm{\varepsilon}\sim\Normal(\bm{0},\sigma^{2}\bm{I})$ are independent, and $\bm{y}=\bm{f}+\bm{Z}\bm{u}+\bm{\varepsilon}$ is a linear combination of Gaussian-distributed quantities, so it is Gaussian-distributed. The mean is $m\bm{1}$ and the covariance is $\bm{K}+\bm{Z}(\sigma_b^{2}\bm{I})\bm{Z}^{\tp}+\sigma^{2}\bm{I}=\bm{K}_y$ (Eq. (28.9) of Chapter 28). Taking the logarithm of the multivariate Gaussian density gives
$$ \begin{aligned} &\ln p(\bm{y}\mid\bm{\theta})\\ &=-\tfrac12(\bm{y}-m\bm{1})^{\tp}\bm{K}_y^{-1}(\bm{y}-m\bm{1})\\ &\quad-\tfrac12\ln\abs{\bm{K}_y}-\tfrac N2\ln2\pi , \end{aligned} $$where $\bm{K}_y=\bm{K}+\sigma_b^{2}\bm{Z}\bm{Z}^{\tp}+\sigma^{2}\bm{I}$ and $\bm{\theta}=(\ell_c,\ell_T,\sigma_f,\sigma,\sigma_b)$. The form is the same as the equation in Chapter 12; only $\bm{K}_y$ is replaced. As in Chapter 12, the computation is done with the Cholesky decomposition.
Exercise 28.3: Translating the prediction error into the language of conductivity
Solution
(1) $10^{0.253}=1.79$. The prediction of the conductivity of a sample fired in a new batch is typically off by a factor of about 1.8 (either too high or too low). Since $10^{-0.253}=0.56$, we may also say “0.56 to 1.8 times the prediction.”
(2) The observed value is $10^{-3.248}=5.65\times10^{-4}\ \mathrm{S\,cm^{-1}}$ and the true value is $10^{-3.401}=3.97\times10^{-4}\ \mathrm{S\,cm^{-1}}$. The ratio is $10^{-3.248+3.401}=10^{0.153}=1.42$, so the reported value is 40 % higher than the true value.
(3) This value was chosen because it was the largest among the five additional experiments, so it is quite likely to be inflated by noise and the batch offset (Chapter 28, Section 28.9.2). Before reporting it, remake the sample several times under the same condition, including other batches, and show the mean and standard deviation. Alternatively, attach the predicted mean of the Gaussian process and its width (after accumulating observations, $\mu_*\pm2\sigma_*$). For comparison, it is also good to put a baseline sample (a condition measured many times in the past) in the same batch and show the value with the batch offset subtracted (Exercise 28.4).
Exercise 28.4: Putting a baseline sample in each batch
Solution
(1) When measured in separate batches $j,j'$, $y_{\mathrm A}-y_{\mathrm R}=\bigl(g_{\mathrm A}-g_{\mathrm R}\bigr)$ $+(u_j-u_{j'})$ $+(\varepsilon_{\mathrm A}-\varepsilon_{\mathrm R})$. The four random variables are independent, so the variance of the difference is $2\sigma_b^{2}+2\sigma^{2}$ $=2\times0.0064+2\times0.0025$ $=0.0178$, and the standard deviation is $\sqrt{0.0178}=0.133$.
(2) In the same batch $j$, $u_j$ cancels, and $y_{\mathrm A}-y_{\mathrm R}=(g_{\mathrm A}-g_{\mathrm R})+(\varepsilon_{\mathrm A}-\varepsilon_{\mathrm R})$. The variance is $2\sigma^{2}=0.005$ and the standard deviation is $\sqrt{0.005}=0.071$.
(3) If we put the baseline sample in the same batch and take the difference, the uncertainty of the difference becomes roughly half (0.133 → 0.071). In each batch of the additional experiments, it is good to fire one baseline sample together with the samples of the new conditions. From the value of the baseline sample we can estimate the offset $u_j$ of that batch, so we can separate whether a new condition is good or bad from the batch offset. On the surrogate model side, include the batch term of Section 28.5.2 ($\sigma_b^{2}\bm{Z}\bm{Z}^{\tp}$), and add the observations of the baseline sample to the data together with their batch numbers. Then, through the correlation between observations in the same batch, the Gaussian process automatically subtracts the offset when evaluating the new conditions.
Exercise 28.5: Start over with a different seed
Solution
Compute as follows (using the same functions as in the main text).
import ch28_capstone as cc
d, u = cc.clean_from_seed(20261113)
X, y, b = cc.stack(d["c"], d["T"]), d["y"], d["batch"]
fr, fg = cc.folds_random(len(y), 5, 20261112), cc.folds_group(b)
for key in ("mean", "gp"):
rr = cc.cross_validate(key, X, y, b, fr)
rg = cc.cross_validate(key, X, y, b, fg)
print(key, cc.mae_rmse(y, rr["pred"]), cc.mae_rmse(y, rg["pred"]))
rg = cc.cross_validate("gp", X, y, b, fg)
print(cc.coverage(y, rg["pred"], rg["s_obs"]))
The results (Python 3.12.13, numpy 2.5.4, scipy 1.18.1) are as follows. The true batch offsets of this data set are, from B1 in order, $+0.070$, $-0.173$, $-0.018$, $+0.030$, $-0.053$.
- Model that answers with the mean: random RMSE 0.277, batch-wise RMSE 0.295.
- Gaussian process: random RMSE 0.081, batch-wise RMSE 0.230. Batch-wise coverage 0.825.
The conclusion is preserved. The Gaussian process beats the baseline (0.295) even batch-wise, but the error under random splits (0.081) is about one third of the batch-wise error (0.230) and is therefore optimistic. The coverage is 0.825, which is higher than for the data in this chapter (0.70) but does not reach the nominal 0.95. It is a value that falls within the results of 100 data sets generated in the same way (Table 28.5: mean 0.846, interquartile range 0.800–0.925).
Exercise 28.6: Coverage of an overconfident interval
Solution
The half-width of the interval is $a=1.96\times0.035=0.0686$. The probability that the error $e\sim\Normal(0,0.094^{2})$ falls inside the interval is, after standardization,
$$ \begin{aligned} P(\abs{e}\le a)&=2\,\Phi\!\left(\frac{0.0686}{0.094}\right)-1\\ &=2\,\Phi(0.730)-1\\ &=2\times0.767-1=0.534 . \end{aligned} $$An interval with nominal 95 % coverage actually contains the truth only about 53 % of the time. This nearly agrees with the coverage of 0.55 under random splits in Section 28.7.4. The median predicted standard deviation there is 0.035, and the RMSE of the Gaussian process under random splits is about 0.10, so this simple calculation explains well the magnitude of the failure. If the width of the interval is shrunk to about 0.37 times (0.035/0.094), the coverage drops from 0.95 to 0.53.
Exercise 28.7: Checking a report
Solution
We list the main problems and how to fix them.
- Leakage in preprocessing: standardization and the correlation-based selection of descriptors are done on all 60 points before the split. The selection of descriptors in particular uses the target values, so the target values of the validation data enter the selection (in the numerical experiment of Chapter 6, Section 6.7, even irrelevant descriptors turned $R^{2}$ into 0.46). Fix: split first, and redo the standardization and selection within the training data of each fold (nested cross-validation).
- Splits that cross groups: the data from the three laboratories may have systematic offsets for each laboratory (instruments, procedures, ways of measuring). Under random splits, other samples from the same laboratory are on the training side, so the result is optimistic. Fix: split by laboratory (and further by batch). If the model is to be used in a new laboratory or a new batch, report the error of a split matched to that use.
- $R^{2}$ is the only metric: $R^{2}$ comes out high when the range of the target values is wide (Chapter 6, Section 6.10). Fix: show the RMSE or MAE with units, and place it alongside baseline values such as that of the model that answers with the mean. Also attach a scatter plot of predicted versus measured values and the coverage of the prediction interval.
- A single success: making one sample at the condition with the largest prediction and succeeding is not a proof that the method is effective (it may have been luck, or other methods might have found it too). Fix: show the results of many comparisons, on synthetic data and past data, against random search and the like with the same budget. Carry out the actual additional experiments for several candidates as well.
- Reporting the value of one sample as a “record high”: an observed value selected because it is the maximum comes out high (Chapter 28, Section 28.9.2). Fix: remake the sample under the same condition and show the mean and the spread, and also show the difference from the baseline sample within the same batch.
- No information for reproduction: the seed, the library versions, the hyperparameters and how they were chosen, the split assignments, and the checks and treatments of the data are not written. Fix: write the items of Table 28.9, and publish the data and the scripts (the FAIR principles).
- “Effective for searching for new materials” is an overstatement: what was verified is prediction within the range of known firing conditions. The performance of extrapolation to a new composition system has not been evaluated. Fix: limit the claim to the range that was evaluated, or perform an evaluation that leaves out a whole lineage (Chapter 6, Section 6.8).