Artificial Intelligence Applications in Engineering (MUH-920), week 7 of 14

Learning from Data: The Machine Learning Workflow and Regression

Prof. Dr. Utku Kose, Süleyman Demirel University

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 yy depends on the inputs xx through an unknown function ff and a random error ε\varepsilon with mean zero:

y=f(x)+εy = f(x) + \varepsilon

A model f^\hat{f}, read "f hat", is chosen from a family of candidate functions so that it fits the nn training pairs (xi,yi)(x_i, y_i) well. Its average loss on the training data is the empirical risk, and for the squared loss it is the mean squared error [3]:

MSE=1n∑i=1n(yi−f^(xi))2\text{MSE} = \frac{1}{n} \sum_{i=1}^{n} (y_i - \hat{f}(x_i))^2

The simplest model predicts the same constant cc for every input. The derivative of ∑i(yi−c)2\sum_i (y_i - c)^2 with respect to cc is −2∑i(yi−c)-2 \sum_i (y_i - c), and it is zero when

c=1n∑i=1nyi=y‾c = \frac{1}{n} \sum_{i=1}^{n} y_i = \overline{y}

so the mean is the best constant under squared loss, and every other constant has a larger error by exactly (c−y‾)2(c - \overline{y})^2. 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. y‾=(48+43+40+35+31)/5=197/5=39.4\overline{y} = (48 + 43 + 40 + 35 + 31)/5 = 197/5 = 39.4 MPa.

Step 2. Its error. The deviations yi−y‾y_i - \overline{y} are 8.6, 3.6, 0.6, −4.4, −8.4, and

MSE(39.4)=73.96+12.96+0.36+19.36+70.565=177.25=35.44\text{MSE}(39.4) = \frac{73.96 + 12.96 + 0.36 + 19.36 + 70.56}{5} = \frac{177.2}{5} = 35.44

Step 3. Another constant. For c=40c = 40 the deviations are 8, 3, 0, −5-5 and −9-9:

MSE(40)=64+9+0+25+815=1795=35.8\text{MSE}(40) = \frac{64 + 9 + 0 + 25 + 81}{5} = \frac{179}{5} = 35.8

which exceeds 35.44 by (40−39.4)2=0.36(40 - 39.4)^2 = 0.36, 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 kk-fold cross-validation the nn training examples are divided into kk folds of about n/kn/k examples each. The model is trained kk times, each time on k−1k - 1 folds, and its error EjE_j is measured on the fold jj that was left out. The estimate is the mean of the kk errors, and their standard deviation shows how much the estimate depends on the split [5, 6]:

CVk=1k∑j=1kEj,    s=1k−1∑j=1k(Ej−CVk)2\text{CV}_k = \frac{1}{k} \sum_{j=1}^{k} E_j, \;\; s = \sqrt{\frac{1}{k - 1} \sum_{j=1}^{k} (E_j - \text{CV}_k)^2}

Why both too simple and too flexible models fail follows from the expected squared error at an input x0x_0, averaged over the training sets that could have been drawn [3]:

E[(y0−f^(x0))2]=Bias2+Variance+σ2\text{E}[(y_0 - \hat{f}(x_0))^2] = \text{Bias}^2 + \text{Variance} + \sigma^2
Bias=E[f^(x0)]−f(x0),    Variance=E[(f^(x0)−E[f^(x0)])2]\text{Bias} = \text{E}[\hat{f}(x_0)] - f(x_0), \;\; \text{Variance} = \text{E}[(\hat{f}(x_0) - \text{E}[\hat{f}(x_0)])^2]

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 σ2\sigma^2 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 1030/10=1031030/10 = 103 mixes and trains each model on 1030−103=9271030 - 103 = 927 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):

CV5=4.2+3.8+5.1+4.6+3.95=21.65=4.32 MPa\text{CV}_5 = \frac{4.2 + 3.8 + 5.1 + 4.6 + 3.9}{5} = \frac{21.6}{5} = 4.32 \text{ MPa}

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

