Salta al contenuto
Note per Studenti Introduction to Machine Learning - Mock Exam 2 Report

Introduction to Machine Learning - Mock Exam 2

Questa pagina non ha ancora la versione ripasso: qui sotto c'è il testo completo.

In questa pagina 14

The written tests of this course are not public. This mock exam is therefore built only on the notes of the course (learning and data, statistical learning framework, Hoeffding bound, perceptron and its convergence bound, ADALINE, logistic regression, linear regression, Bernoulli likelihood, classification metrics, model selection, and the Python notebooks). The questions and the data are new: it is not a copy of any real test. The official format, from the course description, is continuous activities on the course platform and a final closed-book written test. The format used here is a proposal of this site, not declared by the course: 10 multiple-choice questions worth 1.5 points each and 3 problems worth 5 points each, for a total of 30 points, in 90 minutes, with four options per question and exactly one correct option.

Conventions used in the whole test: every input vector contains the constant coordinate x0=1x_0 = 1 when a weight vector is used; log⁡\log and ln⁡\ln are the natural logarithm; matrices are written by rows, so [ [1, 2], [3, 4] ] has first row 1,21, 2.

How to use it: work with a timer, write each formula in letters before putting the numbers in, and look at the "Result" only when a question is finished.

Question 1

The first lecture says when machine learning is the right tool: three things must hold together. Which of the following problems satisfies all three?

  • A) Computing the area of a circle from its radius: a pattern exists and many data points can be recorded, so machine learning is the right tool even if the exact formula is known.
  • B) Predicting a label that was assigned by tossing a fair coin for every object, with a million recorded examples: the data are plentiful, so machine learning will find the rule.
  • C) Deciding whether to approve credit from historical records of applicants: a pattern links the applicant information to good or bad customers, nobody can write it as a formula, and the records are available.
  • D) A relation between inputs and outputs that exists and cannot be written as a formula, but for which no example has ever been recorded.
Show the result

C

Show the full solution

C is correct: the credit example of Introduction to Machine Learning - Learning, Data and TasksMachine learning builds a hypothesis g that approximates an unknown target function f using only a set of historical examples (input, output). The course lecture frames learning as adaptive behaviour, shows through the credit-approval example the components of learning (input x, output y, target f, data, hypothesis g, hypothesis set, learning algorithm) and warns that a model is only as unbiased as its data. Tasks named in the course are classification and regression, supervised and non-supervised problems.Introduction to Machine Learning - Learning, Data and Tasks → has all three requirements stated on the slide: a pattern exists, we cannot pin it down mathematically, we have data on it. A fails the second requirement: when the pattern can be written as an exact formula (the area of a circle) it can be pinned down mathematically and there is nothing to learn. B fails the first: labels assigned by a coin have no pattern, so no quantity of data reveals one. D fails the third: without data there is no experience from which to choose a hypothesis.

Question 2

A single perceptron has to classify the four points (0,0)(0,0) and (1,1)(1,1), labelled +1+1, and (0,1)(0,1) and (1,0)(1,0), labelled −1-1. Which statement is correct?

  • A) No straight line separates the two classes, so the Perceptron Learning Algorithm, which stops only when every point is correct, would never stop; this is why the notebooks add a maximum number of iterations.
  • B) The line x1+x2−1=0x_1 + x_2 - 1 = 0 separates them: (0,0)(0,0) and (1,1)(1,1) lie on one side and (0,1)(0,1) and (1,0)(1,0) on the other.
  • C) After adding the constant coordinate x0=1x_0 = 1 and running the algorithm for enough epochs, the weights found separate the four points.
  • D) The bound K≤R2/γ2K \le R^2/\gamma^2 guarantees that the algorithm stops after a finite number of updates on these points.
Show the result

A

Show the full solution

A is correct: these four points are the exclusive-or pattern of Halfspaces and the Perceptron AlgorithmA perceptron computes h(x) = sign(w^T x) where x includes a constant coordinate x0 = 1 that absorbs the threshold into the bias weight w0; its decision boundary is the hyperplane w^T x = 0 (a line in the plane, x2 = -(w1/w2) x1 - w0/w2). The Perceptron Learning Algorithm scans the data and, on every misclassified point, replaces w by w + y x. A single perceptron cannot separate the exclusive-or pattern; two perceptrons feeding a third give a multilayer network.Halfspaces and the Perceptron Algorithm →; whichever line is drawn, one point ends on the wrong side, and an algorithm that stops only when all points are correct never stops, so a maximum number of iterations is needed. B is false: for x1+x2−1x_1 + x_2 - 1 the point (0,0)(0,0) gives −1-1 and the point (1,1)(1,1) gives +1+1, so two points of the same class are on opposite sides of the line (and (0,1)(0,1) and (1,0)(1,0) lie on it). C is false: the constant coordinate only absorbs the threshold into the weight w0w_0; the hypothesis is still a single halfspace, which cannot represent this pattern. D is false: the bound of Perceptron Convergence and the Margin BoundThe distance of a point x from the hyperplane w^T x + b = 0 is |w^T x + b| / sqrt(w^T w), obtained by writing x = x_p + gamma with gamma parallel to w. If the data are linearly separable with margin gamma (a unit vector w* with y_i w*^T x_i >= gamma for all i) and every point lies in a ball of radius R, the Perceptron Learning Algorithm makes at most K <= R^2 / gamma^2 updates. Proof: after K updates w_{K+1}^T w* >= K gamma, hence norm of w_{K+1} >= K gamma; and norm of w_{K+1} squared <= K R^2; combine.Perceptron Convergence and the Margin Bound → assumes that the data are linearly separable with a margin γ>0\gamma > 0, and here no such margin exists.

Question 3

With the notation of the course, a column vector is X=[x1,x2,x3,x4]TX = [x_1, x_2, x_3, x_4]^T and its norm is ∥X∥=x12+x22+x32+x42\|X\| = \sqrt{x_1^2 + x_2^2 + x_3^2 + x_4^2}. For X=[2,−1,4,2]TX = [2, -1, 4, 2]^T, what is ∥X∥\|X\|?

  • A) 77
  • B) 99
  • C) 2525
  • D) 55
