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

Introduction to Machine Learning - Mock Exam 3

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, perceptron and its convergence bound, ADALINE, logistic regression, linear regression, classification metrics, 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: an input vector contains the constant coordinate x0=1x_0 = 1 when the text says so, and in the problem on the hyperplane the bias bb is written separately; labels are ±1\pm 1 for the perceptron and ADALINE; where a number is rounded, three 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 diagram of the components of learning in the course, which description is correct?

  • A) The hypothesis set H\mathcal{H} is produced by the learning algorithm from the data.
  • B) The data are generated by the unknown target function ff; the learning algorithm uses them together with the hypothesis set H\mathcal{H} and returns a final hypothesis g∈Hg \in \mathcal{H} with g≈fg \approx f.
  • C) The final hypothesis gg is the target function ff, which becomes known at the end of the training.
  • D) The samples are generated by the final hypothesis gg, and the algorithm then looks for the target ff.
Show the result

B

Show the full solution

B is the diagram of Introduction to Machine Learning - Learning, Data and TasksMachine learning builds a hypothesis g that approximates an unknown target function f using only a set of historical examples (input, output). The course lecture frames learning as adaptive behaviour, shows through the credit-approval example the components of learning (input x, output y, target f, data, hypothesis g, hypothesis set, learning algorithm) and warns that a model is only as unbiased as its data. Tasks named in the course are classification and regression, supervised and non-supervised problems.Introduction to Machine Learning - Learning, Data and Tasks →: the unknown target ff generates the samples SS, the hypothesis set H\mathcal{H} and the samples enter the learning algorithm, and the algorithm returns g≈fg \approx f. A is false: the hypothesis set is one of the two inputs of the algorithm, fixed in advance, not an output. C is false: ff stays unknown; gg is only an approximation of it. D is false: it is the target ff, not gg, that generates the data.

Question 2

A hypothesis is fitted to samples whose inputs crowd in the region where the input density P(x)P(x) is large, between two values aa and bb. Outside [a,b][a, b] there are few or no samples. What do the course notes say about the behaviour of the hypothesis outside this region?

  • A) A small in-sample error guarantees that the hypothesis is close to the target everywhere.
  • B) The algorithm minimises EinE_{\text{in}} over the whole input space, so the hypothesis follows ff also where nothing was observed.
  • C) The error outside [a,b][a, b] is irrelevant, because the only error that matters is EinE_{\text{in}} on the samples.
  • D) Where there are no samples the hypothesis is not constrained at all, so it can be far from ff there: the error on the samples is only a proxy for the error on the inputs that will really be seen.
Show the result

D

Show the full solution

D is the point of the section on the input distribution in 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 →: in the regions without data the hypothesis is not constrained, and the sketch hatches the gap between the hypothesis and ff there. A is false for the same reason: EinE_{\text{in}} says nothing about regions without samples. B is false: EinE_{\text{in}} is computed only on the samples, so only the samples constrain the hypothesis. C is false: the notes say that what matters is the error over the whole input distribution (called EoutE_{\text{out}} in 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 →), and that EinE_{\text{in}} is only a proxy for it.

Question 3

Which statement compares the perceptron and ADALINE correctly?

  • A) The perceptron compares the real number wTx\mathbf{w}^T\mathbf{x} with the label, while ADALINE compares its sign.
  • B) Both are updated only on the misclassified points, with the rule w+y x\mathbf{w} + y\,\mathbf{x}.
  • C) The perceptron is updated only on misclassified points with w+y x\mathbf{w} + y\,\mathbf{x} and stops when no point is misclassified; ADALINE uses all the points with w−η∇Ein\mathbf{w} - \eta\nabla E_{\text{in}} and stops by a stopping rule (no errors or a maximum number of epochs).
  • D) Both stop only when the squared error is zero.
Show the result

C

Show the full solution

C is the comparison table of ADALINE and Gradient DescentADALINE is a perceptron whose activation function is the identity: during training the unit outputs w^T x and the in-sample error E_in = (1/N) sum (y_i - w^T x_i)^2 is minimised by gradient descent, w_new = w_old - eta * grad E_in, with partial derivatives dE_in/dw_j = (2/N) sum (y_i - w^T x_i)(-x_i^j) and matrix form grad E_in proportional to -X^T (Y - X w). The prediction is still the sign of w^T x. Learning rate eta sets the step size and a stopping rule ends the iteration.ADALINE and Gradient Descent →: the perceptron uses only the misclassified points, the update is w+y x\mathbf{w} + y\,\mathbf{x} and it stops when no point is misclassified; ADALINE uses all the points, the update is w−η∇Ein\mathbf{w} - \eta\nabla E_{\text{in}} and it stops with a stopping rule. A swaps the two: the perceptron compares the sign of wTx\mathbf{w}^T\mathbf{x} with the label, ADALINE the number wTx\mathbf{w}^T\mathbf{x} itself. B is false for ADALINE, which learns from all the points, not only from the mistakes. D is false: the perceptron has no squared error and stops when there are no mistakes; ADALINE stops with a stopping rule, not necessarily at zero error.

