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

Introduction to Machine Learning - Mock Exam 1

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, nearest neighbour, linear regression, 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, so x=[1,x1,x2]T\mathbf{x} = [1, x_1, x_2]^T and w=[w0,w1,w2]T\mathbf{w} = [w_0, w_1, w_2]^T; labels are ±1\pm 1 for the perceptron and 0/10/1 for logistic regression; log⁡\log is the natural logarithm.

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

A discussion about a risk-scoring system says: "a machine-learning algorithm is just a complex formula, and a formula such as y=a x+by = a\,\mathbf{x} + b cannot be racist or sexist". Which conclusion does the course draw?

  • A) The formula a x+ba\,\mathbf{x} + b cannot be biased, because it is only mathematics, whatever the data are.
  • B) A hypothesis learned from data inherits what is in the data: if x\mathbf{x} is biased, then a x+ba\,\mathbf{x} + b is biased too.
  • C) The quality of the answer depends only on the formula, not on how the data were collected.
  • D) In the case study, the defendant given the high risk score (8) went on to commit further offences.
Show the result

B

Show the full solution

B is correct: the reply quoted in 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 → is "if x\mathbf{x} is biased, then a x+ba\,\mathbf{x} + b will be biased too", and the consequence stated there is that a hypothesis learned from data inherits whatever is in the data. A is the claim that the reply rejects. C is false: the note says the quality of the answer depends on how the data were collected, not only on the formula. D is false: in the case study the defendant rated high risk (score 8) had no subsequent offences.

Question 2

Four samples (xi,yi)(x_i, y_i) are given: (0,1.5)(0, 1.5), (1,2.5)(1, 2.5), (2,6)(2, 6), (3,6.5)(3, 6.5). The hypothesis is h(x)=2x+1h(x) = 2x + 1 and the error function is the squared difference. What is the in-sample error Ein(h)E_{\text{in}}(h)?

  • A) 1.751.75
  • B) 0.6250.625
  • C) 0.1250.125
  • D) 0.43750.4375
Show the result

D

Show the full solution

The differences yi−h(xi)y_i - h(x_i) are 0.50.5, −0.5-0.5, 11, −0.5-0.5. Their squares are 0.250.25, 0.250.25, 11, 0.250.25, with sum (SSE) 1.751.75, and the in-sample error of The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization → is the average over the N=4N = 4 points:

Ein(h)=14∑i=14(yi−h(xi))2=1.754=0.4375.E_{\text{in}}(h) = \frac{1}{4}\sum_{i=1}^{4}\big(y_i - h(x_i)\big)^2 = \frac{1.75}{4} = 0.4375 .

So D is correct. A is the sum of squares without the factor 1/N1/N. B is the mean of the absolute values ∣yi−h(xi)∣|y_i - h(x_i)|: the notes mention the absolute value as one possible way to make errors non-negative but choose the square. C is the mean of the signed differences, 0.5/40.5/4: signed differences cancel, which is why they are not a good measure.

Question 3

A hypothesis hh is fixed before looking at the data. Its in-sample error is measured on N=250N = 250 independent samples. Using the Hoeffding inequality of the course for one fixed hypothesis, which is the upper bound for P(∣Ein(h)−Eout(h)∣>0.1)P\big(|E_{\text{in}}(h) - E_{\text{out}}(h)| > 0.1\big)?

  • A) 2e−5≈0.01352e^{-5} \approx 0.0135
  • B) e−5≈0.0067e^{-5} \approx 0.0067
  • C) 2e−50≈3.9⋅10−222e^{-50} \approx 3.9 \cdot 10^{-22}
  • D) 2e−2.5≈0.1642e^{-2.5} \approx 0.164
Show the result

A

Show the full solution

For one fixed hypothesis the inequality 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 → is P(∣ν−μ∣>ε)≤2e−2ε2NP(|\nu - \mu| > \varepsilon) \le 2e^{-2\varepsilon^2 N}, with ν=Ein(h)\nu = E_{\text{in}}(h) and μ=Eout(h)\mu = E_{\text{out}}(h). Here 2ε2N=2⋅0.01⋅250=52\varepsilon^2 N = 2 \cdot 0.01 \cdot 250 = 5, so the bound is 2e−5≈0.01352e^{-5} \approx 0.0135: A is correct. B drops the factor 22 in front of the exponential. C uses 2εN=502\varepsilon N = 50 in the exponent, forgetting that ε\varepsilon is squared. D uses ε2N=2.5\varepsilon^2 N = 2.5, forgetting the factor 22 in the exponent.

Question 4

A test object must be classified by K-nearest neighbour with K=5K = 5 and a plain majority vote (all neighbours count the same). The distances from the test object to the seven training objects, with their classes, are: 0.50.5 (B), 0.80.8 (A), 1.11.1 (B), 1.31.3 (A), 1.91.9 (A), 2.42.4 (C), 3.03.0 (C). Which class is predicted?

  • A) Class B, the class of the nearest object.
  • B) Class C, the class of the two farthest objects.
  • C) Class A.
  • D) There is a tie between A and B, so no class is predicted.
Show the result

C

Show the full solution