Show the result

D

Show the full solution

The squares of the entries are 44, 11, 1616, 44, with sum 2525, and ∥X∥=25=5\|X\| = \sqrt{25} = 5 (the same quantity that bounds each point by RR in Perceptron Convergence and the Margin BoundThe distance of a point x from the hyperplane w^T x + b = 0 is |w^T x + b| / sqrt(w^T w), obtained by writing x = x_p + gamma with gamma parallel to w. If the data are linearly separable with margin gamma (a unit vector w* with y_i w*^T x_i >= gamma for all i) and every point lies in a ball of radius R, the Perceptron Learning Algorithm makes at most K <= R^2 / gamma^2 updates. Proof: after K updates w_{K+1}^T w* >= K gamma, hence norm of w_{K+1} >= K gamma; and norm of w_{K+1} squared <= K R^2; combine.Perceptron Convergence and the Margin Bound →; the notation page of that note gives the formula). So D is correct. A is the sum of the entries, 2−1+4+2=72 - 1 + 4 + 2 = 7, which is not a norm. B is the sum of the absolute values, 2+1+4+2=92 + 1 + 4 + 2 = 9, another quantity that is not the one defined in the notes. C is the sum of the squares, XTX=25X^TX = 25, which is ∥X∥2\|X\|^2: the square root is missing.

Question 4

An ADALINE with weights w=[0.5,−1,0.25]T\mathbf{w} = [0.5, -1, 0.25]^T is trained by stochastic gradient descent. The notebook updates the weights after each example with w←w+η⋅2⋅xi⋅errori\mathbf{w} \leftarrow \mathbf{w} + \eta \cdot 2 \cdot \mathbf{x}_i \cdot \text{error}_i, where the error is the label minus the output wTxi\mathbf{w}^T\mathbf{x}_i of the unit. The example is x=[1,2,−2]T\mathbf{x} = [1, 2, -2]^T with label y=−1y = -1, and η=0.05\eta = 0.05. What are the weights after this single update?

  • A) [0.5,−1,0.25][0.5, -1, 0.25], because the point is already classified correctly
  • B) [0.6,−0.8,0.05][0.6, -0.8, 0.05]
  • C) [0.4,−1.2,0.45][0.4, -1.2, 0.45]
  • D) [0.55,−0.9,0.15][0.55, -0.9, 0.15]
Show the result

B

Show the full solution

The output of the unit is the real number wTx=0.5⋅1+(−1)⋅2+0.25⋅(−2)=−2\mathbf{w}^T\mathbf{x} = 0.5 \cdot 1 + (-1)\cdot 2 + 0.25 \cdot (-2) = -2, so the error is y−wTx=−1−(−2)=1y - \mathbf{w}^T\mathbf{x} = -1 - (-2) = 1. The correction is η⋅2⋅error⋅x=0.05⋅2⋅1⋅[1,2,−2]=[0.1,0.2,−0.2]\eta \cdot 2 \cdot \text{error} \cdot \mathbf{x} = 0.05 \cdot 2 \cdot 1 \cdot [1, 2, -2] = [0.1, 0.2, -0.2], and the new weights are [0.6,−0.8,0.05][0.6, -0.8, 0.05]: B is correct (see ADALINE and Gradient DescentADALINE is a perceptron whose activation function is the identity: during training the unit outputs w^T x and the in-sample error E_in = (1/N) sum (y_i - w^T x_i)^2 is minimised by gradient descent, w_new = w_old - eta * grad E_in, with partial derivatives dE_in/dw_j = (2/N) sum (y_i - w^T x_i)(-x_i^j) and matrix form grad E_in proportional to -X^T (Y - X w). The prediction is still the sign of w^T x. Learning rate eta sets the step size and a stopping rule ends the iteration.ADALINE and Gradient Descent →). A computes the error on the sign of the output, as the perceptron does (sign⁡(−2)=−1=y\operatorname{sign}(-2) = -1 = y, no mistake, no update); ADALINE instead computes the error on the real number wTx\mathbf{w}^T\mathbf{x}, which is 11, not 00. C subtracts the correction instead of adding it (with the error defined as y−wTxy - \mathbf{w}^T\mathbf{x} the sign is plus). D forgets the factor 22 of the derivative of the square: it uses 0.05⋅[1,2,−2]0.05 \cdot [1, 2, -2].

Question 5

Logistic regression minimises the cost J(θ)=−ℓ(θ)J(\theta) = -\ell(\theta), where ℓ\ell is the Bernoulli log-likelihood. Which statement about its gradient-descent step, compared with that of ADALINE, is correct?

  • A) The gradient is 1m(hθ(X)−y)\frac{1}{m}\big(h_\theta(X) - y\big) with no data matrix, because the sigmoid already contains the inputs.
  • B) The gradient has the same form as for ADALINE, but the output error is computed before the sigmoid, on z=θTxz = \theta^T\mathbf{x}, while ADALINE computes it after the identity.
  • C) The gradient is 1mXT(hθ(X)−y)\frac{1}{m}X^T\big(h_\theta(X) - y\big) and the update is θnew=θold−η ∂J/∂θ\theta_{\text{new}} = \theta_{\text{old}} - \eta\,\partial J/\partial\theta: the same form as for ADALINE, with the output error computed after the sigmoid instead of after the identity.
  • D) The update is θnew=θold+η ∂J/∂θ\theta_{\text{new}} = \theta_{\text{old}} + \eta\,\partial J/\partial\theta, because JJ comes from a log-likelihood and the log-likelihood has to be maximised.
Show the result

C

Show the full solution