Question 4

Which statement compares perceptron, ADALINE and logistic regression correctly, as in the summary table of the course?

  • A) The perceptron outputs sign⁡(wTx)\operatorname{sign}(\mathbf{w}^T\mathbf{x}) and is updated on its mistakes; ADALINE outputs wTx\mathbf{w}^T\mathbf{x} and minimises the squared error; logistic regression outputs σ(wTx)\sigma(\mathbf{w}^T\mathbf{x}) and minimises J(θ)=−ℓ(θ)J(\theta) = -\ell(\theta).
  • B) The three models have the same output, sign⁡(wTx)\operatorname{sign}(\mathbf{w}^T\mathbf{x}), and differ only in the learning rate.
  • C) Logistic regression minimises the squared error like ADALINE, with the sigmoid applied to the output.
  • D) ADALINE outputs σ(wTx)\sigma(\mathbf{w}^T\mathbf{x}) and logistic regression outputs wTx\mathbf{w}^T\mathbf{x}.
Show the result

A

Show the full solution

A is the summary table of 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 →: perceptron, output the sign, update w+yx\mathbf{w} + y\mathbf{x} on mistakes, stops when there are no mistakes; ADALINE, output wTx\mathbf{w}^T\mathbf{x}, squared error, stopping rule; logistic regression, output σ(wTx)\sigma(\mathbf{w}^T\mathbf{x}), cost J(θ)=−ℓ(θ)J(\theta) = -\ell(\theta), stopping rule. B is false: the three outputs are different (sign, identity, sigmoid). C is false: logistic regression minimises the cost −ℓ(θ)-\ell(\theta) obtained from the Bernoulli likelihood, not the squared error. D swaps the two activation functions: the identity belongs to ADALINE, the sigmoid to logistic regression.

Question 5

A data set has N=200N = 200 samples with 33 features, and the constant column is added to the data matrix XX. The weight vector is w\mathbf{w} and YY is the vector of the outputs. Which statement about Ein(w)=1N∥Xw−Y∥2E_{\text{in}}(\mathbf{w}) = \frac{1}{N}\|X\mathbf{w} - Y\|^2 is correct?

  • A) XX is 4×2004 \times 200 (one column per sample), w\mathbf{w} is 4×14 \times 1, and Xw−YX\mathbf{w} - Y is 4×14 \times 1, with one error for each weight.
  • B) XX is 200×4200 \times 4, w\mathbf{w} is 4×14 \times 1, and Xw−YX\mathbf{w} - Y is 200×1200 \times 1 with one error did_i for each sample; EinE_{\text{in}} is the single number 1200∑idi2\frac{1}{200}\sum_i d_i^2.
  • C) XX is 200×4200 \times 4, and EinE_{\text{in}} is the 200×1200 \times 1 vector Xw−YX\mathbf{w} - Y, one error for each sample, with no squares.
  • D) XX is 200×3200 \times 3, because the constant column is not part of the data matrix.
Show the result

B

Show the full solution

B follows 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 →: the examples are the rows of XX (xiT\mathbf{x}_i^T has the constant coordinate and the 33 features, so 44 columns) and the outputs are the column YY; the vector Xw−YX\mathbf{w} - Y is N×1N \times 1 with entries di=wTxi−yid_i = \mathbf{w}^T\mathbf{x}_i - y_i, and since d12+⋯+dN2=∥d∥2d_1^2 + \dots + d_N^2 = \|\mathbf{d}\|^2 the error is the number 1N∥Xw−Y∥2\frac{1}{N}\|X\mathbf{w} - Y\|^2. A has the examples in the columns and gives one error per weight instead of one per sample. C is false: the vector of the errors is squared, summed and divided by NN, giving a single number. D is false: the data matrix of the course carries the column of ones.

Question 6

On a data set with 55 positive and 9595 negative objects a classifier gives TP=1TP = 1, FN=4FN = 4, FP=3FP = 3, TN=92TN = 92. Which conclusion is drawn in the course notes?

  • A) The accuracy 0.930.93 shows that the classifier finds most of the positive objects.
  • B) The recall is 1/(1+3)=0.251/(1 + 3) = 0.25 and the precision is 1/(1+4)=0.21/(1 + 4) = 0.2.
  • C) Accuracy is the only measure that matters here, because it is the highest of the three.
  • D) The accuracy is 0.930.93, but the recall is 0.20.2 and the precision is 0.250.25: with unbalanced classes most objects are negative and are classified correctly anyway, so accuracy alone is not enough.