s=1.1484=0.287=0.5357 MPas = \sqrt{\frac{1.148}{4}} = \sqrt{0.287} = 0.5357 \text{ MPa}

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 f(x0)=10f(x_0) = 10 MPa and the noise variance is σ2=1\sigma^2 = 1. 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 (8+9+13+10)/4=10(8 + 9 + 13 + 10)/4 = 10, so the bias is 10−10=010 - 10 = 0. The variance is ((8−10)2+(9−10)2+(13−10)2+(10−10)2)/4=(4+1+9+0)/4=3.5((8 - 10)^2 + (9 - 10)^2 + (13 - 10)^2 + (10 - 10)^2)/4 = (4 + 1 + 9 + 0)/4 = 3.5, and the expected error is 0+3.5+1=4.50 + 3.5 + 1 = 4.5.

Step 2. The rigid model. The mean prediction is (7+7.5+7.2+7.3)/4=7.25(7 + 7.5 + 7.2 + 7.3)/4 = 7.25, so the bias is 7.25−10=−2.757.25 - 10 = -2.75 and Bias2=7.5625\text{Bias}^2 = 7.5625. The deviations from 7.25 are −0.25-0.25, 0.25, −0.05-0.05 and 0.05, so the variance is (0.0625+0.0625+0.0025+0.0025)/4=0.0325(0.0625 + 0.0625 + 0.0025 + 0.0025)/4 = 0.0325, and the expected error is 7.5625+0.0325+1=8.5957.5625 + 0.0325 + 1 = 8.595.

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 y^=β0+β1x\hat{y} = \beta_0 + \beta_1 x that minimises the sum of squared residuals has the slope and intercept

β1=SxySxx=∑i(xi−x‾)(yi−y‾)∑i(xi−x‾)2,    β0=y‾−β1x‾\beta_1 = \frac{S_{xy}}{S_{xx}} = \frac{\sum_i (x_i - \overline{x})(y_i - \overline{y})}{\sum_i (x_i - \overline{x})^2}, \;\; \beta_0 = \overline{y} - \beta_1 \overline{x}

which follow from setting the derivatives with respect to β0\beta_0 and β1\beta_1 to zero. With many inputs collected in a matrix XX, one row per example and a first column of ones, the same conditions give the normal equations and their solution β=(X⊤X)−1X⊤y\beta = (X^{\top} X)^{-1} X^{\top} y [3].

Ridge and lasso. Ridge regression adds the penalty λ∑jβj2\lambda \sum_j \beta_j^2 and the lasso the penalty λ∑j∣βj∣\lambda \sum_j |\beta_j| to the sum of squared residuals, with a tuning constant λ≥0\lambda \ge 0 [8, 9]. The ridge solution is β=(X⊤X+λI)−1X⊤y\beta = (X^{\top} X + \lambda I)^{-1} X^{\top} y, where II is the identity matrix. For one centred input both solutions can be written down directly:

β1ridge=SxySxx+λ,    β1lasso=sign(Sxy)max⁡(∣Sxy∣−λ/2,0)Sxx\beta_1^{\text{ridge}} = \frac{S_{xy}}{S_{xx} + \lambda}, \;\; \beta_1^{\text{lasso}} = \frac{\text{sign}(S_{xy}) \max(|S_{xy}| - \lambda/2, 0)}{S_{xx}}

Ridge shrinks the slope towards zero, while the lasso subtracts a fixed amount and sets the slope exactly to zero once λ≥2∣Sxy∣\lambda \ge 2|S_{xy}|, which is how it selects features.

Nearest neighbours. The kk-nearest-neighbour prediction is the mean target of the kk training examples closest to the query xx, with the Euclidean distance over the pp inputs [10]:

y^(x)=1k∑i∈Nk(x)yi,    d(x,xi)=∑j=1p(xj−xij)2\hat{y}(x) = \frac{1}{k} \sum_{i \in N_k(x)} y_i, \;\; d(x, x_i) = \sqrt{\sum_{j=1}^{p} (x_j - x_{ij})^2}

