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

Introduction to Machine Learning - Mock Exam 5

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, 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 w=[w0,w1,w2]T\mathbf{w} = [w_0, w_1, w_2]^T is used; labels are ±1\pm 1 for the perceptron; log⁡\log and ln⁡\ln are the natural logarithm; where a number is rounded, three or four significant digits are enough.

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

In the credit-approval example of the first lecture an applicant is described by age, gender, salary and current debt, and the system has to say whether credit is approved. Which description matches the course?

  • A) Age, gender, salary and current debt are the output yy; "approve credit" is the input x\mathbf{x}.
  • B) The four values are the target function ff, and the hypothesis gg is the applicant.
  • C) The four values are the features through which the applicant (the object) is given to the algorithm; the output yy is the decision, good or bad customer.
  • D) The applicant is given to the algorithm as such, and the features are only used to draw the plots.
Show the result

C

Show the full solution

C is correct: 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 → an object is not given to the algorithm as such, but through its features (age, gender, salary and current debt in the credit case), and in the table of the components x\mathbf{x} is the attributes of the customer application while yy is the credit approval, good or bad customer. A swaps input and output. B is false: the target function ff is the unknown ideal credit formula and gg the formula actually used; the applicant is an input, not a function. D contradicts the sentence above: the algorithm sees the applicant only through the features.

Question 2

In the finite-hypothesis bound P(∣Ein(g)−Eout(g)∣>ε)≤2M e−2ε2NP\big(|E_{\text{in}}(g) - E_{\text{out}}(g)| > \varepsilon\big) \le 2M\,e^{-2\varepsilon^2 N}, which reading of the symbols is correct?

  • A) gg is the hypothesis returned by the algorithm after looking at the data; Ein(g)E_{\text{in}}(g) is its error on the NN samples and Eout(g)E_{\text{out}}(g) its error over the whole input distribution; ε\varepsilon is the tolerated gap and MM the number of hypotheses.
  • B) MM is the number of samples and NN the number of hypotheses.
  • C) Eout(g)E_{\text{out}}(g) is the error of gg on the NN samples and Ein(g)E_{\text{in}}(g) the error on new inputs.
  • D) ε\varepsilon is the probability that the bound fails and the right-hand side is the tolerated gap.
Show the result

A

Show the full solution

A is the reading 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 →: gg is chosen after looking at the data (this is why the factor MM is needed), Ein(g)E_{\text{in}}(g) is measured on the NN samples, Eout(g)E_{\text{out}}(g) is the error over the whole input distribution, ε>0\varepsilon > 0 is the tolerated gap, and the hypothesis set has MM elements. B swaps MM and NN: NN appears in the exponent and counts the samples. C swaps the two errors. D mixes the gap ε\varepsilon with the probability: the note lists exactly this confusion (gap ε\varepsilon against probability δ\delta) among the typical errors; the left-hand side of the inequality is the probability, ε\varepsilon is the gap inside it.

Question 3

A perceptron has weights w=[w0,w1,w2]T=[−3,1,1.5]T\mathbf{w} = [w_0, w_1, w_2]^T = [-3, 1, 1.5]^T on the inputs x=[1,x1,x2]T\mathbf{x} = [1, x_1, x_2]^T, and it classifies the point (3,1)(3, 1) as +1+1. The weights are replaced by −2w=[6,−2,−3]T-2\mathbf{w} = [6, -2, -3]^T. What happens?

  • A) The boundary is the same line and no prediction changes, because only the length of w\mathbf{w} changes.
  • B) The boundary rotates, because the slope −w1/w2-w_1/w_2 is multiplied by −2-2.
  • C) The boundary moves parallel to itself, because the intercept −w0/w2-w_0/w_2 is multiplied by 22.
  • D) The boundary is the same line, but the sign of every wTx\mathbf{w}^T\mathbf{x} is reversed, so the two sides exchange their classes: the point (3,1)(3, 1) becomes −1-1.
Show the result

D

Show the full solution

In 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 boundary is w1x1+w2x2+w0=0w_1x_1 + w_2x_2 + w_0 = 0, that is x2=−w1w2x1−w0w2x_2 = -\dfrac{w_1}{w_2}x_1 - \dfrac{w_0}{w_2}. With the old weights the slope is −1/1.5=−2/3-1/1.5 = -2/3 and the intercept is 3/1.5=23/1.5 = 2; with the new weights the slope is −(−2)/(−3)=−2/3-(-2)/(-3) = -2/3 and the intercept is −6/(−3)=2-6/(-3) = 2: the same line, because every weight is multiplied by the same non-zero number and the factors cancel in the ratios. The classes, however, depend on the sign of wTx\mathbf{w}^T\mathbf{x}: for the point (3,1)(3, 1), x=[1,3,1]T\mathbf{x} = [1, 3, 1]^T, the old value is −3+3+1.5=1.5>0-3 + 3 + 1.5 = 1.5 > 0 (class +1+1), the new one is 6−6−3=−3<06 - 6 - 3 = -3 < 0 (class −1-1). So D is correct. A would be true for a positive factor, but −2-2 is negative. B is false: in the ratio −w1/w2-w_1/w_2 the factors −2-2 cancel, so the slope is unchanged. C is false: the intercept is also unchanged.

Question 4

A nearest-neighbour classifier has stored 80008000 training objects and is used to classify 250250 new objects with K=5K = 5. How many distances does the test phase compute in total, and what changes with K=1K = 1?

  • A) 2 000 0002\,000\,000 with K=5K = 5 and 400 000400\,000 with K=1K = 1, because only the distances to the KK kept neighbours are computed.
  • B) 12501250 with K=5K = 5 and 250250 with K=1K = 1, one distance for each neighbour kept.
  • C) 2 000 0002\,000\,000 with K=5K = 5 and also with K=1K = 1: each prediction computes the distance from all the training objects, sorts them and only then keeps the first KK.
  • D) 80008000 with both values of KK, because the distances between the training objects are computed once and reused for every new object.
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 → for one point is: compute the distances from all the training points, sort them, keep the first KK, predict by the majority. So one prediction needs 80008000 distances, 250250 predictions need 250⋅8000=2 000 000250 \cdot 8000 = 2\,000\,000, whatever KK is: KK only decides how many of the sorted distances are kept, so C is correct (the cost is paid at prediction time, as the note remarks). A counts only the kept neighbours, but they cannot be known before computing and sorting all the distances (2 000 000/5=400 0002\,000\,000/5 = 400\,000 is not a count of anything in the algorithm). B (250⋅5250 \cdot 5) has the same flaw. D is false: the training phase does almost nothing (the data are stored), and the distance from a new point to the training objects depends on the new point, so it cannot be computed in advance.