Show the result

D

Show the full solution

D is the lesson of the worked example of 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 →: accuracy is (1+92)/100=0.93(1 + 92)/100 = 0.93, recall is TP/(TP+FN)=1/5=0.2TP/(TP + FN) = 1/5 = 0.2 and precision is TP/(TP+FP)=1/4=0.25TP/(TP + FP) = 1/4 = 0.25. A is false: only 11 of the 55 positives was found (recall 0.20.2). B swaps the two definitions: recall divides by the actual positives TP+FNTP + FN, precision by the objects called positive TP+FPTP + FP. C is false: recall and precision show what the accuracy hides when the classes are unbalanced.

Question 7

In the first notebook with random samples, which statement is correct?

  • A) In np.random.normal(loc = 1.0, scale = 0.2, size = 100) the parameter loc is the mean and scale the standard deviation, while in np.random.exponential(scale = 0.2, size = 100) the parameter scale is the mean of the distribution.
  • B) In np.random.normal(loc = 1.0, scale = 0.2, size = 100) the parameter scale is the variance of the distribution.
  • C) plt.hist(x, density = True) draws the number of samples in each bin, so it cannot be compared with the theoretical density.
  • D) norm.pdf(x, loc = 1.0, scale = 0.2) draws 100100 new random numbers from the normal distribution.
Show the result

A

Show the full solution

A is the description in Python Notebooks - Random Samples, Plots and Linear Algebra with NumPyThe first course notebook draws random samples with NumPy (uniform with np.random.rand, normal and exponential), plots them with matplotlib (line and scatter plots, histograms compared with the theoretical density from scipy.stats), and shows the NumPy products used later: np.dot and np.inner between a matrix and a vector and between two matrices, with the transpose. This note reproduces the code of the notebook "matplotlib, random numbers and statistics" with the meaning of each call.Python Notebooks - Random Samples, Plots and Linear Algebra with NumPy →: for the normal samples loc =1.0= 1.0 is the mean and scale =0.2= 0.2 the standard deviation, and for the exponential samples scale is the mean of the distribution. B is false: scale is the standard deviation, not the variance. C is false: with density = True the histogram is normalised to area 11, exactly so that it can be compared with the red points of the theoretical density. D is false: norm.pdf evaluates the theoretical density at the sampled values x; the samples come from np.random.normal.

Question 8

In the batch ADALINE notebook the sum of squared errors is computed by

python
def error_sse(errors):
    error = np.sum(np.square(errors)) / 2
    return error

What does error_sse(np.array([1, -2, 2])) return?

  • A) 99
  • B) 33
  • C) 4.54.5
  • D) 0.50.5
Show the result

C

Show the full solution

In Python Notebooks - Perceptron and ADALINE from ScratchCode of the course notebooks that implement the Perceptron Learning Algorithm first with Python lists, then with plots of the successive lines, then with NumPy arrays (data matrix X with a column of ones, update w + eta * y * x on mistakes, epoch counter), and finally ADALINE: batch gradient descent with delta_w = eta * 2 * X^T (y - X w) / N and the stochastic version that shuffles the data and updates after every example. Differences between the versions (condition for a mistake, learning rate, stopping rule) are pointed out.Python Notebooks - Perceptron and ADALINE from Scratch → the SSE of this notebook is divided by 2, unlike the SSE of the exercises. The squares are 11, 44, 44, their sum is 99, and 9/2=4.59/2 = 4.5: C is correct. A is the sum of squares without the division by 2. B is the mean of the squares, 9/39/3: the function divides by 2, not by the number of points. D squares the sum of the errors instead of summing the squares: (1−2+2)2/2=0.5(1 - 2 + 2)^2/2 = 0.5, and signed errors would partly cancel.

Question 9

In the first scikit-learn example the notebook computes f1_score(lr_pred, y_test), with the predictions first and the true labels second, while the scikit-learn convention is the opposite order. Which statement is correct?

  • A) The call raises an error, because the true labels must always be the first argument.
  • B) The result is the same: exchanging the arguments exchanges precision and recall, and F1F_1 is symmetric in them; for example precision 0.90.9 and recall 0.60.6, or precision 0.60.6 and recall 0.90.9, both give F1=0.72F_1 = 0.72.
  • C) The result changes: with the arguments exchanged the same predictions give 0.720.72 in one order and 0.90.9 in the other.
  • D) The call returns the recall instead of the F1F_1 score, because the roles of the two arguments are exchanged.
Show the result

B

Show the full solution

