Fundamentals of AI/ML for Chemical Engineers: Linear Regression, Principal Component Analysis, Validation and Regularisation

Section 1 of the Chemical Engineering paper now ends with "Fundamentals of AI/ML: Linear Regression; Principal Component Analysis (PCA)" — a heading that no chapter in the course taught. Linear regression fits a model ŷ = b₀ + b₁x by least squares: for the five points (1, 2.1), (2, 3.9), (3, 6.2), (4, 7.8), (5, 10.1) the line is ŷ = 0.05 + 1.99x with R² = 0.9973 and a prediction of 11.99 at x = 6. PCA finds the orthogonal directions of greatest variance of multivariate data — the eigenvectors of the covariance (or correlation) matrix — so that a plant with many correlated sensors is described by a few scores: two near-identical temperatures and one pressure give eigenvalues 2.02, 0.98, 0.002, and the first component carries 67.2% of the variance. A model is only as good as its error on data it has not seen: leave-one-out validation of the fitted line gives an RMSE of 0.228.
Overview

Linear Regression by Least Squares

1 min read · 1 part

Supervised learning fits a function to labelled examples; linear regression is its simplest form: ŷ = b₀ + b₁x (or ŷ = Xb for several inputs). The least-squares criterion minimises the sum of squared residuals SS_res = Σ(yᵢ − ŷᵢ)²; setting the derivatives to zero gives the normal equations, b₁ = S_xy/S_xx and b₀ = ȳ − b₁x̄ with S_xy = Σ(x − x̄)(y − ȳ), S_xx = Σ(x − x̄)². For the data x = 1…5, y = 2.1, 3.9, 6.2, 7.8, 10.1: x̄ = 3, ȳ = 6.02, S_xx = 10, S_xy = 19.9, so b₁ = 1.99, b₀ = 0.05. The goodness of fit R² = 1 − SS_res/SS_tot = 1 − 0.107/39.708 = 0.9973 (the fraction of variance explained, and for one input equal to r²). The residual variance s² = SS_res/(n − 2) = 0.0357, and the slope has a standard error √(s²/S_xx) = 0.0597, so the slope is far from zero. Prediction at x = 6 is 11.99 — an interpolation within the data would be safer than this extrapolation.

QuantityFormulaWorked value
SlopeS_xy/S_xx1.99
Interceptȳ − b₁x̄0.05
R²1 − SS_res/SS_tot0.9973
Standard error of slope√(s²/S_xx)0.0597

Supervised learning fits a function to labelled examples; linear regression is its simplest form: ŷ = b₀ + b₁x (or ŷ = Xb for several inputs). The least-squares criterion minimises the sum…

Principal Component Analysis

2 min read · 2 parts

PCA is unsupervised dimension reduction. Centre (and usually scale to unit variance) the data matrix X, form the covariance matrix C = XᵀX/(n − 1), and take its eigen-decomposition: the eigenvectors are the principal directions (loadings), the eigenvalues λ_k the variance along them, and the scores are the projections t_k = Xv_k. The components are orthogonal, ordered by variance, and the explained-variance ratio of component k is λ_k/Σλ. Worked in two dimensions: ten points (2.5, 2.4), (0.5, 0.7), (2.2, 2.9), (1.9, 2.2), (3.1, 3.0), (2.3, 2.7), (2.0, 1.6), (1.0, 1.1), (1.5, 1.6), (1.1, 0.9). The covariance matrix of the centred data is [[0.6166, 0.6154], [0.6154, 0.7166]], with eigenvalues 1.2840 and 0.0491 (so PC1 explains 96.3%) and first eigenvector (0.678, 0.735) (up to sign) — the two variables are strongly correlated and one score describes them almost completely. Total variance = trace of C = sum of eigenvalues, a check that nothing is lost until components are dropped.

Process example. Six readings of three sensors: reactor temperatures T₁ = 300…350 K and T₂ = 301, 311, 319, 332, 339, 352 K (nearly identical), and a pressure P. Standardising each column and taking the correlation matrix gives eigenvalues 2.015, 0.982, 0.002 (sum = 3, the number of variables), so PC1 explains 67.2%, PC2 32.7% and PC3 0.1%; PC1 loads almost equally on T₁ and T₂ (the shared temperature trend) and PC2 mainly on the pressure. Two components describe the plant at 99.9% of the variance — a data-driven basis for fault detection (Hotelling T², the squared prediction error) and for soft sensors. Scaling matters: PCA on raw data is dominated by the variable with the largest units (T in hundreds against P near 1); use correlation-matrix PCA when units differ. The number of components is chosen from the scree plot (the elbow) or by retaining 90–95% of the variance.

PCA stepOperationOutput
1. Centre and scaleSubtract mean; divide by std if units differZ
2. Covariance / correlationC = ZᵀZ/(n − 1)p × p matrix
3. Eigen-decompositionCv = λvLoadings v, variances λ
4. Scorest = ZvReduced coordinates