C is correct: the page summarised in Logistic RegressionLogistic regression models the probability p of the positive class: the logit (log of the odds p/(1-p)) is assumed linear in the input, logit(p) = w^T x = z. Inverting it gives p = 1/(1 + e^(-z)), the logistic sigmoid; an object goes to class 1 when the sigmoid exceeds 0.5, i.e. when z > 0. The parameters are learned by maximising the Bernoulli log-likelihood, equivalently minimising the cost J = -y log(yhat) - (1 - y) log(1 - yhat), by gradient descent with gradient (1/m) X^T (h(x) - y).Logistic Regression → gives ∂J(θ)∂θ=1mXT(hθ(X)−y)\dfrac{\partial J(\theta)}{\partial\theta} = \dfrac{1}{m}X^T\big(h_\theta(X) - y\big) and θnew=θold−η ∂J(θ)∂θ\theta_{\text{new}} = \theta_{\text{old}} - \eta\,\dfrac{\partial J(\theta)}{\partial\theta}, and the note comments that it is the form of ADALINE and Gradient DescentADALINE is a perceptron whose activation function is the identity: during training the unit outputs w^T x and the in-sample error E_in = (1/N) sum (y_i - w^T x_i)^2 is minimised by gradient descent, w_new = w_old - eta * grad E_in, with partial derivatives dE_in/dw_j = (2/N) sum (y_i - w^T x_i)(-x_i^j) and matrix form grad E_in proportional to -X^T (Y - X w). The prediction is still the sign of w^T x. Learning rate eta sets the step size and a stopping rule ends the iteration.ADALINE and Gradient Descent → with the output error hθ(x)−yh_\theta(\mathbf{x}) - y computed after the sigmoid instead of after the identity. A is false: the gradient contains XTX^T, as for ADALINE. B is false because it swaps the two models: the logistic error is computed after the sigmoid, and ADALINE's after the identity. D is false: the course minimises −ℓ(θ)-\ell(\theta), which is a cost, so the gradient is subtracted; adding it would increase the cost (the notebook writes the equivalent step +ηXT(y−y^)/m+\eta X^T(y - \hat y)/m, with the error defined the other way round).

Question 6

In linear regression the data matrix XX has 50005000 rows (one per object) and 44 columns (the constant column included). The closed form w=(XTX)−1XTY\mathbf{w} = (X^TX)^{-1}X^TY is used. Which statement is correct?

  • A) XTXX^TX is a 5000×50005000 \times 5000 matrix and it is the one that has to be inverted, so the cost grows with the number of objects.
  • B) XTXX^TX is a 4×44 \times 4 matrix, and it is the only matrix to invert, whatever the number of rows; the number of rows only affects the cost of forming the product.
  • C) Since XX is not square, X−1X^{-1} does not exist and the closed form cannot be applied.
  • D) The formula works in every case, also when XTXX^TX cannot be inverted.
Show the result

B

Show the full solution

B is correct: XTX^T is 4×50004 \times 5000, so XTXX^TX is (4×5000)(5000×4)=4×4(4\times5000)(5000\times4) = 4\times4, and this is the matrix whose inverse is needed; this is the argument about the cost of the formula in Linear RegressionIn linear regression the hypothesis is h(x) = w^T x and the in-sample error is E_in(w) = (1/N) sum (w^T x_i - y_i)^2 = (1/N) times the squared norm of (Xw - Y), with X the N-row data matrix. Setting the gradient (2/N) X^T (Xw - Y) to zero gives the normal equations X^T X w = X^T Y and the closed-form solution w = (X^T X)^{-1} X^T Y, where (X^T X)^{-1} X^T is the pseudo-inverse of X; only a small square matrix (number of features) has to be inverted. Polynomial regression is the same formula on a data matrix with columns 1, x, x^2, ...Linear Regression →, where NN only affects the cost of forming XTXX^TX. A mixes up the order of the product: XXTXX^T would be 5000×50005000\times5000, but the formula contains XTXX^TX. C is false: it is exactly because XX has no inverse that the matrix (XTX)−1XT(X^TX)^{-1}X^T, called the pseudo-inverse of XX, is used. D is false: the note states that the formula assumes that XTXX^TX is invertible.

Question 7

The actual labels of eight objects are y=[1,0,0,1,1,0,1,0]\mathbf{y} = [1, 0, 0, 1, 1, 0, 1, 0] and the predicted labels are y^=[1,0,1,1,0,0,1,1]\hat{\mathbf{y}} = [1, 0, 1, 1, 0, 0, 1, 1], with 11 the positive class. Which is the confusion matrix, with the rows for the actual class (positive first) and the columns for the predicted class (positive first)?

  • A) [ [3, 1], [2, 2] ]
  • B) [ [3, 2], [1, 2] ]
  • C) [ [2, 2], [1, 3] ]
  • D) [ [3, 1], [1, 3] ]
Show the result

A

Show the full solution

Compare the pairs (y,y^)(y, \hat y) one by one, as in Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →: (1,1)(1,1) occurs three times (objects 1, 4, 7): TP=3TP = 3; (1,0)(1,0) once (object 5): FN=1FN = 1; (0,1)(0,1) twice (objects 3 and 8): FP=2FP = 2; (0,0)(0,0) twice (objects 2 and 6): TN=2TN = 2. With the layout [TPFNFPTN]\begin{bmatrix}TP & FN\\ FP & TN\end{bmatrix} the matrix is [ [3, 1], [2, 2] ]: A is correct. B is the transpose (rows for the predicted class, columns for the actual one), which swaps FNFN and FPFP. C is the matrix obtained taking 00 as the positive class (TNTN in the first place). D has the right TPTP and FNFN but counts FPFP and TNTN wrongly (11 and 33 instead of 22 and 22): the actual negatives are objects 2, 3, 6 and 8, and two of them (3 and 8) are predicted positive.

Question 8

Two 2×32\times3 arrays are defined in NumPy: A = np.array([ [1, 0, 2], [3, 1, -1] ]) and B = np.array([ [2, 1, 0], [1, 1, 1] ]). Which statement is correct?

  • A) np.dot(A, B) returns [ [2, 3], [7, 3] ].
  • B) np.inner(A, B) returns [ [2, 7], [3, 3] ].
  • C) np.inner(A, B) signals an error, for the same reason as np.dot(A, B).
  • D) np.inner(A, B) returns [ [2, 3], [7, 3] ], the same matrix as np.dot(A, B.T).
Show the result

D

Show the full solution

