Skip to content
New
Latest News || 27 October 2026: Dr Soumava Mukherjee's invited talk at Queen's University Belfast joined device-level hardware innovation with channel-level control. || 22 October 2026: I received a Certificate of Appreciation for serving as a reviewer for IEEE IMAS 2026. || 15 October 2026: I presented a poster on beam-domain ML fingerprinting for RIS-aided mmWave localisation at the Centre for Wireless Innovation's annual symposium. || 15 October 2026: CWI's annual symposium brought research and industry perspectives on 6G, ISAC, optical wireless, AI, and future networks to Queen's University Belfast. || 14 October 2026: Erik Nordell of Ericsson visited our Keysight Lab for a live RIS-assisted video streaming demonstration.
Knowledge Hubmachine learning6. Regression Algorithms

machine learning learning note

6. Regression Algorithms

A deeper explanation of regression models for predicting continuous values, with intuition, assumptions, and practical guidance.

At a glance

  • Predict a quantityRegressors output numbers. Linear, polynomial and local-neighbour fits make different shape assumptions.
  • Report errors in useful unitsMAE and RMSE use target units; MSE uses squared units. Large misses weigh more strongly in MSE/RMSE.
  • Tune flexibility using validationExtra polynomial powers can fit noise. Keep preprocessing and model selection away from the final test data.

What is Regression?

Regression is a supervised learning task where the target is a continuous numerical value. Instead of predicting a class such as "spam" or "not spam", a regression model predicts a quantity.

Examples:

  • House price in pounds.
  • Temperature tomorrow.
  • Received signal strength.
  • Localization error in meters.
  • Battery lifetime in hours.

The central question is: "Given these input features, what number should the model predict?"

References for this section3

Regression vs. Classification

QuestionTask
Is this email spam?Classification
What is the price of this house?Regression
Which modulation type is this?Classification
What is the expected channel gain?Regression
References for this section3

1. Linear Regression

Linear regression is the simplest and most interpretable regression model. It assumes the output can be approximated by a weighted sum of the input features.

Least squares: which line has the smallest total square area?

1. Formula and symbols
y^=β0+β1x,SSE=∑i=1n(yi−y^i)2\widehat y=\beta_0+\beta_1x,\qquad\mathrm{SSE}=\sum_{i=1}^{n}(y_i-\widehat y_i)^2
β1⋆=∑i(xi−xˉ)(yi−yˉ)∑i(xi−xˉ)2,β0⋆=yˉ−β1⋆xˉ\beta_1^{\star}=\frac{\sum_i(x_i-\bar x)(y_i-\bar y)}{\sum_i(x_i-\bar x)^2},\qquad\beta_0^{\star}=\bar y-\beta_1^{\star}\bar x
  • xx: log₁₀(distance / 10 m): 0 at 10 m, 1 at 100 m
  • yy: Measured received power in dBm
  • β0\beta_0: Intercept: predicted power at 10 m
  • β1\beta_1: Slope in dB per decade of distance
  • SSE\mathrm{SSE}: Sum of squared errors: the total area of the residual squares
  • xˉ, yˉ\bar x,\ \bar y: Means of the inputs and targets
  • β⋆\beta^{\star}: Least-squares solution: the line with the smallest SSE

A slope of β₁ dB per decade corresponds to a path-loss exponent of −β₁/10.

10 m31.6 m100 m-80-60-40Distance (log scale)Received power (dBm)— your line- - least squares● measurement□ squared residualarea = (miss)²Total square areayoursbestbest = 19% of yours
2. Work with the current inputs
SSEyours=∑i(yi−(−52.0−15xi))2=534.3 dB2\mathrm{SSE}_{\rm yours}=\sum_i\big(y_i-(-52.0-15x_i)\big)^2=534.3\ \mathrm{dB^2}
β1⋆=−30.391.009=−30.12,β0⋆=−63.66−(−30.12)(0.502)=−48.54\beta_1^\star=\frac{-30.39}{1.009}=-30.12,\quad\beta_0^\star=-63.66-(-30.12)(0.502)=-48.54
SSE⋆=99.1 dB2,R2=1−SSE⋆∑i(yi−yˉ)2=0.902\mathrm{SSE}^\star=99.1\ \mathrm{dB^2},\quad R^2=1-\frac{\mathrm{SSE}^\star}{\sum_i(y_i-\bar y)^2}=0.902
3. Result
Your total square area (SSE)534.3 dB²5.39 × the minimum
Least-squares SSE99.1 dB²
Best slope → path-loss exponent-30.1 dB/dec → n = 3.01
Twelve illustrative received-power measurements against log-distance. Each orange square has a side equal to the vertical miss (residual) of your line, so its area is that point’s squared error. Move the slope and intercept to shrink the total area; the dashed teal line is the exact least-squares answer. One big miss costs more than two half-size misses, because area grows with the square.
References for this section3