B is the remark 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 →: exchanging the two arguments exchanges precision and recall, and the formula of 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 →, F1=2⋅Recall⋅PrecisionRecall+PrecisionF_1 = \dfrac{2\cdot\text{Recall}\cdot\text{Precision}}{\text{Recall} + \text{Precision}}, does not change when the two are swapped; with the numbers of the option, 2⋅0.9⋅0.60.9+0.6=0.72\dfrac{2\cdot 0.9\cdot 0.6}{0.9 + 0.6} = 0.72 in both orders. A is false: the notebook runs and uses that order. C is false for the symmetry just shown. D is false: the function still returns the F1F_1 score; only precision and recall are exchanged inside it.

Question 10

With t = " logging" (two spaces, then the word), what does t.strip("g") return?

  • A) " loggin"
  • B) "logging"
  • C) " logging"
  • D) " loin"
Show the result

A

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 →, strip with an argument removes only the given characters from the two ends of the string. The left end of t is a space, which is not a g, so nothing is removed there; the right end is a g, which is removed, and the next character is n, so the call returns " loggin": A is correct. B is the result of t.strip() without argument, which removes white space, not of strip("g"). C is the result when the end of the string is not a g: the notebook example x.strip("g") with a trailing space leaves x unchanged, but here the string ends with g. D removes every g, also the one inside the word, which is what replace does, not strip.

Problem 1 (points 5)

An ADALINE unit has the input x=[1,x1]T\mathbf{x} = [1, x_1]^T (constant coordinate and one feature). Five samples (x1,y)(x_1, y) are given: (−2,−1)(-2, -1), (−1,−1)(-1, -1), (1,+1)(1, +1), (2,+1)(2, +1), (4,+1)(4, +1). Two weight vectors are compared: wA=[0,1]T\mathbf{w}_A = [0, 1]^T and wB=[0,0.5]T\mathbf{w}_B = [0, 0.5]^T.

a) For each weight vector compute the number wTx\mathbf{w}^T\mathbf{x} that the unit gives on the five samples, the class predicted sign⁡(wTx)\operatorname{sign}(\mathbf{w}^T\mathbf{x}), and the number of misclassified samples (1.5 points).

b) Compute the in-sample error Ein=1N∑i(yi−wTxi)2E_{\text{in}} = \frac{1}{N}\sum_i (y_i - \mathbf{w}^T\mathbf{x}_i)^2 for wA\mathbf{w}_A and for wB\mathbf{w}_B (1.5 points).

c) With wA\mathbf{w}_A, which sample contributes most to EinE_{\text{in}}? Is it misclassified? Explain why the unit still counts it as a large error (1 point).

d) The notebook loop stops when all(adaline_output * y > 0). Does it stop with wA\mathbf{w}_A? And with wB\mathbf{w}_B? Which of the two weight vectors does ADALINE judge better, and can the perceptron tell them apart (1 point)?

Show the result

a) wA\mathbf{w}_A: outputs −2,−1,1,2,4-2, -1, 1, 2, 4; classes −1,−1,+1,+1,+1-1, -1, +1, +1, +1; 00 mistakes. wB\mathbf{w}_B: outputs −1,−0.5,0.5,1,2-1, -0.5, 0.5, 1, 2; classes −1,−1,+1,+1,+1-1, -1, +1, +1, +1; 00 mistakes.

b) wA\mathbf{w}_A: Ein=11/5=2.2E_{\text{in}} = 11/5 = 2.2. wB\mathbf{w}_B: Ein=1.5/5=0.3E_{\text{in}} = 1.5/5 = 0.3.

c) The sample (4,+1)(4, +1): output 44, error 1−4=−31 - 4 = -3, contribution 99 out of 1111. It is correctly classified: the error is computed on the real number 44, not on its sign.

d) The products adaline_output * y are 2,1,1,2,42, 1, 1, 2, 4 for wA\mathbf{w}_A and 1,0.5,0.5,1,21, 0.5, 0.5, 1, 2 for wB\mathbf{w}_B: all positive, so the loop stops at once with both, although EinE_{\text{in}} is not minimal. ADALINE prefers wB\mathbf{w}_B (0.3<2.20.3 < 2.2); the perceptron sees no mistake with either and cannot tell them apart.

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 unit and the error, 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 → for the stopping test, 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 perceptron.

a) Outputs and classes. The activation of ADALINE is the identity, so the unit computes wTx=w0+w1x1\mathbf{w}^T\mathbf{x} = w_0 + w_1x_1 and the class predicted is its sign.

x1x_1 −2-2 −1-1 11 22 44
yy −1-1 −1-1 +1+1 +1+1 +1+1
wATx=x1\mathbf{w}_A^T\mathbf{x} = x_1 −2-2 −1-1 11 22 44
class with wA\mathbf{w}_A −1-1 −1-1 +1+1 +1+1 +1+1
wBTx=0.5 x1\mathbf{w}_B^T\mathbf{x} = 0.5\,x_1 −1-1 −0.5-0.5 0.50.5 11 22
class with wB\mathbf{w}_B −1-1 −1-1 +1+1 +1+1 +1+1