Inputs in different units must first be standardised, z=(x−μ)/σz = (x - \mu)/\sigma with the mean μ\mu and standard deviation σ\sigma 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 tt of an input that minimises the summed squared error of the two children, each predicting the mean of its examples [11]:

SSE(t)=∑xi<t(yi−y‾L)2+∑xi≥t(yi−y‾R)2\text{SSE}(t) = \sum_{x_i < t} (y_i - \overline{y}_L)^2 + \sum_{x_i \ge t} (y_i - \overline{y}_R)^2

A random forest averages BB trees, f^(x)=1B∑b=1BTb(x)\hat{f}(x) = \frac{1}{B} \sum_{b=1}^{B} T_b(x). If every tree has the variance σ2\sigma^2 and two trees are correlated with ρ\rho, the average has the variance ρσ2+(1−ρ)σ2/B\rho \sigma^2 + (1 - \rho)\sigma^2/B [3, 12]. Gradient boosting starts from the mean and adds small trees hmh_m fitted to the current residuals, scaled by a learning rate ν\nu (nu) [13]:

Fm(x)=Fm−1(x)+ν hm(x)F_m(x) = F_{m-1}(x) + \nu\, h_m(x)

Worked example: A least-squares line through the five mixes

Step 1. Means and deviations. x‾=(0.40+0.45+0.50+0.55+0.60)/5=0.5\overline{x} = (0.40 + 0.45 + 0.50 + 0.55 + 0.60)/5 = 0.5 and y‾=39.4\overline{y} = 39.4. The deviations are xi−x‾x_i - \overline{x} = −0.1, −0.05, 0, 0.05, 0.1 and yi−y‾y_i - \overline{y} = 8.6, 3.6, 0.6, −4.4, −8.4.

Step 2. The two sums.

Sxy=(−0.1)×(8.6)+(−0.05)×(3.6)+(0)×(0.6)+(0.05)×(−4.4)+(0.1)×(−8.4)=−2.1S_{xy} = (-0.1) \times (8.6) + (-0.05) \times (3.6) + (0) \times (0.6) + (0.05) \times (-4.4) + (0.1) \times (-8.4) = -2.1
Sxx=(−0.1)2+(−0.05)2+(0)2+(0.05)2+(0.1)2=0.025S_{xx} = (-0.1)^2 + (-0.05)^2 + (0)^2 + (0.05)^2 + (0.1)^2 = 0.025

Step 3. The coefficients.

β1=−2.10.025=−84,    β0=39.4−(−84)×0.5=39.4+42=81.4\beta_1 = \frac{-2.1}{0.025} = -84, \;\; \beta_0 = 39.4 - (-84) \times 0.5 = 39.4 + 42 = 81.4

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. y^=81.4−84x\hat{y} = 81.4 - 84 x gives 47.8, 43.6, 39.4, 35.2, 31 MPa, and the residuals y−y^y - \hat{y} are 0.2, −0.6, 0.6, −0.2, 0 MPa.

Step 5. Shrinkage. With λ=0.025\lambda = 0.025, ridge gives β1=−2.1/(0.025+0.025)=−2.1/0.05=−42\beta_1 = -2.1/(0.025 + 0.025) = -2.1/0.05 = -42, half of the least-squares slope. The lasso with λ=2\lambda = 2 gives β1=−(2.1−1)/0.025=−1.1/0.025=−44\beta_1 = -(2.1 - 1)/0.025 = -1.1/0.025 = -44, and with λ=4.2=2×2.1\lambda = 4.2 = 2 \times 2.1 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 k=3k = 3.

Step 1. Raw distances. For mix 1, (0.40−0.48)2+(7−28)2=0.0064+441=21.0002\sqrt{(0.40 - 0.48)^2 + (7 - 28)^2} = \sqrt{0.0064 + 441} = 21.0002. The age dominates every distance, so the three nearest mixes are those with the same age, mixes 2, 3, 5, and the prediction is (43+40+31)/3=38(43 + 40 + 31)/3 = 38 MPa.