Question 5

In the scheme of the last lectures a model is defined by choosing its hyper-parameters, it is then trained on the training set, and it is finally evaluated on a test set. Which assignment is correct for nearest neighbour with K=5K = 5, for a perceptron whose weight vector w\mathbf{w} is learned, and for the F1F_1 score measured at the end?

  • A) KK is fixed by the training on the training set, and w\mathbf{w} is chosen before the training.
  • B) KK is a hyper-parameter chosen to define the model; w\mathbf{w} is an optimisation parameter fixed by the training; the F1F_1 score on the test set is the performance.
  • C) KK and w\mathbf{w} are both fixed by the training, and the test set is used to fix them.
  • D) KK and w\mathbf{w} are both hyper-parameters, and the training fixes the performance.
Show the result

B

Show the full solution

B is the scheme 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 1): two models are defined by choosing their hyper-parameters (for nearest neighbour, the value of KK, see 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 →); each model is then trained on the training set, and the training fixes the optimisation parameters (the vector w\mathbf{w}, or θ\theta); the trained models are evaluated on a test set, which gives a performance for each. A swaps the roles. C is false: KK is not fixed by the training, and a test set used to fix anything is no longer a test set (selecting the model on the test set is listed among the typical errors). D is false: the weight vector is an optimisation parameter, and the performance is a result of the evaluation, not something that training fixes.

Question 6

Four models are compared with 55-fold cross-validation, and all the models use the same folds. As in the pipeline of the course, one performance is collected for each fold of each model. How many performance values are collected, and how many paired differences does the test between Model 1 and Model 2 use?

  • A) 2020 performance values and 55 differences.
  • B) 55 performance values and 2020 differences.
  • C) 2020 performance values and 2020 differences.
  • D) 44 performance values, one for each model, and 11 difference.
Show the result

A

Show the full solution

In 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 → each fold is the test set exactly once and one performance is collected per fold, repeated for each model: 4⋅5=204 \cdot 5 = 20 values. Because all the models use the same folds, the score of Model 1 on fold ii is paired with the score of Model 2 on the same fold ii, so comparing two models gives one difference M1 exi−M2 exiM_1\,ex_i - M_2\,ex_i for each fold, that is 55 differences: A is correct (the code of 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 → does the same with cross_validate and the same k_fold object). B swaps the two counts. C counts a difference for every score, but a difference needs a pair of scores from the same fold. D takes the average of the folds (one score per model), which loses the pairs on which the paired test works.

Question 7

The list version of the perceptron of the course notebook is run on a new data set, starting from w = [0.0, 0.0, 0.0]:

python
dataset = [ [1, 2, 1, 1],
            [1, 4, 3, -1],
            [1, 1, 3, 1],
            [1, 3, 0.5, -1] ]

num_errors = 0
for elem in dataset:
    y = elem[3]
    x = elem[:3]
    output = (w[0] * x[0]) + (w[1] * x[1]) + (w[2] * x[2])
    if (output >= 0 and y < 0) or (output < 0 and y > 0):
        w[0] = w[0] + (x[0] * y)
        w[1] = w[1] + (x[1] * y)
        w[2] = w[2] + (x[2] * y)
        num_errors += 1

After this single pass over the four rows, which are w and num_errors?

  • A) w = [0, 0, 0] and num_errors = 0, because every output is 00.
  • B) w = [-1, -4, -3] and num_errors = 1.
  • C) w = [1, -1, 1] and num_errors = 3.
  • D) w = [0, -3, 0] and num_errors = 2.
Show the result

D

Show the full solution

Follow the loop of 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 → row by row, with the test (output >= 0 and y < 0) or (output < 0 and y > 0): an output exactly 00 is a mistake only when the label is negative.

  • Row 1, x=[1,2,1]\mathbf{x} = [1, 2, 1], y=+1y = +1: output 00; the first clause needs y<0y < 0, the second needs output < 0: no mistake, w stays [0,0,0][0, 0, 0].
  • Row 2, x=[1,4,3]\mathbf{x} = [1, 4, 3], y=−1y = -1: output 0≥00 \ge 0 and y<0y < 0: mistake; w =[0,0,0]−[1,4,3]=[−1,−4,−3]= [0, 0, 0] - [1, 4, 3] = [-1, -4, -3].
  • Row 3, x=[1,1,3]\mathbf{x} = [1, 1, 3], y=+1y = +1: output −1−4−9=−14<0-1 - 4 - 9 = -14 < 0: mistake; w =[−1,−4,−3]+[1,1,3]=[0,−3,0]= [-1, -4, -3] + [1, 1, 3] = [0, -3, 0].
  • Row 4, x=[1,3,0.5]\mathbf{x} = [1, 3, 0.5], y=−1y = -1: output 0−9+0=−90 - 9 + 0 = -9, negative with a negative label: correct.

So w = [0, -3, 0] and num_errors = 2: D is correct, and since num_errors is not 00 the loop would start another pass. A is what one would get with the NumPy test dot * y < 0, which does not count a zero output as a mistake, but this is the list version. B stops after the first update. C is what the plotting version of the notebook gives, whose test (dot_prod >= 0 and y < 0) or (dot_prod <= 0 and y >= 0) makes an output 00 a mistake whatever the label (here Row 1 would already be a mistake).

Question 8

In the exercise notebooks the mini-batch update of the version of 8 April is

python
w = w + eta * np.dot(np.transpose(X_batch), errors) / X_batch.shape[0]