np.inner(A, B) of two 2-D arrays has as entry (i,j)(i, j) the product of row ii of A with row jj of B, as explained in Python Notebooks - Random Samples, Plots and Linear Algebra with NumPyThe first course notebook draws random samples with NumPy (uniform with np.random.rand, normal and exponential), plots them with matplotlib (line and scatter plots, histograms compared with the theoretical density from scipy.stats), and shows the NumPy products used later: np.dot and np.inner between a matrix and a vector and between two matrices, with the transpose. This note reproduces the code of the notebook "matplotlib, random numbers and statistics" with the meaning of each call.Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy →: row 1 of A is [1,0,2][1,0,2] and gives 1⋅2+0⋅1+2⋅0=21\cdot2 + 0\cdot1 + 2\cdot0 = 2 with row 1 of B and 1⋅1+0⋅1+2⋅1=31\cdot1 + 0\cdot1 + 2\cdot1 = 3 with row 2; row 2 of A is [3,1,−1][3,1,-1] and gives 6+1+0=76 + 1 + 0 = 7 and 3+1−1=33 + 1 - 1 = 3. So the result is [ [2, 3], [7, 3] ], the same as np.dot(A, B.T): D is correct. A is false: np.dot(A, B) is a matrix product, which needs the number of columns of A (33) to equal the number of rows of B (22), so NumPy signals an error. B gives the transposed matrix: the entry (1,2)(1,2) is 33, not 77. C is false: np.inner works on these shapes, because it multiplies rows by rows.

Question 9

In the NumPy version of the perceptron of the course notebook the mistake test is if ((np.dot(w, x) * y) < 0): and, after each epoch over all the points, the loop ends if num_errors == 0. The data set is the usual one, with the column of ones, but the weights are started from w = [0, 0, 0]. What happens?

  • A) The first point is a mistake, w becomes w + eta * (x * y), and the algorithm continues as usual until the points are separated.
  • B) No update is ever made: every product np.dot(w, x) * y is 00, which is not smaller than 00; the first epoch ends with num_errors == 0, the loop stops with epochs = 1 and w still equal to zero.
  • C) The loop never ends, because the products are always 00 and the counter of errors is never reset.
  • D) The loop diverges, because the learning rate of the notebook is outside the range 0<η≤10 < \eta \le 1 written in its comment.
Show the result

B

Show the full solution

With w = [0, 0, 0] the scalar product np.dot(w, x) is 00 for every point, so the product with y is 00, and the test < 0 is false: a point with output exactly 00 is not counted as a mistake. No update is made, num_errors stays 00 during the first epoch, and the check num_errors == 0 ends the loop with epochs = 1: B is correct, as in Python Notebooks - Perceptron and ADALINE from ScratchCode of the course notebooks that implement the Perceptron Learning Algorithm first with Python lists, then with plots of the successive lines, then with NumPy arrays (data matrix X with a column of ones, update w + eta * y * x on mistakes, epoch counter), and finally ADALINE: batch gradient descent with delta_w = eta * 2 * X^T (y - X w) / N and the stochastic version that shuffles the data and updates after every example. Differences between the versions (condition for a mistake, learning rate, stopping rule) are pointed out.Python Notebooks - Perceptron and ADALINE from Scratch →, whose note observes that from w = 0 the loop would never update and that the notebook therefore starts from random weights. A would need the point to count as a mistake, but the test is a strict inequality. C is false: the exit condition is satisfied after the first epoch. D is false: the learning rate is not even used, because no update takes place (and the comment of the notebook about 0<η≤10 < \eta \le 1 is not enforced by the code).

Question 10

In the logistic-regression notebook there are N = 100 points per class, the mini-batch size is batch_size = 50 and max_epochs = 100. In every epoch the loop for j in range(0, y.shape[0], batch_size): updates w once for each block, and all the epochs are executed. How many updates of w are made in total?

  • A) 400400
  • B) 100100
  • C) 200200
  • D) 2000020000
Show the result

A

Show the full solution

The data set has 2N=2002N = 200 objects (the points of the two classes are stacked), so range(0, 200, 50) gives the starting indices 0,50,100,1500, 50, 100, 150: four mini-batches, hence four updates per epoch. Over max_epochs = 100 epochs this makes 4⋅100=4004 \cdot 100 = 400 updates: A is correct (see Python Notebooks - Exercises on Perceptron, Regression and Logistic RegressionThe exercise notebooks of the course: generating two- and three-class data with NumPy distributions, training an ADALINE/perceptron by mini-batch stochastic gradient descent and plotting the errors per epoch, polynomial regression by the closed form w = (X^T X)^{-1} X^T y on a data matrix with columns 1, x, x^2, and logistic regression trained by mini-batch gradient descent on the log loss. Statement and solution code are given, with the inconsistencies between statement and code pointed out.Python Notebooks - Exercises on Perceptron, Regression and Logistic Regression →). B counts one update per epoch, as if the whole data set were one batch. C counts the number of objects, as if the update were made after every example (stochastic gradient descent with batch size 1 would give 200⋅100=20000200 \cdot 100 = 20000, which is D, not the case here). Note that the vector errors_epoch of the notebook stores the log-loss cost of each epoch, summed over the objects, not a number of updates or of mistakes.

Problem 1 (points 5)

A learning algorithm chooses its final hypothesis gg from a finite hypothesis set with M=12M = 12 hypotheses, using N=500N = 500 independent samples. The tolerated gap is ε=0.08\varepsilon = 0.08.

a) Compute the upper bound for P(∣Ein(g)−Eout(g)∣>0.08)P\big(|E_{\text{in}}(g) - E_{\text{out}}(g)| > 0.08\big) (1 point).

b) A colleague applies to gg the inequality for one fixed hypothesis, 2e−2ε2N2e^{-2\varepsilon^2 N}. Compute the number obtained, say by which factor it differs from the answer of part a), and explain why it is not a valid bound for gg (1 point).

c) Find the smallest number of samples NN for which the bound of part a) is at most δ=0.01\delta = 0.01, first with M=12M = 12 and then with M=120M = 120 hypotheses. Compare the two values of NN with the ratio of the two values of MM (2 points).

