Practice

Exercises.

All 105 exercises in the book, chapter by chapter. Each one has a hint and a worked solution at the end of its chapter.

Show exercises of these kinds

Part 0: Toolkit

Toolkit 0.1

Vectors and Matrices

  1. by hand

    Let a=[2, −1, 3]a = [2,\ -1,\ 3] and b=[1, 4, 0]b = [1,\ 4,\ 0]. Work out a+ba + b, then 3a3a, then a⋅ba \cdot b.

  2. by hand

    Check that [3, 4][3,\ 4] and [−4, 3][-4,\ 3] have a dot product of zero. Then find a vector whose dot product with [2, 5][2,\ 5] is zero. What do such pairs look like when drawn as arrows?

  3. by hand

    Three students have features (hours studied, hours slept) of [4, 7][4,\ 7], [2, 8][2,\ 8] and [6, 5][6,\ 5]. A model uses weights w=[5, 2]w = [5,\ 2] and a bias of 10. What score does it predict for each student? What are the shapes of the matrix, the weight vector and the result?

  4. in code

    Put the three students from the previous exercise into a NumPy array X and the weights into w. Compute the predictions with X @ w + 10. Then try w @ X and explain what happens.

  5. with the figure

    Go back to the figure “How much do two arrows agree?”. Keeping the length of b about the same, swing it all the way round a. Where does b point when the dot product is largest? Where is it most negative? Where is it zero?

Hints and worked solutions in toolkit 0.1 →
Toolkit 0.2

Derivatives and Gradients

  1. by hand

    For f(x)=x2f(x) = x^2, estimate the slope at x=3x = 3 with a nudge of 0.1, then with a nudge of 0.01. What value are the estimates heading towards, and what does the rule give?

  2. by hand

    Where is the lowest point of f(x)=x2−6x+10f(x) = x^2 - 6x + 10, and how low is it?

  3. by hand

    Let f(w,b)=w2+3b2f(w, b) = w^2 + 3b^2. Find the gradient at w=2w = 2, b=1b = 1. If you wanted to make ff smaller, in which direction would you move?

  4. by hand

    Let y=(3x+1)2y = (3x + 1)^2. Use the chain rule to find how fast yy changes with xx at x=1x = 1. Check your answer by nudging xx to 1.001.

  5. with the figure

    In the figure “Which way is up?”, drag the point slowly along one of the rings. What stays true about the arrow the whole way round? Then drag it to the centre. Why does the arrow vanish there?

Hints and worked solutions in toolkit 0.2 →
Toolkit 0.3

Probability

  1. by hand

    Eight quiz scores are 2, 4, 4, 4, 5, 5, 7 and 9. Find the average, then the standard deviation (divide by the number of values).

  2. by hand

    Exam scores follow a bell curve with an average of 70 and a standard deviation of 8. Roughly what share of students score between 62 and 78? Between 54 and 86? Above 86?

  3. by hand

    Out of 100 emails, 30 are spam. The word “free” appears in 18 of the spam emails and in 7 of the others. What is the chance that a spam email contains “free”? What is the chance that an email containing “free” is spam?

  4. in code

    Simulate rolling a die 10 times and work out the share of sixes. Run it several times. Then do the same with 10,000 rolls. What changes?

  5. with the figure

    In the figure “Chance settles down in the long run”, roll ten times and note the tallest and shortest bars. Press Reset and repeat a few times. Then press the 1,000 button several times. How far from the rings do the bars stray in each case?

Hints and worked solutions in toolkit 0.3 →

Part I: Learning from Data

Chapter 1

