Salta al contenuto
Note per Studenti Introduction to Machine Learning - Program Map Report

Introduction to Machine Learning - Program Map

In questa pagina 7

The program has six parts. The notes were written only from the materials of the 2023-24 edition of the course: the slides of the first lecture, the handwritten tablet notes of ten lectures (28 February to 6 May) and the course notebooks. The Moodle "Content" pages of the course only point to chapters of the free textbook (Understanding Machine Learning: introduction, chapter 1; chapters 2.1-2.3; 9.1 halfspaces, perceptron and linear programming; 12.1.1 convexity; 14.1 gradient descent; 9.2 linear regression; 9.3 logistic regression; 19.1 nearest neighbour; 11.1-11.4 model selection and validation; PAC learning and Hoeffding). Those chapters are used here only to name and order topics; nothing from them is written without a lecture page or a notebook behind it.

1. Python (language, data analysis, empirical study of random variables)

item where
language basics, control flow, lists, functions, files existing notes Python - BasicsPython 3 is a high-level, general-purpose, interpreted language. A program is a sequence of statements run by the interpreter, either interactively at the prompt or from a file with the edit/run loop. Variables are names bound to values by assignment; the basic types are int, float, str and bool, with explicit conversions (int, float, str, bool) and input always returning a string. Arithmetic uses the operators plus, minus, star, slash, double slash, percent and double star with precedence rules, relational operators produce booleans, and and, or, not combine them (precedence not, and, or; De Morgan's laws).Python - Basics → and Python - Control Flow, Lists, Functions and FilesA program makes decisions with if, elif and else, whose blocks are defined by the colon and by four-space indentation (an IndentationError otherwise). It repeats statements with while loops (condition, counter, update; infinite loops and sentinel loops) and for loops over range or over a sequence. A list is an ordered mutable container with zero-based indices, len, append, insert, pop, remove, the in operator, slicing, and sorted versus sort. Functions are defined with def, take parameters, return values with return (print is not return; no return gives None), have local variables, must be defined before being called and can live in separate modules imported with import. Text files are opened with the with statement in modes r, w or a with utf-8 encoding and read as strings.Python - Control Flow, Lists, Functions and Files → (Foundations of Computer Science)
strings and regular expressions 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 →
samples from distributions, histograms against densities, plots, matrix products 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 →
data analysis with tables (pandas), loading a data set, label encoding only through the examples 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 DataFrame built from fold scores, head(), ARFF loading); the source has no dedicated pandas lecture
probability background existing notes Central Limit Theoremthe standardized arithmetic mean of iid random variables with finite variance converges in distribution to N(0,1), whatever the distribution of the variables, which justifies the Gaussian approximation of sums.Central Limit Theorem →, Markov and Chebyshev InequalitiesFor a nonnegative random variable P(X >= a) is at most E(X)/a (Markov), and for any random variable with finite mean and variance P(

2. Introduction to machine learning

item where
what learning is, objectives, resources, case study on bias, instances and features 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 →
target function, data, hypothesis, hypothesis set, learning algorithm the same note (components of learning and the learning diagram)
in-sample error, error function, sum of squared errors, train/validation of data 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 →
empirical risk minimisation (as a named theory) textbook chapters 2.1-2.3 are only pointed to; the procedure itself (choose hh with smallest EinE_{\text{in}}) is described in the note above
generalisation error 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(
overfitting only sketched 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 → (flexible curve through the samples, regions without data); no named lecture
evaluation of a classifier 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 →
types of learning (supervised, non-supervised) named in the objectives; the whole material is supervised; no material on non-supervised or other types of learning

3. Clustering (k-means / Lloyd, linkage, Gaussian mixtures with EM)

No material in the course source. The handwritten notes, the slides and the notebooks contain nothing on clustering, k-means, hierarchical clustering with linkage, or Gaussian mixture models trained with the EM algorithm, and the Moodle content pages do not point to any chapter on them. These items are listed in the official program but are not covered by the notes.

4. Classification

item where
linear model, halfspaces, perceptron 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 →
perceptron convergence Perceptron Convergence and the Margin BoundThe distance of a point x from the hyperplane w^T x + b = 0 is
code of perceptron and ADALINE 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 →
ADALINE and gradient descent 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 →
convexity (textbook 12.1.1) pointer only; related prerequisites in the existing notes Convex Functions in Several VariablesA set C is convex if it contains the segment between any two of its points; f on C is convex if f(tx + (1-t)y) <= t f(x) + (1-t) f(y) for t in [0,1], i.e. the graph lies below chords. If f is differentiable it is convex if and only if f(y) >= f(x) + grad f(x)·(y - x) (graph above every tangent plane). If f is C^2 on an open convex set it is convex if and only if the Hessian is positive semidefinite at every point; positive definite everywhere implies strictly convex (not conversely: x^4). For a convex function every critical point is a global minimum.Convex Functions in Several Variables → and Differentiability and the Gradientf is differentiable at x0 if f(x) = f(x0) + grad f(x0)·(x - x0) + o(‖x - x0‖), i.e. near x0 the graph is indistinguishable from the tangent plane z = f(x0) + grad f(x0)·(x - x0). Differentiable implies continuous, with partial derivatives and D_v f = grad f · v; continuous partial derivatives imply differentiable. The gradient gives the direction of steepest increase (slope ‖grad f‖) and is orthogonal to level curves.Differentiability and the Gradient →
linear programming for halfspaces (9.1) pointer only, no material
logistic regression 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 → with Bernoulli Distribution and Maximum Likelihood EstimationA binary outcome (heads = 1, tails = 0) is modelled by a Bernoulli distribution with parameter theta: P(x
nearest neighbour 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 → (one handwritten page)
finite hypothesis class and PAC learning the finite-class bound with Hoeffding and the union bound 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(
support vector machines, multilayer networks, backpropagation, deep learning only named on handwritten pages (see Halfspaces and the Perceptron AlgorithmA perceptron computes h(x) = sign(w^T x) where x includes a constant coordinate x0 = 1 that absorbs the threshold into the bias weight w0; its decision boundary is the hyperplane w^T x = 0 (a line in the plane, x2 = -(w1/w2) x1 - w0/w2). The Perceptron Learning Algorithm scans the data and, on every misclassified point, replaces w by w + y x. A single perceptron cannot separate the exclusive-or pattern; two perceptrons feeding a third give a multilayer network.Halfspaces and the Perceptron Algorithm →); decision trees, SVC and random forests appear only as black-box scikit-learn models in the notebooks

5. Regression

item where
linear regression, normal equations, pseudo-inverse 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 → (also Least Squares Estimation - Linear and Weighted Least SquaresThe least squares estimator minimises the sum of squared deviations between observed and predicted outputs; for models linear in the parameters it has a closed form given by the normal equation, extended to weighted least squares and illustrated on a straight-line fit and on a DC motor.Least Squares Estimation - Linear and Weighted Least Squares →)
gradient descent for the squared error 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 →
polynomial regression only as an exercise: statement, data generation and solved closed form with a quadratic hypothesis on cubic data 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 →; no handwritten lecture, no discussion of the choice of degree

6. Evaluation

item where
train, validation and test sets, hold-out, repeated hold-out 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 →
k-fold cross-validation the same note, and the code in Python Notebooks - scikit-learn Model Comparison and Wilcoxon TestTwo example notebooks compare six scikit-learn classifiers (logistic regression, perceptron, KNN, decision tree, SVC, random forest) on a real data set loaded from the UCI repository: hold-out split with train_test_split, F1 score, k-fold cross-validation with cross_validate and scoring f1_macro, box plots of the fold scores, and the Wilcoxon signed-rank test (scipy.stats.wilcoxon) on the paired fold scores; the second notebook adds a stratified test set, more folds on the best models and the final training and test of the chosen model. A separate short notebook draws two normal samples to see how often the Wilcoxon test rejects at the 0.05 level.Python Notebooks - scikit-learn Model Comparison and Wilcoxon Test →
performance measures 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 →
statistical significance: null hypothesis, α\alpha, p-value, t-test named, Wilcoxon test the model-selection note; the exact test statistic of the Wilcoxon test is not written out in the source; use of the test in the notebooks
maximum likelihood estimation worked only for the Bernoulli parameter in Bernoulli Distribution and Maximum Likelihood EstimationA binary outcome (heads = 1, tails = 0) is modelled by a Bernoulli distribution with parameter theta: P(x
confidence intervals no material in the course source

Notes on the handwritten material

Some pages are sketches with few words; where the handwriting or the drawing is ambiguous the notes say so (for example the reading of the scores of the model-comparison sketch, the percentages beside the all-positive classifier, the sizes of the data matrix in the regression page, the second sketch of the gradient-descent page).

Versione ripasso

Introduction to Machine Learning - Program Map

Teoria collegata