Intuition

For one feature:

y^=β0+β1x\widehat y=\beta_0+\beta_1x
  • y^\widehat y is the predicted output
  • xx: input feature.
  • β1\beta _{1}: learned slope.
  • β0\beta _{0}: intercept.

For many features:

y^=β0+∑j=1pβjxj\widehat y=\beta_0+\sum_{j=1}^{p}\beta_jx_j
  • xjx_{j}: input feature j.
  • βj\beta _{j}: learned weight for feature j.
  • pp: number of features.
  • β0\beta _{0} remains the intercept.

Training finds weights that minimize the difference between predicted and true values, often using mean squared error.

References for this section3

Strengths

  • Very fast.
  • Easy to interpret.
  • Good baseline.
  • Can extrapolate outside the training range.
References for this section3

Weaknesses

  • Assumes a mostly linear relationship.
  • Sensitive to outliers.
  • Cannot naturally model complex feature interactions.
References for this section3

Best Use Cases

  • Quick baselines.
  • Scientific modeling where interpretability matters.
  • Problems with approximately linear relationships.
References for this section3

2. Ridge and Lasso Regression

Ridge and Lasso are regularized versions of linear regression. They add a penalty to discourage overly large weights.

Ridge shrinks, lasso selects: follow the coefficient paths

1. Formula and symbols
Ridge: min⁡β 12n∥y−Xβ∥2+λ2∥β∥22 ⇒ (1nX⊤X+λI)β=1nX⊤y\text{Ridge: }\min_\beta\ \frac1{2n}\lVert y-X\beta\rVert^2+\frac\lambda2\lVert\beta\rVert_2^2\ \Rightarrow\ \Big(\tfrac1nX^\top X+\lambda I\Big)\beta=\tfrac1nX^\top y
Lasso: min⁡β 12n∥y−Xβ∥2+λ∥β∥1,βj←Sλ(ρj)1n∥xj∥2,  Sλ(ρ)=sign⁡(ρ)max⁡(∣ρ∣−λ,0)\text{Lasso: }\min_\beta\ \frac1{2n}\lVert y-X\beta\rVert^2+\lambda\lVert\beta\rVert_1,\qquad\beta_j\leftarrow\frac{S_\lambda(\rho_j)}{\tfrac1n\lVert x_j\rVert^2},\ \ S_\lambda(\rho)=\operatorname{sign}(\rho)\max(|\rho|-\lambda,0)
  • XX: Matrix of 5 standardised features for n = 40 examples
  • yy: Centred targets
  • βj\beta_j: Coefficient of feature j
  • λ\lambda: Regularisation strength
  • ∥β∥22\lVert\beta\rVert_2^2: Sum of squared coefficients (ridge penalty)
  • ∥β∥1\lVert\beta\rVert_1: Sum of absolute coefficients (lasso penalty)
  • ρj\rho_j: Correlation of feature j with the residual that excludes feature j
  • SλS_\lambda: Soft-threshold: anything smaller than λ becomes exactly zero

The data were generated from β = (3, −2, 0, 1.5, 0) with correlated features 1, 3 and 5, so features 3 and 5 are decoys.