A mini-batch has 44 objects, η=0.1\eta = 0.1, the current weights are w=[1,1,1]\mathbf{w} = [1, 1, 1] and np.dot(np.transpose(X_batch), errors) is [8,−4,2][8, -4, 2]. Which are the new weights?

  • A) [1.8,0.6,1.2][1.8, 0.6, 1.2]
  • B) [0.2,−0.1,0.05][0.2, -0.1, 0.05]
  • C) [1.2,0.9,1.05][1.2, 0.9, 1.05]
  • D) [0.8,1.1,0.95][0.8, 1.1, 0.95]
Show the result

C

Show the full solution

In 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 → this version divides the update by the size of the batch, X_batch.shape[0] =4= 4: the correction is 0.1⋅[8,−4,2]/4=[0.2,−0.1,0.05]0.1 \cdot [8, -4, 2]/4 = [0.2, -0.1, 0.05] and it is added to the weights, [1,1,1]+[0.2,−0.1,0.05]=[1.2,0.9,1.05][1, 1, 1] + [0.2, -0.1, 0.05] = [1.2, 0.9, 1.05], so C is correct. A is the update of the version of 4 April, which does not divide by the batch size (0.1⋅[8,−4,2]=[0.8,−0.4,0.2]0.1 \cdot [8, -4, 2] = [0.8, -0.4, 0.2]). B is the correction alone, without adding it to w. D subtracts the correction instead of adding it: the errors there are defined as y−outputy - \text{output}, so the step is added (see the sign convention in 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 →).

Question 9

In the short notebook of 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 → two samples data1 and data2 are drawn from the same normal distribution, wilcoxon(data1, data2, mode="approx") is called, and at the end the cells plot data1 - data2 (scatter plot and histogram). Why is this quantity plotted?

  • A) The test works on the differences of the pairs, and when the two samples come from the same distribution these differences are spread around 00.
  • B) Because data1 - data2 is the p-value returned by the test.
  • C) Because data1 - data2 is the significance level α\alpha, which has to be fixed before the experiment.
  • D) To show that the two samples come from different distributions, since the differences are far from 00.
Show the result

A

Show the full solution

A is correct: the notebook plots the differences of the pairs, "the quantity on which the test works", and 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 → explains that if the two sets of scores were equivalent the differences would spread around 00 in a bell shape. B is false: the p-value is the second number returned by wilcoxon (the variable p in the cell), not a list of differences. C is false: α\alpha is a number decided in advance (the rule of the notebook compares pp with 0.050.05), not a quantity computed from the samples. D is false for the same reason as A: the two samples come from the same distribution, so the differences are centred near 00; a flagged repetition would only be a false alarm.

Question 10

A perceptron starts from w1=0\mathbf{w}_1 = \mathbf{0}. The data have margin γ=0.25\gamma = 0.25 with respect to a unit vector w∗\mathbf{w}^* and every point satisfies ∥xi∥≤R=2\|\mathbf{x}_i\| \le R = 2. After K=16K = 16 updates, between which two values does the proof of the margin bound place ∥w17∥\|\mathbf{w}_{17}\|?

  • A) Between 44 and 6464.
  • B) Between 44 and 88.
  • C) Between 11 and 88.
  • D) Between 44 and 3232.
Show the result

B

Show the full solution

The proof 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 → has two inequalities on wK+1\mathbf{w}_{K+1}. Step 1 and Step 2 give the lower bound ∥wK+1∥≥Kγ=16⋅0.25=4\|\mathbf{w}_{K+1}\| \ge K\gamma = 16 \cdot 0.25 = 4. Step 3 gives ∥wK+1∥2≤KR2=16⋅4=64\|\mathbf{w}_{K+1}\|^2 \le K R^2 = 16 \cdot 4 = 64, so the norm itself is at most 64=8\sqrt{64} = 8 (this step uses that an update is made only on a mistake, so the cross term 2yiwK+1Txi2y_i\mathbf{w}_{K+1}^T\mathbf{x}_i is not positive). Hence 4≤∥w17∥≤84 \le \|\mathbf{w}_{17}\| \le 8, and B is correct. (Consistency check: K2γ2=16≤KR2=64K^2\gamma^2 = 16 \le KR^2 = 64, that is K≤R2/γ2=64K \le R^2/\gamma^2 = 64, true for K=16K = 16.) A uses 6464, the bound on the squared norm, as a bound on the norm. C takes Kγ2=1K\gamma^2 = 1 as the lower bound, but the lower bound is KγK\gamma. D takes KR=32KR = 32 as the upper bound, but the squared norm grows at most like KR2K R^2, so the norm at most like RKR\sqrt{K}.

Problem 1 (points 5)

Five samples (xi,yi)(x_i, y_i) are given: (1,2)(1, 2), (2,5)(2, 5), (3,5)(3, 5), (4,8)(4, 8), (5,10)(5, 10). The first hypothesis is a constant, h(x)=ch(x) = c. The in-sample error is Ein(h)=1N∑i=1N(yi−h(xi))2E_{\text{in}}(h) = \frac{1}{N}\sum_{i=1}^{N}\big(y_i - h(x_i)\big)^2.

a) Compute the total of the signed differences ∑i(yi−c)\sum_i (y_i - c) for c=3c = 3, c=6c = 6 and c=9c = 9. Explain why this total is not a good measure of the error of a hypothesis (1 point).

b) Compute the sum of the squared differences L(c)=∑i(yi−c)2L(c) = \sum_i (y_i - c)^2 for the same three values of cc. Find the best constant by setting the derivative of LL to zero, compute EinE_{\text{in}} of the best constant and check that at this constant the signed total of part a) is zero (1.5 points).

c) Another way to make the differences non-negative is the absolute value. Compare c=5c = 5 and c=6c = 6 with the sum of the absolute differences and with the sum of the squared differences. Do the two measures prefer the same constant (1 point)?