What Is Learning?

  1. think

    For each task, name some features, name the label, and say whether it is regression or classification.

    1. Estimating the price a house will sell for.
    2. Deciding whether an email is spam.
    3. Forecasting tomorrow’s highest temperature.
    4. Recognising which of three species a flower belongs to.
  2. by hand

    Six students studied for 1, 2, 3, 4, 5 and 6 hours. Their results were fail, fail, pass, fail, pass, pass. Using a rule of the form “pass if hours are at least t”, which threshold makes the fewest mistakes? Can any threshold be right about all six?

  3. think

    A model is right about 100% of the examples it was trained on and 60% of a set of new examples. What has probably happened, and which number describes how good the model is?

  4. think

    Give one task where writing the rules by hand is the better choice, and say why.

  5. with the figure

    In the figure “Find the cut-off”, put the threshold at 2 hours and count the mistakes. Move it to 6 hours and count again. Which kind of mistake does each setting make? Where between them do the mistakes disappear?

Hints and worked solutions in chapter 1 →
Chapter 2

Linear Regression

  1. by hand

    Three points: (0, 1), (2, 2) and (4, 6). Use the formula to find the best line. Then work out its three residuals, its MSE and its RMSE.

  2. by hand

    For the same three points, work out R². Start with the MSE of the lazy model that predicts the average for everyone.

  3. by hand

    The best line for the twelve students is w=5.31w = 5.31, b=42.44b = 42.44. What does it predict for 4.5 hours of study? For 20 hours? What is wrong with the second answer?

  4. in code

    Fit a line to the twelve students with NumPy and check that you get the numbers from the chapter. Hours: 1, 1.5, 2, 3, 3.5, 4, 5, 5.5, 6, 7, 8, 9. Scores: 48, 53, 50, 60, 57, 66, 68, 75, 71, 82, 83, 91.

  5. with the figure

    In the figure “Every miss, and their average”, make the line flat at the average score, about 67. Read the error. Then tilt the line until the error is as low as you can get it, and reveal the best line. How do your three numbers compare with the R² of 0.966 in the chapter?

Hints and worked solutions in chapter 2 →
Chapter 3

Gradient Descent

  1. by hand

    The loss is L(w)=(w−3)2L(w) = (w - 3)^2, whose steepness is 2(w−3)2(w - 3). Start at w=0w = 0 with a learning rate of 0.1 and take three steps. How does the distance from the best value change with each step?

  2. by hand

    Same loss, same start, but a learning rate of 1.1. Take three steps. Then say which learning rate would reach the lowest point in a single step.

  3. by hand

    A model y^=wx+b\hat{y} = wx + b starts at w=1w = 1, b=0b = 0. There is one example: x=2x = 2, y=10y = 10. The loss is (y^−y)2(\hat{y} - y)^2. Take one gradient step with a learning rate of 0.01, and check that the loss went down.

  4. in code

    Write gradient descent for a line through the three points (0, 1), (2, 2) and (4, 6), starting from w=0w = 0, b=0b = 0 with a learning rate of 0.05. Check that it arrives at the best line, w=1.25w = 1.25 and b=0.5b = 0.5. Then change the learning rate to 0.2 and run it again.

  5. with the figure

    In the figure “Three learning rates”, find the largest learning rate at which the run still settles. Then go a little higher. Describe what the error does in each case, and compare your limit with the 0.164 given in the chapter.

Hints and worked solutions in chapter 3 →
Chapter 4

Generalization

  1. think

    Three models were trained on the same data. Their errors are:

    Model Training error Validation error
    A 40 42
    B 15 18
    C 3 55

    Which model underfits, which overfits, and which would you choose?

  2. by hand

    You have 20 examples and run 5-fold cross-validation. In each round, how many examples are trained on and how many are held out? How many models are trained in total, and how many times is each example held out? What would the answers be if every fold held just one example?

  3. think

    A friend trains 50 different models, measures each on the test set, and reports the best score, 91% accurate. What is wrong with that number, and what should they have done?

  4. in code

    Make 15 noisy training points from a sine curve, and 200 new points the same way. Fit curves of degree 1, 3 and 9 to the training points, and print the error of each on both sets.

  5. with the figure

    In the figure “The same model, different classes”, draw six new classes at degree 1, then reset and draw six at degree 8. For each, describe how much the fitted curves differ from one another, and how far each set is from the true pattern.

Hints and worked solutions in chapter 4 →
Chapter 5

