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 when a weight vector is used; labels are for the perceptron; and 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 ; "approve credit" is the input .
- B) The four values are the target function , and the hypothesis is the applicant.
- C) The four values are the features through which the applicant (the object) is given to the algorithm; the output 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 is the attributes of the customer application while is the credit approval, good or bad customer. A swaps input and output. B is false: the target function is the unknown ideal credit formula and 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 , which reading of the symbols is correct?
- A) is the hypothesis returned by the algorithm after looking at the data; is its error on the samples and its error over the whole input distribution; is the tolerated gap and the number of hypotheses.
- B) is the number of samples and the number of hypotheses.
- C) is the error of on the samples and the error on new inputs.
- D) 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 →: is chosen after looking at the data (this is why the factor is needed), is measured on the samples, is the error over the whole input distribution, is the tolerated gap, and the hypothesis set has elements. B swaps and : appears in the exponent and counts the samples. C swaps the two errors. D mixes the gap with the probability: the note lists exactly this confusion (gap against probability ) among the typical errors; the left-hand side of the inequality is the probability, is the gap inside it.
Question 3
A perceptron has weights on the inputs , and it classifies the point as . The weights are replaced by . What happens?
- A) The boundary is the same line and no prediction changes, because only the length of changes.
- B) The boundary rotates, because the slope is multiplied by .
- C) The boundary moves parallel to itself, because the intercept is multiplied by .
- D) The boundary is the same line, but the sign of every is reversed, so the two sides exchange their classes: the point becomes .
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 , that is . With the old weights the slope is and the intercept is ; with the new weights the slope is and the intercept is : 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 : for the point , , the old value is (class ), the new one is (class ). So D is correct. A would be true for a positive factor, but is negative. B is false: in the ratio the factors cancel, so the slope is unchanged. C is false: the intercept is also unchanged.
Question 4
A nearest-neighbour classifier has stored training objects and is used to classify new objects with . How many distances does the test phase compute in total, and what changes with ?
- A) with and with , because only the distances to the kept neighbours are computed.
- B) with and with , one distance for each neighbour kept.
- C) with and also with : each prediction computes the distance from all the training objects, sorts them and only then keeps the first .
- D) with both values of , 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 , predict by the majority. So one prediction needs distances, predictions need , whatever is: 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 ( is not a count of anything in the algorithm). B () 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 , for a perceptron whose weight vector is learned, and for the score measured at the end?
- A) is fixed by the training on the training set, and is chosen before the training.
- B) is a hyper-parameter chosen to define the model; is an optimisation parameter fixed by the training; the score on the test set is the performance.
- C) and are both fixed by the training, and the test set is used to fix them.
- D) and 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 , 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 , or ); the trained models are evaluated on a test set, which gives a performance for each. A swaps the roles. C is false: 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 -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) performance values and differences.
- B) performance values and differences.
- C) performance values and differences.
- D) performance values, one for each model, and 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: values. Because all the models use the same folds, the score of Model 1 on fold is paired with the score of Model 2 on the same fold , so comparing two models gives one difference for each fold, that is 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]:
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 += 1After this single pass over the four rows, which are w and num_errors?
- A)
w = [0, 0, 0]andnum_errors = 0, because every output is . - B)
w = [-1, -4, -3]andnum_errors = 1. - C)
w = [1, -1, 1]andnum_errors = 3. - D)
w = [0, -3, 0]andnum_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 is a mistake only when the label is negative.
- Row 1, , : output ; the first clause needs , the second needs
output < 0: no mistake,wstays . - Row 2, , : output and : mistake;
w. - Row 3, , : output : mistake;
w. - Row 4, , : output , negative with a negative label: correct.
So w = [0, -3, 0] and num_errors = 2: D is correct, and since num_errors is not 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 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
w = w + eta * np.dot(np.transpose(X_batch), errors) / X_batch.shape[0]A mini-batch has objects, , the current weights are and np.dot(np.transpose(X_batch), errors) is . Which are the new weights?
- A)
- B)
- C)
- D)
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] : the correction is and it is added to the weights, , so C is correct. A is the update of the version of 4 April, which does not divide by the batch size (). B is the correction alone, without adding it to w. D subtracts the correction instead of adding it: the errors there are defined as , 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 .
- B) Because
data1 - data2is the p-value returned by the test. - C) Because
data1 - data2is the significance level , 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 .
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 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: is a number decided in advance (the rule of the notebook compares with ), 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 ; a flagged repetition would only be a false alarm.
Question 10
A perceptron starts from . The data have margin with respect to a unit vector and every point satisfies . After updates, between which two values does the proof of the margin bound place ?
- A) Between and .
- B) Between and .
- C) Between and .
- D) Between and .
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 . Step 1 and Step 2 give the lower bound . Step 3 gives , so the norm itself is at most (this step uses that an update is made only on a mistake, so the cross term is not positive). Hence , and B is correct. (Consistency check: , that is , true for .) A uses , the bound on the squared norm, as a bound on the norm. C takes as the lower bound, but the lower bound is . D takes as the upper bound, but the squared norm grows at most like , so the norm at most like .
Problem 1 (points 5)
Five samples are given: , , , , . The first hypothesis is a constant, . The in-sample error is .
a) Compute the total of the signed differences for , and . 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 for the same three values of . Find the best constant by setting the derivative of to zero, compute 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 and 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 with is proposed. Compute its with the matrix form and compare it with the best constant. Then use two new samples that were not used before, and , 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) for . The total is : it decreases without limit as grows and cancels positive and negative differences.
b) , , . gives , the mean of the outputs. . At the signed total is .
c) Absolute sums: for , for ; squared sums: for , for . The absolute measure prefers , the squared one prefers .
d) , , , , against for the constant. On the test points: the sloped hypothesis gives differences and , mean squared error ; the constant gives and , mean squared error . The ranking is confirmed, but the error of the sloped hypothesis on new samples () is larger than its ().
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 , with sum and mean (the values of do not matter for a constant).
a) Signed total. The differences are added:
This is the measure the notes reject: a point above the constant and a point below it cancel. For the total is although the single differences are ; and since keeps decreasing as grows, an algorithm that looked for the smallest total would prefer (total ) to and would run off to infinity. The total has no minimum, so it cannot rank hypotheses.
b) Squared differences. With : . With : . With : . The derivative is
the mean of the outputs (the result derived in the note). The in-sample error of the best constant is . The derivative is minus twice the signed total of part a), so the signed total is exactly at the best constant: .
c) Absolute differences. For the differences are and the sum of the absolute values is ; for it is . So with the absolute value is better than . With the squares, against , so 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 , and :
So and , much smaller than : 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: and , differences and , mean squared error . For the constant : differences and , mean squared error . The ranking is confirmed, and the constant is far worse because the new inputs lie beyond the range to 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 () than on the samples used to judge it (): 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 in and then dividing again in (or not at all); reading as the error ; 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, (no constant column), is fitted to three samples : , , . The error is with , and the data matrix is the single column .
a) Compute the weight given by the closed form , the value of at this weight and the value of at (1 point).
b) Write the derivative and compute it at . Run three steps of gradient descent from with , giving and after each step (1.5 points).
c) Show that , where is the weight of part a), and find as a function of . Compute for , , and , say what each value does to the successive weights, and find the range of for which the iteration approaches (1.5 points).
d) With compute the first two steps from and the corresponding ; compare with the first two steps for , and comment on the sketch of the bowl and the staircase (1 point).
Show the result
a) , , ; ; .
b) , equal to at . Steps with : (), (), ().
c) . For : . Convergence for , that is ; with the weights approach from one side, with they jump from side to side.
d) : (), then (): the error grows. : (), then ().
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 .
a) Closed form. The matrix has one column, so (a matrix: its size is the number of features) and . Then . The residuals are , , , with squares , , , so . At the errors are the outputs themselves: . In general, expanding the squares,
a parabola, the bowl of the sketch, with its minimum at .
b) Gradient descent. The derivative of the note, , is
which at is : negative, because is on the left of the minimum, so the step goes to the right. With :
- step 1: ; ;
- step 2: the derivative at is , so ; ;
- step 3: the derivative at is , so ; .
The steps (, , ) get shorter because the slope is smaller near the bottom, as in the sketch of the note.
c) The factor . Since , the derivative can be written (it vanishes at , which is the normal equation of the closed form). Then
(In general .) After steps the distance from is times the starting distance, here from . The four values are
For and , : the weights approach from the left, the distance shrinking by at each step (the numbers of part b: , , ) or by (almost at after one step). For , : the weights jump from one side of to the other (, , , ...) and the distance shrinks only slowly. For , : the distance grows at each step and the weights run away. The iteration approaches if , that is , which gives (in general ).
d) A learning rate that is too large. With : the first step is , which overshoots by , with , higher than the at the start; the derivative there is , so the second step is , with , even higher. With : () and then (), almost the minimum . 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 " too large" of the typical errors. The closed form needs no learning rate and no stopping rule: it gives at once, which is what gradient descent approaches when is in the right range.
Typical mistakes: the sign of the step (adding the derivative moves away from the minimum); forgetting the factor in the derivative; computing without the factor ; thinking that a larger is always faster ( diverges while 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
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 and ) 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 (1.5 points).
d) Apply the update 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) , shape (4, 3); labels is ['A', 'B', 'A', 'B'] and y_class .
c) np.dot(X, w) ; the products are ; the number of errors is (rows 2 and 4). Boundary: .
d) The first mistake is row 2: . The outputs become , all with the sign of the label: errors. Boundary: (slope , intercept ).
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 and . 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 first:
The labels are the stripped classes ['A', 'B', 'A', 'B']. The vector -np.ones(4) is , and y_class[labels == "A"] = 1 sets to the positions where the class is A (positions and in the counting from ): y_class , the "class against the rest" labels of the notebook with A as the positive class.
c) Outputs, errors and boundary. With , the outputs of the four rows are , , and . All are positive, so np.sign gives and the products with y_class are . 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 and (class B, predicted ), so the number of errors is . The boundary is
d) One update. The first misclassified row in the order of the data set is row , with (row is correct). The update is
The new outputs are , , and : the products with the labels are , all positive, so the number of errors is (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 by , towards the correct sign). The new boundary is : the points of class A, and , lie above the line, those of class B, and , 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 instead of ; 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: chosen after the data, on the samples, on the whole distribution, the gap | swapping and or the two errors; confusing the gap with the probability |
| Question 3 | 1.5 | D: same line, signs of reversed, class of becomes | thinking a negative factor changes nothing; thinking the line moves |
| Question 4 | 1.5 | C: distances whatever | counting only the kept neighbours; reusing distances computed in training |
| Question 5 | 1.5 | B: hyper-parameter, fixed by training, performance on the test set | fixing or with the test set; swapping the roles |
| Question 6 | 1.5 | A: values, paired differences | counting a difference for every score; one score per model |
| Question 7 | 1.5 | D: only rows 2 and 3 are mistakes, , 2 errors | using the NumPy test; using the plotting version; stopping at the first update |
| Question 8 | 1.5 | C: correction added to | 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 ; reading them as proof of a difference |
| Question 10 | 1.5 | B: lower bound , upper bound | using the squared norm as norm; ; |
| Problem 1 | 5 | totals and why they fail (1); , , , signed total (1.5); absolute sums and against squares and , opposite preferences (1); , test errors and and the comment (1.5) | adding signed differences; mixing SSE and ; no test set |
| Problem 2 | 5 | , , , and (1); derivative, at , three steps , , with their errors (1.5); , its four values, range (1.5); gives and with growing error, comparison with (1) | sign of the step; missing factor 2; without ; thinking larger is always better |
| Problem 3 | 5 | the lines, the pieces with and without spaces, the four cleaned strings (1.5); with shape and (1); outputs, products, errors, boundary (1.5); update to , errors, boundary (1) | spaces left by split; strip in place; no column of ones; labels |
| Total | 30 |