From rules to data
A rule-based system encodes what experts know. A machine learning system estimates a function from examples of inputs and outputs, so that it can predict outputs for new inputs [1]. In supervised learning, every example carries the correct answer: a measured strength, a failure label, a power output. In unsupervised learning, the examples carry no answers and the task is to find structure, such as groups or unusual points, which is the topic of Week 9. In reinforcement learning, an agent learns from rewards obtained by acting, which Week 14 treats. Regression is supervised learning with a continuous target, and classification, the topic of Week 8, predicts a category.
Breiman described two cultures in statistical modelling [2]. The data modelling culture assumes a stochastic model of how the data were generated and estimates its parameters; the algorithmic culture treats the mechanism as unknown and judges models by their predictive accuracy on new data. Engineering needs both views. A fitted coefficient of a physical law can be interpreted and extrapolated with care, while a random forest may predict better inside the range of the data but says little outside it.
Formulas: Learning a function from examples
Supervised learning assumes that a measured target depends on the inputs through an unknown function and a random error with mean zero:
A model , read "f hat", is chosen from a family of candidate functions so that it fits the training pairs well. Its average loss on the training data is the empirical risk, and for the squared loss it is the mean squared error [3]:
The simplest model predicts the same constant for every input. The derivative of with respect to is , and it is zero when
so the mean is the best constant under squared loss, and every other constant has a larger error by exactly . This constant model is the baseline against which the coefficient of determination of this week measures every other model.
Worked example: The best constant for five concrete mixes
Five mixes with the water-cement ratios 0.4, 0.45, 0.5, 0.55, 0.6 reached the compressive strengths 48, 43, 40, 35, 31 MPa.
Step 1. The mean. MPa.
Step 2. Its error. The deviations are 8.6, 3.6, 0.6, −4.4, −8.4, and
Step 3. Another constant. For the deviations are 8, 3, 0, and :
which exceeds 35.44 by , as the formula predicts.
The workflow of a data-driven project
The CRISP-DM process model, developed with industrial partners, describes six phases: business understanding, data understanding, data preparation, modelling, evaluation and deployment [4]. The phases form a loop rather than a line, because evaluation often sends the team back to the data. In engineering terms, the first phase fixes the decision that the model will support and the accuracy it needs; the second checks where the data came from, which units they use and which conditions they cover; the third handles missing values, outliers and derived features; and the last phases test the model honestly and document its limits.
Data are evidence and deserve the same care as a laboratory measurement. A dataset records a particular population of mixes, machines or buildings under particular conditions. A model trained on it inherits these limits, and predictions outside the covered range are extrapolations that no validation score protects.
Check your understanding. In which phase of CRISP-DM does a team decide what decision the model will support and how accurate it must be?
Honest evaluation: Splits and cross-validation
A model that is judged on the data it was trained on looks better than it is. The standard protection is to hold out data. A test set is set aside at the start and used once, at the end, to estimate performance on new data. Model choices, such as the degree of a polynomial or the depth of a tree, are made with a validation set or with k-fold cross-validation on the training data: The training data are divided into k parts, each part serves once as validation data while the other parts train the model, and the k scores are averaged. Kohavi's study recommended ten-fold stratified cross-validation for model selection on real-world data [5].
Model complexity trades bias against variance [3, 6]. A model that is too simple misses real structure and has high error on training and new data alike. A model that is too flexible fits the noise of the training data, so its training error is low but its error on new data rises. The best complexity lies between, and only data that the model has not seen can locate it.
Animation: Underfitting and overfitting
Polynomials of growing degree are fitted to noisy samples of a smooth curve. Watch the training error fall steadily while the error on new data first falls and then rises.
Check your understanding. A regression tree reaches a training R-squared of 0.99 and a cross-validated R-squared of 0.61. What is the most likely diagnosis?
Formulas: Cross-validation and the bias-variance decomposition
In -fold cross-validation the training examples are divided into folds of about examples each. The model is trained times, each time on folds, and its error is measured on the fold that was left out. The estimate is the mean of the errors, and their standard deviation shows how much the estimate depends on the split [5, 6]:
Why both too simple and too flexible models fail follows from the expected squared error at an input , averaged over the training sets that could have been drawn [3]:
The bias measures how far the average model is from the truth, the variance how much the model changes from one training set to the next, and is the variance of the noise, which no model can remove.
Worked example: Five folds and the size of the folds
Step 1. Fold sizes. The UCI concrete data hold 1030 mixes [7]. Ten-fold cross-validation uses folds of mixes and trains each model on mixes.
Step 2. The estimate. A five-fold run gives the fold errors 4.2, 3.8, 5.1, 4.6, 3.9 MPa (MAE):
Step 3. The spread. The deviations from 4.32 are −0.12, −0.52, 0.78, 0.28, −0.42, their squares 0.0144, 0.2704, 0.6084, 0.0784, 0.1764, and
A difference of 0.1 MPa between two models is therefore far inside the noise of the estimate.
Worked example: Bias and variance of two models
Suppose the true strength at one mix is MPa and the noise variance is . Four training sets give a flexible model the predictions 8, 9, 13, 10 and a rigid model the predictions 7, 7.5, 7.2, 7.3.
Step 1. The flexible model. The mean prediction is , so the bias is . The variance is , and the expected error is .
Step 2. The rigid model. The mean prediction is , so the bias is and . The deviations from 7.25 are , 0.25, and 0.05, so the variance is , and the expected error is .
The rigid model is stable but systematically wrong; the flexible model is right on average but unstable. Here the flexible model wins, while with less data its variance would grow and the comparison could turn. The animation above shows the same trade-off over the degree of a polynomial. Part A of the interactive lab lets polynomial, nearest-neighbour and tree models fit noisy strength data and shows where overfitting starts, and Part B estimates both terms by repeated sampling.
Models for regression
Linear regression fits a weighted sum of the inputs by least squares. It is fast, interpretable and a mandatory baseline. Scaling the inputs does not change its predictions but matters for regularised variants. Ridge regression adds a penalty on the squared size of the coefficients, which stabilises the fit when inputs are correlated [8], and the lasso penalises absolute values, which drives some coefficients exactly to zero and selects features [9].
Nonlinear relationships need more flexible models. The k-nearest-neighbour method predicts the average target of the k most similar training examples [10]. A regression tree splits the input space into boxes with a constant prediction in each box [11]. A random forest averages many trees grown on bootstrap samples with random subsets of features, which reduces variance substantially [12]. Gradient boosting adds shallow trees one after another, each correcting the errors of the current ensemble, and implementations such as XGBoost made it a leading method for tabular data [13]. scikit-learn exposes all of these through the same fit and predict interface [14].
Formulas: Least squares, ridge, lasso, neighbours, trees and ensembles
Least squares. For one input, the line that minimises the sum of squared residuals has the slope and intercept
which follow from setting the derivatives with respect to and to zero. With many inputs collected in a matrix , one row per example and a first column of ones, the same conditions give the normal equations and their solution [3].
Ridge and lasso. Ridge regression adds the penalty and the lasso the penalty to the sum of squared residuals, with a tuning constant [8, 9]. The ridge solution is , where is the identity matrix. For one centred input both solutions can be written down directly:
Ridge shrinks the slope towards zero, while the lasso subtracts a fixed amount and sets the slope exactly to zero once , which is how it selects features.
Nearest neighbours. The -nearest-neighbour prediction is the mean target of the training examples closest to the query , with the Euclidean distance over the inputs [10]:
Inputs in different units must first be standardised, with the mean and standard deviation of the training data, or the input with the largest numbers decides alone.
Trees and ensembles. A regression tree splits a node at the threshold of an input that minimises the summed squared error of the two children, each predicting the mean of its examples [11]:
A random forest averages trees, . If every tree has the variance and two trees are correlated with , the average has the variance [3, 12]. Gradient boosting starts from the mean and adds small trees fitted to the current residuals, scaled by a learning rate (nu) [13]:
Worked example: A least-squares line through the five mixes
Step 1. Means and deviations. and . The deviations are = −0.1, −0.05, 0, 0.05, 0.1 and = 8.6, 3.6, 0.6, −4.4, −8.4.
Step 2. The two sums.
Step 3. The coefficients.
The strength falls by 0.84 MPa for every increase of the water-cement ratio by 0.01, as Abrams' law leads one to expect [15].
Step 4. Predictions and residuals. gives 47.8, 43.6, 39.4, 35.2, 31 MPa, and the residuals are 0.2, −0.6, 0.6, −0.2, 0 MPa.
Step 5. Shrinkage. With , ridge gives , half of the least-squares slope. The lasso with gives , and with the slope becomes exactly zero. Part C of the interactive lab computes every term of these formulas for any pairs and shrinks the slope with both penalties.
Worked example: Nearest neighbours with and without scaling
Six training mixes have a water-cement ratio, an age in days and a strength in MPa. The query mix has the ratio 0.48 and the age 28 days, and .
Step 1. Raw distances. For mix 1, . The age dominates every distance, so the three nearest mixes are those with the same age, mixes 2, 3, 5, and the prediction is MPa.
Step 2. Standardisation. The training means are for the ratio and 45.1667 days for the age, and the standard deviations, computed with the divisor 6, are 0.071102 and 32.5598 days. Each difference to the query is divided by its standard deviation, for mix 1 and , so .
| Mix | Ratio | Age (d) | Strength (MPa) | Raw distance | Scaled ratio difference | Scaled age difference | Scaled distance |
|---|---|---|---|---|---|---|---|
| 1 | 0.4 | 7 | 35 | 21.0002 | −1.1251 | −0.645 | 1.2969 |
| 2 | 0.45 | 28 | 43 | 0.03 | −0.4219 | 0 | 0.4219 |
| 3 | 0.5 | 28 | 40 | 0.02 | 0.2813 | 0 | 0.2813 |
| 4 | 0.55 | 90 | 41 | 62 | 0.9845 | 1.9042 | 2.1436 |
| 5 | 0.6 | 28 | 31 | 0.12 | 1.6877 | 0 | 1.6877 |
| 6 | 0.42 | 90 | 55 | 62 | −0.8439 | 1.9042 | 2.0828 |
Step 3. The scaled prediction. The three nearest mixes are now 1, 2, 3, and the prediction is MPa. Mix 5, whose ratio differs from the query by 0.12, left the neighbourhood, and mix 1, whose ratio differs by 0.08 and whose age differs by 21 days, entered it. After scaling, 21 days weigh as much as in the ratio. Part D of the interactive lab moves the query and shows both neighbourhoods.
Worked example: The best first split and one boosting step
Step 1. Candidate thresholds. The midpoints between neighbouring ratios are 0.425, 0.475, 0.525 and 0.575. For each, the children predict their means:
| Threshold | Left strengths | Left mean | Left SSE | Right strengths | Right mean | Right SSE | Total |
|---|---|---|---|---|---|---|---|
| 0.425 | 48 | 48 | 0 | 43, 40, 35, 31 | 37.25 | 84.75 | 84.75 |
| 0.475 | 48, 43 | 45.5 | 12.5 | 40, 35, 31 | 35.3333 | 40.6667 | 53.1667 |
| 0.525 | 48, 43, 40 | 43.6667 | 32.6667 | 35, 31 | 33 | 8 | 40.6667 |
| 0.575 | 48, 43, 40, 35 | 41.5 | 89 | 31 | 31 | 0 | 89 |
For the threshold 0.525, for example, the left SSE is .
Step 2. The split. The threshold 0.525 gives the smallest total, 40.6667, against 177.2 without a split, so the tree first separates the two weakest mixes.
Step 3. One boosting step. Boosting starts from . The residuals are 8.6, 3.6, 0.6, −4.4, −8.4, and a stump fitted to them uses the same threshold, with the means on the left and on the right. With :
The new residuals are 6.4667, 1.4667, −1.5333, −1.2, −5.2, and the mean squared error falls from 35.44 to .
Step 4. Averaging trees. With MPa² and , one tree has the variance 16, an average of 10 trees , and an average of 100 trees . Averaging removes the independent part of the variance but not the correlated part, which is why random forests also decorrelate their trees with random subsets of features [12]. Part E of the interactive lab searches splits and adds boosting stumps step by step.
Measuring errors
The mean absolute error (MAE) averages the absolute differences between predictions and measurements and keeps the units of the target. The root mean squared error (RMSE) penalises large errors more strongly. The coefficient of determination R-squared compares the model with the constant prediction of the mean: A value of 1 means perfect predictions and 0 means no better than the mean. Numbers alone hide patterns, so a parity plot of predicted against measured values and residual plots against each input belong to every report. A residual trend against age, for example, reveals that the model misses the strength gain of concrete over time.
For concrete, the physics offers guidance. Abrams found that strength falls as the water-cement ratio rises [15], and strength grows with age at a decreasing rate. Yeh showed that neural networks trained on mix proportions and age predict the strength of high-performance concrete better than regression on the traditional ratio alone [16]. A derived feature such as the water-binder ratio can help simple models and makes the model easier to interpret.