d) Two bad events E1E_1 and E2E_2 of two similar hypotheses have P(E1)=0.03P(E_1) = 0.03, P(E2)=0.025P(E_2) = 0.025 and P(E1∩E2)=0.02P(E_1 \cap E_2) = 0.02. Compute P(E1∪E2)P(E_1 \cup E_2) and the value given by the union bound, and say what the comparison shows about the factor MM (1 point).

Show the result

a) 2Me−2ε2N=24 e−6.4≈0.03992Me^{-2\varepsilon^2N} = 24\,e^{-6.4} \approx 0.0399.

b) 2e−6.4≈0.003322e^{-6.4} \approx 0.00332; it is 1212 times smaller, so it understates the bound by the factor MM; it is not valid because gg is chosen after looking at the data.

c) N≥12ε2ln⁡2MδN \ge \dfrac{1}{2\varepsilon^2}\ln\dfrac{2M}{\delta}: N=609N = 609 for M=12M = 12, N=788N = 788 for M=120M = 120. Ten times more hypotheses need only about 29% more samples (179179 more).

d) P(E1∪E2)=0.035P(E_1 \cup E_2) = 0.035; union bound 0.0550.055. The bound overestimates when the events overlap, so the factor MM is pessimistic for similar hypotheses.

Show the full solution

a) The result of PAC Learning and Hoeffding's InequalityFor a finite hypothesis set of M hypotheses and N independent samples, the probability that the in-sample error of the chosen hypothesis g differs from its true error by more than epsilon is at most 2 M exp(-2 epsilon^2 N). The bound comes from Hoeffding's inequality for one hypothesis, P(|nu - mu| > epsilon) <= 2 exp(-2 epsilon^2 N), and from the union bound P(E1 or ... or EM) <= P(E1) + ... + P(EM), which is exact only for disjoint events and loose when the bad events overlap.PAC Learning and Hoeffding's Inequality → for MM hypotheses and NN samples is

P(∣Ein(g)−Eout(g)∣>ε)≤2M e−2ε2N.P\big(|E_{\text{in}}(g) - E_{\text{out}}(g)| > \varepsilon\big) \le 2M\,e^{-2\varepsilon^2N}.

The exponent is 2ε2N=2⋅0.0064⋅500=6.42\varepsilon^2N = 2 \cdot 0.0064 \cdot 500 = 6.4 (the gap is squared: 0.082=0.00640.08^2 = 0.0064). Then

2Me−2ε2N=2⋅12⋅e−6.4=24⋅0.0016616≈0.0399.2Me^{-2\varepsilon^2N} = 2 \cdot 12 \cdot e^{-6.4} = 24 \cdot 0.0016616 \approx 0.0399 .

With these data the probability that the gap of gg exceeds 0.080.08 is at most about 4%.

b) For one fixed hypothesis Hoeffding's inequality gives 2e−6.4≈0.003322e^{-6.4} \approx 0.00332. Compared with part a) it is 1212 times smaller: the missing factor is exactly MM. The single-hypothesis inequality is valid only for a hypothesis fixed before looking at the data (a bin with a given fraction of marbles). The algorithm picks gg after seeing the samples, so gg may be any of the 1212 hypotheses; the gap of gg exceeds ε\varepsilon if at least one of the events Em={∣Ein(hm)−Eout(hm)∣>ε}E_m = \{|E_{\text{in}}(h_m) - E_{\text{out}}(h_m)| > \varepsilon\} happens, and the union bound adds the MM probabilities, each at most 2e−2ε2N2e^{-2\varepsilon^2N}.

c) Solve 2Me−2ε2N≤δ2Me^{-2\varepsilon^2N} \le \delta for NN: take the logarithm, ln⁡(2M)−2ε2N≤ln⁡δ\ln(2M) - 2\varepsilon^2N \le \ln\delta, so

N≥12ε2ln⁡2Mδ,12ε2=10.0128=78.125.N \ge \frac{1}{2\varepsilon^2}\ln\frac{2M}{\delta},\qquad \frac{1}{2\varepsilon^2} = \frac{1}{0.0128} = 78.125 .

For M=12M = 12: ln⁡240.01=ln⁡2400≈7.7832\ln\dfrac{24}{0.01} = \ln 2400 \approx 7.7832 and N≥78.125⋅7.7832≈608.1N \ge 78.125 \cdot 7.7832 \approx 608.1, so N=609N = 609 (check: at N=609N = 609 the bound is 0.00988≤0.010.00988 \le 0.01, at N=608N = 608 it is 0.01001>0.010.01001 > 0.01).

For M=120M = 120: ln⁡2400.01=ln⁡24000≈10.0858\ln\dfrac{240}{0.01} = \ln 24000 \approx 10.0858 and N≥78.125⋅10.0858≈787.95N \ge 78.125 \cdot 10.0858 \approx 787.95, so N=788N = 788 (at N=787N = 787 the bound is 0.01012>0.010.01012 > 0.01).

The hypothesis set is ten times larger, but the number of samples grows only from 609609 to 788788, that is by 179179 samples, about 29%: the difference is ln⁡102ε2≈180\dfrac{\ln 10}{2\varepsilon^2} \approx 180. This is the reading of the bound: the probability is exponentially small in NN and grows only linearly in MM, so MM enters the required NN through a logarithm.

d) Inclusion-exclusion for two events that can share outcomes:

P(E1∪E2)=P(E1)+P(E2)−P(E1∩E2)=0.03+0.025−0.02=0.035.P(E_1 \cup E_2) = P(E_1) + P(E_2) - P(E_1 \cap E_2) = 0.03 + 0.025 - 0.02 = 0.035 .

The union bound drops the intersection: P(E1)+P(E2)=0.055≥0.035P(E_1) + P(E_2) = 0.055 \ge 0.035. The two events overlap strongly (0.020.02 out of 0.0250.025 for the smaller one), so the bound overestimates by more than half. Two similar hypotheses have almost the same bad event, so counting both, as the factor MM does, is pessimistic: the bound of part a) is safe but loose.