Regularization

  1. by hand

    Two models have the same mean squared error, 10. Model A has weights [2, 2][2,\ 2] and model B has weights [0, 3][0,\ 3]. With λ=1\lambda = 1, which model does ridge prefer, and which does lasso prefer?

  2. by hand

    A model has a single weight. Without a penalty the best value is 4, and the loss is (w−4)2(w - 4)^2. Add a ridge penalty, giving (w−4)2+λw2(w - 4)^2 + \lambda w^2. Find the best ww for λ=0\lambda = 0, 1 and 3. Does it ever reach zero?

  3. by hand

    Now use a lasso penalty on the same model: (w−4)2+λw(w - 4)^2 + \lambda w, for ww at or above zero. Find the best ww for λ=2\lambda = 2, 8 and 10.

  4. think

    You fit a ridge model for a range of λ values, from very small to very large. Sketch, in words, what happens to the training error and to the validation error along the way. Where is the best λ?

  5. with the figure

    In the figure “Shrinking against switching off”, raise λ slowly with ridge selected, then again with lasso. How does the way the bars shrink differ? At λ=1\lambda = 1 under lasso, how many features are still in use?

Hints and worked solutions in chapter 5 →

Part II: Classification

Chapter 6

Logistic Regression

  1. by hand

    Work out the sigmoid of 0, of 2 and of −2. What do the last two answers add up to, and why?

  2. by hand

    The fitted model is w=1.56w = 1.56, b=−6.03b = -6.03. With a threshold of 50%, how many hours of study put a student exactly on the boundary? Where does the boundary move if the threshold is raised to 73%?

  3. by hand

    A model makes three predictions. It gives a student who passed a 90% chance of passing, another student who passed a 60% chance, and a student who failed a 20% chance of passing. What is the log loss of each prediction, and the average? How does that compare with a model that says 50% for everyone?

  4. by hand

    With w=1.56w = 1.56, each extra hour multiplies the odds of passing by e1.56≈4.76e^{1.56} \approx 4.76. At 3.87 hours the odds are even, 1 to 1. What are the odds, and the probability, one hour later?

  5. with the figure

    In the figure “What the two numbers do”, set ww to about 1.55 and bb to −6.0, close to the fitted values. Where does the curve cross 50%? Now double ww to about 3.1 and adjust bb until the crossing is back in the same place. What changed about the curve, and what would that mean for the model’s predictions?

Hints and worked solutions in chapter 6 →
Chapter 7

Measuring Classifiers

  1. by hand

    At a threshold of 0.50 the screening model catches 17 of the 20 ill patients and raises 15 false alarms among the 180 healthy ones. Fill in the four cells of the confusion matrix, then work out accuracy, precision, recall and F1.

  2. by hand

    For the same 200 patients, work out accuracy, precision and recall for a model that flags everyone, and for a model that flags no one.

  3. by hand

    A false alarm costs 1 (a follow-up test) and a missed illness costs 20. Threshold A gives 15 false alarms and 3 misses. Threshold B gives 40 false alarms and 1 miss. Which is cheaper? Which has the higher accuracy?

  4. think

    What does an AUC of 0.5 tell you about a model? What about an AUC of 0.3, and what would you do with such a model?

  5. with the figure

    In the figure “A trade, not a free choice”, read precision and recall at a threshold of 0.50 and at 0.70. Then find the lowest threshold at which no ill patient is missed, and read the precision there.

Hints and worked solutions in chapter 7 →
Chapter 8

Nearest Neighbours

  1. by hand

    Five known points: A (1, 1) filled, B (2, 1) filled, C (4, 3) hollow, D (5, 4) hollow and E (3, 3) hollow. Classify the new point (2, 2) with k = 1, with k = 3 and with k = 5.

  2. by hand

    Three people, described by income in dollars and age in years: P (30,000 and 25), Q (30,500 and 60) and R (32,000 and 26). Using the raw numbers, who is nearer to P? Now divide incomes by 1,000 and ages by 15, roughly their typical spreads, and answer again.

  3. think

    Why does k-NN with k = 1 always make zero mistakes on the points it has stored? Why is that not good news?

  4. in code

    Write k-NN in NumPy: a function that takes the known points, their labels, a new point and k, and returns the predicted label. Check it against your answers to the first exercise.

  5. with the figure

    In the figure “Mistakes against k”, read the two curves at k = 1, at about k = 25 and at k = 41. At which of the three is the gap between the curves largest, and what does the gap tell you?