In both cases the predicted classes equal the labels: no sample is misclassified.

b) In-sample error. The error of a sample is y−wTxy - \mathbf{w}^T\mathbf{x}, computed on the real number. For wA\mathbf{w}_A the errors are −1−(−2)=1-1 - (-2) = 1, −1−(−1)=0-1 - (-1) = 0, 1−1=01 - 1 = 0, 1−2=−11 - 2 = -1, 1−4=−31 - 4 = -3; the squares are 1,0,0,1,91, 0, 0, 1, 9, with sum 1111, so Ein(wA)=11/5=2.2E_{\text{in}}(\mathbf{w}_A) = 11/5 = 2.2. For wB\mathbf{w}_B the errors are 00, −0.5-0.5, 0.50.5, 00, −1-1; the squares are 0,0.25,0.25,0,10, 0.25, 0.25, 0, 1, with sum 1.51.5, so Ein(wB)=1.5/5=0.3E_{\text{in}}(\mathbf{w}_B) = 1.5/5 = 0.3.

c) The largest contribution. For wA\mathbf{w}_A the sample (4,+1)(4, +1) has output 44 and error 1−4=−31 - 4 = -3: its square, 99, is 99 out of the total 1111. It is correctly classified, since the output is positive and the label is +1+1. ADALINE still counts a large error because it compares the label with the number wTx\mathbf{w}^T\mathbf{x} itself and not with its sign: an output far above the label is as bad as one far below it.

d) Stopping test and comparison. The test all(adaline_output * y > 0) asks that every product y wTxy\,\mathbf{w}^T\mathbf{x} is positive, that is every point is on the correct side. For wA\mathbf{w}_A the products are 2,1,1,2,42, 1, 1, 2, 4 and for wB\mathbf{w}_B they are 1,0.5,0.5,1,21, 0.5, 0.5, 1, 2: all positive, so the loop stops immediately in both cases, even though the quantity being minimised, the squared error, is still far from its minimum (as the note observes, the check is made on the sign while the minimised quantity is the squared error). ADALINE judges wB\mathbf{w}_B better, since 0.3<2.20.3 < 2.2. The perceptron uses only the misclassified points and there are none, so for the perceptron the two weight vectors are equivalent.

Typical mistakes: applying the sign before computing the error; forgetting to divide by NN; confusing "no mistakes" with "minimum squared error"; computing y wTxy\,\mathbf{w}^T\mathbf{x} with the wrong sign for the negative samples.

Problem 2 (points 5)

A classifier for three classes 00, 11, 22 is tested on 4545 objects. The confusion matrix has the actual class in the rows and the predicted class in the columns:

predicted 0 predicted 1 predicted 2
actual 0 18 1 1
actual 1 3 9 3
actual 2 2 2 6

a) Give the total of each row and of each column, and the accuracy (1 point).

b) Compute recalli\text{recall}_i and precisioni\text{precision}_i for each class ii (1.5 points).

c) Compute the F1F_1 score of each class and the macro F1F_1, that is the F1F_1 averaged over the classes (1.5 points).

d) Which class has the lowest F1F_1? For class 00 the recall is higher than the precision: say which entries of the matrix make the denominator of the precision larger (1 point).

Show the result

a) Rows: 20,15,1020, 15, 10. Columns: 23,12,1023, 12, 10. Accuracy =(18+9+6)/45=33/45≈0.733= (18 + 9 + 6)/45 = 33/45 \approx 0.733.

b) recall0=18/20=0.9\text{recall}_0 = 18/20 = 0.9, recall1=9/15=0.6\text{recall}_1 = 9/15 = 0.6, recall2=6/10=0.6\text{recall}_2 = 6/10 = 0.6; precision0=18/23≈0.783\text{precision}_0 = 18/23 \approx 0.783, precision1=9/12=0.75\text{precision}_1 = 9/12 = 0.75, precision2=6/10=0.6\text{precision}_2 = 6/10 = 0.6.

c) F1≈0.837, 0.667, 0.600F_1 \approx 0.837,\ 0.667,\ 0.600; macro F1≈0.701F_1 \approx 0.701.

d) Class 22 has the lowest F1F_1 (0.60.6). For class 00 the column total 2323 exceeds the row total 2020 because 33 objects of class 11 and 22 objects of class 22 were assigned to class 00.

Show the full solution

Setting: 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 the multi-class view; the macro average is the one of the f1_macro score 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 →.

a) Totals and accuracy. The row of class ii is the total of the actual objects of class ii: 18+1+1=2018 + 1 + 1 = 20, 3+9+3=153 + 9 + 3 = 15, 2+2+6=102 + 2 + 6 = 10. The column of class ii collects the objects assigned to class ii: 18+3+2=2318 + 3 + 2 = 23, 1+9+2=121 + 9 + 2 = 12, 1+3+6=101 + 3 + 6 = 10. Both sets of totals add up to 4545. The diagonal holds the correct answers, TP0=18TP_0 = 18, TP1=9TP_1 = 9, TP2=6TP_2 = 6, so