The test phase of Nearest NeighbourK-nearest neighbours (KNN) has an almost empty training phase (the data are just stored) and does all the work at test time: given a point, compute its distance from all training points, sort the distances, keep the K shortest and predict the (weighted) majority class among them. The course source has one handwritten page on it; the notebooks use it as one of six scikit-learn classifiers, and the model-comparison example contrasts KNN with K=1 and K=5.Nearest Neighbour → is: compute the distances from all the training points (here they are given), sort them, keep the first KK elements, predict by the majority of their classes. The distances are already in increasing order, and the first five are 0.50.5 (B), 0.80.8 (A), 1.11.1 (B), 1.31.3 (A), 1.91.9 (A): three votes for A and two for B, so the prediction is A and C is correct. A is the answer for K=1K = 1 and for K=3K = 3 (B, A, B), but not for K=5K = 5: the value of KK is a hyper-parameter and changes the prediction. B uses the two farthest objects, which the algorithm discards. D is false: 33 against 22 is not a tie.

Question 5

In the course notes, what does the evaluation of a classifier consist in?

  • A) The actual output is given by the hypothesis hh and the predicted output by the target ff; they are compared on new objects.
  • B) The vector y\mathbf{y} of the actual outputs, given by the target ff, is compared with the vector y^\hat{\mathbf{y}} of the predicted outputs, given by the hypothesis hh, on the same objects.
  • C) The weight vector of one hypothesis is compared with the weight vector of another, without using any object.
  • D) Binary versus multi-class and single-label versus multi-label are the same distinction, and the notes develop the multi-label case.
Show the result

B

Show the full solution

B is correct, 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 →: the target function f(x)f(\mathbf{x}) gives the actual output, the hypothesis h(x)h(\mathbf{x}) gives the predicted output, and evaluating a classifier means comparing the two on the same objects. A swaps the roles of ff and hh. C is false: the comparison is between outputs on objects, not between weights. D is false: the notes list single-label versus multi-label as another distinction beside binary versus multi-class, and say that the material that follows is single-label.

Question 6

Which description of the final procedure of the course for choosing a model (the letter-recognition example) is correct?

  • A) Run k-fold cross-validation on the whole data set, choose the best model and report its cross-validation score; no separate test set is kept.
  • B) Keep a test set of 20% of the data, score each of the six models on it, choose the best model from the test scores and then retrain it.
  • C) Keep a test set, run cross-validation on the training set, choose the best model and evaluate it on the test set after each fold.
  • D) Keep a stratified test set of 20% of the data untouched, run cross-validation on the training set only, compare the best models with a statistical test, train the chosen model on the whole training set and evaluate it once on the test set.
Show the result

D

Show the full solution

D is the procedure of 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 → (section on the final notebook, code in Python Notebooks - scikit-learn Model Comparison and Wilcoxon TestTwo example notebooks compare six scikit-learn classifiers (logistic regression, perceptron, KNN, decision tree, SVC, random forest) on a real data set loaded from the UCI repository: hold-out split with train_test_split, F1 score, k-fold cross-validation with cross_validate and scoring f1_macro, box plots of the fold scores, and the Wilcoxon signed-rank test (scipy.stats.wilcoxon) on the paired fold scores; the second notebook adds a stratified test set, more folds on the best models and the final training and test of the chosen model. A separate short notebook draws two normal samples to see how often the Wilcoxon test rejects at the 0.05 level.Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test →): the test set is held out first and not touched until the end; k-fold cross-validation runs on the training set only; the best models are compared with the Wilcoxon test; the chosen model is trained on the whole training set and evaluated once on the test set. A is wrong because it keeps no test set. B is wrong because the test set is not used to choose the model. C is wrong because the test set is used once, at the end, not after each fold.

Question 7

A perceptron has weights (w0,w1,w2)=(−6,2,3)(w_0, w_1, w_2) = (-6, 2, 3) on the features (x1,x2)(x_1, x_2). As in the course notebooks, its boundary wTx=0\mathbf{w}^T\mathbf{x} = 0 is drawn in the (x1,x2)(x_1, x_2) plane as the line x2=a x1+bx_2 = a\,x_1 + b. What are aa and bb?

  • A) a=−2/3a = -2/3, b=2b = 2
  • B) a=2/3a = 2/3, b=−2b = -2
  • C) a=−3/2a = -3/2, b=2b = 2
  • D) a=−2/3a = -2/3, b=−2b = -2
Show the result

A

Show the full solution

From w1x1+w2x2+w0=0w_1x_1 + w_2x_2 + w_0 = 0 we get x2=−w1w2x1−w0w2x_2 = -\dfrac{w_1}{w_2}x_1 - \dfrac{w_0}{w_2} (see 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 →; the notebook 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 → draws the line with exactly this formula). With the data: slope a=−23a = -\dfrac{2}{3} and intercept b=−−63=2b = -\dfrac{-6}{3} = 2, so A is correct. B has both signs wrong. C uses −w2/w1-w_2/w_1 for the slope. D uses w0/w2=−2w_0/w_2 = -2 instead of −w0/w2=2-w_0/w_2 = 2 for the intercept.