Typical mistakes: using 2e−2ε2N2e^{-2\varepsilon^2N} without MM for a gg chosen from the data; forgetting to square ε\varepsilon; exchanging ε\varepsilon (the gap) and δ\delta (the probability); rounding NN down instead of up; thinking that the union bound is an equality.

Problem 2 (points 5)

Two coins are tossed independently; heads is coded 11 and tails 00, and the tosses of one coin are independent and identically distributed with probability of heads θ\theta. Coin A gives, in 16 tosses, the sequence H T T H H H T H H T H H T H H H. Coin B gives 5 heads in 12 tosses.

a) For coin A, write the likelihood L(θ)L(\theta) as a function of the number of heads KK and of the number of tosses nn, and compute it at θ=0.5\theta = 0.5 and at θ=0.7\theta = 0.7 (1 point).

b) Write the log-likelihood of coin A, find the maximum likelihood estimate θ^A\hat\theta_A by setting the derivative to zero, and compute ℓ(θ^A)\ell(\hat\theta_A) and its difference from ℓ(0.5)\ell(0.5) (1.5 points).

c) Compute θ^B\hat\theta_B for coin B and the value ℓB(θ^B)\ell_B(\hat\theta_B) of its log-likelihood (1 point).

d) If the two coins were assumed to have the same θ\theta (one i.i.d. sample of 28 tosses), find the estimate and the total log-likelihood. Compare it with ℓA(θ^A)+ℓB(θ^B)\ell_A(\hat\theta_A) + \ell_B(\hat\theta_B) and comment (1.5 points).

Show the result

a) K=11K = 11, n=16n = 16: L(θ)=θ11(1−θ)5L(\theta) = \theta^{11}(1-\theta)^{5}; L(0.5)=0.516≈1.53⋅10−5L(0.5) = 0.5^{16} \approx 1.53\cdot10^{-5}, L(0.7)≈4.80⋅10−5L(0.7) \approx 4.80\cdot10^{-5}.

b) ℓ(θ)=11ln⁡θ+5ln⁡(1−θ)\ell(\theta) = 11\ln\theta + 5\ln(1-\theta); θ^A=11/16=0.6875\hat\theta_A = 11/16 = 0.6875; ℓ(θ^A)≈−9.937\ell(\hat\theta_A) \approx -9.937, ℓ(0.5)≈−11.090\ell(0.5) \approx -11.090, difference ≈1.153\approx 1.153 (likelihood ≈3.17\approx 3.17 times larger).

c) θ^B=5/12≈0.4167\hat\theta_B = 5/12 \approx 0.4167; ℓB(θ^B)≈−8.150\ell_B(\hat\theta_B) \approx -8.150.

d) θ^=16/28=4/7≈0.5714\hat\theta = 16/28 = 4/7 \approx 0.5714; total ℓ≈−19.121\ell \approx -19.121 against −9.937−8.150=−18.088-9.937 - 8.150 = -18.088 with two separate parameters: the separate fit is larger by about 1.0341.034, which is the price of forcing the same θ\theta on two coins that look different.

Show the full solution

a) Each toss contributes the factor θx(1−θ)1−x\theta^{x}(1-\theta)^{1-x} of the Bernoulli distribution, a head giving θ\theta and a tail 1−θ1-\theta (Bernoulli Distribution and Maximum Likelihood EstimationA binary outcome (heads = 1, tails = 0) is modelled by a Bernoulli distribution with parameter theta: P(x | theta) = theta^x (1 - theta)^(1 - x). For independent identically distributed observations the likelihood is the product of the single probabilities; with K heads in n tosses it is L(theta) = theta^K (1 - theta)^(n - K). Maximising the log-likelihood l(theta) = K log theta + (n - K) log(1 - theta) (maximum likelihood estimation) gives theta = K / n.Bernoulli Distribution and Maximum Likelihood Estimation →). Because the tosses are independent and identically distributed, the likelihood is the product of the factors; counting the heads in the sequence H T T H H H T H H T H H T H H H (positions 1,4,5,6,8,9,11,12,14,15,161, 4, 5, 6, 8, 9, 11, 12, 14, 15, 16) gives K=11K = 11, and the tails are n−K=16−11=5n - K = 16 - 11 = 5:

L(θ)=θK(1−θ)n−K=θ11(1−θ)5.L(\theta) = \theta^{K}(1-\theta)^{n-K} = \theta^{11}(1-\theta)^{5}.

At θ=0.5\theta = 0.5: L=0.511⋅0.55=0.516≈1.53⋅10−5L = 0.5^{11} \cdot 0.5^{5} = 0.5^{16} \approx 1.53 \cdot 10^{-5}. At θ=0.7\theta = 0.7: L=0.711⋅0.35≈0.019773⋅0.00243≈4.80⋅10−5L = 0.7^{11} \cdot 0.3^{5} \approx 0.019773 \cdot 0.00243 \approx 4.80 \cdot 10^{-5}. The value at 0.70.7 is about three times larger: the data are more probable under θ=0.7\theta = 0.7 than under a fair coin.

b) The product is turned into a sum with the logarithm, which has its maximum at the same θ\theta:

ℓ(θ)=Kln⁡θ+(n−K)ln⁡(1−θ)=11ln⁡θ+5ln⁡(1−θ).\ell(\theta) = K\ln\theta + (n-K)\ln(1-\theta) = 11\ln\theta + 5\ln(1-\theta).

Set the derivative to zero, remembering the factor −1-1 from the chain rule on ln⁡(1−θ)\ln(1-\theta):

dℓdθ=Kθ−n−K1−θ=0  ⟹  K(1−θ)=(n−K)θ  ⟹  K=nθ  ⟹  θ^A=Kn=1116=0.6875,\frac{d\ell}{d\theta} = \frac{K}{\theta} - \frac{n-K}{1-\theta} = 0 \;\Longrightarrow\; K(1-\theta) = (n-K)\theta \;\Longrightarrow\; K = n\theta \;\Longrightarrow\; \hat\theta_A = \frac{K}{n} = \frac{11}{16} = 0.6875,

