~/teaching · machine learning · session 1, wednesday 14 october 2026
Frame before you model, then least squares: decision, leakage, normal equations and conditioning
Session 1 of the Machine Learning course: write the decision first, then solve the regression as a projection.
Abstract
This is the first working session of the Machine Learning course at Centrale Méditerranée (option DDEFI, 2026-2027). It has two halves that look unrelated and are not. The first half frames a project before any code: which decision the model serves, what the target column really records, which two metrics are read and by whom, which limits the model must respect, and how the data can leak the future into training. The second half takes the simplest model there is, the straight line fitted by ordinary least squares, and reads it four ways: as a minimisation, as a linear system, as an orthogonal projection and as a computation on a machine that rounds.
The running example of the course is a credit default score built on the UCI Default of Credit Card Clients data (Taiwan, 2005, CC BY 4.0 licence). The least-squares half works on five illustrative clients small enough to check every number by hand, then on California Housing in a lab.
After the session you can write the decision, the target, the metrics and a guard-rail of a project in five lines, draw a leakage map before opening the file, derive the normal equations, show why the residual is perpendicular to every column of the design matrix, and explain why serious libraries never form the inverse of .
Plan of the deck
- Framing an ML project. The decision, the question, the target, the two metrics, the guard-rails, the working loop and the data pipeline.
- Team activity on paper. Each team of three writes five signed lines framing the running project, which later open the project repository.
- The criterion and the normal equations. From the sum of squared gaps to its gradient, then to a linear system, checked on five clients.
- Projection, hat matrix and R². The fitted values are the orthogonal projection of the observations; Pythagoras gives the variance decomposition.
- Gauss-Markov. Why least squares rather than another unbiased line, and where the standard error of a coefficient comes from.
- SVD, conditioning and multicollinearity. The same solution written for a machine that rounds, and what happens when two columns almost coincide.
- History and use in 2026. From Legendre and Gauss to Golub and Kahan, and why the line remains the first model of every project.
- Lab: ols(X, y) three ways. Normal equations, SVD and scikit-learn must agree, with geometric checks and a condition number recorded.
Start from the decision, not from the data
A model is only worth building if someone will act differently after reading its output, so the decision is written down before anything else.
The reflex when a CSV arrives is to open it and look for patterns. The deck asks for the opposite order. First write who decides, between which options, and what each kind of error costs. On the running project, a credit analyst approves, refuses or sends a file for manual review, a committee sets the threshold, and accepting a client who then defaults is more expensive than turning away a good one. That asymmetry will decide the metric and, later in the course, the threshold.
A vague objective such as predict default is a verb and a column, not a question. A usable question names four things: a decision, a measure of success, a scope (this portfolio, this month) and an owner who will act on the answer. When one of the four is missing, the project tends to optimise a number nobody reads.
The target is a dated trace
The target is the column the model learns, and it is never the phenomenon itself. In the credit data it is late payment the following month, recorded by the bank's own rule for October 2005. A client who pays late in October and settles in November counts as a default; a client who vanishes with the full credit line in December does not. So the target is neither a "bad customer" nor a loss in euros. The first question to ask a business team is how the column was built, by whom, and on which date its value is known.
Two metrics, the accuracy trap and the guard-rails
One number helps the data team choose between models, another tells the business whether to deploy, and neither of them is accuracy.
The deck separates a model metric and a business metric because they have different readers. The model metric (log-loss, AUC, Brier score) is computed at every training run on the validation split and must react to small improvements. The business metric is expressed in euros lost or good customers refused, read by the credit committee after deployment. Both are fixed in the decision log before the first training run.
| Portfolio | Share of defaults | Accuracy of the constant model | Defaults detected |
|---|---|---|---|
| Retail example | 2 % | 98 % | 0 % |
| Course project (UCI Default) | 22.1 % | 77.9 % | 0 % |
As soon as one class is rare, accuracy flatters a model that has learned nothing. This constant model is still useful: it becomes the first baseline of the project, and its log-loss, which equals the entropy of the target, is the floor any real model has to beat.
Guard-rails, written before training
- What the model never does. It does not refuse a client on its own, and it does not use sex, directly or through a proxy. Marital status stays as an input, under audit: kept only if it adds information beyond payment history and if the gap in treatment it creates can be justified.
- Who signs. A named person validates the threshold and the deployment.
- When to stop. The stopping criteria (AUC below the baseline, input drift, a substantiated complaint) are written before the model exists, so they cannot be bent to fit the result.
- Regulation. Credit scoring of natural persons is a high-risk use under Annex III, point 5(b) of the EU AI Act (Regulation (EU) 2024/1689), which brings documentation, human oversight and logging obligations.
Data leakage: point-in-time join, frozen split, leakage map
A model that saw information from after the prediction date looks brilliant in development and fails in production, so the data is prepared in a strict order.
The deck presents the project as a loop rather than a pipeline: an evaluation can reveal a leak, the leak changes the data map, the map changes the question. Each turn is recorded in a decision log with the date, the alternative rejected, the reason and a number that a command reproduces. Within one turn, though, the order of the data steps is fixed.
The data steps, in order
- Sources. List each table with its licence and the exact definition of every column.
- Point-in-time join. To predict at date , keep only the records dated . In the credit data the features stop at the end of September 2005 and the target is October, so anything known later is forbidden.
- Frozen split. Split train, validation and test, stratified on the target so each part keeps 22.1 % of defaults, and fix it with a random seed and the SHA-256 hash of the file. The test set is opened once, at the milestone.
- Leakage map. One line per column: when it is known, whether it may be used, and why. It is written from the column definitions, so it can be done before looking at the data.
- Model. Only now, and the first model is a constant.
Remark (The most common leak in practice). Joining several tables naively takes today's version of each row instead of the version known on the prediction date. The model has then seen the future, which no validation score will reveal.
Least squares and the normal equations
We look for the line that makes the sum of squared vertical gaps as small as possible, and setting the slope of that sum to zero gives a small linear system.
Write the observations as a vector and the variables as a matrix whose first column is all ones, for the intercept. The model is , and ordinary least squares picks the that minimises the squared norm of the residual.
Expanding uses only two facts: the transpose of a product reverses the order, and a scalar equals its own transpose, so the two cross terms merge. Differentiating uses two rules, the gradient of is and the gradient of is when is symmetric.
A zero gradient is enough because is convex: its Hessian is positive semi-definite (the proof comes with convex optimisation). is invertible exactly when no column of can be rebuilt from the other columns, which rules out, for instance, the same amount in euros and in thousands of euros.
Worked example: five clients
The deck uses five illustrative clients: tenure years and average balance in thousands of euros. A hand-drawn line leaves a sum of squares of 2.0. Can another line do better?
Step by step
- Four sums. , , , , , so has rows and , and .
- Two equations. and . Subtracting three times the first from the second leaves .
- Solution. , then . The line leaves 1.9, less than 2.0.
- Check. At the gradient is , not zero: the hand-drawn line was not the minimum.
The fitted values are a projection: hat matrix, Xᵀe = 0, R²
The best line is the point of the plane spanned by the columns that lies closest to the data, so the leftover error stands at a right angle to that plane.
Substituting into makes a matrix appear in front of , the hat matrix, named for turning into . It is , while is only .
The two identities on the right say that is an orthogonal projection: projecting twice changes nothing, and the projection is not oblique. Every lies in the column space of , while the observed does not. The closest point of that space is the foot of the perpendicular, , and the residual is perpendicular to every column. This is the zero-gradient condition read as geometry.
The second formula is a proof of least squares without derivatives: the gap to any other line is the residual plus a piece inside the plane, and Pythagoras makes the cross term vanish.
| Client | x | y | ŷ | e | x · e |
|---|---|---|---|---|---|
| 1 | 1 | 2 | 2.2 | −0.2 | −0.2 |
| 2 | 2 | 3 | 3.1 | −0.1 | −0.2 |
| 3 | 3 | 5 | 4.0 | 1.0 | 3.0 |
| 4 | 4 | 4 | 4.9 | −0.9 | −3.6 |
| 5 | 5 | 6 | 5.8 | 0.2 | 1.0 |
| Sum | 15 | 20 | 20.0 | 0.0 | 0.0 |
On the same numbers, Pythagoras holds to the decimal: , and for the hand-drawn line . The trace of equals , a quick sanity check.
R² needs the intercept
With the five clients, predicting the mean 4 for everyone leaves , the line leaves , so . The split of the total variance relies on the residuals summing to zero, which is only guaranteed when the column of ones is in the model. Without it, the usual formula can go negative: the deck shows a two-point fit through the origin that gives . A negative R² in a report usually means a forgotten intercept, or a test score computed after a leak.
Remark (Gauss-Markov, in brief). If the noise is centred with covariance (no normality needed), is unbiased with , and no other linear unbiased estimator has a smaller variance. On the five clients the least-squares slope has variance , against for the slope joining the first and last client. With , that is a standard error of 0.252 against 0.281.
Condition number and SVD: why we never invert XᵀX
Computers round every number, and forming XᵀX squares how much those rounding errors can grow, so libraries solve least squares another way.
The singular value decomposition writes , where has orthonormal columns spanning the same plane as , holds the singular values , and is a rotation of the coefficients. In that basis the solution needs no matrix inverse, only divisions, and the hat matrix becomes .
Each component of along is divided by , so a small singular value amplifies whatever lands in its direction, noise included. The condition number bounds that amplification: a relative error on the data can grow by up to on the coefficients. Forming squares it. With , the machine works at , which already spends half the significant digits of a double. This is why np.linalg.lstsq goes through the SVD and other solvers through QR, never through .
| Unit of tenure | κ(X) | κ(XᵀX) |
|---|---|---|
| Years (1 to 5) | 8.4 | 70 |
| Months (12 to 60) | 93 | 8,721 |
The practical answer is to standardise the columns and to record np.linalg.cond(X) before delivering a model. In the lab, on raw California Housing, is around , and after standardisation it falls to about 7 and the three implementations agree to .
Multicollinearity
When two columns are almost parallel, the direction that separates them is barely present in the data, its singular value is tiny, and the variance along it explodes. The deck adds to the five clients a second, slightly noisy measure of tenure, correlated at 0.998 with the first. The coefficients jump to and with standard errors near 5, and goes from 8.4 to 85. Their sum, 0.97, stays close to the original slope 0.9, and the prediction for client 3 only moves from 4.00 to 4.23: the data pin down the total effect, not how to share it. Remedies are dropping a column or ridge regularisation, which adds to every .
import numpy as np x = np.array([1, 2, 3, 4, 5.]) y = np.array([2, 3, 5, 4, 6.]) X = np.column_stack([np.ones(5), x]) # SVD route: divisions by singular values, no inverse U, s, Vt = np.linalg.svd(X, full_matrices=False) beta = Vt.T @ ((U.T @ y) / s) # [1.3, 0.9] e = y - X @ beta print(X.T @ e) # ~[0, 0]: residual orthogonal print(s[0] / s[-1]) # condition number, about 8.4
Key takeaways
- Write the decision, its owner and the cost of each error before touching the data; the target, the metric and the threshold follow from it.
- The target is a dated record made by a rule, not the phenomenon, and accuracy is misleading as soon as one class is rare.
- Protect the evaluation in a fixed order: point-in-time join, split frozen by seed and file hash, leakage map, then a constant baseline.
- Least squares solves the normal equations , and geometrically, is an orthogonal projection and .
- R² splits the variance cleanly only when the model contains the intercept; a negative R² usually signals a missing constant or a leak.
- Check before delivering, standardise the columns, and solve through SVD or QR, never through .
Glossary
- Ordinary least squares (OLS)
- Estimation of a linear model by minimising the sum of squared residuals.
- Normal equations
- The system that the least-squares solution satisfies.
- Hat matrix
- , which maps the observations to the fitted values .
- Orthogonal projection
- A linear map with , which sends a vector to the closest point of a subspace.
- Residual
- The gap between observed and fitted values; in least squares it is orthogonal to the columns of .
- Coefficient of determination (R²)
- Share of the variance around the mean removed by the model, .
- Singular value decomposition (SVD)
- Factorisation into orthonormal columns, singular values and a rotation.
- Condition number
- Ratio of the largest to the smallest singular value; it bounds how much relative errors can be amplified.
- Multicollinearity
- Near-linear dependence between columns, which inflates the variance of individual coefficients.
- Data leakage
- Information unavailable at prediction time that reaches the training data and inflates scores.
- Point-in-time join
- A join that keeps, for a prediction at date , only records known at or before .
- Leakage map
- A table with one line per column stating when it is known, whether it may be used, and why.
- Baseline
- The simplest reference model, here a constant prediction, that any useful model must beat.
- Guard-rail
- A limit on what the model may do, written before training: excluded variables, signatory, stopping criteria.
The other notes of the course
One public summary per deck, in the order of the course.
Previous: Kaggle, GitHub, Python: the toolsNext: Maximum likelihood and logistic regression
- IntroductionAI winters, jobs and method
- ToolsKaggle, GitHub, Python: the tools
- Session 1Project framing and least squares
- Session 2Maximum likelihood and logistic regression
- Session 3Gradient descent, ridge and lasso
- Session 4Decision threshold and reproducible ML
- HomeworkA defensible baseline model
- Session 5Kernels, SVM and decision trees
- Session 6Forests, boosting, honest comparison
- Session 7SHAP, fairness, PCA and clustering
- HomeworkA documented champion model
- Session 8Neural networks, drift, conformal prediction
- HomeworkA delivered machine learning project
- Session 9Defending a machine learning project
- ReferenceCredit default scoring project
- ReferenceAsset returns: XGBoost and sentiment
- ReferencePython code for every ML model
- ReferenceDeep learning essentials
- ReferenceOpen data ML projects by sector
- ReferenceData and AI engineer handbook
- ReferenceData engineering, SRE and cloud
- ReferencePanorama of machine learning models
About these notes
Written by the lecturer from the slides of the deck, as a public summary: the key ideas, the formulas and one worked example. The exercises, their solutions, the tests and the grading stay in the deck, for the students of the course.
Revision: .