Step 2. Standardisation. The training means are μ=0.486667\mu = 0.486667 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 (0.40−0.48)/0.071102=−1.1251(0.40 - 0.48)/0.071102 = -1.1251 and (7−28)/32.5598=−0.645(7 - 28)/32.5598 = -0.645, so −1.12512+−0.6452=1.2969\sqrt{-1.1251^2 + -0.645^2} = 1.2969.

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 (35+43+40)/3=39.3333(35 + 43 + 40)/3 = 39.3333 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 0.645×0.071102=0.0460.645 \times 0.071102 = 0.046 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 (48−43.6667)2+(43−43.6667)2+(40−43.6667)2=18.7778+0.4444+13.4444=32.6667(48 - 43.6667)^2 + (43 - 43.6667)^2 + (40 - 43.6667)^2 = 18.7778 + 0.4444 + 13.4444 = 32.6667.

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 F0=39.4F_0 = 39.4. 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 43.6667−39.4=4.266743.6667 - 39.4 = 4.2667 on the left and 33−39.4=−6.433 - 39.4 = -6.4 on the right. With ν=0.5\nu = 0.5:

F1=39.4+0.5×4.2667=41.5333 on the left,    F1=39.4+0.5×(−6.4)=36.2 on the rightF_1 = 39.4 + 0.5 \times 4.2667 = 41.5333 \text{ on the left}, \;\; F_1 = 39.4 + 0.5 \times (-6.4) = 36.2 \text{ on the right}

The new residuals are 6.4667, 1.4667, −1.5333, −1.2, −5.2, and the mean squared error falls from 35.44 to (41.8182+2.1512+2.351+1.44+27.04)/5=14.9601(41.8182 + 2.1512 + 2.351 + 1.44 + 27.04)/5 = 14.9601.

Step 4. Averaging trees. With σ2=16\sigma^2 = 16 MPa² and ρ=0.3\rho = 0.3, one tree has the variance 16, an average of 10 trees 0.3×16+0.7×16/10=4.8+1.12=5.920.3 \times 16 + 0.7 \times 16/10 = 4.8 + 1.12 = 5.92, and an average of 100 trees 4.8+0.112=4.9124.8 + 0.112 = 4.912. 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.

Parity plot of a gradient boosting model on held-out data of the synthetic concrete stand-in used by the notebook when the UCI data cannot be downloaded. Points on the diagonal are perfect predictions.
Figure 7.1. Parity plot of a gradient boosting model on held-out data of the synthetic concrete stand-in used by the notebook when the UCI data cannot be downloaded. Points on the diagonal are perfect predictions.

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 yiy_i, the predictions y^i\hat{y}_i and the residuals ei=yi−y^ie_i = y_i - \hat{y}_i of nn examples [6]:

MAE=1n∑i=1n∣ei∣,    RMSE=1n∑i=1nei2\text{MAE} = \frac{1}{n} \sum_{i=1}^{n} |e_i|, \;\; \text{RMSE} = \sqrt{\frac{1}{n} \sum_{i=1}^{n} e_i^2}
R2=1−SSresSStot=1−∑iei2∑i(yi−y‾)2R^2 = 1 - \frac{\text{SS}_{\text{res}}}{\text{SS}_{\text{tot}}} = 1 - \frac{\sum_i e_i^2}{\sum_i (y_i - \overline{y})^2}

SStot\text{SS}_{\text{tot}} is the squared error of the constant prediction y‾\overline{y}, so R2R^2 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 SS of concrete through the water-cement ratio w/cw/c with two constants AA and BB [15]:

S=ABw/cS = \frac{A}{B^{w/c}}

Taking logarithms gives ln⁡S=ln⁡A−(w/c)ln⁡B\ln S = \ln A - (w/c) \ln B, a straight line in w/cw/c, so the constants can be fitted with least squares on ln⁡S\ln S 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. (0.2+0.6+0.6+0.2+0)/5=1.6/5=0.32(0.2 + 0.6 + 0.6 + 0.2 + 0)/5 = 1.6/5 = 0.32 MPa.