Ridge (L2)−3−10.5-202log₁₀ λ → stronger penaltyLasso (L1)−3−10.5-202log₁₀ λ → stronger penaltyβ1β2β3 (decoy)β4β5 (decoy)
2. Work with the current inputs
βridge=(2.39, −1.69, 0.36, 1.35, −0.04),∥β∥2=3.246\beta_{\rm ridge}=(2.39,\ -1.69,\ 0.36,\ 1.35,\ -0.04),\quad\lVert\beta\rVert_2=3.246
βlasso=(2.81, −1.74, 0.00, 1.43, 0.00),∥β∥1=5.975\beta_{\rm lasso}=(2.81,\ -1.74,\ 0.00,\ 1.43,\ 0.00),\quad\lVert\beta\rVert_1=5.975
βtrue=(3, −2, 0, 1.5, 0),λ=0.1000\beta_{\rm true}=(3,\ -2,\ 0,\ 1.5,\ 0),\quad\lambda=0.1000
3. Result
Lasso non-zero coefficients3 of 5zeroed: β3, β5
Ridge non-zero coefficients5 of 5smallest |β| = 0.037
Five standardised features; the true model uses features 1, 2 and 4 only. Each curve shows one coefficient as λ grows from left to right; the orange line marks your λ. Ridge pulls every coefficient smoothly towards zero but keeps them all. Lasso drives the decoy features 3 and 5 to exactly zero first, then the weaker true ones: it performs feature selection.
References for this section3

Ridge Regression

Ridge uses an L2 penalty. It shrinks weights smoothly and is useful when many features are correlated.

Equation-style view:

min⁡β0,β∑i(yi−y^i)2\min_{\beta_0,\beta}\sum_i(y_i-\widehat y_i)^2
  • yiy_{i}: measured target for sample i.
  • y^i\widehat y_i: model prediction for sample i.
  • ∑i\sum _{i} adds squared errors across samples.
min⁡β0,β[∑i(yi−y^i)2+λ∑j=1pβj2]\min_{\beta_0,\beta}\left[\sum_i(y_i-\widehat y_i)^2+\lambda\sum_{j=1}^p\beta_j^2\right]
  • ∑i(yi−y^i)2\sum _{i}(y_{i} - \widehat y_{i})^2 measures fit error
  • λ∑jβj2\lambda \sum _{j}\beta _{j}^2 penalizes large feature weights.
  • λ≥0\lambda ≥ 0 controls penalty strength; the intercept is normally excluded from the penalty.

In simple words, Ridge fits the data while keeping the weights from becoming unnecessarily large. This often makes the model more stable on new data.

References for this section3

Lasso Regression

Lasso uses an L1 penalty. It can push some weights exactly to zero, which makes it useful for feature selection.

min⁡β0,β[∑i(yi−y^i)2+λ∑j=1p∣βj∣]\min_{\beta_0,\beta}\left[\sum_i(y_i-\widehat y_i)^2+\lambda\sum_{j=1}^p\lvert\beta_j\rvert\right]
  • ∑i(yi−y^i)2\sum _{i}(y_{i} - \widehat y_{i})^2 measures fit error
  • λ∑j∣βj∣\lambda \sum _{j}|\beta _{j}| penalizes absolute feature weights.
  • λ≥0\lambda ≥ 0 controls penalty strength; the intercept is normally excluded.
References for this section3

Why Regularization Matters

Without regularization, a model may fit noise in the training data. Regularization constrains the fit and can improve generalization; select its strength using validation.

References for this section3

3. K-Nearest Neighbors Regressor

KNN regression predicts a number by averaging the target values of nearby training examples.

References for this section3

Intuition

If a new house is similar to five nearby houses in the dataset, KNN predicts the average price of those five houses.

References for this section3

Strengths

  • Simple and non-parametric.
  • Can model non-linear relationships.
  • No explicit training phase.
References for this section3

Weaknesses

  • Slow prediction for large datasets.
  • Sensitive to feature scaling.
  • Performs poorly when irrelevant features dominate distance.
References for this section3

Best Use Cases

  • Small datasets.
  • Local interpolation problems.
  • Situations where similar inputs should have similar outputs.
References for this section3

4. Polynomial Regression

Polynomial regression extends linear regression by adding powers of features, such as x^2, x^3, and interactions.

References for this section3

Intuition

A straight line cannot fit a curved trend. Polynomial features allow a linear model to fit curves.