Hints and worked solutions in chapter 8 →
Chapter 9

Naive Bayes

  1. by hand

    A test catches 90% of the people who have an illness and wrongly flags 5% of the people who do not. One person in a hundred has the illness. Someone tests positive. How likely is it that they are ill? Work it out by imagining 10,000 people.

  2. by hand

    An inbox has 10 spam messages and 20 normal ones. The spam messages contain 100 words in total, with “prize” appearing 6 times and “meeting” once. The normal messages contain 200 words, with “prize” appearing once and “meeting” 10 times. Classify the message “prize meeting” without smoothing.

  3. by hand

    In the same inbox the word “lottery” appears 3 times in spam and never in normal messages. The inbox uses 50 different words. What share does “lottery” get in each class without smoothing, and with it? Why does the difference matter?

  4. think

    Naive Bayes assumes the words in a message are independent of each other given the class. Give an example where that is plainly false, and say what effect it has on the model’s output.

  5. with the figure

    In the figure “What a positive test means”, set the share of people who are ill to 10%, then 5%, then 1%, and write down what a positive result means each time. Why does the same test give such different answers?

Hints and worked solutions in chapter 9 →
Chapter 10

Support Vector Machines

  1. by hand

    A boundary has w=[1, 1]w = [1,\ 1] and b=−5b = -5. How wide is its street? For each of the points (4, 3), (2, 2.5) and (1, 1), work out the score w⋅x+bw \cdot x + b and say where the point lies.

  2. think

    An SVM is trained on 100 points that a line separates cleanly, and 4 of them turn out to be support vectors. How many points could you delete without changing the boundary at all? What happens if you delete one of the 4?

  3. by hand

    The RBF kernel scores the similarity of two points as e−γd2e^{-\gamma d^2}, where dd is the distance between them. Work it out for points 1 apart and 2 apart, first with γ=1\gamma = 1 and then with γ=0.1\gamma = 0.1. What does γ control?

  4. think

    You train an SVM with a very small C and another with a very large C on noisy data. Which is more likely to underfit, and which to overfit? How does C relate to the λ of ridge regression?

  5. with the figure

    In the figure “How much to mind the awkward points”, read the width of the street and the number of points inside it at C = 100 and at C = 0.01. Which setting would you expect to do better on new data if the awkward points are noise?

Hints and worked solutions in chapter 10 →

Part IV: Neural Networks

Chapter 14

A Single Neuron

  1. by hand

    A neuron has weights [0.5, 2, −1][0.5,\ 2,\ -1] and a bias of 1. What does it output for the inputs [3, −1, 2][3,\ -1,\ 2]?

  2. by hand

    A layer of three neurons reads the inputs [1, 2][1,\ 2]. The neurons have weights [1, −1][1,\ -1], [0.5, 0.5][0.5,\ 0.5] and [−2, 1][-2,\ 1], and biases 0, 1 and 3. What are the three outputs?

  3. think

    A neuron has weights [1, 1][1,\ 1] and a bias of −3, and answers “yes” when its output is above zero. Describe its decision boundary. Then explain why no single neuron can answer “yes” for the inputs (0, 1) and (1, 0) but “no” for (0, 0) and (1, 1).

  4. in code

    Make a batch of 4 examples with 3 features each, and pass it through a layer of 5 neurons using NumPy. What shapes do the weights, the biases and the output have?

  5. with the figure

    In the figure “One neuron draws one straight line”, get as many of the forty students on the correct side as you can. Then try to beat 37. What stops you?

Hints and worked solutions in chapter 14 →
Chapter 15