accuracy=#correct answers#total answers=18+9+645=3345=0.733.\text{accuracy} = \frac{\#\text{correct answers}}{\#\text{total answers}} = \frac{18 + 9 + 6}{45} = \frac{33}{45} = 0.733 .

b) Recall and precision per class. Each class is seen as "class ii against the rest":

recalli=TPi#total of class i (row),precisioni=TPi#assigned to class i (column).\text{recall}_i = \frac{TP_i}{\#\text{total of class }i\text{ (row)}},\qquad \text{precision}_i = \frac{TP_i}{\#\text{assigned to class }i\text{ (column)}}.

Recall: 18/20=0.918/20 = 0.9, 9/15=0.69/15 = 0.6, 6/10=0.66/10 = 0.6. Precision: 18/23=0.78318/23 = 0.783, 9/12=0.759/12 = 0.75, 6/10=0.66/10 = 0.6.

c) F1F_1 and its macro average. For each class F1=2⋅recall⋅precisionrecall+precisionF_1 = \dfrac{2\cdot\text{recall}\cdot\text{precision}}{\text{recall} + \text{precision}}:

  • class 00: 2⋅0.9⋅0.7830.9+0.783=1.4091.683=0.837\dfrac{2\cdot 0.9\cdot 0.783}{0.9 + 0.783} = \dfrac{1.409}{1.683} = 0.837;
  • class 11: 2⋅0.6⋅0.750.6+0.75=0.91.35=0.667\dfrac{2\cdot 0.6\cdot 0.75}{0.6 + 0.75} = \dfrac{0.9}{1.35} = 0.667;
  • class 22: 2⋅0.6⋅0.60.6+0.6=0.6\dfrac{2\cdot 0.6\cdot 0.6}{0.6 + 0.6} = 0.6.

The macro F1F_1 is the plain average of the three: 0.837+0.667+0.6003=0.701\dfrac{0.837 + 0.667 + 0.600}{3} = 0.701, a little lower than the accuracy 0.7330.733 because every class counts the same whatever its size.

d) Reading the matrix. The lowest F1F_1 is that of class 22, with recall and precision both 0.60.6. Class 00 has a recall of 0.90.9 (only 22 of its 2020 objects are lost) but a precision of 0.7830.783: the column of class 00 has 2323 objects, of which only 1818 are really of class 00; the other 55 are the 33 objects of class 11 and the 22 objects of class 22 in the first column, and they enlarge the denominator of the precision without changing the recall.

Typical mistakes: swapping rows and columns (recall and precision exchange); dividing the recall by the predicted total; averaging recall and precision of all classes before computing F1F_1 instead of averaging the F1F_1 of the classes; using the accuracy alone to judge each class.

Problem 3 (points 5)

In the plane, a hyperplane is written with the bias separate, wTx+b=0\mathbf{w}^T\mathbf{x} + b = 0, with w=[6,8]T\mathbf{w} = [6, 8]^T and b=−20b = -20. Four labelled points are given: P1=(5,5)P_1 = (5, 5) with y=+1y = +1, P2=(1,1)P_2 = (1, 1) with y=−1y = -1, P3=(−2,3)P_3 = (-2, 3) with y=−1y = -1, P4=(4,1)P_4 = (4, 1) with y=+1y = +1.

a) Compute wTx+b\mathbf{w}^T\mathbf{x} + b and the distance from the hyperplane for each point (1.5 points).

b) For P1P_1 find the number α=wTx+bwTw\alpha = \dfrac{\mathbf{w}^T\mathbf{x} + b}{\mathbf{w}^T\mathbf{w}}, the vector γ=αw\boldsymbol\gamma = \alpha\mathbf{w} and the point xp=x−γ\mathbf{x}_p = \mathbf{x} - \boldsymbol\gamma of the hyperplane nearest to P1P_1. Check that xp\mathbf{x}_p lies on the hyperplane and that ∥γ∥\|\boldsymbol\gamma\| equals the distance of part a (1.5 points).

c) Write the same hyperplane with a vector w\mathbf{w} of norm 11, and also with w′=[3,4]T\mathbf{w}' = [3, 4]^T, b′=−10b' = -10. Show that the distance of P1P_1 does not change (1 point).

d) Are the four points on the correct side of the hyperplane? Which is the closest to it, and at what distance (1 point)?

Show the result

a) wTx+b=50, −6, −8, 12\mathbf{w}^T\mathbf{x} + b = 50,\ -6,\ -8,\ 12 for P1,…,P4P_1, \dots, P_4; ∥w∥=10\|\mathbf{w}\| = 10; distances 5, 0.6, 0.8, 1.25,\ 0.6,\ 0.8,\ 1.2.