d) The sloped hypothesis h(x)=w0+w1xh(x) = w_0 + w_1x with w=[0,2]T\mathbf{w} = [0, 2]^T is proposed. Compute its EinE_{\text{in}} with the matrix form 1N∥Xw−Y∥2\frac{1}{N}\|X\mathbf{w} - Y\|^2 and compare it with the best constant. Then use two new samples that were not used before, (6,12.5)(6, 12.5) and (7,13)(7, 13), as a test set: compute the mean squared error of the best constant and of the sloped hypothesis on them, and comment (1.5 points).

Show the result

a) ∑i(yi−c)=15, 0, −15\sum_i(y_i - c) = 15,\ 0,\ -15 for c=3,6,9c = 3, 6, 9. The total is 30−5c30 - 5c: it decreases without limit as cc grows and cancels positive and negative differences.

b) L(3)=83L(3) = 83, L(6)=38L(6) = 38, L(9)=83L(9) = 83. dL/dc=10c−60=0dL/dc = 10c - 60 = 0 gives c=6c = 6, the mean of the outputs. Ein=38/5=7.6E_{\text{in}} = 38/5 = 7.6. At c=6c = 6 the signed total is 30−30=030 - 30 = 0.

c) Absolute sums: 1111 for c=5c = 5, 1212 for c=6c = 6; squared sums: 4343 for c=5c = 5, 3838 for c=6c = 6. The absolute measure prefers c=5c = 5, the squared one prefers c=6c = 6.

d) Xw=[2,4,6,8,10]TX\mathbf{w} = [2, 4, 6, 8, 10]^T, Y−Xw=[0,1,−1,0,0]TY - X\mathbf{w} = [0, 1, -1, 0, 0]^T, SSE=2\text{SSE} = 2, Ein=0.4E_{\text{in}} = 0.4, against 7.67.6 for the constant. On the test points: the sloped hypothesis gives differences 0.50.5 and −1-1, mean squared error 0.6250.625; the constant 66 gives 6.56.5 and 77, mean squared error 45.62545.625. The ranking is confirmed, but the error of the sloped hypothesis on new samples (0.6250.625) is larger than its EinE_{\text{in}} (0.40.4).

Show the full solution

Setting: 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 → for the comparison of hypotheses with a pointwise error, 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 the matrix form of the error, 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 → for the test points. The five outputs are y=2,5,5,8,10y = 2, 5, 5, 8, 10, with sum 3030 and mean 66 (the values of xx do not matter for a constant).

a) Signed total. The differences yi−cy_i - c are added:

∑i=15(yi−c)=30−5c={15c=30c=6−15c=9\sum_{i=1}^{5}(y_i - c) = 30 - 5c = \begin{cases}15 & c = 3\\ 0 & c = 6\\ -15 & c = 9\end{cases}

This is the measure the notes reject: a point above the constant and a point below it cancel. For c=6c = 6 the total is 00 although the single differences are −4,−1,−1,2,4-4, -1, -1, 2, 4; and since 30−5c30 - 5c keeps decreasing as cc grows, an algorithm that looked for the smallest total would prefer c=9c = 9 (total −15-15) to c=6c = 6 and would run off to infinity. The total has no minimum, so it cannot rank hypotheses.

b) Squared differences. With y−3=(−1,2,2,5,7)y - 3 = (-1, 2, 2, 5, 7): L(3)=1+4+4+25+49=83L(3) = 1 + 4 + 4 + 25 + 49 = 83. With y−6=(−4,−1,−1,2,4)y - 6 = (-4, -1, -1, 2, 4): L(6)=16+1+1+4+16=38L(6) = 16 + 1 + 1 + 4 + 16 = 38. With y−9=(−7,−4,−4,−1,1)y - 9 = (-7, -4, -4, -1, 1): L(9)=49+16+16+1+1=83L(9) = 49 + 16 + 16 + 1 + 1 = 83. The derivative is

dLdc=−2∑i=15(yi−c)=−2(30−5c)=10c−60=0  ⟹  c=6,\frac{dL}{dc} = -2\sum_{i=1}^{5}(y_i - c) = -2(30 - 5c) = 10c - 60 = 0 \;\Longrightarrow\; c = 6,

the mean of the outputs (the result derived in the note). The in-sample error of the best constant is Ein=L(6)/N=38/5=7.6E_{\text{in}} = L(6)/N = 38/5 = 7.6. The derivative is minus twice the signed total of part a), so the signed total is exactly 00 at the best constant: 30−5⋅6=030 - 5 \cdot 6 = 0.

c) Absolute differences. For c=5c = 5 the differences are −3,0,0,3,5-3, 0, 0, 3, 5 and the sum of the absolute values is 3+0+0+3+5=113 + 0 + 0 + 3 + 5 = 11; for c=6c = 6 it is 4+1+1+2+4=124 + 1 + 1 + 2 + 4 = 12. So with the absolute value c=5c = 5 is better than c=6c = 6. With the squares, L(5)=9+0+0+9+25=43L(5) = 9 + 0 + 0 + 9 + 25 = 43 against L(6)=38L(6) = 38, so c=6c = 6 is better. The two measures rank the same two hypotheses in opposite ways: the choice of the error function changes which hypothesis is selected, and the course takes the square, which is also the error that gives the closed form and the gradient of the next notes.

d) Line against constant, and the test set. The data matrix has the column of ones and the column of xx, and Y=[2,5,5,8,10]TY = [2, 5, 5, 8, 10]^T:

Xw=[1112131415][02]=[246810],Y−Xw=[01−100].X\mathbf{w} = \begin{bmatrix}1 & 1\\ 1 & 2\\ 1 & 3\\ 1 & 4\\ 1 & 5\end{bmatrix}\begin{bmatrix}0\\ 2\end{bmatrix} = \begin{bmatrix}2\\ 4\\ 6\\ 8\\ 10\end{bmatrix},\qquad Y - X\mathbf{w} = \begin{bmatrix}0\\ 1\\ -1\\ 0\\ 0\end{bmatrix}.