Step 2. RMSE. The squared residuals are 0.04, 0.36, 0.36, 0.04, 0, so SSres=0.8\text{SS}_{\text{res}} = 0.8 and RMSE=0.8/5=0.16=0.4\text{RMSE} = \sqrt{0.8/5} = \sqrt{0.16} = 0.4 MPa.

Step 3. R2R^2. SStot=177.2\text{SS}_{\text{tot}} = 177.2 from the first example, so R2=1−0.8/177.2=0.99549R^2 = 1 - 0.8/177.2 = 0.99549.

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 BB. Dividing S(0.40)=48S(0.40) = 48 by S(0.60)=31S(0.60) = 31 removes AA: 48/31=B0.60−0.40=B0.248/31 = B^{0.60 - 0.40} = B^{0.2}, so

ln⁡B=ln⁡(48/31)0.2=ln⁡1.5483870.2=0.4372140.2=2.186069,    B=e2.186069=8.9002\ln B = \frac{\ln(48/31)}{0.2} = \frac{\ln 1.548387}{0.2} = \frac{0.437214}{0.2} = 2.186069, \;\; B = e^{2.186069} = 8.9002

Step 2. The constant AA. A=48×B0.4=48×e0.4×2.186069=48×e0.874428=115.08A = 48 \times B^{0.4} = 48 \times e^{0.4 \times 2.186069} = 48 \times e^{0.874428} = 115.08 MPa.

Step 3. A prediction. For w/c=0.5w/c = 0.5: S=115.08/e0.5×2.186069=115.08/e1.093034=38.57S = 115.08/e^{0.5 \times 2.186069} = 115.08/e^{1.093034} = 38.57 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 w/c=180/300=0.6w/c = 180/300 = 0.6 but w/b=180/(300+100+50)=180/450=0.4w/b = 180/(300 + 100 + 50) = 180/450 = 0.4. 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 θ\theta 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]:

θ=g(Dtrain),    z=Tθ(x) for training and test data alike\theta = g(D_{\text{train}}), \;\; z = T_{\theta}(x) \text{ for training and test data alike}

For the standard scaler, θ=(μ,σ)\theta = (\mu, \sigma) and Tθ(x)=(x−μ)/σT_{\theta}(x) = (x - \mu)/\sigma. Estimating θ\theta 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. μ=(10+12+14+16+18)/5=14\mu = (10 + 12 + 14 + 16 + 18)/5 = 14 and σ=(16+4+0+4+16)/5=8=2.8284\sigma = \sqrt{(16 + 4 + 0 + 4 + 16)/5} = \sqrt{8} = 2.8284, so the test value becomes z=(30−14)/2.8284=5.6569z = (30 - 14)/2.8284 = 5.6569. It lies more than five standard deviations outside the training data, a clear warning of extrapolation.

Step 2. Leaky scaling. With all six values, μ=100/6=16.6667\mu = 100/6 = 16.6667. 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 σ=253.3334/6=6.4979\sigma = \sqrt{253.3334/6} = 6.4979 and the test value becomes z=(30−16.6667)/6.4979=2.0519z = (30 - 16.6667)/6.4979 = 2.0519.

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.

Open Python step 7 in Colab View the notebook on GitHub

Review cards

Select a card to turn it over.

Supervised learning
Learning a mapping from inputs to known outputs; regression for continuous targets, classification for categories.
k-fold cross-validation
Split training data into k parts; each part validates a model trained on the others; average the scores [5].
Bias and variance
Error from overly simple assumptions versus error from sensitivity to the particular training sample [3].
RMSE
Square root of the mean squared error; in the units of the target; sensitive to large errors.
Data leakage
Information unavailable at prediction time that enters training and inflates scores [17].
Pipeline
scikit-learn object that chains preprocessing and a model so both are fitted only on training data.

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