Question 8

A data set has the labels y = [1, 2, 3, 2, 1, 3]. To train a binary classifier for one class, the exercise notebook runs

python
positive_class = 2
y_class = -np.ones(y.shape[0])
y_class[y == positive_class] = 1

What is the vector y_class?

  • A) [1, -1, -1, -1, 1, -1]
  • B) [0, 1, 0, 1, 0, 0]
  • C) [-1, 1, -1, 1, -1, -1]
  • D) [1, 1, -1, 1, 1, -1]
Show the result

C

Show the full solution

The vector is first filled with −1-1 and then the entries where y equals positive_class become +1+1: the labels equal to 22 are in positions 2 and 4, so y_class = [-1, 1, -1, 1, -1, -1] and C is correct. This is the "class against the rest" reduction of 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 →, with labels ±1\pm 1. A marks the class 11 as positive. B uses the 0/10/1 coding, which the perceptron exercise does not use: the other objects get −1-1. D marks the classes 11 and 22 as positive, but only one class is positive.

Question 9

Which statement about creating strings in Python, as in the course notebook, is correct?

  • A) 'a string' == "a string" is False, because the two strings are written with different quotes.
  • B) A triple-quoted string can span several lines, and its value contains the line breaks (shown as \n).
  • C) The value of a triple-quoted string contains no line breaks: they are removed when the string is created.
  • D) Single quotes are used for strings of one word and double quotes for strings that contain spaces.
Show the result

B

Show the full solution

Question 10

With import re and txt = "The rain in Spain", which call returns None?

  • A) re.search("rain", txt)
  • B) re.search(".*pain", txt)
  • C) re.search("[a-m]in", txt)
  • D) re.search(".*spain", txt)
Show the result

D

Show the full solution

In Python Notebooks - Strings and Regular ExpressionsNotebook on Python strings: quoting (single, double, triple quotes), case methods (upper, lower, title, capitalize, swapcase), removing characters at the ends (strip), searching and replacing (find, startswith, endswith, replace, partition), splitting (split, splitlines), and a first use of regular expressions with the re module (search, findall, sub) with the anchors for start and end of string, the dot, the star, the plus and character classes.Python Notebooks - Strings and Regular Expressions → the search is case sensitive and the pattern .*spain has a lower-case s, while the text contains Spain: there is no match, so D returns None. A matches because rain is in the middle of the text. B matches from the start of the text up to pain (.* is any number of any characters). C matches because a character class [a-m] followed by in is found (a letter between a and m followed by in, here in rain and in Spain).

Problem 1 (points 5)

A perceptron h(x)=sign⁡(wTx)h(\mathbf{x}) = \operatorname{sign}(\mathbf{w}^T\mathbf{x}) is trained with the Perceptron Learning Algorithm starting from w1=[0,0,0]T\mathbf{w}_1 = [0, 0, 0]^T on the following four points, always scanned in this order:

point (x1,x2)(x_1, x_2) yy
P1P_1 (0,0)(0, 0) −1-1
P2P_2 (1,0)(1, 0) −1-1
P3P_3 (2,0.5)(2, 0.5) +1+1
P4P_4 (3,0)(3, 0) +1+1

A point is a mistake, and the update w←w+y x\mathbf{w} \leftarrow \mathbf{w} + y\,\mathbf{x} is made, whenever y wTx≤0y\,\mathbf{w}^T\mathbf{x} \le 0 (the case 00 included). The passes over the four points are repeated until a whole pass has no update.

a) Write every update (point used and weight vector after it) and give the number of updates KK and the number of passes (2 points).

b) Compute y wTxy\,\mathbf{w}^T\mathbf{x} for the four points with the final w\mathbf{w} and check that all of them are correct (0.5 points).

c) The unit vector w∗=13[−2,1,2]T\mathbf{w}^* = \tfrac{1}{3}[-2, 1, 2]^T separates the data. Compute the margin γ=min⁡iyi w∗Txi\gamma = \min_i y_i\,\mathbf{w}^{*T}\mathbf{x}_i, the radius R=max⁡i∥xi∥R = \max_i \|\mathbf{x}_i\| (with the coordinate x0=1x_0 = 1 included) and the bound R2/γ2R^2/\gamma^2 (1.5 points).

d) Compare KK with the bound. What does the bound count, and does it depend on the number of points? (1 point)

Show the result

a) Updates: P1→w=[−1,0,0]TP_1 \to \mathbf{w} = [-1, 0, 0]^T; P3→[0,2,0.5]TP_3 \to [0, 2, 0.5]^T; P1→[−1,2,0.5]TP_1 \to [-1, 2, 0.5]^T; P2→[−2,1,0.5]TP_2 \to [-2, 1, 0.5]^T. K=4K = 4 updates, 3 passes (the third has no update). Final w=[−2,1,0.5]T\mathbf{w} = [-2, 1, 0.5]^T.

b) y wTx=2, 1, 0.25, 1y\,\mathbf{w}^T\mathbf{x} = 2,\ 1,\ 0.25,\ 1 for P1,…,P4P_1, \dots, P_4: all positive.