Check your understanding. A strength model has an MAE of 4.1 MPa and an R-squared of 0.88. Which statement is correct?
Formulas: MAE, RMSE and the coefficient of determination
With the measured values , the predictions and the residuals of examples [6]:
is the squared error of the constant prediction , so is the fraction of that error which the model removes. RMSE is never smaller than MAE, and a large gap between the two signals a few large errors. Abrams' law describes the strength of concrete through the water-cement ratio with two constants and [15]:
Taking logarithms gives , a straight line in , so the constants can be fitted with least squares on or, from two mixes, directly.
Worked example: The error of the least-squares line
The residuals of the line from the previous section are 0.2, −0.6, 0.6, −0.2, 0 MPa.
Step 1. MAE. MPa.
Step 2. RMSE. The squared residuals are 0.04, 0.36, 0.36, 0.04, 0, so and MPa.
Step 3. . from the first example, so .
These are training errors on five mixes that lie almost on a line; the cross-validated errors of a real model are larger, as the knowledge check of the lecture page reminds.
Worked example: Abrams' constants from two mixes
Step 1. The constant . Dividing by removes : , so
Step 2. The constant . MPa.
Step 3. A prediction. For : MPa, close to the 40 MPa measured. The water-binder ratio extends the idea to mixes with slag and fly ash: 180 kg of water with 300 kg of cement, 100 kg of slag and 50 kg of fly ash give but . Part F of the interactive lab computes all three metrics for any measured and predicted values.
Data leakage
Leakage occurs when information that would not be available at prediction time enters the training data [17]. Typical engineering forms are a feature computed from the target, such as a strength class assigned after testing; a measurement taken after the event to be predicted, such as the repair cost of a failure that the model should anticipate; duplicated specimens that appear in both training and test sets; and preprocessing, such as scaling, fitted on the whole dataset before splitting. Leakage produces excellent validation scores and useless models. The defence is to ask for every feature when and how it becomes known in practice, to split before any fitting, and to wrap preprocessing and model into one pipeline.
Check your understanding. A dataset for predicting pump failure contains the column "hours until repair was completed". What is the problem?
Formulas: Fitting preprocessing without leakage
Every preprocessing step has parameters that are estimated from data, such as the mean and standard deviation of a standard scaler or the median used to fill missing values. Without leakage they are estimated from the training data only and then applied unchanged to new data [14, 17]:
For the standard scaler, and . Estimating from all data lets the test examples shape the transformation that is later used to judge them.
Worked example: A scaler that has seen the test point
The training values of an input are 10, 12, 14, 16, 18, and a new test value is 30, far outside the training range.
Step 1. Correct scaling. and , so the test value becomes . It lies more than five standard deviations outside the training data, a clear warning of extrapolation.
Step 2. Leaky scaling. With all six values, . The deviations are −6.6667, −4.6667, −2.6667, −0.6667, 1.3333, 13.3333, their squares 44.4449, 21.7781, 7.1113, 0.4445, 1.7777, 177.7769, so and the test value becomes .
The leaky scaler hides the extrapolation, because the test point has widened the scale that measures it. Wrapping scaler and model into one pipeline, which is fitted inside every training fold, prevents this. Part G of the interactive lab shows other forms of leakage.
Python step 7: Tables with pandas and honest evaluation with scikit-learn
The Python step of this week is part of the Colab notebook, where every explanation stands next to a cell that runs it and the step closes with a quick check and exercises with immediate feedback. The printable lecture notes contain the same step together with the outputs of its code. The Colab button below opens the notebook at the step. Run the setup cell just above the step first, since the exercises use its check function.
Review cards
Select a card to turn it over.
Continue the week
The week continues with the simulation and the self-assessment of the interactive lab and with the Python step and the hands-on work of the Colab notebook. The week overview lists the discipline challenges, the weekly task and the research assignment.
Interactive lab Colab notebook Self-assessment Week overview and tasks
References
[1] Jordan, M. I., & Mitchell, T. M. (2015). Machine learning: Trends, perspectives, and prospects. Science, 349(6245), 255-260. https://doi.org/10.1126/science.aaa8415
[2] Breiman, L. (2001). Statistical modeling: The two cultures. Statistical Science, 16(3), 199-231. https://doi.org/10.1214/ss/1009213726
[3] Hastie, T., Tibshirani, R., & Friedman, J. (2009). The Elements of Statistical Learning: Data Mining, Inference, and Prediction (2nd ed.). Springer. https://doi.org/10.1007/978-0-387-84858-7
[4] Wirth, R., & Hipp, J. (2000). CRISP-DM: Towards a standard process model for data mining. In Proceedings of the 4th International Conference on the Practical Applications of Knowledge Discovery and Data Mining (pp. 29-39).
[5] Kohavi, R. (1995). A study of cross-validation and bootstrap for accuracy estimation and model selection. In Proceedings of the 14th International Joint Conference on Artificial Intelligence (pp. 1137-1143).
[6] James, G., Witten, D., Hastie, T., & Tibshirani, R. (2021). An Introduction to Statistical Learning (2nd ed.). Springer. https://doi.org/10.1007/978-1-0716-1418-1
[7] Yeh, I.-C. (1998). Concrete Compressive Strength [Dataset]. UCI Machine Learning Repository, ID 165. https://doi.org/10.24432/C5PK67
[8] Hoerl, A. E., & Kennard, R. W. (1970). Ridge regression: Biased estimation for nonorthogonal problems. Technometrics, 12(1), 55-67. https://doi.org/10.1080/00401706.1970.10488634
[9] Tibshirani, R. (1996). Regression shrinkage and selection via the lasso. Journal of the Royal Statistical Society: Series B (Methodological), 58(1), 267-288. https://doi.org/10.1111/j.2517-6161.1996.tb02080.x
[10] Cover, T., & Hart, P. (1967). Nearest neighbor pattern classification. IEEE Transactions on Information Theory, 13(1), 21-27. https://doi.org/10.1109/TIT.1967.1053964
[11] Breiman, L., Friedman, J. H., Olshen, R. A., & Stone, C. J. (1984). Classification and Regression Trees. Wadsworth.
[12] Breiman, L. (2001). Random forests. Machine Learning, 45(1), 5-32. https://doi.org/10.1023/A:1010933404324
[13] Chen, T., & Guestrin, C. (2016). XGBoost: A scalable tree boosting system. In Proceedings of the 22nd ACM SIGKDD International Conference on Knowledge Discovery and Data Mining (pp. 785-794). https://doi.org/10.1145/2939672.2939785
[14] Pedregosa, F., Varoquaux, G., Gramfort, A., et al. (2011). Scikit-learn: Machine learning in Python. Journal of Machine Learning Research, 12, 2825-2830.
[15] Abrams, D. A. (1918). Design of Concrete Mixtures (Bulletin 1). Structural Materials Research Laboratory, Lewis Institute, Chicago.
[16] Yeh, I.-C. (1998). Modeling of strength of high-performance concrete using artificial neural networks. Cement and Concrete Research, 28(12), 1797-1808. https://doi.org/10.1016/S0008-8846(98)00165-3
[17] Kaufman, S., Rosset, S., Perlich, C., & Stitelman, O. (2012). Leakage in data mining: Formulation, detection, and avoidance. ACM Transactions on Knowledge Discovery from Data, 6(4), 15. https://doi.org/10.1145/2382577.2382579