y^=β0+β1x+β2x2+β3x3\widehat y=\beta_0+\beta_1x+\beta_2x^2+\beta_3x^3
  • xx: original input feature.
  • x2x^2: squared input feature.
  • x3x^3: cubed input feature.
  • β1\beta _{1}: learned coefficient of the first feature.
  • β2\beta _{2}: learned coefficient of the second feature.
  • β3\beta _{3}: learned coefficient of the third feature.
  • β0\beta _{0}: intercept.
References for this section3

Strengths

  • Captures simple curves.
  • Still relatively interpretable.
  • Easy to implement.
References for this section3

Weaknesses

  • High-degree polynomials can overfit badly.
  • Extrapolation can become unrealistic.
  • Feature scaling becomes important.
References for this section3

5. Support Vector Regression

Support Vector Regression (SVR) is related to SVM classification. Instead of separating classes, it tries to fit a function while ignoring small errors inside a margin.

Support vector regression: a tube that ignores small misses

1. Formula and symbols
min⁡w,b 12w2+C∑i=1nmax⁡(0, ∣yi−(wxi+b)∣−ε)\min_{w,b}\ \tfrac12w^2+C\sum_{i=1}^{n}\max\big(0,\ |y_i-(wx_i+b)|-\varepsilon\big)
OLS for comparison: min⁡w,b ∑i(yi−(wxi+b))2\text{OLS for comparison: }\min_{w,b}\ \sum_i\big(y_i-(wx_i+b)\big)^2
  • w, bw,\ b: Slope and intercept of the fitted line
  • ε\varepsilon: Half-width of the tube: misses smaller than ε cost nothing
  • CC: Cost per unit of miss beyond the tube
  • max⁡(0,∣r∣−ε)\max(0,|r|-\varepsilon): ε-insensitive loss: grows linearly, not quadratically

Targets are standardised before fitting (so w² and the loss have comparable scales); the line is drawn back in dBm.

10 m31.6 m100 m-80-60-40Distance (log scale)Received power (dBm)— SVR line▭ tube ±ε- - least squares● outside tube◯ outlier
2. Work with the current inputs
SVR: y=−53.42−19.30x,points outside tube=6\text{SVR: }y=-53.42-19.30x,\quad\text{points outside tube}=6
OLS: y=−49.67−24.88x\text{OLS: }y=-49.67-24.88x
standardised: yˉ=−62.16, sy=9.08, ε/sy=0.330, C=3.16\text{standardised: }\bar y=-62.16,\ s_y=9.08,\ \varepsilon/s_y=0.330,\ C=3.16
3. Result
SVR slope-19.3 dB/dec
OLS slope-24.9 dB/decpulled by the outlier
Points outside the tube6 of 12these are the support vectors
The same twelve power measurements, with one point (ringed) pushed up as an outlier. SVR fits a line with a tube of half-width ε: points inside cost nothing, points outside (orange) pay linearly. Ordinary least squares (dashed) pays the square of every miss, so the outlier drags it more. Wider ε means fewer points outside and a flatter, more tolerant fit.
References for this section3

Intuition

SVR draws a tube around the prediction function. Errors inside the tube are acceptable. The model focuses mainly on points outside the tube.

References for this section3

Strengths

  • Robust to small noise.
  • Kernel functions allow non-linear regression.
  • Useful for medium-sized datasets.
References for this section3

Weaknesses

  • Can be slow for large datasets.
  • Requires tuning kernel, margin, and regularization parameters.
  • Less interpretable than linear regression.
References for this section3

6. Decision Tree Regressor

A decision tree regressor splits the feature space into regions and predicts the average target value in each region.

A regression tree predicts with flat steps

1. Formula and symbols
split s⋆=arg⁡min⁡s[∑xi≤s(yi−yˉL)2+∑xi>s(yi−yˉR)2]\text{split }s^\star=\arg\min_s\Big[\sum_{x_i\le s}(y_i-\bar y_L)^2+\sum_{x_i>s}(y_i-\bar y_R)^2\Big]
leaf value=yˉleaf=1nleaf∑i∈leafyi,f^forest(x)=1T∑t=1Tf^t(x)\text{leaf value}=\bar y_{\rm leaf}=\frac1{n_{\rm leaf}}\sum_{i\in\rm leaf}y_i,\qquad\widehat f_{\rm forest}(x)=\frac1T\sum_{t=1}^T\widehat f_t(x)
  • ss: Candidate threshold on x
  • yˉL, yˉR\bar y_L,\ \bar y_R: Mean target left and right of the split
  • nleafn_{\rm leaf}: Training points in a leaf (at least 2 here)
  • f^t\widehat f_t: Tree t, grown on its own bootstrap sample
  • TT: Number of trees in the forest