Layers and Activations

  1. by hand

    Apply the ReLU to each of these numbers: −2, 0, 3.5 and −0.1.

  2. by hand

    A first layer computes h=2x+1h = 2x + 1. A second layer computes y=3h−4y = 3h - 4. There is no activation between them. Write yy directly in terms of xx. What does that tell you?

  3. by hand

    A small network computes f(x)=ReLU(x)−2 ReLU(x−1)+ReLU(x−2)f(x) = \text{ReLU}(x) - 2\,\text{ReLU}(x - 1) + \text{ReLU}(x - 2). Work out ff at x=0x = 0, 1, 2 and 3, and describe the shape.

  4. think

    The step function outputs 1 for positive inputs and 0 otherwise. It is not a straight line, so it prevents layers from collapsing. Why is it still a poor activation for a network trained by gradient descent?

  5. with the figure

    In the figure “A curve from straight pieces”, step the number of hidden neurons from 1 to 2 to 8 and note the largest gap each time. Roughly how does the gap shrink as neurons are added, and why does each extra neuron help less than the one before?

Hints and worked solutions in chapter 15 →
Chapter 16

Scoring a Classifier

  1. by hand

    Apply softmax to the scores [0, 0, 0][0,\ 0,\ 0]. Then apply it to [2, 0][2,\ 0] and compare the first probability with the sigmoid of 2.

  2. by hand

    A network gives the probabilities [0.1, 0.7, 0.2][0.1,\ 0.7,\ 0.2]. What is the loss if the correct class is the second? What if it is the first? For the second case, write down the gradient for the three scores.

  3. think

    What happens to the softmax probabilities if you add 5 to every score? What happens if you double every score?

  4. think

    You build a network for 10 classes. Before any training, roughly what should its loss be? If the first loss you see is 8, what does that suggest?

  5. with the figure

    In the figure “From scores to probabilities”, note the three probabilities. Add 3 to every score and compare. Then raise only the highest score by 3 and compare again.

Hints and worked solutions in chapter 16 →
Chapter 17

Backpropagation

  1. by hand

    One neuron with a ReLU: the input is 3, the weight is 1, the bias is −1, and the target is 4. The loss is the squared error. Do the forward pass, then the backward pass, then update the weight and bias with a learning rate of 0.02. What is the loss after the update?

  2. by hand

    Two neurons in a chain, with no biases. The first computes h=ReLU(w1x)h = \text{ReLU}(w_1 x) and the second computes y=w2hy = w_2 h. With x=1x = 1, w1=2w_1 = 2, w2=3w_2 = 3 and a target of 0, the loss is y2y^2. Find the gradient for w2w_2, then for w1w_1.

  3. think

    A network has 10,000 weights. To find the gradient by nudging each weight in turn, how many forward passes are needed for one update? How many passes does backpropagation need?

  4. in code

    Check the chapter’s worked example with code. The neuron computes a=ReLU(wx+b)a = \text{ReLU}(wx + b) with x=2x = 2, b=0.5b = 0.5 and a target of 5, and backpropagation gave a gradient of −14 for the weight at w=0.5w = 0.5. Estimate the same gradient by nudging.

  5. with the figure

    In the figure “Backpropagation against brute force”, pick a weight and compare the two numbers with a small nudge. Then make the nudge very large. Which number changes, and why is the other one unaffected?

Hints and worked solutions in chapter 17 →
Chapter 18

Optimizers

  1. by hand

    A run uses a starting learning rate of 1 and a decay of 0.1. What is the learning rate at step 0, at step 10 and at step 90?

  2. by hand

    With momentum, each update is 0.9 times the previous update, minus the learning rate times the gradient. The learning rate is 0.1. First suppose the gradient is 1 at every step: what are the first three updates, and what do they approach? Then suppose the gradient alternates between 1 and −1: what are the first three updates?

  3. by hand

    The valley in this chapter is f(x,y)=0.05x2+y2f(x, y) = 0.05x^2 + y^2. With plain gradient descent, each step multiplies yy by (1−2η)(1 - 2\eta) and xx by (1−0.1η)(1 - 0.1\eta). Use this to explain why the run diverges just above a learning rate of 1, and why it is slow even at 0.9.

  4. think

    Two weights have gradients that are steadily 100 and 0.01. With plain gradient descent and a learning rate of 0.01, how far does each move in one step? Roughly how far does each move in one step of Adam with the same learning rate? What does that tell you about when Adam helps?

  5. with the figure

    In the figure “A ball that remembers”, raise the momentum from 0 to 0.9 and count the steps to settle. Then try 0.98. What goes wrong, and how does it differ from a learning rate that is too large?