PCA is unsupervised dimension reduction. Centre (and usually scale to unit variance) the data matrix X, form the covariance matrix C = XᵀX/(n − 1), and take its eigen-decomposition: the…

Validation, Over-Fitting and Regularisation

1 min read · 2 parts

A model must be judged on data it was not trained on. Training error always falls as the model grows more flexible; test error falls then rises — over-fitting (high variance) against under-fitting (high bias), the bias–variance trade-off. Cross-validation splits the data; leave-one-out fits the line n times, each time predicting the omitted point: for the five-point example the PRESS (sum of squared prediction errors) gives RMSE_CV = 0.228, larger than the training residual standard deviation √s² = 0.189, as it should be. Report RMSE or MAE, not R² alone (R² never decreases when a variable is added; adjusted R² corrects for this). Regularisation penalises large coefficients: ridge minimises SS_res + λΣb² and shrinks the slope to S_xy/(S_xx + λ) = 19.9/(10 + 5) = 1.327 (from 1.990) with λ = 5; LASSO uses λΣ|b| and drives small coefficients exactly to zero, selecting variables. Ridge also stabilises regression on collinear inputs (such as the two temperatures above), where plain least squares gives huge, opposite-signed coefficients.

⚠️ Correlation is not causation, and PCA is not a model
A high R² between two plant variables can come from a third variable that drives both, and PCA finds directions of variance, not of relevance to the output — the first component can be useless for predicting yield (principal-component regression and partial least squares address that). Always check the residuals for structure, and never extrapolate far beyond the data.
Ridge versus LASSO
Ridge
  • Penalty λΣb²
  • Shrinks the slope (1.990 to 1.327)
  • Stabilises collinear inputs
LASSO
  • Penalty λΣ|b|
  • Drives small coefficients to zero
  • Selects variables

A model must be judged on data it was not trained on. Training error always falls as the model grows more flexible; test error falls then rises — over-fitting (high variance) against…

Using Regression and PCA on a Process

1 min read · 1 part

A typical workflow:
(1) collect and clean plant data (remove outliers, align time stamps, handle missing values);
(2) explore with scatter plots and a correlation matrix;
(3) reduce with PCA if many sensors are collinear;
(4) fit a regression (linear, or polynomial/non-linear if the residuals curve) and read the coefficients' standard errors;
(5) validate on held-out or cross-validated data;
(6) deploy with monitoring because the process drifts. Examples: a soft sensor predicting product purity from temperature profiles; calibration of an analyser; correlating heat-transfer data as Nu = a·Re^b·Pr^c by linear regression on logarithms (ln Nu = ln a + b ln Re + c ln Pr); the Arrhenius fit ln k = ln A − (E/R)(1/T), whose slope gives −E/R. In each, the regression is linear in the parameters even when the model is non-linear in the variables, which is why the same normal equations apply.

TaskMethodLinearised form
Rate constant vs temperatureArrheniusln k = ln A − (E/R)(1/T)
Heat-transfer correlationPower lawln Nu = ln a + b ln Re + c ln Pr
Many collinear sensorsPCAScores replace sensors
Collinear inputs, predictionRidge / PLSShrunk coefficients
Workflow for regression and PCA on plant data
  1. Collect and cleanOutliers, time stamps, missing values
  2. ExploreScatter plots, correlation matrix
  3. Reduce with PCAIf sensors are collinear
  4. FitRead coefficient standard errors
  5. ValidateHeld-out or cross-validated data
  6. Deploy with monitoringThe process drifts

A typical workflow: (1) collect and clean plant data (remove outliers, align time stamps, handle missing values); (2) explore with scatter plots and a correlation matrix; (3) reduce with…

Key takeaways

  • Least squares: b₁ = S_xy/S_xx, b₀ = ȳ − b₁x̄; R² = 1 − SS_res/SS_tot is the fraction of variance explained; extrapolation is riskier than interpolation.
  • PCA: centre (and scale), eigen-decompose the covariance/correlation matrix; eigenvectors are loadings, eigenvalues are variances, explained ratio λ_k/Σλ; scores t = Zv.
  • Use correlation-matrix PCA when units differ; choose components from the scree plot or 90–95% variance.
  • Judge models on unseen data: cross-validation, RMSE, adjusted R²; ridge shrinks coefficients (S_xy/(S_xx + λ)) and LASSO zeroes some.
  • Regression is linear in the parameters, so Arrhenius and power-law correlations are fitted on logarithms.

Practice questions (24)