30 training and 60 validation points from the dashed curve plus Gaussian noise (σ = 0.18).

00.51-101input xtarget y— prediction- - true curve● training○ validation
2. Work with the current inputs
splits at x=0.07, 0.13, 0.37, 0.50, 0.87, 0.93\text{splits at }x=0.07,\ 0.13,\ 0.37,\ 0.50,\ 0.87,\ 0.93
MSEtrain=0.0211,MSEval=0.0682\mathrm{MSE}_{\rm train}=0.0211,\quad\mathrm{MSE}_{\rm val}=0.0682
3. Result
Validation MSE0.0682
Training MSE0.0211
Leaves (steps)7
Each split cuts the x-axis where the two sides become most uniform, and each leaf predicts the mean of its points. More depth gives more, narrower steps: training error keeps falling, but validation error stops improving once the steps start chasing noise.
References for this section3

Intuition

For house prices, a tree may first split by location, then by area, then by number of rooms. Each final leaf stores an average price.

References for this section3

Strengths

  • Handles non-linear relationships.
  • Easy to visualize.
  • Minimal preprocessing.
References for this section3

Weaknesses

  • Can overfit if too deep.
  • Predictions are piecewise constant.
  • Single trees are unstable.
References for this section3

7. Random Forest Regressor

Random forest regression averages predictions from many decision trees.

A random forest averages many step functions

1. Formula and symbols
split s⋆=arg⁡min⁡s[∑xi≤s(yi−yˉL)2+∑xi>s(yi−yˉR)2]\text{split }s^\star=\arg\min_s\Big[\sum_{x_i\le s}(y_i-\bar y_L)^2+\sum_{x_i>s}(y_i-\bar y_R)^2\Big]
leaf value=yˉleaf=1nleaf∑i∈leafyi,f^forest(x)=1T∑t=1Tf^t(x)\text{leaf value}=\bar y_{\rm leaf}=\frac1{n_{\rm leaf}}\sum_{i\in\rm leaf}y_i,\qquad\widehat f_{\rm forest}(x)=\frac1T\sum_{t=1}^T\widehat f_t(x)
  • ss: Candidate threshold on x
  • yˉL, yˉR\bar y_L,\ \bar y_R: Mean target left and right of the split
  • nleafn_{\rm leaf}: Training points in a leaf (at least 2 here)
  • f^t\widehat f_t: Tree t, grown on its own bootstrap sample
  • TT: Number of trees in the forest

30 training and 60 validation points from the dashed curve plus Gaussian noise (σ = 0.18).

00.51-101input xtarget y— prediction- - true curve● training○ validation— single trees
2. Work with the current inputs
f^(0.5)=115∑tf^t(0.5)=0.251\widehat f(0.5)=\frac1{15}\sum_t\widehat f_t(0.5)=0.251
MSEtrain=0.0151,MSEval=0.0548\mathrm{MSE}_{\rm train}=0.0151,\quad\mathrm{MSE}_{\rm val}=0.0548
3. Result
Validation MSE0.0548one tree alone: 0.0770
Training MSE0.0151
Trees averaged15
Each faint line is one tree trained on a bootstrap sample; the thick line is their average. Individual trees are jumpy and disagree, but their errors partly cancel, so the average is smoother and validates better than one tree. A forest still cannot extrapolate beyond the training range: outside it, the prediction stays flat.
References for this section3

Intuition

Each tree makes a different estimate. Averaging many trees reduces variance and gives a more stable prediction.

References for this section3

Strengths

  • Strong tabular-data baseline.
  • Handles feature interactions.
  • Less overfitting than one decision tree.
  • Works with minimal preprocessing.