b) α=50/100=0.5\alpha = 50/100 = 0.5; γ=[3,4]T\boldsymbol\gamma = [3, 4]^T; xp=[2,1]T\mathbf{x}_p = [2, 1]^T; wTxp+b=12+8−20=0\mathbf{w}^T\mathbf{x}_p + b = 12 + 8 - 20 = 0; ∥γ∥=5\|\boldsymbol\gamma\| = 5.

c) Unit vector: w/∥w∥=[0.6,0.8]T\mathbf{w}/\|\mathbf{w}\| = [0.6, 0.8]^T, b/∥w∥=−2b/\|\mathbf{w}\| = -2; for P1P_1: 3+4−2=53 + 4 - 2 = 5. With w′=[3,4]T\mathbf{w}' = [3, 4]^T, b′=−10b' = -10: ∥w′∥=5\|\mathbf{w}'\| = 5, w′Tx+b′=25\mathbf{w}'^T\mathbf{x} + b' = 25, distance 25/5=525/5 = 5.

d) y (wTx+b)=50,6,8,12y\,(\mathbf{w}^T\mathbf{x} + b) = 50, 6, 8, 12, all positive: all four points are on the correct side. The closest is P2P_2, at distance 0.60.6.

Show the full solution

Setting: 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 distance of a point from a hyperplane; the labels and the side of the hyperplane are those 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 →.

a) Distances. The distance of x\mathbf{x} from the hyperplane is ∥γ∥=∣wTx+b∣∥w∥\|\boldsymbol\gamma\| = \dfrac{|\mathbf{w}^T\mathbf{x} + b|}{\|\mathbf{w}\|}, with ∥w∥=36+64=10\|\mathbf{w}\| = \sqrt{36 + 64} = 10.

  • P1=(5,5)P_1 = (5, 5): 6⋅5+8⋅5−20=506\cdot 5 + 8\cdot 5 - 20 = 50, distance 50/10=550/10 = 5.
  • P2=(1,1)P_2 = (1, 1): 6+8−20=−66 + 8 - 20 = -6, distance 0.60.6.
  • P3=(−2,3)P_3 = (-2, 3): −12+24−20=−8-12 + 24 - 20 = -8, distance 0.80.8.
  • P4=(4,1)P_4 = (4, 1): 24+8−20=1224 + 8 - 20 = 12, distance 1.21.2.

b) The nearest point on the hyperplane. The shortest segment from x\mathbf{x} to the hyperplane is perpendicular to it, so γ\boldsymbol\gamma is parallel to w\mathbf{w}, γ=αw\boldsymbol\gamma = \alpha\mathbf{w}, and the nearest point is xp=x−γ\mathbf{x}_p = \mathbf{x} - \boldsymbol\gamma. Asking that xp\mathbf{x}_p lies on the hyperplane, wT(x−αw)+b=0\mathbf{w}^T(\mathbf{x} - \alpha\mathbf{w}) + b = 0, gives α wTw=wTx+b\alpha\,\mathbf{w}^T\mathbf{w} = \mathbf{w}^T\mathbf{x} + b. For P1P_1: wTw=100\mathbf{w}^T\mathbf{w} = 100, so α=50/100=0.5\alpha = 50/100 = 0.5 and γ=0.5 [6,8]T=[3,4]T\boldsymbol\gamma = 0.5\,[6, 8]^T = [3, 4]^T. Then xp=[5,5]T−[3,4]T=[2,1]T\mathbf{x}_p = [5, 5]^T - [3, 4]^T = [2, 1]^T. Check: wTxp+b=6⋅2+8⋅1−20=0\mathbf{w}^T\mathbf{x}_p + b = 6\cdot 2 + 8\cdot 1 - 20 = 0, so xp\mathbf{x}_p is on the hyperplane; and ∥γ∥=9+16=5\|\boldsymbol\gamma\| = \sqrt{9 + 16} = 5, the distance of part a.

c) Scaling the vector. Dividing w\mathbf{w} and bb by ∥w∥=10\|\mathbf{w}\| = 10 gives the unit vector [0.6,0.8]T[0.6, 0.8]^T and b/∥w∥=−2b/\|\mathbf{w}\| = -2: for P1P_1 the value is 0.6⋅5+0.8⋅5−2=50.6\cdot 5 + 0.8\cdot 5 - 2 = 5, which is already the distance (for ∥w∥=1\|\mathbf{w}\| = 1 the distance is simply ∣wTx+b∣|\mathbf{w}^T\mathbf{x} + b|). With w′=[3,4]T\mathbf{w}' = [3, 4]^T and b′=−10b' = -10, which is the same hyperplane (every coefficient divided by 22), w′Tx+b′=15+20−10=25\mathbf{w}'^T\mathbf{x} + b' = 15 + 20 - 10 = 25 and ∥w′∥=5\|\mathbf{w}'\| = 5, so the distance is 25/5=525/5 = 5. The value wTx+b\mathbf{w}^T\mathbf{x} + b changes with the scale of w\mathbf{w}, the distance does not, because the division by ∥w∥\|\mathbf{w}\| removes the scale.