c) yi w∗Txi=2/3, 1/3, 1/3, 1/3y_i\,\mathbf{w}^{*T}\mathbf{x}_i = 2/3,\ 1/3,\ 1/3,\ 1/3, so γ=1/3\gamma = 1/3; R2=10R^2 = 10 (from P4P_4), R=10≈3.16R = \sqrt{10} \approx 3.16; R2/γ2=90R^2/\gamma^2 = 90.

d) K=4≤90K = 4 \le 90. The bound counts updates, not passes; it depends only on RR and γ\gamma, not on the number of points or of features.

Show the full solution

Setting: 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 → for the update rule and 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 → for the bound.

a) The run. Each point is the vector x=[1,x1,x2]T\mathbf{x} = [1, x_1, x_2]^T.

Pass 1.

  • P1P_1, x=[1,0,0]T\mathbf{x} = [1, 0, 0]^T, y=−1y = -1: y wTx=0≤0y\,\mathbf{w}^T\mathbf{x} = 0 \le 0, a mistake. w=[0,0,0]T+(−1)[1,0,0]T=[−1,0,0]T\mathbf{w} = [0,0,0]^T + (-1)[1,0,0]^T = [-1, 0, 0]^T.
  • P2P_2, x=[1,1,0]T\mathbf{x} = [1, 1, 0]^T, y=−1y = -1: wTx=−1\mathbf{w}^T\mathbf{x} = -1, so y wTx=1>0y\,\mathbf{w}^T\mathbf{x} = 1 > 0, correct, no update.
  • P3P_3, x=[1,2,0.5]T\mathbf{x} = [1, 2, 0.5]^T, y=+1y = +1: wTx=−1\mathbf{w}^T\mathbf{x} = -1, y wTx=−1≤0y\,\mathbf{w}^T\mathbf{x} = -1 \le 0, a mistake. w=[−1,0,0]T+[1,2,0.5]T=[0,2,0.5]T\mathbf{w} = [-1, 0, 0]^T + [1, 2, 0.5]^T = [0, 2, 0.5]^T.
  • P4P_4, x=[1,3,0]T\mathbf{x} = [1, 3, 0]^T, y=+1y = +1: wTx=6>0\mathbf{w}^T\mathbf{x} = 6 > 0, correct.

Pass 2.

  • P1P_1: wTx=0\mathbf{w}^T\mathbf{x} = 0, so y wTx=0≤0y\,\mathbf{w}^T\mathbf{x} = 0 \le 0, a mistake (the case 00 counts as a mistake, as in the proof of the bound). w=[0,2,0.5]T−[1,0,0]T=[−1,2,0.5]T\mathbf{w} = [0, 2, 0.5]^T - [1, 0, 0]^T = [-1, 2, 0.5]^T.
  • P2P_2: wTx=−1+2=1\mathbf{w}^T\mathbf{x} = -1 + 2 = 1, y wTx=−1≤0y\,\mathbf{w}^T\mathbf{x} = -1 \le 0, a mistake. w=[−1,2,0.5]T−[1,1,0]T=[−2,1,0.5]T\mathbf{w} = [-1, 2, 0.5]^T - [1, 1, 0]^T = [-2, 1, 0.5]^T.
  • P3P_3: wTx=−2+2+0.25=0.25>0\mathbf{w}^T\mathbf{x} = -2 + 2 + 0.25 = 0.25 > 0, correct.
  • P4P_4: wTx=−2+3=1>0\mathbf{w}^T\mathbf{x} = -2 + 3 = 1 > 0, correct.

Pass 3. P1P_1: wTx=−2\mathbf{w}^T\mathbf{x} = -2, y wTx=2y\,\mathbf{w}^T\mathbf{x} = 2; P2P_2: wTx=−1\mathbf{w}^T\mathbf{x} = -1, value 11; P3P_3: 0.250.25; P4P_4: 11. No update: the algorithm stops with K=4K = 4 updates and w=[−2,1,0.5]T\mathbf{w} = [-2, 1, 0.5]^T.

b) Check. The values computed in pass 3 are 2,1,0.25,12, 1, 0.25, 1, all positive: every point is on the correct side. The boundary is x2=−w1w2x1−w0w2=−2x1+4x_2 = -\dfrac{w_1}{w_2}x_1 - \dfrac{w_0}{w_2} = -2x_1 + 4.

c) Margin and radius. With the unit vector w∗\mathbf{w}^* (check: (4+1+4)/9=1(4 + 1 + 4)/9 = 1) the products yi w∗Txiy_i\,\mathbf{w}^{*T}\mathbf{x}_i are:

  • P1P_1: (−1)⋅−23=23(-1)\cdot\dfrac{-2}{3} = \dfrac{2}{3};
  • P2P_2: (−1)⋅−2+13=13(-1)\cdot\dfrac{-2 + 1}{3} = \dfrac{1}{3};
  • P3P_3: (+1)⋅−2+2+13=13(+1)\cdot\dfrac{-2 + 2 + 1}{3} = \dfrac{1}{3};
  • P4P_4: (+1)⋅−2+33=13(+1)\cdot\dfrac{-2 + 3}{3} = \dfrac{1}{3}.