References for this section3

Weaknesses

  • Less interpretable than one tree.
  • Cannot extrapolate beyond the training target range.
  • Larger memory footprint.
References for this section3

8. Gradient Boosting and XGBoost Regressor

Gradient boosting builds trees sequentially. Each new tree learns to correct the residual errors of the current model.

Gradient boosting: each new tree fixes the remaining errors

1. Formula and symbols
F0(x)=yˉ,ri(m)=yi−Fm−1(xi)F_0(x)=\bar y,\qquad r_i^{(m)}=y_i-F_{m-1}(x_i)
hm=small tree fitted to {(xi,ri(m))},Fm(x)=Fm−1(x)+ν hm(x)h_m=\text{small tree fitted to }\{(x_i,r_i^{(m)})\},\qquad F_m(x)=F_{m-1}(x)+\nu\,h_m(x)
  • FmF_m: Model after m boosting stages
  • yˉ\bar y: Mean training target: the starting guess
  • ri(m)r_i^{(m)}: Residual: what the model still gets wrong at stage m
  • hmh_m: Shallow tree that predicts those residuals
  • ν\nu: Learning rate (shrinkage): how much of each correction is added

For squared loss the residual is exactly the negative gradient, which is why this is called gradient boosting.

-101prediction F_m01input xresiduals r⁽6⁾ and new tree h_606012000.2stages mMSE— train- - validation◯ best stage (lowest validation)
2. Work with the current inputs
F0=yˉ=0.305,F6(0.5)=0.389F_0=\bar y=0.305,\quad F_{6}(0.5)=0.389
MSEtrain(m=6)=0.0751,MSEval(m=6)=0.0956\mathrm{MSE}_{\rm train}(m=6)=0.0751,\quad\mathrm{MSE}_{\rm val}(m=6)=0.0956
best validation: m=47, MSEval=0.0571\text{best validation: }m=47,\ \mathrm{MSE}_{\rm val}=0.0571
3. Result
Validation MSE now0.0956
Training MSE now0.0751
Best stage (early stop)m = 47validation MSE 0.0571
Top left: the boosted prediction after m stages (thick) and after m − 1 stages (faint). Bottom left: the residuals the newest tree was trained on (bars) and that tree’s steps (orange). Right: error against the number of stages. Training error keeps falling towards zero, but validation error reaches a minimum and then rises: too many stages overfit, so stop early.
References for this section3

Intuition

If the model underpredicts one group of samples, the next tree focuses on reducing that underprediction. Over many rounds, the model becomes a strong predictor.

References for this section3

Strengths

  • Often excellent on structured data.
  • Captures non-linear relationships.
  • Works well with mixed feature types.
  • XGBoost adds regularization and scalable training.
References for this section3

Weaknesses

  • Needs careful tuning.
  • Can overfit if trees are too deep or learning rate is too large.
  • Training is more sequential than random forest.
References for this section3

Regression Metrics

MAE, RMSE and R²: how one bad point moves each metric

1. Formula and symbols
MAE=1n∑i∣yi−y^i∣,MSE=1n∑i(yi−y^i)2,RMSE=MSE\mathrm{MAE}=\frac1n\sum_i|y_i-\widehat y_i|,\qquad\mathrm{MSE}=\frac1n\sum_i(y_i-\widehat y_i)^2,\qquad\mathrm{RMSE}=\sqrt{\mathrm{MSE}}
R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2=1-\frac{\sum_i(y_i-\widehat y_i)^2}{\sum_i(y_i-\bar y)^2}
  • yiy_i: Measured value of example i
  • y^i\widehat y_i: Prediction for example i
  • yˉ\bar y: Mean of the measured values
  • nn: Number of examples (12)
  • R2R^2: Fraction of the variance explained by the model (1 is perfect, 0 is no better than the mean)

MAE and RMSE share the target’s unit (dB); MSE is in dB². The least-squares line is refitted after every change.