d) Side and closest point. A point is on the correct side when y (wTx+b)>0y\,(\mathbf{w}^T\mathbf{x} + b) > 0: the products are (+1)⋅50=50(+1)\cdot 50 = 50, (−1)⋅(−6)=6(-1)\cdot(-6) = 6, (−1)⋅(−8)=8(-1)\cdot(-8) = 8, (+1)⋅12=12(+1)\cdot 12 = 12, all positive, so the hyperplane separates the four points. Dividing by ∥w∥=10\|\mathbf{w}\| = 10 gives the distances 5,0.6,0.8,1.25, 0.6, 0.8, 1.2 of part a: the closest point is P2P_2, at distance 0.60.6.

Typical mistakes: forgetting to divide by ∥w∥\|\mathbf{w}\| (that gives 5050, not 55); dividing by wTw\mathbf{w}^T\mathbf{w} instead of ∥w∥\|\mathbf{w}\| (that is α\alpha, not the length of γ\boldsymbol\gamma); forgetting the bias bb in the numerator; dropping the sign of α\alpha for a point on the negative side (there α\alpha is negative, and xp=x−αw\mathbf{x}_p = \mathbf{x} - \alpha\mathbf{w} still reaches the hyperplane).

Self-assessment grid
item points what must be there for full points typical mistakes
Question 1 1.5 B: ff generates the data; the algorithm uses data and H\mathcal{H} to return g≈fg \approx f H\mathcal{H} as an output; gg confused with ff
Question 2 1.5 D: without samples the hypothesis is not constrained; EinE_{\text{in}} is only a proxy trusting a small EinE_{\text{in}} everywhere
Question 3 1.5 C: perceptron on mistakes only with w+yx\mathbf{w} + y\mathbf{x}; ADALINE on all points with −η∇Ein-\eta\nabla E_{\text{in}} swapping sign and real output; ADALINE on mistakes only
Question 4 1.5 A: sign and mistakes; identity and squared error; sigmoid and −ℓ-\ell swapping the activations; squared error for logistic regression
Question 5 1.5 B: XX is 200×4200\times 4, Xw−YX\mathbf{w} - Y is 200×1200\times 1, EinE_{\text{in}} is a number one error per weight; no squares; no constant column
Question 6 1.5 D: accuracy 0.930.93, recall 0.20.2, precision 0.250.25, accuracy not enough swapping recall and precision; trusting accuracy
Question 7 1.5 A: loc mean, scale standard deviation; exponential scale is the mean variance instead of standard deviation; histogram as counts
Question 8 1.5 C: sum of squares 99, divided by 22 forgetting the /2/2; mean instead of /2/2; squaring the sum
Question 9 1.5 B: F1F_1 is symmetric in precision and recall thinking the order changes the score
Question 10 1.5 A: strip("g") removes g only at the ends, spaces stay confusing strip with replace; ignoring the leading spaces
Problem 1 5 outputs and classes, 00 mistakes (1.5); Ein=2.2E_{\text{in}} = 2.2 and 0.30.3 (1.5); sample (4,+1)(4,+1), error on the real number (1); stopping test true for both, wB\mathbf{w}_B better, perceptron cannot tell (1) sign applied before the error; no division by NN; "no mistakes" read as "minimum error"
Problem 2 5 totals 20,15,1020, 15, 10 and 23,12,1023, 12, 10, accuracy 0.7330.733 (1); recalls 0.9,0.6,0.60.9, 0.6, 0.6 and precisions 0.783,0.75,0.60.783, 0.75, 0.6 (1.5); F1F_1 per class and macro 0.7010.701 (1.5); class 22 and the entries of the column of class 00 (1) rows and columns swapped; recall divided by the predicted total; macro of recall and precision
Problem 3 5 values 50,−6,−8,1250, -6, -8, 12 and distances 5,0.6,0.8,1.25, 0.6, 0.8, 1.2 (1.5); α=0.5\alpha = 0.5, xp=[2,1]\mathbf{x}_p = [2,1], check (1.5); unit vector and w′\mathbf{w}' give 55 (1); correct sides, closest P2P_2 at 0.60.6 (1) no division by ∥w∥\|\mathbf{w}\|; wTw\mathbf{w}^T\mathbf{w} instead of ∥w∥\|\mathbf{w}\|; bias forgotten
Total 30