So ∥Xw−Y∥2=2\|X\mathbf{w} - Y\|^2 = 2 and Ein=2/5=0.4E_{\text{in}} = 2/5 = 0.4, much smaller than 7.67.6: on these samples the sloped hypothesis is the better one, by the criterion "the smaller the total, the better". The two new samples are kept out of the choice and used only to check. For the sloped hypothesis: h(6)=12h(6) = 12 and h(7)=14h(7) = 14, differences 0.50.5 and −1-1, mean squared error (0.25+1)/2=0.625(0.25 + 1)/2 = 0.625. For the constant 66: differences 12.5−6=6.512.5 - 6 = 6.5 and 13−6=713 - 6 = 7, mean squared error (42.25+49)/2=45.625(42.25 + 49)/2 = 45.625. The ranking is confirmed, and the constant is far worse because the new inputs lie beyond the range 11 to 55 where the samples are and a constant cannot follow the growth of the output. Note also that the sloped hypothesis has a larger error on the new samples (0.6250.625) than on the samples used to judge it (0.40.4): the error on the samples is only a proxy, usually optimistic, of the error on inputs that will really be seen, which is why part of the data is kept aside.

Typical mistakes: adding the signed differences; dividing by NN in L(c)L(c) and then dividing again in EinE_{\text{in}} (or not at all); reading L(6)=38L(6) = 38 as the error EinE_{\text{in}}; judging the hypotheses on the same points used to build them and calling that a test.

Problem 2 (points 5)

A model with a single weight, h(x)=w xh(x) = w\,x (no constant column), is fitted to three samples (xi,yi)(x_i, y_i): (1,1)(1, 1), (2,5)(2, 5), (3,8)(3, 8). The error is Ein(w)=1N∑i=1N(yi−w xi)2E_{\text{in}}(w) = \frac{1}{N}\sum_{i=1}^{N}(y_i - w\,x_i)^2 with N=3N = 3, and the data matrix is the single column X=[1,2,3]TX = [1, 2, 3]^T.

a) Compute the weight given by the closed form w=(XTX)−1XTYw = (X^TX)^{-1}X^TY, the value of EinE_{\text{in}} at this weight and the value of EinE_{\text{in}} at w=0w = 0 (1 point).

b) Write the derivative dEindw\dfrac{dE_{\text{in}}}{dw} and compute it at w=0w = 0. Run three steps of gradient descent wnew=wold−η dEindww_{\text{new}} = w_{\text{old}} - \eta\,\dfrac{dE_{\text{in}}}{dw} from w=0w = 0 with η=0.05\eta = 0.05, giving ww and EinE_{\text{in}} after each step (1.5 points).

c) Show that wnew−w∗=ρ (wold−w∗)w_{\text{new}} - w^* = \rho\,(w_{\text{old}} - w^*), where w∗w^* is the weight of part a), and find ρ\rho as a function of η\eta. Compute ρ\rho for η=0.05\eta = 0.05, 0.10.1, 0.20.2 and 0.250.25, say what each value does to the successive weights, and find the range of η\eta for which the iteration approaches w∗w^* (1.5 points).

d) With η=0.25\eta = 0.25 compute the first two steps from w=0w = 0 and the corresponding EinE_{\text{in}}; compare with the first two steps for η=0.1\eta = 0.1, and comment on the sketch of the bowl and the staircase (1 point).

Show the result

a) XTX=14X^TX = 14, XTY=35X^TY = 35, w∗=2.5w^* = 2.5; Ein(2.5)=2.5/3≈0.8333E_{\text{in}}(2.5) = 2.5/3 \approx 0.8333; Ein(0)=90/3=30E_{\text{in}}(0) = 90/3 = 30.

b) dEindw=23(14w−35)\dfrac{dE_{\text{in}}}{dw} = \dfrac{2}{3}(14w - 35), equal to −23.33-23.33 at w=0w = 0. Steps with η=0.05\eta = 0.05: w=1.1667w = 1.1667 (Ein=9.130E_{\text{in}} = 9.130), w=1.7889w = 1.7889 (Ein=3.193E_{\text{in}} = 3.193), w=2.1207w = 2.1207 (Ein=1.505E_{\text{in}} = 1.505).

c) ρ=1−2η∑xi2N=1−283η\rho = 1 - \dfrac{2\eta\sum x_i^2}{N} = 1 - \dfrac{28}{3}\eta. For η=0.05,0.1,0.2,0.25\eta = 0.05, 0.1, 0.2, 0.25: ρ=0.5333, 0.0667, −0.8667, −1.3333\rho = 0.5333,\ 0.0667,\ -0.8667,\ -1.3333. Convergence for ∣ρ∣<1|\rho| < 1, that is 0<η<3/14≈0.21430 < \eta < 3/14 \approx 0.2143; with ρ>0\rho > 0 the weights approach w∗w^* from one side, with ρ<0\rho < 0 they jump from side to side.

d) η=0.25\eta = 0.25: w=5.8333w = 5.8333 (Ein=52.69E_{\text{in}} = 52.69), then w=−1.9444w = -1.9444 (Ein=93.01E_{\text{in}} = 93.01): the error grows. η=0.1\eta = 0.1: w=2.3333w = 2.3333 (Ein=0.9630E_{\text{in}} = 0.9630), then w=2.4889w = 2.4889 (Ein=0.8339E_{\text{in}} = 0.8339).

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 the update rule and the bowl of one weight, 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 the closed form, 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 → for EinE_{\text{in}}.

a) Closed form. The matrix XX has one column, so XTX=12+22+32=14X^TX = 1^2 + 2^2 + 3^2 = 14 (a 1×11 \times 1 matrix: its size is the number of features) and XTY=1⋅1+2⋅5+3⋅8=35X^TY = 1\cdot 1 + 2\cdot 5 + 3\cdot 8 = 35. Then w∗=(XTX)−1XTY=35/14=2.5w^* = (X^TX)^{-1}X^TY = 35/14 = 2.5. The residuals yi−w∗xiy_i - w^*x_i are 1−2.5=−1.51 - 2.5 = -1.5, 5−5=05 - 5 = 0, 8−7.5=0.58 - 7.5 = 0.5, with squares 2.252.25, 00, 0.250.25, so Ein(w∗)=2.5/3≈0.8333E_{\text{in}}(w^*) = 2.5/3 \approx 0.8333. At w=0w = 0 the errors are the outputs themselves: Ein(0)=(1+25+64)/3=90/3=30E_{\text{in}}(0) = (1 + 25 + 64)/3 = 90/3 = 30. In general, expanding the squares,