10 m31.6 m100 m-80-60-40Distance (log scale)Received power (dBm)0510error in dB2.3MAE2.9RMSER² = 0.902
2. Work with the current inputs
MAE=112∑∣ri∣=2.27 dB,MSE=8.26 dB2,RMSE=8.26=2.87 dB\mathrm{MAE}=\tfrac1{12}\textstyle\sum|r_i|=2.27\ \mathrm{dB},\quad\mathrm{MSE}=8.26\ \mathrm{dB^2},\quad\mathrm{RMSE}=\sqrt{8.26}=2.87\ \mathrm{dB}
R2=1−8.2684.55=0.902,max⁡i∣ri∣=5.38 dBR^2=1-\frac{8.26}{84.55}=0.902,\quad\max_i|r_i|=5.38\ \mathrm{dB}
3. Result
MAE2.27 dB
RMSE2.87 dBRMSE / MAE = 1.27
R²0.902
The same twelve power measurements with a least-squares line. Push one point (ringed) away and watch the metrics. MAE grows in proportion to the miss; RMSE squares it first, so it jumps faster and is more sensitive to rare large errors. R² compares the error to the spread of the data, so it is unitless.
References for this section3

Mean Absolute Error

Mean Absolute Error (MAE) is the average absolute difference between prediction and true value. It is easy to interpret because it uses the same unit as the target.

MAE=1n∑i=1n∣yi−y^i∣\mathrm{MAE}=\frac1n\sum_{i=1}^n\lvert y_i-\widehat y_i\rvert
  • nn is sample count
  • yi−y^iy_{i} - \widehat y_{i} is sample i's prediction error; absolute value prevents opposite errors cancelling.
References for this section3

Mean Squared Error

Mean Squared Error (MSE) squares the errors before averaging. Large errors are punished more strongly.

MSE=1n∑i=1n(yi−y^i)2\mathrm{MSE}=\frac1n\sum_{i=1}^n(y_i-\widehat y_i)^2
  • nn is sample count
  • yiy_{i} is measured and ŷᵢ predicted; squaring emphasizes larger errors.
References for this section3

Root Mean Squared Error

Root Mean Squared Error (RMSE) is the square root of MSE. It is also in the same unit as the target.

RMSE=1n∑i=1n(yi−y^i)2\mathrm{RMSE}=\sqrt{\frac1n\sum_{i=1}^n(y_i-\widehat y_i)^2}
  • nn is sample count
  • yi−y^iy_{i} - \widehat y_{i} is each error; the square root returns the metric to the target's unit.
References for this section3

R-squared

R-squared measures how much variance in the target is explained by the model. It is useful, but it should not be the only metric.

R2=1−∑i(yi−y^i)2∑i(yi−yˉ)2R^2=1-\frac{\sum_i(y_i-\widehat y_i)^2}{\sum_i(y_i-\bar y)^2}
  • yiy_{i}: measured target for sample i.
  • y^i\widehat y_i: prediction for sample i.
  • yˉ\bar y: mean measured target over the evaluation set.
  • The numerator is model squared error; the denominator is squared error from always predicting the mean.
References for this section3

Practical Checklist

  • Plot predicted values vs. true values.
  • Check residuals for patterns.
  • Scale features for KNN, SVR, linear models, and neural networks.
  • Use cross-validation when data is limited.
  • Compare against a simple baseline, such as predicting the mean.
  • Watch out for outliers, data leakage, and target leakage.

Which fitted shape follows this numeric target?

1. Formula and symbols
y^(x)=∑j=0pβjxj\widehat y(x)=\sum_{j=0}^{p}\beta_jx^j
(XTX+λP)β=XTy,P=diag⁡(0,1,…,1)(X^TX+\lambda P)\beta=X^Ty,\quad P=\operatorname{diag}(0,1,\ldots,1)
MSE=1N∑i(y^i−yi)2\mathrm{MSE}=\frac1N\sum_i(\widehat y_i-y_i)^2
  • pp: degree
  • XX: polynomial design matrix
  • β\beta: learned coefficients
  • yy: training targets
  • λ\lambda: penalty
  • PP: excludes the intercept from that penalty
  • NN: Number of examples in the set being scored

MSE is computed separately on training and validation sets of size N.