The smallest is γ=13\gamma = \dfrac{1}{3}. The squared norms of the vectors [1,x1,x2]T[1, x_1, x_2]^T are 11, 22, 5.255.25, 1010, so R2=10R^2 = 10. The bound is

K≤R2γ2=101/9=90.K \le \frac{R^2}{\gamma^2} = \frac{10}{1/9} = 90 .

d) Comparison. The algorithm made K=4K = 4 updates, far below 9090: the bound is only an upper limit that depends on the geometry (a small margin gives a large bound). It counts updates, not passes over the data (here the algorithm made 3 passes, the last one without updates), and it depends only on RR and γ\gamma, not on the number of points or of features.

Typical mistakes: not counting the value 00 as a mistake (the run changes from the first step); updating on points that are already correct; forgetting the coordinate x0=1x_0 = 1 in the norms (then R2=9R^2 = 9 and the bound would be 8181); confusing the number of updates with the number of passes.

Problem 2 (points 5)

Five samples (xi,yi)(x_i, y_i) are given: (−2,5.5)(-2, 5.5), (−1,1.5)(-1, 1.5), (0,1)(0, 1), (1,2.5)(1, 2.5), (2,4.5)(2, 4.5). The data matrix has a first column of ones. The error is Ein(w)=1N∑i(yi−wTxi)2E_{\text{in}}(\mathbf{w}) = \frac{1}{N}\sum_i (y_i - \mathbf{w}^T\mathbf{x}_i)^2.

a) An ADALINE with the linear hypothesis h(x)=w0+w1xh(x) = w_0 + w_1x starts from W=[0,0]T\mathbf{W} = [0, 0]^T. Compute EinE_{\text{in}} at this point (0.5 points).

b) Compute the gradient ∇Ein=−2NXT(Y−XW)\nabla E_{\text{in}} = -\dfrac{2}{N}X^T(Y - X\mathbf{W}) at W=[0,0]T\mathbf{W} = [0, 0]^T, make one gradient-descent step with η=0.1\eta = 0.1, and compute EinE_{\text{in}} after the step (1.5 points).

c) Fit the quadratic hypothesis h(x)=w0+w1x+w2x2h(x) = w_0 + w_1x + w_2x^2 with the closed form w=(XTX)−1XTY\mathbf{w} = (X^TX)^{-1}X^TY: write the data matrix with the columns 1,x,x21, x, x^2, the matrices XTXX^TX and XTYX^TY, and solve (2 points).

d) Compute EinE_{\text{in}} of the quadratic fit and compare it with the values of parts a and b. What does the closed form guarantee that one gradient step does not? (1 point)

Show the result

a) Ein=12E_{\text{in}} = 12.

b) XTY=[15,−1]TX^TY = [15, -1]^T; ∇Ein=[−6,0.4]T\nabla E_{\text{in}} = [-6, 0.4]^T; Wnew=[0.6,−0.04]T\mathbf{W}_{\text{new}} = [0.6, -0.04]^T; Ein=8.7472E_{\text{in}} = 8.7472.

c) XTX=[5010010010034]X^TX = \begin{bmatrix}5 & 0 & 10\\ 0 & 10 & 0\\ 10 & 0 & 34\end{bmatrix}, XTY=[15,−1,44]TX^TY = [15, -1, 44]^T, w=[1,−0.1,1]T\mathbf{w} = [1, -0.1, 1]^T, that is h(x)=1−0.1x+x2h(x) = 1 - 0.1x + x^2.

d) Fitted values 5.2,2.1,1,1.9,4.85.2, 2.1, 1, 1.9, 4.8; SSE =0.9= 0.9; Ein=0.18E_{\text{in}} = 0.18, much smaller than 1212 and than 8.74728.7472. The closed form gives the exact minimiser of EinE_{\text{in}} in its hypothesis set (the matrix XTXX^TX is invertible), while one step only moves part of the way.

Show the full solution

Setting: 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 → for parts a and b, 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 → for parts c and d; the error is the one of The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization →.

a) Starting error. At W=0\mathbf{W} = \mathbf{0} the output is 00 for every sample, so the errors are the labels themselves:

Ein=5.52+1.52+12+2.52+4.525=30.25+2.25+1+6.25+20.255=605=12.E_{\text{in}} = \frac{5.5^2 + 1.5^2 + 1^2 + 2.5^2 + 4.5^2}{5} = \frac{30.25 + 2.25 + 1 + 6.25 + 20.25}{5} = \frac{60}{5} = 12 .

b) One step. The data matrix is X=[1−21−1101112]X = \begin{bmatrix}1 & -2\\ 1 & -1\\ 1 & 0\\ 1 & 1\\ 1 & 2\end{bmatrix} and Y=[5.5,1.5,1,2.5,4.5]TY = [5.5, 1.5, 1, 2.5, 4.5]^T. At W=0\mathbf{W} = \mathbf{0} the vector Y−XWY - X\mathbf{W} is YY itself, and

