Guide to AI and Data Courses · Lecture Notes
Chapter 3: Machine Learning
Instead of writing the rules that recognize spam one by one, we can show an email filter thousands of labeled messages and let it find the rule itself. Machine learning is the course about that second route: building a model from examples, training it by minimizing a loss function, and finally measuring honestly how well it does on examples it has never seen. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.
Learning outcomes
- The learning problem
- Define a problem by its task, experience and performance measure; tell supervised and unsupervised learning apart with examples.
- Model and loss
- Compute the mean squared error of a simple model and carry out one step of gradient descent by hand.
- Generalization
- Recognize overfitting from training and test error; explain why a validation set and cross-validation are needed.
- Evaluation
- Compute accuracy, precision and recall from a confusion matrix; show why accuracy misleads on imbalanced data.
- Place of the course
- State what separates machine learning from artificial intelligence, data mining, statistics and deep learning.
3.1What question does the course ask?
How does a program generalize from examples?
Machine learning studies algorithms that learn from examples without being explicitly programmed and generalize what they learn to new examples. In Mitchell's definition, a program learns if its performance on task T, measured by P, improves with experience E.
In classical programming a person writes the rules and the computer applies them: given an input and a program, it produces an output. Machine learning turns this around. Inputs and the expected outputs are given as examples, and the computer finds the rule that produced them, the model, by itself. The model is then applied to new inputs.
The three letters in Mitchell's definition are a template for setting up a problem. For a spam filter the task (T) is to label every message "spam" or "normal"; the experience (E) is the messages users have already labeled; the performance (P) is how often the filter decides correctly on new messages. Splitting a problem into these three parts is the most important habit of the first weeks: a project that cannot say what it predicts, what data it learns from and how success is measured is not yet a machine learning problem.
3.1.1Supervised and unsupervised learning
If the examples come with the correct answer (a label), learning is supervised. When the label is a class (spam/normal, sick/healthy) the problem is classification; when it is a number (a house price, tomorrow's demand) it is regression. Without labels, learning is unsupervised: the goal is to find structure in the data, for example grouping customers by their shopping habits (clustering) or reducing hundreds of measurements to a few meaningful dimensions (dimensionality reduction). Learning from rewards is covered in a separate course, Reinforcement Learning.
3.1.2At a glance
| Criterion | Machine Learning |
|---|---|
| Approach | statistical learning |
| Input | labeled or unlabeled examples |
| Output | a model that makes predictions |
| Success measure | error on unseen data |
| Math load | high: linear algebra, probability, optimization |
| Data needs | moderate to large |
3.2A short history
| Year | Milestone |
|---|---|
| 1957 | Rosenblatt introduces the perceptron, one of the first models to tune its weights from examples. |
| 1959 | Samuel's checkers program improves by playing itself; the term "machine learning" spreads. |
| 1986 | Quinlan publishes the ID3 decision tree; the same year backpropagation revives neural networks. |
| 1995 | Cortes and Vapnik publish support vector machines (SVM). |
| 2001 | Breiman introduces random forests: a vote among many trees. |
| 2012 | AlexNet wins the ImageNet challenge by a wide margin; the deep learning era begins. |
3.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Supervised learning | Classification and regression from labeled examples. |
| Unsupervised learning | Clustering and dimensionality reduction on unlabeled data. |
| Model and hypothesis | The form and parameters of the function to be learned. |
| Loss function | Measures how wrong a prediction is; training minimizes it. |
| Generalization | Correct predictions on examples not seen in training. |
| Overfitting | Memorizing the training data; the bias-variance tradeoff. |
| Validation | Training, validation and test sets; cross-validation. |
| Features | Turning raw data into numbers a model can use. |
3.4Model, loss and gradient descent
Training a model means choosing its parameters so that its predictions are as close as possible to the training examples. "Close" is measured by a loss function. The most common loss in regression is the mean squared error (MSE): for every example the difference between the prediction and the true value is squared, and the squares are averaged.
For n examples, L(w) = (1/n) Σ (ŷi − yi)2, where ŷi is the model's prediction for example i and yi is the true value.
The general way to find the parameter that minimizes the loss is gradient descent: compute the derivative of the loss with respect to the parameter (the gradient) and move the parameter a small step against it: w ← w − η · dL/dw. The step size η is the learning rate. If the derivative is positive, the loss grows as w grows, so w is decreased; if it is negative, w is increased.
Three examples are given: (x, y) = (1, 2), (2, 4), (3, 5). The model is a line with one parameter: ŷ = w · x. We start at w = 1 with learning rate η = 0.1.
- Predictions and errors. ŷ = 1, 2, 3; errors ŷ − y = −1, −2, −2.
- Loss. L(1) = (1 + 4 + 4) / 3 = 3.
- Gradient. dL/dw = (2/n) Σ xi(ŷi − yi) = (2/3)(1·(−1) + 2·(−2) + 3·(−2)) = (2/3)(−11) ≈ −7.33.
- Update. w ← 1 − 0.1 · (−7.33) ≈ 1.73.
- New loss. The errors are about −0.27, −0.53, +0.20; L(1.73) ≈ 0.13.
One step brought the loss down from 3 to 0.13. For this simple model the best value can also be found in closed form: w* = Σxy / Σx2 = 25/14 ≈ 1.79, L(w*) ≈ 0.12. A few more steps of gradient descent approach this value.
Real models have thousands to billions of parameters and usually no closed-form solution, but gradient descent keeps working with the same idea. Logistic regression, neural networks and deep learning models are all trained with this loop: predict, compute the loss, find the gradient, update the parameters.
Thinking that a larger learning rate always means faster learning. In the example above, η = 0.5 gives w ≈ 4.67 after the first step, and the loss jumps from 3 to about 39: the step overshoots the valley and lands on the far slope. A very small η, on the other hand, slows training down for nothing.
3.5Generalization and overfitting
A model is judged not by how well it explains the training examples but by how accurately it predicts new ones. This is called generalization. A model that memorizes the training data looks perfect in training but fails on new data; this is overfitting. The opposite is choosing a model too simple to capture the pattern in the data: underfitting.
Polynomials of degree 1, 3 and 9 are fitted to 10 points taken from a noisy curve; the error is then measured on 100 new points from the same curve. A typical result looks like this (the values are illustrative):
| Degree | Training error | Test error | Reading |
|---|---|---|---|
| 1 | 0.90 | 1.00 | underfitting: a straight line cannot follow the curve |
| 3 | 0.30 | 0.40 | good generalization |
| 9 | 0.00 | 2.50 | overfitting: passes exactly through the 10 points, swings between them |
A degree-9 polynomial has 10 coefficients, so it can pass exactly through 10 points; its training error is zero. But because it has learned the noise as well, it does worst on new points.
This example shows the most important rule of the course: a model is evaluated on data that was not used for training. The data is split into three from the start: the training set trains the model, the validation set chooses the kind of model and its settings (hyperparameters such as the polynomial degree or the tree depth), and the test set is used once, at the very end, to report the real performance of the chosen model.
3.5.1Cross-validation
With little data, setting aside a separate validation set is expensive. In k-fold cross-validation the training data is split into k equal parts; the model is trained k times, each time using one part for validation and the rest for training. The average of the k validation errors is used to choose the hyperparameters. 5 and 10 are the most common values of k.
3.5.2Bias and variance
Overfitting and underfitting are explained by two sources of error. Bias is the systematic error that comes from the model's assumptions not matching reality (following a curve with a straight line). Variance is the model's oversensitivity to small changes in the training data (the degree-9 polynomial). As the model grows more complex, bias falls and variance rises; a good model balances the two. Regularization (adding large coefficients to the loss as a penalty) and more data are the two basic ways to reduce variance.
Choosing a hyperparameter by looking at the result on the test set. Once the test set has been used for a choice it is no longer independent, and the reported performance is optimistic. The choice is made with the validation set or cross-validation; the test set is looked at once, at the end.
3.6Evaluating a classifier
The most obvious measure in classification is accuracy: the share of examples classified correctly. But when one of the classes is rare, accuracy misleads. To see this, the predictions are placed in a confusion matrix: the class of interest is called "positive" and four numbers are kept.
| Actually positive | Actually negative | |
|---|---|---|
| Predicted positive | TP (true positive) | FP (false positive) |
| Predicted negative | FN (false negative) | TN (true negative) |
Precision = TP / (TP + FP): of the examples we called positive, how many really are? Recall = TP / (TP + FN): of the real positives, how many did we catch? Their harmonic mean is called F1: F1 = 2 · P · R / (P + R).
50 of 1000 messages are spam. Two filters are tried.
- Filter A calls every message "normal". TP = 0, FN = 50, TN = 950: accuracy 950/1000 = 95%, recall 0. It does not catch a single spam message.
- Filter B has TP = 40, FN = 10, FP = 30, TN = 920. Accuracy 960/1000 = 96%; precision 40/70 ≈ 0.57; recall 40/50 = 0.80; F1 ≈ 0.67.
The two filters have almost the same accuracy, but only B does the job. On imbalanced data, accuracy is never reported on its own.
Which measure matters depends on the application. In cancer screening, missing a patient (FN) is very costly, so recall comes first. In an email filter, throwing an important message into the spam folder (FP) is more annoying, so precision comes first. One of the key skills of the course is choosing the performance measure (Mitchell's P) according to these costs when the problem is set up. In regression, the mean squared error or the mean absolute error is used.
3.7How is the course taught?
3.7.1A typical workflow
A spam filter collects past messages and their labels, turns word counts into features, trains a logistic regression, measures accuracy on held-out test messages and classifies new incoming mail. No rules are written by hand; they are learned from data.
3.7.2Topics over the semester
- The learning problem; supervised and unsupervised learning
- Linear regression and gradient descent
- Logistic regression and classification
- Evaluation: train/test split, cross-validation
- Overfitting, regularization, bias-variance
- Decision trees
- Ensembles: random forests, gradient boosting
- Support vector machines and kernels
- k-nearest neighbors and naive Bayes
- Clustering: k-means, hierarchical clustering
- Dimensionality reduction: PCA
- Feature engineering and model selection
This is a typical semester; the order and coverage vary between universities.
3.7.3Skills you will gain
- Python and NumPy
- data preparation with pandas
- scikit-learn
- cross-validation
- choosing the right metric
- reporting results with plots and tables
3.7.4Try it yourself
The Try It: Should We Grant the Loan? slide in the presentation lets you solve a typical problem of this course yourself: The bank knows the income, debt ratio and repayment outcome of past applications. Click the chart to add a new application; the model decides by looking at the k most similar past ones.
3.8Are you ready for this course?
3.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Artificial Intelligence | an agent that learns from data; statistical generalization instead of search |
| Linear Algebra | feature vectors, matrix multiplication, PCA |
| Probability and Statistics | generalization error, bias-variance, probabilistic models |
| Optimization | loss minimization, regularization |
| Programming | reading data, loops and functions in Python or Java |
| Calculus | derivatives, partial derivatives and the chain rule: the language of gradient descent |
3.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you take a derivative and a partial derivative? | Derivatives and the chain rule from calculus |
| Can you multiply matrices and take a dot product? | Linear Algebra |
| Can you explain mean, variance and conditional probability? | Probability and Statistics |
| Can you write loops and functions in Python and read a CSV file? | An intro programming course, then a short pandas tutorial |
3.9Neighboring courses
3.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| subfield | This course is a subfield of Artificial Intelligence | an agent that learns from data; statistical generalization instead of search |
| subfield | Artificial Neural Networks is a subfield of this course | parametric model, loss function, gradient descent |
| subfield | Reinforcement Learning is a subfield of this course | learning from rewards instead of labels |
| builds on | This course builds on Linear Algebra | feature vectors, matrix multiplication, PCA |
| builds on | This course builds on Probability and Statistics | generalization error, bias-variance, probabilistic models |
| builds on | This course builds on Optimization | loss minimization, regularization |
| application | Machine Learning Systems and MLOps applies the methods of this course | deploying, monitoring and retraining models |
| application | AI in Cybersecurity applies the methods of this course | intrusion detection, malware classification |
| application | Bioinformatics applies the methods of this course | gene expression classification, protein structure |
| shares methods | Shares methods with Pattern Recognition | classifiers, decision boundaries |
| shares methods | Shares methods with Probabilistic Graphical Models | probabilistic classifiers, EM algorithm |
| shares methods | Shares methods with Explainable AI and AI Ethics | model explanation, feature importance |
| shares methods | Shares methods with Data Mining | same algorithms; the goal is discovery, not prediction |
| shares methods | Shares methods with Data Science | predictive models |
| shares methods | Shares methods with Information Theory | cross-entropy loss, decision tree split criterion |
3.9.2Where it differs
- Artificial Intelligence: AI is the framework; ML focuses only on learning from data within it.
- Data Mining: They share algorithms; ML aims to predict new examples, data mining to discover patterns in data.
- Probability and Statistics: Statistics emphasizes a model's meaning and uncertainty, ML its predictive performance.
- Deep Learning: Deep learning is a branch of ML; it learns features from raw data instead of hand-designing them.
3.10In practice
3.10.1Applications
| Area | What is done |
|---|---|
| Spam filtering | Classifying emails by their content. |
| Credit scoring | Predicting an applicant's risk of default. |
| Recommendation | Products or content a user is likely to enjoy. |
| Medical prediction | Estimating disease risk from patient data. |
| Demand forecasting | Sales and inventory planning. |
| Fraud detection | Catching unusual card transactions. |
3.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| Biased data, biased decisions | Discrimination in historical data passes straight into the model: hiring or credit models can systematically exclude some groups. |
| Data leakage | When test information leaks into training, a model looks flawless on paper and fails in the field. |
| Privacy | Personal information in the training data can be extracted from the model; GDPR and similar laws limit how data may be used. |
| Misplaced confidence | High accuracy collapses when the data distribution shifts, and the model looks just as confident on cases it does not know. |
These issues are discussed in depth in Explainable AI and AI Ethics.
3.10.3Tools and datasets
Tools: scikit-learn, pandas, NumPy, XGBoost, Weka, R.
Well-known datasets: Iris, MNIST, UCI Machine Learning Repository, Titanic (Kaggle), Adult (income), Wine.
3.11Common misconceptions
A more complex model is always better.
A complex model can memorize the training data (overfitting) and do worse on new data.
Training accuracy shows success.
Success is measured on test data never used in training.
More data solves every problem.
More biased or noisy data only multiplies the errors.
The model learns cause and effect.
ML finds correlations; causation needs experiments or causal inference.
3.12Summary
- Machine learning learns a model from examples instead of writing rules by hand; a problem is defined by its task (T), experience (E) and performance measure (P).
- Learning with labeled data is supervised (classification, regression); learning with unlabeled data is unsupervised (clustering, dimensionality reduction).
- Training means minimizing a loss function; gradient descent updates a parameter in steps of size η against the gradient.
- The real goal is generalization: a model with zero training error may have overfitted. Models are chosen with a validation set or cross-validation, and the final report uses the test set.
- With imbalanced classes accuracy misleads; precision, recall and F1 are computed from the confusion matrix.
3.13Test Yourself
Is each of the following supervised or unsupervised? If supervised, is it classification or regression? (a) Predicting a house's price from its floor area and location. (b) Grouping customers by their purchase history. (c) Deciding whether an X-ray image shows pneumonia.
Answer
(a) Supervised, regression: the label is a number. (b) Unsupervised, clustering: the groups are not named or counted in advance. (c) Supervised, classification: the label is "yes/no".
Data (1, 1), (2, 3), model ŷ = w · x, MSE loss, start at w = 0, η = 0.1. What is w after one gradient step?
Answer
The errors are −1, −3. dL/dw = (2/2)(1·(−1) + 2·(−3)) = −7. w ← 0 − 0.1 · (−7) = 0.7. (The best value is Σxy/Σx2 = 7/5 = 1.4.)
A model has 99% training accuracy and 70% test accuracy. What does this show, and what can be done?
Answer
Overfitting: the model has memorized the training data. One can try a simpler model or lower complexity (for example limiting the tree depth), regularization, more training data, and choosing hyperparameters with cross-validation.
A screening test has TP = 30, FP = 10, FN = 20, TN = 940. Compute accuracy, precision and recall. Which number should worry us most?
Answer
Accuracy 970/1000 = 97%, precision 30/40 = 0.75, recall 30/50 = 0.60. Recall is the worry: 40% of the real cases are missed, and the high accuracy hides it.
A student tries five tree depths, picks the depth that does best on the test set and reports that test result. What is wrong?
Answer
Because the test set was used to choose the model, the reported performance is optimistic (a kind of data leakage). The depth should be chosen with a validation set or cross-validation, and the test set looked at only once, at the end.
A supermarket chain wants to discover which products are bought together, and also to forecast next week's sales. Which is more a data mining question, and which more a machine learning question?
Answer
Discovering products bought together (association rules) is a search for patterns in the data, closer to data mining. Forecasting next week's sales is prediction on a new example, a machine learning (regression) question. The two courses often share algorithms; the difference is the goal.
3.14After this course
Machine learning is the crossroads of the map: neural networks and reinforcement learning are its branches; MLOps, cybersecurity and bioinformatics apply its methods. After this course you can go deeper (neural networks, deep learning) or move on to an application area.
Courses that build on or extend this one: Artificial Neural Networks, Reinforcement Learning, Machine Learning Systems and MLOps, AI in Cybersecurity, Bioinformatics.
Related careers: Machine learning engineer, Data scientist, Researcher, MLOps engineer.
3.15Further reading
- T. M. Mitchell, Machine Learning (1997), Chapter 1: defines the learning problem by T, E and P; the source of the definition used in these notes.
- E. Alpaydın, Introduction to Machine Learning (4th ed., 2020), Chapter 2: covers supervised learning, model complexity and generalization at textbook level.
- A. Géron, Hands-On Machine Learning (3rd ed., 2022), Chapters 2–4: runs a project end to end with scikit-learn and shows cross-validation and the confusion matrix in code.
3.16References
- Mitchell, Machine Learning, McGraw-Hill, 1997.
- Bishop, Pattern Recognition and Machine Learning, Springer, 2006.
- Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009.
- Alpaydın, Introduction to Machine Learning, 4th ed., MIT Press, 2020.
- Géron, Hands-On Machine Learning with Scikit-Learn, Keras and TensorFlow, 3rd ed., O'Reilly, 2022.
Related pages: Slides · Slides (PDF) · Course page