Attempt each one before opening the answer. Every explanation names the tempting wrong option as well as the right one, because that is where marks are lost.

  1. Fit a least-squares line to (1, 2.1), (2, 3.9), (3, 6.2), (4, 7.8), (5, 10.1). The slope is (two decimals):

    Numerical answer — type the value.

    Show answer

    Answer: 1.99

    x̄ = 3, ȳ = 6.02, S_xx = 10, S_xy = 19.9; b₁ = 19.9/10 = 1.99 and b₀ = 6.02 − 1.99 × 3 = 0.05.
  2. For the same data the fitted value at x = 6 (extrapolation), to two decimals, is:

    Numerical answer — type the value.

    Show answer

    Answer: 11.99

    ŷ = 0.05 + 1.99 × 6 = 11.99. Predictions this far from the data centre have wider uncertainty than those inside the range.
  3. R² = 0.9 for a fitted regression means:

    1. 90% of the variance of y is explained by the model
    2. there is a 90% chance of causation
    3. the slope is 0.9
    4. the model is correct 90% of the time
    Show answer

    Answer: A — 90% of the variance of y is explained by the model

    R² = 1 − SS_res/SS_tot is the explained fraction of variance; it says nothing about causation, correct form or predictive error on new data.
Show the other 21 questions
  1. In PCA, the first principal component is:

    1. the line that best predicts the output
    2. the variable with the largest mean
    3. the direction (eigenvector of the covariance matrix) along which the data have the largest variance
    4. the eigenvector with the smallest eigenvalue
    Show answer

    Answer: C — the direction (eigenvector of the covariance matrix) along which the data have the largest variance

    PCA is unsupervised: it ranks directions by variance (eigenvalue), not by relevance to any output. The largest eigenvalue belongs to PC1.
  2. For the ten-point two-variable data set given in the chapter (centred), the eigenvalues of the covariance matrix are 1.2840 and 0.0491. The percentage of variance explained by PC1 (one decimal) is:

    Numerical answer — type the value.

    Show answer

    Answer: 96.3

    λ₁/(λ₁ + λ₂) = 1.2840/(1.2840 + 0.0491) = 96.3%.
  3. When variables in a plant data set have different units (for example temperature in K and pressure in bar), PCA should normally be done on:

    1. the correlation matrix (standardised variables)
    2. only the variable with the largest mean
    3. the inverse of the data matrix
    4. the raw covariance matrix
    Show answer

    Answer: A — the correlation matrix (standardised variables)

    Raw covariance PCA is dominated by the variable with the largest numerical variance (T in hundreds of K); standardising puts every variable on equal footing.
  4. A ridge regression with penalty λ = 5 is fitted to the five-point data (S_xx = 10, S_xy = 19.9 on centred data). The ridge slope S_xy/(S_xx + λ) is (three decimals):

    Numerical answer — type the value.

    Show answer

    Answer: 1.327

    19.9/(10 + 5) = 1.327, down from the least-squares slope 1.99 — shrinkage trades a little bias for lower variance.
  5. Which statements about validating regression models are correct?

    1. A perfect fit to the training data guarantees good predictions
    2. Cross-validation estimates error on unseen data
    3. Training error always decreases as model flexibility increases
    4. LASSO can drive some coefficients exactly to zero
    Show answer

    Answer: B — Cross-validation estimates error on unseen data; C — Training error always decreases as model flexibility increases; D — LASSO can drive some coefficients exactly to zero

    A perfect training fit often means over-fitting noise; only error on held-out data tells you about prediction.
  6. To fit the correlation Nu = a Re^b Pr^c by linear regression, the model is linearised by taking:

    1. reciprocals of Nu only
    2. logarithms: ln Nu = ln a + b ln Re + c ln Pr
    3. square roots of every variable
    4. no change: it is already linear
    Show answer

    Answer: B — logarithms: ln Nu = ln a + b ln Re + c ln Pr

    A power law is linear in the logarithms, with ln a, b and c as the linear parameters, so ordinary least squares applies.
  7. A fitted model predicts ŷ = 4.2 at a point where the measured value is y = 5. The residual y − ŷ (one decimal) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.8

    Residual = observed − predicted = 5 − 4.2 = 0.8. Writing −0.8 uses predicted − observed; least squares minimises the sum of squared residuals, so the sign convention matters only for plots.
  8. A regression has residual sum of squares 2 and total sum of squares (about the mean) 20. Its R² (one decimal) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.9

    R² = 1 − SS_res/SS_tot = 1 − 0.1 = 0.9. Reporting 0.1 gives the unexplained fraction instead of the explained one.
  9. A covariance matrix has eigenvalues 4 and 1. The fraction of total variance captured by the first principal component (one decimal) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.8

    Total variance = trace = 4 + 1 = 5, so PC1 explains 4/5 = 0.8. Dividing 4 by 1 compares the two components instead of measuring PC1 against the whole.
  10. The principal components obtained from a covariance matrix are

    1. mutually orthogonal, so their scores are uncorrelated
    2. ordered by increasing variance
    3. dependent on the order of the samples
    4. always aligned with the original variables
    Show answer

    Answer: A — mutually orthogonal, so their scores are uncorrelated

    They are eigenvectors of a symmetric matrix, hence orthogonal, and are ordered by DECREASING variance. They are generally rotated away from the original axes, and shuffling samples leaves the covariance unchanged.
  11. A model with very low training error but high error on new validation data is said to be

    1. over-fitted
    2. well regularised
    3. unbiased and low-variance
    4. under-fitted
    Show answer

    Answer: A — over-fitted

    It has learned the noise of the training set (high variance). An under-fitted model is poor on BOTH sets; regularisation is the remedy for over-fitting, not its description.
  12. For the data (1, 1), (2, 3), (3, 4), (4, 6), the least-squares line ŷ = a + bx has intercept a = ____ (one decimal).

    Numerical answer — type the value.

    Show answer

    Answer: -0.5

    x̄ = 2.5, ȳ = 3.5, S_xy = 8, S_xx = 5, so b = 1.6 and a = ȳ − bx̄ = 3.5 − 4 = −0.5. Taking the first data point (a = 1 − 1.6 = −0.6) forces the line through one point rather than through the centroid.
  13. For the covariance matrix [[2, 1], [1, 2]], the fraction of variance explained by the first principal component (two decimals) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.75

    Eigenvalues are 3 and 1 (trace 4), so PC1 explains 3/4 = 0.75. Reading 2/4 = 0.50 from the diagonal ignores the covariance, which is exactly what PCA exploits.
  14. Leave-one-out cross-validation is applied to a data set of 50 samples. How many times is the model fitted? ____

    Numerical answer — type the value.

    Show answer

    Answer: 50

    Each sample is held out once while the model is fitted to the other 49, giving 50 fits. Answering 49 confuses the training-set size with the number of folds.
  15. A model's validation residuals are 1, −1, 2 and −2. The root-mean-square error (three decimals) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 1.581

    MSE = (1 + 1 + 4 + 4)/4 = 2.5 and RMSE = √2.5 = 1.581. Averaging the signed residuals gives 0, which hides the error completely.
  16. The model y = a·e^(bx) is linearised as ln y = ln a + bx, and the fit gives ln y = 0.693 + 0.5x. The value of a (two decimals) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 2.00

    a = e^0.693 = 2.00 (and b = 0.5). Reporting 0.69 takes the intercept itself, which is ln a, not a. Substituting the answer back into the relation confirms it.
  17. A regression with 3 predictors fitted to 20 observations gives R² = 0.9. The adjusted R², 1 − (1 − R²)(n − 1)/(n − p − 1), to four decimals, is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.8813

    1 − 0.1 × 19/16 = 1 − 0.11875 = 0.8813. Using n − p (17) in the denominator gives 0.8882; the extra 1 accounts for the fitted intercept.
  18. For the covariance matrix [[2, 1], [1, 2]], the first principal component has unit-length loading vector (w, w). The value of w (four decimals) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.7071

    The eigenvector for λ = 3 is along (1, 1); normalising gives w = 1/√2 = 0.7071. Answering 1 forgets to normalise, and 0.5 normalises the sum instead of the length.
  19. For the data (1, 1), (2, 3), (3, 4), (4, 6), the Pearson correlation coefficient r (four decimals) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.9923

    S_xy = 8, S_xx = 5, S_yy = 13, so r = 8/√65 = 0.9923 and R² = r² = 0.9846 for this straight-line fit. Quoting R² as r confuses the two by squaring.
  20. Two standardised variables have correlation 0.6, so their correlation matrix is [[1, 0.6], [0.6, 1]]. The fraction of variance explained by PC1 (one decimal) is ____.

    Numerical answer — type the value.

    Show answer

    Answer: 0.8

    Eigenvalues are 1 ± ρ = 1.6 and 0.4, total 2, so PC1 explains 0.8. Answering 0.6 takes the correlation itself as the explained fraction.
  21. Which statements about regression fitting and regularisation are correct?

    1. The lasso penalty can never make a coefficient exactly zero.
    2. Increasing the ridge penalty λ shrinks the coefficients towards zero.
    3. In ordinary least squares, adding a predictor never lowers the training R².
    4. Cross-validation estimates how well the model will predict new data.
    Show answer

    Answer: B — Increasing the ridge penalty λ shrinks the coefficients towards zero.; C — In ordinary least squares, adding a predictor never lowers the training R².; D — Cross-validation estimates how well the model will predict new data.

    Ridge minimises SSE + λΣβ², shrinking coefficients; CV mimics unseen data; OLS with an extra column can only reduce SSE. The L1 (lasso) penalty is exactly what sets some coefficients to zero, which is its use for variable selection, so the last statement is the trap.