Ein(w)=13(90−70 w+14 w2),E_{\text{in}}(w) = \frac{1}{3}\big(90 - 70\,w + 14\,w^2\big),

a parabola, the bowl of the sketch, with its minimum at w∗=70/28=2.5w^* = 70/28 = 2.5.

b) Gradient descent. The derivative of the note, dEindw=2N∑i(yi−w xi)(−xi)\dfrac{dE_{\text{in}}}{dw} = \dfrac{2}{N}\sum_i (y_i - w\,x_i)(-x_i), is

dEindw=23(14 w−35),\frac{dE_{\text{in}}}{dw} = \frac{2}{3}\big(14\,w - 35\big),

which at w=0w = 0 is −703=−23.33-\dfrac{70}{3} = -23.33: negative, because w=0w = 0 is on the left of the minimum, so the step goes to the right. With η=0.05\eta = 0.05:

  • step 1: w=0−0.05⋅(−23.33)=1.1667w = 0 - 0.05 \cdot (-23.33) = 1.1667; Ein=(90−81.67+19.06)/3=9.130E_{\text{in}} = (90 - 81.67 + 19.06)/3 = 9.130;
  • step 2: the derivative at 1.16671.1667 is 23(16.33−35)=−12.44\frac{2}{3}(16.33 - 35) = -12.44, so w=1.1667+0.6222=1.7889w = 1.1667 + 0.6222 = 1.7889; Ein=3.193E_{\text{in}} = 3.193;
  • step 3: the derivative at 1.78891.7889 is 23(25.04−35)=−6.64\frac{2}{3}(25.04 - 35) = -6.64, so w=1.7889+0.3319=2.1207w = 1.7889 + 0.3319 = 2.1207; Ein=1.505E_{\text{in}} = 1.505.

The steps (1.171.17, 0.620.62, 0.330.33) get shorter because the slope is smaller near the bottom, as in the sketch of the note.

c) The factor ρ\rho. Since w∗=35/14w^* = 35/14, the derivative can be written dEindw=23⋅14 (w−w∗)=283(w−w∗)\dfrac{dE_{\text{in}}}{dw} = \dfrac{2}{3}\cdot 14\,(w - w^*) = \dfrac{28}{3}(w - w^*) (it vanishes at w∗w^*, which is the normal equation of the closed form). Then

wnew−w∗=wold−w∗−η 283(wold−w∗)=(1−283η)(wold−w∗),ρ=1−283η.w_{\text{new}} - w^* = w_{\text{old}} - w^* - \eta\,\frac{28}{3}(w_{\text{old}} - w^*) = \Big(1 - \frac{28}{3}\eta\Big)(w_{\text{old}} - w^*),\qquad \rho = 1 - \frac{28}{3}\eta .

(In general ρ=1−2η∑xi2/N\rho = 1 - 2\eta\sum x_i^2/N.) After kk steps the distance from w∗w^* is ρk\rho^k times the starting distance, here ρk⋅(−2.5)\rho^k \cdot (-2.5) from w=0w = 0. The four values are

η\eta 0.050.05 0.10.1 0.20.2 0.250.25
ρ\rho 0.53330.5333 0.06670.0667 −0.8667-0.8667 −1.3333-1.3333

For η=0.05\eta = 0.05 and 0.10.1, 0<ρ<10 < \rho < 1: the weights approach w∗w^* from the left, the distance shrinking by 0.53330.5333 at each step (the numbers of part b: −1.333-1.333, −0.711-0.711, −0.379-0.379) or by 0.06670.0667 (almost at w∗w^* after one step). For η=0.2\eta = 0.2, ρ=−0.8667\rho = -0.8667: the weights jump from one side of w∗w^* to the other (4.6674.667, 0.6220.622, 4.1274.127, ...) and the distance shrinks only slowly. For η=0.25\eta = 0.25, ρ=−1.3333\rho = -1.3333: the distance grows at each step and the weights run away. The iteration approaches w∗w^* if ∣ρ∣<1|\rho| < 1, that is −1<1−283η<1-1 < 1 - \frac{28}{3}\eta < 1, which gives 0<η<628=314≈0.21430 < \eta < \dfrac{6}{28} = \dfrac{3}{14} \approx 0.2143 (in general η<N/∑xi2\eta < N/\sum x_i^2).

d) A learning rate that is too large. With η=0.25\eta = 0.25: the first step is w=0+0.25⋅23.33=5.8333w = 0 + 0.25 \cdot 23.33 = 5.8333, which overshoots w∗=2.5w^* = 2.5 by 3.333.33, with Ein=(90−408.33+476.39)/3=52.69E_{\text{in}} = (90 - 408.33 + 476.39)/3 = 52.69, higher than the 3030 at the start; the derivative there is 23(81.67−35)=31.11\frac{2}{3}(81.67 - 35) = 31.11, so the second step is w=5.8333−7.7778=−1.9444w = 5.8333 - 7.7778 = -1.9444, with Ein=93.01E_{\text{in}} = 93.01, even higher. With η=0.1\eta = 0.1: w=0+0.1⋅23.33=2.3333w = 0 + 0.1\cdot 23.33 = 2.3333 (Ein=0.9630E_{\text{in}} = 0.9630) and then w=2.4889w = 2.4889 (Ein=0.8339E_{\text{in}} = 0.8339), almost the minimum 0.83330.8333. In the picture of the bowl, a step that is too long jumps over the bottom to the other wall, higher than where it started, instead of forming the shrinking staircase; this is the "η\eta too large" of the typical errors. The closed form needs no learning rate and no stopping rule: it gives w∗=2.5w^* = 2.5 at once, which is what gradient descent approaches when η\eta is in the right range.

Typical mistakes: the sign of the step (adding the derivative moves away from the minimum); forgetting the factor 22 in the derivative; computing EinE_{\text{in}} without the factor 1/N1/N; thinking that a larger η\eta is always faster (η=0.25\eta = 0.25 diverges while η=0.1\eta = 0.1 is almost there after one step).