XTY=[5.5+1.5+1+2.5+4.5−11−1.5+0+2.5+9]=[15−1].X^TY = \begin{bmatrix}5.5 + 1.5 + 1 + 2.5 + 4.5\\ -11 - 1.5 + 0 + 2.5 + 9\end{bmatrix} = \begin{bmatrix}15\\ -1\end{bmatrix}.

The gradient with the constant 2/N=0.42/N = 0.4 is ∇Ein=−0.4 [15,−1]T=[−6,0.4]T\nabla E_{\text{in}} = -0.4\,[15, -1]^T = [-6, 0.4]^T. The rule Wnew=Wold−η ∇Ein\mathbf{W}_{\text{new}} = \mathbf{W}_{\text{old}} - \eta\,\nabla E_{\text{in}} gives

Wnew=[0,0]T−0.1 [−6,0.4]T=[0.6,−0.04]T.\mathbf{W}_{\text{new}} = [0, 0]^T - 0.1\,[-6, 0.4]^T = [0.6, -0.04]^T .

The new residuals yi−(0.6−0.04xi)y_i - (0.6 - 0.04x_i) are 4.824.82, 0.860.86, 0.40.4, 1.941.94, 3.983.98, and

Ein=23.2324+0.7396+0.16+3.7636+15.84045=43.7365=8.7472.E_{\text{in}} = \frac{23.2324 + 0.7396 + 0.16 + 3.7636 + 15.8404}{5} = \frac{43.736}{5} = 8.7472 .

The error went down from 1212 to 8.74728.7472: the step moves against the gradient, but it is still far from the minimum.

c) Closed form for the quadratic. The hypothesis is linear in the weights, so the data matrix gets the columns 1,x,x21, x, x^2:

Xreg=[1−241−11100111124].X_{\text{reg}} = \begin{bmatrix}1 & -2 & 4\\ 1 & -1 & 1\\ 1 & 0 & 0\\ 1 & 1 & 1\\ 1 & 2 & 4\end{bmatrix}.

The sums of powers are ∑x=0\sum x = 0, ∑x2=10\sum x^2 = 10, ∑x3=0\sum x^3 = 0, ∑x4=34\sum x^4 = 34, so

XTX=[5010010010034],XTY=[15−15.5⋅4+1.5+0+2.5+4.5⋅4]=[15−144].X^TX = \begin{bmatrix}5 & 0 & 10\\ 0 & 10 & 0\\ 10 & 0 & 34\end{bmatrix},\qquad X^TY = \begin{bmatrix}15\\ -1\\ 5.5\cdot 4 + 1.5 + 0 + 2.5 + 4.5\cdot 4\end{bmatrix} = \begin{bmatrix}15\\ -1\\ 44\end{bmatrix}.

The normal equations XTX w=XTYX^TX\,\mathbf{w} = X^TY read 5w0+10w2=155w_0 + 10w_2 = 15, 10w1=−110w_1 = -1, 10w0+34w2=4410w_0 + 34w_2 = 44. The second gives w1=−0.1w_1 = -0.1. From the first, w0=3−2w2w_0 = 3 - 2w_2; in the third, 30−20w2+34w2=4430 - 20w_2 + 34w_2 = 44, so 14w2=1414w_2 = 14 and w2=1w_2 = 1, w0=1w_0 = 1. Hence w=[1,−0.1,1]T\mathbf{w} = [1, -0.1, 1]^T and h(x)=1−0.1x+x2h(x) = 1 - 0.1x + x^2. (The matrix XTXX^TX is invertible: its determinant is 700700.)

d) Error of the fit. The fitted values are h(−2)=5.2h(-2) = 5.2, h(−1)=2.1h(-1) = 2.1, h(0)=1h(0) = 1, h(1)=1.9h(1) = 1.9, h(2)=4.8h(2) = 4.8, with residuals 0.30.3, −0.6-0.6, 00, 0.60.6, −0.3-0.3. The SSE is 0.09+0.36+0+0.36+0.09=0.90.09 + 0.36 + 0 + 0.36 + 0.09 = 0.9 and Ein=0.9/5=0.18E_{\text{in}} = 0.9/5 = 0.18. This is much smaller than 1212 (start) and than 8.74728.7472 (after one step). The closed form returns the exact minimiser of EinE_{\text{in}} over the quadratic hypotheses in one shot, with the inversion of a matrix whose size is the number of columns (3×33 \times 3); gradient descent only approaches the minimum step by step and needs a learning rate and a stopping rule.

Typical mistakes: the sign of the update (the step is −η∇Ein-\eta\nabla E_{\text{in}}, that is +ηXT(Y−XW)+\eta X^T(Y - X\mathbf{W}) without the constant); forgetting the column of ones or the column x2x^2; forgetting to divide by NN when computing EinE_{\text{in}} (SSE instead of the average); using X−1X^{-1} for a non-square matrix.

Problem 3 (points 5)

A logistic-regression classifier has y^=σ(wTx)\hat y = \sigma(\mathbf{w}^T\mathbf{x}) with σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}) and weights w=[w0,w1]T=[−2,1]T\mathbf{w} = [w_0, w_1]^T = [-2, 1]^T. Seven objects have one feature x1x_1 and a label y∈{0,1}y \in \{0, 1\}:

object 1 2 3 4 5 6 7
x1x_1 0.50.5 1.01.0 1.81.8 2.22.2 2.62.6 3.03.0 4.04.0
yy 00 11 11 00 11 11 11

a) Compute z=wTxz = \mathbf{w}^T\mathbf{x} and the probability y^\hat y of the positive class for each object (1 point).

b) Assign each object to a class (class 11 when y^>0.5\hat y > 0.5), build the confusion matrix with the positive class y=1y = 1, and compute accuracy, recall, precision and F1F_1 (1.5 points).

c) Compute the cost J(θ)=∑i[−yilog⁡y^i−(1−yi)log⁡(1−y^i)]J(\theta) = \sum_i\big[-y_i\log\hat y_i - (1 - y_i)\log(1 - \hat y_i)\big] over the seven objects (1.5 points).

d) Make one gradient-descent step with η=0.5\eta = 0.5, using ∂J∂θ=1mXT(y^−y)\dfrac{\partial J}{\partial \theta} = \dfrac{1}{m}X^T(\hat{\mathbf{y}} - \mathbf{y}) with m=7m = 7. Give the new weights and the new cost, and say whether the cost has decreased (1 point).

Show the result

a) z=−1.5,−1,−0.2,0.2,0.6,1,2z = -1.5, -1, -0.2, 0.2, 0.6, 1, 2; y^=0.182, 0.269, 0.450, 0.550, 0.646, 0.731, 0.881\hat y = 0.182,\ 0.269,\ 0.450,\ 0.550,\ 0.646,\ 0.731,\ 0.881.

b) Predicted classes 0,0,0,1,1,1,10, 0, 0, 1, 1, 1, 1. TP=3TP = 3, FN=2FN = 2, FP=1FP = 1, TN=1TN = 1. Accuracy =4/7≈0.571= 4/7 \approx 0.571; recall =3/5=0.6= 3/5 = 0.6; precision =3/4=0.75= 3/4 = 0.75; F1=2/3≈0.667F_1 = 2/3 \approx 0.667.

c) Terms 0.201, 1.313, 0.798, 0.798, 0.437, 0.313, 0.1270.201,\ 1.313,\ 0.798,\ 0.798,\ 0.437,\ 0.313,\ 0.127; J≈3.989J \approx 3.989.

d) Gradient [−0.1844,−0.3750]T[-0.1844, -0.3750]^T; wnew=[−1.9078,1.1875]T\mathbf{w}_{\text{new}} = [-1.9078, 1.1875]^T; the new cost is J≈3.546J \approx 3.546: it has decreased.

Show the full solution

Setting: 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 → for the model, the cost and the gradient step; 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 → for part b.

a) Scores and probabilities. With the bias coordinate x0=1x_0 = 1, z=−2+x1z = -2 + x_1:

object 1 2 3 4 5 6 7
zz −1.5-1.5 −1-1 −0.2-0.2 0.20.2 0.60.6 11 22
y^=σ(z)\hat y = \sigma(z) 0.1820.182 0.2690.269 0.4500.450 0.5500.550 0.6460.646 0.7310.731 0.8810.881

For example σ(−1.5)=1/(1+e1.5)=1/5.482=0.182\sigma(-1.5) = 1/(1 + e^{1.5}) = 1/5.482 = 0.182.

b) Classes and metrics. The rule y^>0.5\hat y > 0.5 is the same as z>0z > 0: objects 4,5,6,74, 5, 6, 7 go to class 11, objects 1,2,31, 2, 3 to class 00. Comparing with the labels (rows actual, columns predicted):

                 Pred P   Pred N
  Actual P          3        2
  Actual N          1        1
  • TP=3TP = 3: objects 5,6,75, 6, 7; FN=2FN = 2: objects 2,32, 3 (actual 11, predicted 00); FP=1FP = 1: object 44; TN=1TN = 1: object 11.
  • Accuracy=3+17=0.571\text{Accuracy} = \dfrac{3 + 1}{7} = 0.571, Recall=33+2=0.6\text{Recall} = \dfrac{3}{3 + 2} = 0.6, Precision=33+1=0.75\text{Precision} = \dfrac{3}{3 + 1} = 0.75.
  • F1=2⋅0.6⋅0.750.6+0.75=0.91.35=0.667F_1 = \dfrac{2 \cdot 0.6 \cdot 0.75}{0.6 + 0.75} = \dfrac{0.9}{1.35} = 0.667.

c) Cost. For y=1y = 1 the term is −log⁡y^-\log\hat y, for y=0y = 0 it is −log⁡(1−y^)-\log(1 - \hat y) (this is −ℓ-\ell, the Bernoulli log-likelihood with the sign changed, see 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 →):

  • object 1 (y=0y = 0): −log⁡(1−0.182)=0.201-\log(1 - 0.182) = 0.201;
  • object 2 (y=1y = 1): −log⁡0.269=1.313-\log 0.269 = 1.313;
  • object 3 (y=1y = 1): −log⁡0.450=0.798-\log 0.450 = 0.798;
  • object 4 (y=0y = 0): −log⁡(1−0.550)=0.798-\log(1 - 0.550) = 0.798;
  • object 5 (y=1y = 1): −log⁡0.646=0.437-\log 0.646 = 0.437;
  • object 6 (y=1y = 1): −log⁡0.731=0.313-\log 0.731 = 0.313;
  • object 7 (y=1y = 1): −log⁡0.881=0.127-\log 0.881 = 0.127.