● Train · ○ Validation · Solid: fit · Dashed: generating functionx = −1x = +1; y-axis ±1.575
Model family
2. Work with the current inputs
(XTX+1.00×10−6P)β=XTy,p=1(X^TX+1.00\times10^{-6}P)\beta=X^Ty,\quad p=1
MSEtrain=112∑i(y^i−yi)2=0.2193\mathrm{MSE}_{\rm train}=\frac1{12}\sum_i(\widehat y_i-y_i)^2=0.2193
MSEval=140∑j(y^j−yj)2=0.2893\mathrm{MSE}_{\rm val}=\frac1{40}\sum_j(\widehat y_j-y_j)^2=0.2893
3. Result
Training MSE0.2193
Validation MSE0.2893
Prediction at x = 0.50.478
Twelve training and forty distinct validation examples from sin(πx)+0.3x with deterministic independent Gaussian noise. Only training labels enter fitting; validation is for tuning, not a final test score. Polynomial powers use x in [−1,1]; P leaves the intercept unpenalized. Outside the Ridge lab, λ=10⁻⁶ is a small fixed penalty. RBF KRR uses a fixed training-mean baseline. Axes rescale to show unstable fits; this is not a statistical bias/variance decomposition.
References for this section3

Python: Load Common Regressors

Regressors follow the same scikit-learn pattern as classifiers:

  • fit(X_train, y_train) learns the mapping.
  • predict(X_test) returns continuous values.
  • Metrics such as MAE, RMSE, and R-squared evaluate the predictions.
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor

regressors = {
    "linear": LinearRegression(),
    "ridge": Ridge(alpha=1.0),
    "lasso": Lasso(alpha=0.01),
    "knn": KNeighborsRegressor(n_neighbors=5),
    "decision_tree": DecisionTreeRegressor(max_depth=6, random_state=42),
    "svr": SVR(kernel="rbf"),
    "random_forest": RandomForestRegressor(n_estimators=200, random_state=42),
    "gradient_boosting": GradientBoostingRegressor(random_state=42),
}
References for this section3

Python: Compare Regressors on One Dataset

Select the family on validation data, refit that choice on development data, then inspect the final test score once. This small example uses a single split; use fold-local pipelines for cross-validation.

from sklearn.base import clone
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import mean_absolute_error, r2_score

X, y = load_diabetes(return_X_y=True)
X_dev, X_test, y_dev, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
X_train, X_validation, y_train, y_validation = train_test_split(
    X_dev, y_dev, test_size=0.25, random_state=43
)

scores = {}
for name, reg in regressors.items():
    candidate = make_pipeline(StandardScaler(), clone(reg))
    candidate.fit(X_train, y_train)
    pred = candidate.predict(X_validation)
    scores[name] = mean_absolute_error(y_validation, pred)
    print(name, "validation MAE=", round(scores[name], 3))

best_name = min(scores, key=scores.get)
model = make_pipeline(StandardScaler(), clone(regressors[best_name]))
model.fit(X_dev, y_dev)
pred = model.predict(X_test)
print("Selected:", best_name)
print("Final test MAE:", mean_absolute_error(y_test, pred))
print("Final test R2:", r2_score(y_test, pred))
References for this section3

Python: Save and Load a Regressor

import joblib

final_regressor = RandomForestRegressor(
    n_estimators=300,
    max_depth=None,
    random_state=42,
    n_jobs=-1
)
final_regressor.fit(X_train, y_train)

joblib.dump(final_regressor, "regressor.joblib")

loaded_regressor = joblib.load("regressor.joblib")
print(loaded_regressor.predict(X_test[:5]))
References for this section3

Takeaway

  • Regression output: a number, such as distance or received power.
  • Linear model: fast and interpretable.
  • Tree ensemble: often strong on tabular features; kernel/neural model: can learn more complex nonlinear patterns.
  • Choose by: data shape, interpretability, error cost, and deployment budget.

Continue with Ridge and Kernel Ridge Regression to build on this note.

References for this section3

Check your understanding

0 of 4 answered

  1. Absolute prediction errors are 1 and 3 metres. What is MAE?

  2. For those same errors, what is MSE?

  3. Nearest-neighbour target values are 2, 4 and 9. What is the uniform KNN prediction?

  4. Is cubic regression linear in its fitted coefficients?

Complete references and further reading