Hints and worked solutions in chapter 18 →
Chapter 19

Keeping Networks Honest

  1. by hand

    A layer outputs [2, 4, 6, 8][2,\ 4,\ 6,\ 8]. Dropout at a rate of 50% happens to switch off the second and third neurons. What does the layer pass on, after scaling? Compare the average before and after.

  2. by hand

    A layer has the weights [3, −4, 0.5][3,\ -4,\ 0.5] and a penalty strength of λ=0.01\lambda = 0.01. What does the penalty add to the loss? What does it add to the gradient of each weight?

  3. think

    During training, the loss on held-out data at the end of each epoch is 0.90, 0.61, 0.48, 0.45, 0.47, 0.52 and 0.60. The training loss falls throughout. Which epoch’s weights should you keep? Why should you not stop the moment the held-out loss first rises?

  4. think

    A network is right about 96% of its training examples and 70% of new ones. List four things you could try, starting with the one most likely to help.

  5. with the figure

    In the figure “Smaller weights, smoother regions”, train with λ off, with λ = 0.001 and with λ = 0.1. Compare the shapes of the regions and the accuracy on new points with the table in the chapter. What has gone wrong at 0.1?

Hints and worked solutions in chapter 19 →
Chapter 20

One Network, Many Jobs

  1. think

    For each task, say how many outputs the network needs, what activation goes on them, and which loss to use.

    1. Estimating the price of a house.
    2. Deciding whether an email is spam.
    3. Recognising a handwritten digit, 0 to 9.
    4. Tagging a photo with any of “beach”, “people” and “night”, in any combination.
    5. Locating an object in an image by its x and y coordinates.
  2. by hand

    A yes-or-no network outputs a probability of 0.8. What is the binary cross-entropy if the true answer is yes? What if it is no? In each case, what is the gradient for the score that went into the sigmoid?

  3. by hand

    A network predicts [2.5, 0, 2][2.5,\ 0,\ 2] for three examples whose targets are [3, −0.5, 2][3,\ -0.5,\ 2]. What is the mean squared error? What is its gradient for each prediction?

  4. think

    A network has no hidden layers and one output with a sigmoid, trained with binary cross-entropy. Which model from earlier in the book is it? What does adding a hidden layer with ReLU change?

  5. with the figure

    In the figure “A network with one neuron”, choose the output with no activation and drag the training steps upward. What do the weight and bias approach? Then switch the output layer to the sigmoid and do it again. Which earlier models have you just trained?

Hints and worked solutions in chapter 20 →
Chapter 21

A Real Dataset

  1. by hand

    The network has 784 inputs, two hidden layers of 64 neurons and 10 outputs. How many weights and biases does it have in total?

  2. by hand

    There are 60,000 training images and the batch size is 128. How many steps are in one epoch, and how many images are in the last batch? How many updates does the network receive in five epochs?

  3. by hand

    Pixels are scaled by subtracting 127.5 and dividing by 127.5. What do the pixel values 0, 255 and 51 become? Why must an image given to the finished network be scaled the same way?

  4. think

    The confusion matrix shows that shirts are often mistaken for T-shirts, pullovers and coats, while trousers are almost never mistaken for anything. Why might that be? Would changing a threshold help? What would?

  5. with the figure

    In the figure “Which clothes get mixed up”, click the cell for shirts that the network called T-shirts, and look at the images. Then click the diagonal cell for trousers. What do the mistaken images have in common, and why are trousers so easy?

Hints and worked solutions in chapter 21 →
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in