Problem 3 (points 5)

The notebooks of the course read data as text and clean it with string methods before using them. A small data set has been read into the string

python
raw = """ 1.5, 2.0 , A
3.0,0.5, B
 2.5 , 3.5,A
4.0, 1.0 ,B"""

Each line has two features and a class (A or B), separated by commas, with irregular spaces. import re and import numpy as np have been run.

a) Give the list lines = raw.splitlines(), the list lines[0].split(",") (showing the spaces) and the same list after applying strip() to each element, and the result of re.sub(" +", "", line) for each of the four lines (1.5 points).

b) From the cleaned values build the data matrix X (a column of ones, then x1x_1 and x2x_2) with its shape, and the label vector y_class obtained with y_class = -np.ones(4) followed by y_class[labels == "A"] = 1, where labels is the array of the four stripped classes (1 point).

c) A perceptron has the weights w = [1, 2, 1.5]. Compute np.dot(X, w), the products y_class * np.sign(np.dot(X, w)) and the number of errors counted by sum((y_class * np.sign(np.dot(X, w))) < 0). Write the boundary of this perceptron as x2=a x1+bx_2 = a\,x_1 + b (1.5 points).

d) Apply the update w←w+y x\mathbf{w} \leftarrow \mathbf{w} + y\,\mathbf{x} to the first misclassified row (in the order of the data set). Give the new weights, the new number of errors and the new boundary (1 point).

Show the result

a) lines is the list of the four lines ' 1.5, 2.0 , A', '3.0,0.5, B', ' 2.5 , 3.5,A', '4.0, 1.0 ,B'. lines[0].split(",") is [' 1.5', ' 2.0 ', ' A'], and after strip() on each element ['1.5', '2.0', 'A']. re.sub(" +", "", line) removes every space: '1.5,2.0,A', '3.0,0.5,B', '2.5,3.5,A', '4.0,1.0,B'.

b) X=[11.52130.512.53.5141]X = \begin{bmatrix}1 & 1.5 & 2\\ 1 & 3 & 0.5\\ 1 & 2.5 & 3.5\\ 1 & 4 & 1\end{bmatrix}, shape (4, 3); labels is ['A', 'B', 'A', 'B'] and y_class =[1,−1,1,−1]= [1, -1, 1, -1].

c) np.dot(X, w) =[7,7.75,11.25,10.5]= [7, 7.75, 11.25, 10.5]; the products are [1,−1,1,−1][1, -1, 1, -1]; the number of errors is 22 (rows 2 and 4). Boundary: x2=−43x1−23x_2 = -\tfrac{4}{3}x_1 - \tfrac{2}{3}.

d) The first mistake is row 2: w=[1,2,1.5]−[1,3,0.5]=[0,−1,1]\mathbf{w} = [1, 2, 1.5] - [1, 3, 0.5] = [0, -1, 1]. The outputs become [0.5,−2.5,1,−3][0.5, -2.5, 1, -3], all with the sign of the label: 00 errors. Boundary: x2=x1x_2 = x_1 (slope 11, intercept 00).

Show the full solution

Setting: 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 → for the string methods, 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 → for the data matrix, the one-class-against-the-rest labels and the count of errors, 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 boundary and the update.

a) Cleaning the text. splitlines() cuts the string at the line breaks and returns the list of the four lines, with their spaces untouched: [' 1.5, 2.0 , A', '3.0,0.5, B', ' 2.5 , 3.5,A', '4.0, 1.0 ,B']. For the first line split(",") cuts at the commas only, so the pieces keep their spaces: [' 1.5', ' 2.0 ', ' A'] (a space before 1.5, a space before and after 2.0, a space before A). strip() removes the white space at the two ends of a string and returns a new string (the original is not changed), so applied to each piece it gives ['1.5', '2.0', 'A']. The pattern " +" is one or more spaces, replaced here by the empty string, so re.sub(" +", "", line) deletes all the spaces: '1.5,2.0,A', '3.0,0.5,B', '2.5,3.5,A', '4.0,1.0,B'; splitting these at the commas gives the same pieces as the strip() route. The numbers are still strings and are converted with float.

b) Data matrix and labels. The features of the four rows are x1=1.5,3.0,2.5,4.0x_1 = 1.5, 3.0, 2.5, 4.0 and x2=2.0,0.5,3.5,1.0x_2 = 2.0, 0.5, 3.5, 1.0. As in the exercise notebook, X = np.stack((np.ones(4), x1, x2), axis = 1) puts the three vectors as the columns of the data matrix, one row per object and the bias coordinate x0=1x_0 = 1 first:

X=[11.52130.512.53.5141],shape (4,3).X = \begin{bmatrix}1 & 1.5 & 2\\ 1 & 3 & 0.5\\ 1 & 2.5 & 3.5\\ 1 & 4 & 1\end{bmatrix},\qquad \text{shape } (4, 3).

The labels are the stripped classes ['A', 'B', 'A', 'B']. The vector -np.ones(4) is [−1,−1,−1,−1][-1, -1, -1, -1], and y_class[labels == "A"] = 1 sets to +1+1 the positions where the class is A (positions 11 and 33 in the counting from 11): y_class =[1,−1,1,−1]= [1, -1, 1, -1], the "class against the rest" labels of the notebook with A as the positive class.

c) Outputs, errors and boundary. With w=[1,2,1.5]T\mathbf{w} = [1, 2, 1.5]^T, the outputs wTx\mathbf{w}^T\mathbf{x} of the four rows are 1+2⋅1.5+1.5⋅2=71 + 2\cdot 1.5 + 1.5\cdot 2 = 7, 1+6+0.75=7.751 + 6 + 0.75 = 7.75, 1+5+5.25=11.251 + 5 + 5.25 = 11.25 and 1+8+1.5=10.51 + 8 + 1.5 = 10.5. All are positive, so np.sign gives [1,1,1,1][1, 1, 1, 1] and the products with y_class are [1,−1,1,−1][1, -1, 1, -1]. The expression sum((y_class * np.sign(np.dot(X, w))) < 0) counts the products that are negative, that is the misclassified objects (the zero-one loss of the notebook): rows 22 and 44 (class B, predicted +1+1), so the number of errors is 22. The boundary w1x1+w2x2+w0=0w_1x_1 + w_2x_2 + w_0 = 0 is