The sum is J≈3.989J \approx 3.989 (computed with unrounded probabilities).

d) One gradient step. The output errors y^i−yi\hat y_i - y_i are 0.1820.182, −0.731-0.731, −0.550-0.550, 0.5500.550, −0.354-0.354, −0.269-0.269, −0.119-0.119. The gradient components are

∂J∂w0=17∑i(y^i−yi)=−1.2917=−0.1844,∂J∂w1=17∑i(y^i−yi) xi1=−2.6257=−0.3750.\frac{\partial J}{\partial w_0} = \frac{1}{7}\sum_i(\hat y_i - y_i) = \frac{-1.291}{7} = -0.1844,\qquad \frac{\partial J}{\partial w_1} = \frac{1}{7}\sum_i(\hat y_i - y_i)\,x_{i1} = \frac{-2.625}{7} = -0.3750 .

The update θnew=θold−η ∂J/∂θ\theta_{\text{new}} = \theta_{\text{old}} - \eta\,\partial J/\partial\theta gives

w0=−2+0.5⋅0.1844=−1.9078,w1=1+0.5⋅0.3750=1.1875.w_0 = -2 + 0.5 \cdot 0.1844 = -1.9078,\qquad w_1 = 1 + 0.5 \cdot 0.3750 = 1.1875 .

With the new weights the cost is J≈3.546<3.989J \approx 3.546 < 3.989: it has decreased (and object 33 now has z=−1.9078+1.1875⋅1.8=0.2297>0z = -1.9078 + 1.1875 \cdot 1.8 = 0.2297 > 0, so it is assigned to class 11).

Typical mistakes: using the logit instead of the probability; minimising ℓ\ell instead of −ℓ-\ell (sign of the cost); forgetting the factor 1/m1/m in the gradient; adding the gradient instead of subtracting it; confusing precision with recall (swapping FPFP and FNFN in the denominators); mixing the 0/10/1 coding with the ±1\pm 1 coding.

Self-assessment grid
item points what must be there for full points typical mistakes
Question 1 1.5 B: a hypothesis learned from data inherits the bias of the data trusting the formula and ignoring how the data were collected
Question 2 1.5 D: squared differences averaged over N=4N = 4, 0.43750.4375 forgetting 1/N1/N; absolute values; signed differences
Question 3 1.5 A: 2e−2ε2N=2e−52e^{-2\varepsilon^2 N} = 2e^{-5} dropping the 2; not squaring ε\varepsilon
Question 4 1.5 C: five nearest neighbours, three A against two B using K=1K = 1 or K=3K = 3; using the farthest objects
Question 5 1.5 B: actual outputs of ff against predicted outputs of hh on the same objects swapping ff and hh; comparing weights
Question 6 1.5 D: test set kept aside, cross-validation on the training set only, one final evaluation choosing the model with the test set; no test set
Question 7 1.5 A: a=−w1/w2a = -w_1/w_2, b=−w0/w2b = -w_0/w_2 wrong signs; swapping w1w_1 and w2w_2
Question 8 1.5 C: −1-1 everywhere, +1+1 where the label equals the positive class 0/10/1 coding; marking more than one class
Question 9 1.5 B: triple quotes span lines and keep the line breaks thinking single and double quotes differ
Question 10 1.5 D: case-sensitive search, .*spain gives None ignoring the case; misreading the character class
Problem 1 5 the four updates with the weights [−1,0,0][-1,0,0], [0,2,0.5][0,2,0.5], [−1,2,0.5][-1,2,0.5], [−2,1,0.5][-2,1,0.5] and K=4K = 4 (2); check of the final w\mathbf{w} (0.5); γ=1/3\gamma = 1/3, R2=10R^2 = 10, bound 9090 (1.5); comparison and meaning of the bound (1) the value 00 not counted as a mistake; no x0=1x_0 = 1 in the norms; updates confused with passes
Problem 2 5 Ein=12E_{\text{in}} = 12 (0.5); gradient [−6,0.4][-6, 0.4], W=[0.6,−0.04]\mathbf{W} = [0.6, -0.04], Ein=8.7472E_{\text{in}} = 8.7472 (1.5); XTXX^TX, XTYX^TY and w=[1,−0.1,1]\mathbf{w} = [1, -0.1, 1] (2); Ein=0.18E_{\text{in}} = 0.18 and the comparison (1) wrong sign of the step; missing column x2x^2; SSE instead of the average
Problem 3 5 zz and y^\hat y (1); confusion matrix and the four measures (1.5); J≈3.989J \approx 3.989 (1.5); new weights, J≈3.546J \approx 3.546 and the comment (1) logit instead of probability; wrong sign of the cost; missing 1/m1/m; swapped FPFP and FNFN
Total 30