Introduction to Machine Learning - Learning, Data and Tasks
In questa pagina 7
This note collects the content of the first lecture (slides) and of the first handwritten page of the second one. It fixes the vocabulary used by all the other notes of the course: the statistical side is 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 → and 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 →; the first algorithm is 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 program is mapped in Introduction to Machine Learning - Program MapMap of the official program of Introduction to Machine Learning (Python, introduction to ML, clustering, classification, regression, evaluation) onto the notes of the course source: lecture slides, handwritten lecture notes and notebooks of the 2023-24 edition. For each program item it gives the note that covers it, or says that the source has no material (clustering, k-means, linkage, Gaussian mixtures and EM, confidence intervals) or only a textbook-chapter pointer (convexity, PAC definition, empirical risk minimisation, linear programming).Introduction to Machine Learning - Program Map →.
1. Objectives and resources of the course
The course ("Machine Learning and Python") states four goals:
- teach the fundamental concepts of machine learning, with a special focus on classification and regression tasks, using the Python programming language;
- first, the basics of Python programming (see 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 →);
- in parallel with the principles and methodologies of machine learning, the "nuts and bolts" of manipulating, processing, cleaning and crunching data with Python;
- at the end, a toolbox to analyse a supervised or non-supervised problem, design an experiment and choose the appropriate model.
Resources named on the slides:
| kind | resource |
|---|---|
| free book (theory) | Understanding Machine Learning: From Theory to Algorithms (the textbook chapters cited by the course are listed in the program map) |
| free books (Python) | A Whirlwind Tour of Python; Python Data Science Handbook |
| lists of free books | two GitHub collections, one on machine-learning books and one on Python books |
| online training | Datacamp |
| printed book (cheap) | Python Machine Learning, third edition |
| environment | Anaconda with Jupyter Notebook |
The slides also point to an article, "Machine Learning and Artificial Intelligence: Two Fellow Travelers on the Quest for Intelligent Behavior in Machines" (Frontiers in Big Data, 2018), for the relation between AI and ML, and to a YouTube video recommended "for the way ML is presented".
2. What is learning
Learning as adaptive behaviour. To act successfully in a complex environment, biological systems have developed sophisticated adaptive behaviour through learning and evolution. The capstone of adaptive behaviour is learning and intelligence; the slide states that the best way to build intelligent systems at present seems to be learning and inference.
Two definitions of learning are quoted:
- the acquisition of knowledge about the world (a 1985 definition from biophysics and psychiatry);
- an adaptive change in behaviour caused by experience (a 1988 definition from neuroscience).
Machine learning is the second definition made concrete: the "experience" is a set of data, and the "change in behaviour" is the choice of a function (the hypothesis) that will be used on new inputs.
3. Representing the world: features
An object is not given to the algorithm as such, but through features: the slide shows the photograph of a tiger with a few regions of the image circled and linked to a list "feature 1, feature 2, feature 3, ...". The labels on the slide are "What" (the object) and "Why" (the features that make us say what it is). In the credit example below the features are age, gender, salary and current debt; in the notebooks they are the coordinates of each point (see 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 →).
4. Bias encoded in the data
Two slides use a recidivism-risk system (COMPAS, Correctional Offender Management Profiling for Alternative Sanctions) as a case study. Two defendants are shown with their risk scores:
| prior offences | subsequent offences | score | |
|---|---|---|---|
| first defendant | 2 armed robberies, 1 attempted armed robbery | 1 grand theft | low risk, 3 |
| second defendant | 4 juvenile misdemeanors | none | high risk, 8 |
The caption states that the second defendant was rated high risk for future crime after she and a friend took a child's bike and scooter that were sitting outside, and that she did not reoffend. The labels "Who" and "Why" on the slides frame the questions: who is scored, and why the system gives that score.
The next slide, "Bias encoded in data", reports an exchange of December 2020. One side argues that machine-learning algorithms are essentially just complex mathematical formulas and cannot be racist or sexist any more than the formula can. The reply is: if is biased, then will be biased too. A comic closes the slide: the data are poured into "a big pile of linear algebra", the answers are collected on the other side, and if they are wrong one just stirs the pile until they look right.
Consequence for the course: a hypothesis learned from data inherits whatever is in the data; the quality of the answer depends on how the data were collected, not only on the formula.
5. The essence of learning
A sequence of slides (based on the Caltech telecourse material) plays a classification game. Small pictures are shown one at a time and labelled "merlion" or "not merlion": two orange circles with a small orange square between them, and an orange four-pointed star are merlions; a red four-pointed star is not. The audience is then asked whether a new picture (two purple squares with a purple circle between them) is a merlion. The answer is not given on the slides: the examples differ in colour and shape, so which property defines the class has to be inferred from the labelled examples.
The slide that follows states when machine learning is the right tool. We have a problem where
- a pattern exists;
- we cannot pin it down mathematically;
- we have data on it.
6. Components of learning
The running example is credit approval: the input is the applicant information, the output is "do we approve credit?". One applicant is described by
| feature | value |
|---|---|
| age | 23 years |
| gender | male |
| salary | 30,000 euros per year |
| current debt | 15,000 euros |
The abstract components are:
| symbol | meaning | credit example |
|---|---|---|
| input | attributes of the customer application | |
| output | credit approval: good or bad customer | |
| target function (unknown) | the ideal credit formula | |
| data | historical records | |
| hypothesis | the formula actually used |
The handwritten diagram of the second lecture adds the two missing pieces, the hypothesis set and the learning algorithm:
Unknown target function f
|
| D (the data are generated by f)
v
Samples S = {(x1,y1), ..., (xm,ym)} Hypothesis set H = {h}
| |
+-----------+ +-----------+
v v
Learning Algorithm
|
v
Final hypothesis g(x) ~ f(x) (g approximately f)The goal is : the algorithm looks inside the hypothesis set for an element that behaves like on the samples, hoping that it behaves like also on inputs it has never seen. How "behaves like" is measured is the subject of The Statistical Learning Framework and Empirical Risk MinimizationA hypothesis is judged by an error function computed pointwise on the data and averaged: the in-sample (empirical) error E_in(h) = (1/N) sum of e(f(x_i), h(x_i)); with squared differences it is the sum of squared errors. The learning algorithms of the course all search the hypothesis set for the h with small in-sample error, but what matters is the error on new inputs drawn from the same input distribution, so the data must cover the regions where the inputs live, and part of the data must be held back to check the result.The Statistical Learning Framework and Empirical Risk Minimization →; why the hope is justified for a finite is shown 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 →.
7. Tasks named in the course
- Classification: the output is a class label (in the perceptron notes ; later, several classes). 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 →, 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 →, 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 → and 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 →.
- Regression: the output is a real number. See 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 →.
- Supervised / non-supervised problems: named in the objectives. All the material of the course source is supervised (every example comes with its output ); clustering and other non-supervised methods are in the official program but there is no lecture material on them (see the program map).
Versione ripasso
- Course goals: fundamentals of ML with classification and regression in Python; Python basics; manipulating, cleaning and processing data; choose a model and design an experiment for a supervised or non-supervised problem.
- Learning = an adaptive change in behaviour caused by experience (neuroscience definition), or the acquisition of knowledge about the world (biophysics definition). ML makes the second definition concrete: the experience is a data set, the change is the choice of a function.
- Best way to build intelligent systems at present: learning and inference.
- An object is given to the algorithm through features (the "why" that explains the "what"); e.g. credit case: age, gender, salary, current debt.
- Use ML when three things hold: a pattern exists, it cannot be pinned down mathematically, and there are data on it.
- Components of learning: input , output , target (unknown), data generated by , hypothesis , hypothesis set , learning algorithm (it picks from using the samples). Goal: , also on inputs never seen.
f --D--> samples S ----+
+--> learning algorithm --> g ~ f
hypothesis set H +- Credit approval example: input = applicant data, output = good or bad customer; is the ideal credit formula, the formula actually used.
- Classification: = class label (perceptron: ). Regression: is a real number. Supervised: every example comes with its output ; non-supervised methods are in the program but not in the material.
- Bias: a hypothesis inherits what is in the data. Risk-score case study (COMPAS): a high-risk score given to a defendant who did not reoffend; the argument "a formula cannot be racist" fails because if is biased then is biased too.
- Pointers to the theory: 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 → (how "behaves like " is measured), 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 → (why the hope is justified for a finite ), first algorithm 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 →; classification metrics in Classification Metrics - Confusion Matrix, Precision, Recall and F1The performance of a classifier is read from the confusion matrix, whose rows are the actual classes and columns the predicted ones: TP, FN / FP, TN for a binary problem. Accuracy = (TP + TN) / total; recall = TP / (TP + FN); precision = TP / (TP + FP); F1 = 2 recall precision / (recall + precision). With an unbalanced data set accuracy can look good while recall is poor (10 positive and 90 negative objects: accuracy 0.87, recall 0.10, precision 0.20). In multi-class problems the confusion matrix is square and recall and precision are computed class by class from the diagonal.Classification Metrics - Confusion Matrix, Precision, Recall and F1 →; program in Introduction to Machine Learning - Program MapMap of the official program of Introduction to Machine Learning (Python, introduction to ML, clustering, classification, regression, evaluation) onto the notes of the course source: lecture slides, handwritten lecture notes and notebooks of the 2023-24 edition. For each program item it gives the note that covers it, or says that the source has no material (clustering, k-means, linkage, Gaussian mixtures and EM, confidence intervals) or only a textbook-chapter pointer (convexity, PAC definition, empirical risk minimisation, linear programming).Introduction to Machine Learning - Program Map →.
- Typical errors: reading a good score on the data as a guarantee about the world; the data themselves may be biased; confusing the target (unknown) with the hypothesis (learned).