x2=−w1w2 x1−w0w2=−21.5 x1−11.5=−43 x1−23.x_2 = -\frac{w_1}{w_2}\,x_1 - \frac{w_0}{w_2} = -\frac{2}{1.5}\,x_1 - \frac{1}{1.5} = -\frac{4}{3}\,x_1 - \frac{2}{3}.

d) One update. The first misclassified row in the order of the data set is row 22, x=[1,3,0.5]T\mathbf{x} = [1, 3, 0.5]^T with y=−1y = -1 (row 11 is correct). The update is

wnew=wold+y x=[1,2,1.5]T−[1,3,0.5]T=[0,−1,1]T.\mathbf{w}_{\text{new}} = \mathbf{w}_{\text{old}} + y\,\mathbf{x} = [1, 2, 1.5]^T - [1, 3, 0.5]^T = [0, -1, 1]^T .

The new outputs are 0−1.5+2=0.50 - 1.5 + 2 = 0.5, 0−3+0.5=−2.50 - 3 + 0.5 = -2.5, 0−2.5+3.5=10 - 2.5 + 3.5 = 1 and 0−4+1=−30 - 4 + 1 = -3: the products with the labels are 0.5,2.5,1,30.5, 2.5, 1, 3, all positive, so the number of errors is 00 (the check 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 →: the update changed the value on row 22 by y∥x∥2=−10.25y\|\mathbf{x}\|^2 = -10.25, towards the correct sign). The new boundary is x2=−−11x1−01=x1x_2 = -\frac{-1}{1}x_1 - \frac{0}{1} = x_1: the points of class A, (1.5,2)(1.5, 2) and (2.5,3.5)(2.5, 3.5), lie above the line, those of class B, (3,0.5)(3, 0.5) and (4,1)(4, 1), below it.

Typical mistakes: expecting split(",") to remove the spaces; expecting strip() to change the string in place; leaving the pieces as strings and then trying to build the data matrix; forgetting the column of ones in X; using y_class =[1,0,1,0]= [1, 0, 1, 0] instead of ±1\pm 1; reading the count of errors as the sum of the products; updating on a row that is already correct.

Self-assessment grid
item points what must be there for full points typical mistakes
Question 1 1.5 C: features describe the applicant, the output is good or bad customer swapping input and output; confusing features with the target function
Question 2 1.5 A: gg chosen after the data, EinE_{\text{in}} on the samples, EoutE_{\text{out}} on the whole distribution, ε\varepsilon the gap swapping MM and NN or the two errors; confusing the gap with the probability
Question 3 1.5 D: same line, signs of wTx\mathbf{w}^T\mathbf{x} reversed, class of (3,1)(3,1) becomes −1-1 thinking a negative factor changes nothing; thinking the line moves
Question 4 1.5 C: 250⋅8000=2 000 000250 \cdot 8000 = 2\,000\,000 distances whatever KK counting only the KK kept neighbours; reusing distances computed in training
Question 5 1.5 B: KK hyper-parameter, w\mathbf{w} fixed by training, performance on the test set fixing KK or w\mathbf{w} with the test set; swapping the roles
Question 6 1.5 A: 4⋅5=204 \cdot 5 = 20 values, 55 paired differences counting a difference for every score; one score per model
Question 7 1.5 D: only rows 2 and 3 are mistakes, w=[0,−3,0]\mathbf{w} = [0, -3, 0], 2 errors using the NumPy test; using the plotting version; stopping at the first update
Question 8 1.5 C: correction [0.2,−0.1,0.05][0.2, -0.1, 0.05] added to w\mathbf{w} no division by the batch size; forgetting w +; wrong sign
Question 9 1.5 A: the test works on the differences of the pairs, spread around 0 under the null hypothesis reading the differences as the p-value or as α\alpha; reading them as proof of a difference
Question 10 1.5 B: lower bound Kγ=4K\gamma = 4, upper bound RK=8R\sqrt{K} = 8 using the squared norm as norm; Kγ2K\gamma^2; KRKR
Problem 1 5 totals 15,0,−1515, 0, -15 and why they fail (1); L=83,38,83L = 83, 38, 83, c=6c = 6, Ein=7.6E_{\text{in}} = 7.6, signed total 00 (1.5); absolute sums 1111 and 1212 against squares 4343 and 3838, opposite preferences (1); Ein=0.4E_{\text{in}} = 0.4, test errors 0.6250.625 and 45.62545.625 and the comment (1.5) adding signed differences; mixing SSE and EinE_{\text{in}}; no test set
Problem 2 5 XTX=14X^TX = 14, XTY=35X^TY = 35, w∗=2.5w^* = 2.5, Ein=0.8333E_{\text{in}} = 0.8333 and 3030 (1); derivative, −23.33-23.33 at 00, three steps 1.16671.1667, 1.78891.7889, 2.12072.1207 with their errors (1.5); ρ=1−283η\rho = 1 - \frac{28}{3}\eta, its four values, range 0<η<3/140 < \eta < 3/14 (1.5); η=0.25\eta = 0.25 gives 5.83335.8333 and −1.9444-1.9444 with growing error, comparison with η=0.1\eta = 0.1 (1) sign of the step; missing factor 2; EinE_{\text{in}} without 1/N1/N; thinking larger η\eta is always better
Problem 3 5 the lines, the pieces with and without spaces, the four cleaned strings (1.5); XX with shape (4,3)(4, 3) and y=[1,−1,1,−1]\mathbf{y} = [1, -1, 1, -1] (1); outputs, products, 22 errors, boundary −43x1−23-\frac{4}{3}x_1 - \frac{2}{3} (1.5); update to [0,−1,1][0, -1, 1], 00 errors, boundary x2=x1x_2 = x_1 (1) spaces left by split; strip in place; no column of ones; labels 0/10/1
Total 30