the observed fraction of heads. The values: ℓ(θ^A)=11ln⁡0.6875+5ln⁡0.3125=11(−0.37469)+5(−1.16315)≈−4.1216−5.8157=−9.937\ell(\hat\theta_A) = 11\ln 0.6875 + 5\ln 0.3125 = 11(-0.37469) + 5(-1.16315) \approx -4.1216 - 5.8157 = -9.937, and ℓ(0.5)=16ln⁡0.5≈−11.090\ell(0.5) = 16\ln 0.5 \approx -11.090. The difference is 1.1531.153, so the likelihood at θ^A\hat\theta_A is e1.153≈3.17e^{1.153} \approx 3.17 times the likelihood at 0.50.5; also L(θ^A)≈4.83⋅10−5L(\hat\theta_A) \approx 4.83 \cdot 10^{-5}, slightly above the value at 0.70.7, as it must be for the maximum.

c) Coin B has K=5K = 5 and n=12n = 12, so θ^B=5/12≈0.4167\hat\theta_B = 5/12 \approx 0.4167 and

ℓB(θ^B)=5ln⁡512+7ln⁡712=5(−0.87547)+7(−0.53900)≈−4.3773−3.7730=−8.150.\ell_B(\hat\theta_B) = 5\ln\frac{5}{12} + 7\ln\frac{7}{12} = 5(-0.87547) + 7(-0.53900) \approx -4.3773 - 3.7730 = -8.150 .

d) If the same θ\theta is used for all 28 tosses, "identical distribution" applies to the whole sample: K=11+5=16K = 11 + 5 = 16 heads in n=16+12=28n = 16 + 12 = 28 tosses, and the same formula gives θ^=16/28=4/7≈0.5714\hat\theta = 16/28 = 4/7 \approx 0.5714. The total log-likelihood is

ℓ(θ^)=16ln⁡47+12ln⁡37≈16(−0.55962)+12(−0.84730)≈−8.954−10.168=−19.121.\ell(\hat\theta) = 16\ln\frac{4}{7} + 12\ln\frac{3}{7} \approx 16(-0.55962) + 12(-0.84730) \approx -8.954 - 10.168 = -19.121 .

With one parameter per coin the total is −9.937+(−8.150)=−18.088-9.937 + (-8.150) = -18.088, which is higher by about 1.0341.034. A model with two free parameters can always do at least as well on the data as one with a single shared parameter (the shared value is one of the choices available to the two-parameter fit), and here the gain is clear because the two estimates, 0.68750.6875 and 0.41670.4167, are far apart: the data support different probabilities of heads.

Typical mistakes: counting the tails instead of the heads in KK; forgetting the factor −1-1 in the derivative of ln⁡(1−θ)\ln(1-\theta); reading the likelihood as the probability of θ\theta instead of the probability of the data as a function of θ\theta; averaging θ^A\hat\theta_A and θ^B\hat\theta_B instead of pooling the counts (0.54170.5417 instead of 0.57140.5714).

Problem 3 (points 5)

Two models, Model 1 (nearest neighbour with K=1K = 1) and Model 2 (nearest neighbour with K=5K = 5), are compared on a data set of 500500 objects. The hold-out is repeated 66 times: each run uses a different random split in 80% training and 20% test objects, and both models use the same split in each run. The F1F_1 scores on the test part are:

run 1 2 3 4 5 6
Model 1 0.82 0.77 0.91 0.70 0.88 0.75
Model 2 0.78 0.80 0.86 0.71 0.81 0.77

a) Give the number of training and test objects of each run and explain why the scores are paired. Compute the six differences (Model 1 minus Model 2), then list their absolute values in decreasing order, each labelled with the model that was better in that run (1.5 points).

b) In how many runs is each model better? What does the ordered list of part a) show about the size of the differences in favour of each model? (1 point)

c) The null hypothesis is that the two models perform equally, and the significance level was fixed before the experiment at α=0.05\alpha = 0.05. The Wilcoxon test (as in the notebooks, scipy.stats.wilcoxon(scores_1, scores_2)) returns the p-value 0.43750.4375 on these six pairs. State the decision. A student proposes to raise α\alpha to 0.50.5 after seeing the p-value, in order to declare the models different: say why this is not acceptable (1.5 points).

d) If the same procedure with α=0.05\alpha = 0.05 is applied to 200200 comparisons between pairs of models that are really equivalent, how many "significant" results are expected by chance? (1 point)

Show the result

a) 400400 training and 100100 test objects per run. Differences: +0.04+0.04, −0.03-0.03, +0.05+0.05, −0.01-0.01, +0.07+0.07, −0.02-0.02. Ordered absolute values: 0.070.07 (Model 1), 0.050.05 (Model 1), 0.040.04 (Model 1), 0.030.03 (Model 2), 0.020.02 (Model 2), 0.010.01 (Model 2).

b) Three runs each (runs 1, 3, 5 for Model 1; runs 2, 4, 6 for Model 2). The three largest differences favour Model 1, the three smallest favour Model 2.

c) p=0.4375>0.05p = 0.4375 > 0.05: H0H_0 is not rejected, the two models are probably equivalent on these data. α\alpha must be decided before the experiment; choosing it after the p-value defeats its meaning.

d) About 200⋅0.05=10200 \cdot 0.05 = 10.

Show the full solution

a) With 500500 objects and a 20% test part, each run trains on 500⋅0.8=400500 \cdot 0.8 = 400 objects and is tested on 500⋅0.2=100500 \cdot 0.2 = 100 (Model Selection and Validation - Hold-Out, k-Fold and Statistical TestsTo decide which of two models is better, fix their hyper-parameters, train each on a training set (this fits the parameters, the vector w or theta) and measure a performance score such as F1 on a separate test set; one split is too fragile, so the hold-out is repeated K times (or K-fold cross-validation is used) and the paired scores of the two models are compared with a statistical test. The null hypothesis H0 is that the two models perform equally; the significance level alpha is fixed before the experiment, and the p-value is the probability of observing the obtained differences under H0. Parametric test: t-test; non-parametric: Wilcoxon.Model Selection and Validation - Hold-Out, k-Fold and Statistical Tests →). The split is arbitrary and the score depends on which objects land in the test part, so one split is fragile and the hold-out is repeated. The scores are paired because in each run the two models use the same training and test objects: the score of Model 1 in run ii is compared only with the score of Model 2 in the same run ii, which removes the effect of an easy or a hard split from the comparison. What matters is the list of differences M1 exi−M2 exiM_1\,ex_i - M_2\,ex_i:

run 1 2 3 4 5 6
M1−M2M_1 - M_2 0.82−0.78=+0.040.82 - 0.78 = +0.04 0.77−0.80=−0.030.77 - 0.80 = -0.03 0.91−0.86=+0.050.91 - 0.86 = +0.05 0.70−0.71=−0.010.70 - 0.71 = -0.01 0.88−0.81=+0.070.88 - 0.81 = +0.07 0.75−0.77=−0.020.75 - 0.77 = -0.02

The absolute values in decreasing order, each with the better model (a positive difference means Model 1, a negative one Model 2), as in the Wilcoxon example of the notes:

   0.07  -> M1   (run 5)
   0.05  -> M1   (run 3)
   0.04  -> M1   (run 1)
   0.03  -> M2   (run 2)
   0.02  -> M2   (run 6)
   0.01  -> M2   (run 4)

b) Model 1 is better in runs 1, 3 and 5, Model 2 in runs 2, 4 and 6: three runs each, so counting the wins does not separate the models. The ordered list shows a clear pattern in the size of the differences: all the large differences (0.070.07, 0.050.05, 0.040.04) are in favour of Model 1, all the small ones (0.030.03, 0.020.02, 0.010.01) in favour of Model 2. So the differences are not spread symmetrically around 00: when Model 1 wins it wins by more, and when Model 2 wins it wins by little. Whether this is more than chance is exactly what the statistical test has to decide, and with only six runs the evidence is weak.

c) The significance level α=0.05\alpha = 0.05 is the total area of the two tails A1+A2A_1 + A_2 of the distribution of the differences expected if the models were equivalent, and it is decided before the experiment. The rule of the notebook is: if the p-value is greater than 0.050.05 the two samples are probably from the same distribution, otherwise they are probably different. Here p=0.4375>0.05p = 0.4375 > 0.05, so the null hypothesis H0H_0 (the two models perform equally) is not rejected: the observed differences are quite compatible with equivalent models. Raising α\alpha to 0.50.5 after seeing p=0.4375p = 0.4375 is not acceptable: α\alpha is the probability of a false alarm that we agree to accept when the models are equal, and a value chosen after the result, only to make the result "significant", is no longer a probability fixed in advance; with α=0.5\alpha = 0.5 one would declare a difference in half of the comparisons between equivalent models. The notebook says exactly this: "stop here and decide the α\alpha value" before reading the p-value.

d) With α=0.05\alpha = 0.05 (5%), in about 55 comparisons out of 100100 between two equivalent models a "significant" difference will appear by chance (remark of the notes). For 200200 comparisons the expected number is 200⋅0.05=10200 \cdot 0.05 = 10.

Typical mistakes: comparing the scores of the two models on different splits (no pairing); subtracting in the wrong order and mixing the signs of the differences; deciding α\alpha after reading the p-value; reading a p-value above α\alpha as a proof that the models are equal instead of "no evidence of a difference".

Self-assessment grid
item points what must be there for full points typical mistakes
Question 1 1.5 C: pattern exists, cannot be written as a formula, data available accepting a problem with a known formula, with no pattern, or with no data
Question 2 1.5 A: exclusive-or is not separable, PLA never stops, maximum iterations thinking the bias coordinate or the margin bound fixes it
Question 3 1.5 D: 4+1+16+4=5\sqrt{4+1+16+4} = 5 sum of the entries; sum of the absolute values; forgetting the square root
Question 4 1.5 B: error 11 on the real output, correction [0.1,0.2,−0.2][0.1, 0.2, -0.2], weights [0.6,−0.8,0.05][0.6, -0.8, 0.05] error on the sign; wrong sign of the step; missing factor 22
Question 5 1.5 C: 1mXT(hθ(X)−y)\frac1mX^T(h_\theta(X)-y), subtracted, error after the sigmoid dropping XTX^T; swapping sigmoid and identity; adding the gradient
Question 6 1.5 B: XTXX^TX is 4×44\times4 whatever the number of rows inverting a matrix of size NN; denying the pseudo-inverse; ignoring the invertibility condition
Question 7 1.5 A: [ [3, 1], [2, 2] ] transposed matrix; positive class swapped; miscounting
Question 8 1.5 D: np.inner multiplies rows by rows, np.dot(A, B) is undefined applying the matrix product to equal shapes; transposed result
Question 9 1.5 B: strict inequality, no update, stops with epochs = 1 counting a zero output as a mistake; thinking the loop never ends
Question 10 1.5 A: four mini-batches per epoch times 100100 epochs one update per epoch or per object
Problem 1 5 bound 24e−6.4≈0.039924e^{-6.4} \approx 0.0399 (1); 0.003320.00332, factor MM, gg chosen after the data (1); N=609N = 609 and 788788, linear in MM but logarithmic in NN (2); 0.0350.035 against 0.0550.055 (1) no factor MM; ε\varepsilon not squared; NN rounded down; union bound as equality
Problem 2 5 K=11K = 11, L(θ)=θ11(1−θ)5L(\theta) = \theta^{11}(1-\theta)^5 and its values (1); θ^A=11/16\hat\theta_A = 11/16 and ℓ=−9.937\ell = -9.937 (1.5); θ^B=5/12\hat\theta_B = 5/12, ℓB=−8.150\ell_B = -8.150 (1); pooled 4/74/7, −19.121-19.121 against −18.088-18.088 (1.5) counting tails; missing −1-1 in the derivative; averaging the two estimates
Problem 3 5 400400 and 100100 objects, pairing, six differences and the ordered labelled list (1.5); three wins each and the pattern of the sizes (1); p=0.4375>0.05p = 0.4375 > 0.05, α\alpha fixed in advance (1.5); 1010 false alarms (1) unpaired scores; α\alpha chosen after the p-value; "not rejected" read as "proved equal"
Total 30