Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Linear models

Linear models

Basics of modeling, optimization, and regularization

Mahmood Amintoosi, Spring 2026

Computer Science Dept, Ferdowsi University of Mashhad

I should mention that the original material of this course was from Open Machine Learning Course, by Joaquin Vanschoren and others.

Source

Notation and Definitions

  • A scalar is a simple numeric value, denoted by an italic letter: x=3.24x=3.24

  • A vector is a 1D ordered array of n scalars, denoted by a bold letter: x=[3.24,1.2]\mathbf{x}=[3.24, 1.2]

    • xix_i denotes the iith element of a vector, thus x0=3.24x_0 = 3.24.

      • Note: some other courses use x(i)x^{(i)} notation

  • A set is an unordered collection of unique elements, denote by caligraphic capital: S={3.24,1.2}\mathcal{S}=\{3.24, 1.2\}

  • A matrix is a 2D array of scalars, denoted by bold capital: X=[3.241.22.240.2]\mathbf{X}=\begin{bmatrix} 3.24 & 1.2 \\ 2.24 & 0.2 \end{bmatrix}

    • Xi\textbf{X}_{i} denotes the iith row of the matrix

    • X:,j\textbf{X}_{:,j} denotes the jjth column

    • Xi,j\textbf{X}_{i,j} denotes the element in the iith row, jjth column, thus X1,0=2.24\mathbf{X}_{1,0} = 2.24

  • Xn×p\mathbf{X}^{n \times p}, an n×pn \times p matrix, can represent nn data points in a pp-dimensional space

    • Every row is a vector that can represent a point in an p-dimensional space, given a basis.

    • The standard basis for a Euclidean space is the set of unit vectors

  • E.g. if X=[3.241.22.240.23.00.6]\mathbf{X}=\begin{bmatrix} 3.24 & 1.2 \\ 2.24 & 0.2 \\ 3.0 & 0.6 \end{bmatrix}

Source
Loading...
  • A tensor is an k-dimensional array of data, denoted by an italic capital: TT

    • k is also called the order, degree, or rank

    • Ti,j,k,...T_{i,j,k,...} denotes the element or sub-tensor in the corresponding position

    • A set of color images can be represented by:

      • a 4D tensor (sample x height x width x color channel)

      • a 2D tensor (sample x flattened vector of pixel values)

Basic operations

  • Sums and products are denoted by capital Sigma and capital Pi:

∑i=0p=x0+x1+...+xp∏i=0p=x0⋅x1⋅...⋅xp\sum_{i=0}^{p} = x_0 + x_1 + ... + x_p \quad \prod_{i=0}^{p} = x_0 \cdot x_1 \cdot ... \cdot x_p
  • Operations on vectors are element-wise: e.g. x+z=[x0+z0,x1+z1,...,xp+zp]\mathbf{x}+\mathbf{z} = [x_0+z_0,x_1+z_1, ... , x_p+z_p]

  • Dot product wx=w⋅x=wTx=∑i=0pwi⋅xi=w0⋅x0+w1⋅x1+...+wp⋅xp\mathbf{w}\mathbf{x} = \mathbf{w} \cdot \mathbf{x} = \mathbf{w}^{T} \mathbf{x} = \sum_{i=0}^{p} w_i \cdot x_i = w_0 \cdot x_0 + w_1 \cdot x_1 + ... + w_p \cdot x_p

  • Matrix product Wx=[w0⋅x...wp⋅x]\mathbf{W}\mathbf{x} = \begin{bmatrix} \mathbf{w_0} \cdot \mathbf{x} \\ ... \\ \mathbf{w_p} \cdot \mathbf{x} \end{bmatrix}

  • A function f(x)=yf(x) = y relates an input element xx to an output yy

    • It has a local minimum at x=cx=c if f(x)≥f(c)f(x) \geq f(c) in interval (c−ϵ,c+ϵ)(c-\epsilon, c+\epsilon)

    • It has a global minimum at x=cx=c if f(x)≥f(c)f(x) \geq f(c) for any value for xx

  • A vector function consumes an input and produces a vector: f(x)=y\mathbf{f}(\mathbf{x}) = \mathbf{y}

  • max⁡x∈Xf(x)\underset{x\in X}{\operatorname{max}}f(x) returns the largest value f(x) for any x

  • argmax⁡x∈Xf(x)\underset{x\in X}{\operatorname{argmax}}f(x) returns the element x that maximizes f(x)

Gradients

  • A derivative f′f' of a function ff describes how fast ff grows or decreases

  • The process of finding a derivative is called differentiation

    • Derivatives for basic functions are known

    • For non-basic functions we use the chain rule: F(x)=f(g(x))→F′(x)=f′(g(x))g′(x)F(x) = f(g(x)) \rightarrow F'(x)=f'(g(x))g'(x)

  • A function is differentiable if it has a derivative in any point of it’s domain

    • It’s continuously differentiable if f′f' is a continuous function

    • We say ff is smooth if it is infinitely differentiable, i.e., f′,f′′,f′′′,...f', f'', f''', ... all exist

  • A gradient ∇f\nabla f is the derivative of a function in multiple dimensions

    • It is a vector of partial derivatives: ∇f=[∂f∂x0,∂f∂x1,...]\nabla f = \left[ \frac{\partial f}{\partial x_0}, \frac{\partial f}{\partial x_1},... \right]

    • E.g. f=2x0+3x12−sin⁡(x2)→∇f=[2,6x1,−cos(x2)]f=2x_0+3x_1^{2}-\sin(x_2) \rightarrow \nabla f= [2, 6x_1, -cos(x_2)]

  • Example: f=−(x02+x12)f = -(x_0^2+x_1^2)

    • ∇f=[∂f∂x0,∂f∂x1]=[−2x0,−2x1]\nabla f = \left[\frac{\partial f}{\partial x_0},\frac{\partial f}{\partial x_1}\right] = \left[-2x_0,-2x_1\right]

    • Evaluated at point (-4,1): ∇f(−4,1)=[8,−2]\nabla f(-4,1) = [8,-2]

      • These are the slopes at point (-4,1) in the direction of x0x_0 and x1x_1 respectively

Source
Loading...
Source
Loading...

Distributions and Probabilities

  • The normal (Gaussian) distribution with mean μ\mu and standard deviation σ\sigma is noted as N(μ,σ)N(\mu,\sigma)

  • A random variable XX can be continuous or discrete

  • A probability distribution fXf_X of a continuous variable XX: probability density function (pdf)

    • The expectation is given by E[X]=∫xfX(x)dx\mathbb{E}[X] = \int x f_{X}(x) dx

  • A probability distribution of a discrete variable: probability mass function (pmf)

    • The expectation (or mean) μX=E[X]=∑i=1k[xi⋅Pr(X=xi)]\mu_X = \mathbb{E}[X] = \sum_{i=1}^k[x_i \cdot Pr(X=x_i)]

Linear models

Linear models make a prediction using a linear function of the input features XX

fw(x)=∑i=1pwi⋅xi+w0f_{\mathbf{w}}(\mathbf{x}) = \sum_{i=1}^{p} w_i \cdot x_i + w_{0}

Learn ww from XX, given a loss function L\mathcal{L}:

argmin⁡wL(fw(X))\underset{\mathbf{w}}{\operatorname{argmin}} \mathcal{L}(f_\mathbf{w}(X))
  • Many algorithms with different L\mathcal{L}: Least squares, Ridge, Lasso, Logistic Regression, Linear SVMs,...

  • Can be very powerful (and fast), especially for large datasets with many features.

  • Can be generalized to learn non-linear patterns: Generalized Linear Models

    • Features can be augmentented with polynomials of the original features

    • Features can be transformed according to a distribution (Poisson, Tweedie, Gamma,...)

    • Some linear models (e.g. SVMs) can be kernelized to learn non-linear functions

Linear models for regression

  • Prediction formula for input features x:

    • w1w_1 ... wpw_p usually called weights or coefficients , w0w_0 the bias or intercept

    • Assumes that errors are N(0,σ)N(0,\sigma)

y^=wx+w0=∑i=1pwi⋅xi+w0=w1⋅x1+w2⋅x2+...+wp⋅xp+w0\hat{y} = \mathbf{w}\mathbf{x} + w_0 = \sum_{i=1}^{p} w_i \cdot x_i + w_0 = w_1 \cdot x_1 + w_2 \cdot x_2 + ... + w_p \cdot x_p + w_0
Source
w_1: 0.393906  w_0: -0.031804
Loading...

Linear Regression (aka Ordinary Least Squares)

  • Loss function is the sum of squared errors (SSE) (or residuals) between predictions y^i\hat{y}_i (red) and the true regression targets yiy_i (blue) on the training set.

LSSE=∑n=1N(yn−y^n)2=∑n=1N(yn−(wTxn+w0))2\mathcal{L}_{SSE} = \sum_{n=1}^{N} (y_n-\hat{y}_n)^2 = \sum_{n=1}^{N} (y_n-(\mathbf{w}^T\mathbf{x_n} + w_0))^2

Solving ordinary least squares

Closed-Form Solution

  • Convex optimization problem with unique closed-form solution:

    w∗=(XTX)−1XTy\mathbf{w}^{*} = (X^{T}X)^{-1} X^T \mathbf{y}

If we have:

x=[x0x1],w=[w0w1]\mathbf{x} = \begin{bmatrix} x_0\\x_1 \end{bmatrix}, \mathbf{w} = \begin{bmatrix} w_0\\w_1 \end{bmatrix}

then y^\hat{y} can be considered as dot product of two vectors:

y^=w0x0+w1x1=wTx\begin{aligned} \hat{y} = w_0 x_0+ w_1 x_1 = \mathbf{w}^T\mathbf{x} \end{aligned}

If ithi^{th} instance is shown by xi\mathbf{x}_i

xi=[xi,0xi,1],\mathbf{x}_i = \begin{bmatrix} x_{i,0}\\x_{i,1} \end{bmatrix},

then:

y^i=w0xi,0+w1xi,1\begin{aligned} \hat{y}_i = w_0 x_{i,0}+ w_1 x_{i,1} \end{aligned}

Loss: Sum of Squared Error:

LSSE=∑i=1nerrori2=∑i=1n(yi^−yi)2=∑i=1n(w0xi,0+w1xi,1−yi)2=∑i=1n(wTxi−yi)2=∑i=1n(xiTw−yi)2=∣∣Xw−y∣∣22=(Xw−y)T(Xw−y)\begin{aligned} \mathcal{L}_{SSE} &= \sum_{i=1}^n{error_i}^2 \\ &= \sum_{i=1}^n{(\hat{y_i} - y_i)}^2 \\ &= \sum_{i=1}^n{(w_0 x_{i,0} + w_1 x_{i,1} - y_i)}^2\\ &= \sum_{i=1}^n{(\mathbf{w}^T\mathbf{x}_{i} - y_i)}^2 = \sum_{i=1}^n{(\mathbf{x}_{i}^T\mathbf{w} - y_i)}^2\\ &= ||X\mathbf{w} - \mathbf{y}||_2^2 = (X\mathbf{w} - \mathbf{y})^T(X\mathbf{w} - \mathbf{y}) \end{aligned}

where:

X=[x1Tx2T⋮xnT],y=[y1y2⋮yn]X = \begin{bmatrix} \mathbf{x_1}^T \\ \mathbf{x_2}^T \\ \vdots \\ \mathbf{x_n}^T \end{bmatrix}, \mathbf{y} = \begin{bmatrix} y_1 \\ y_2 \\ \vdots \\ y_n \end{bmatrix}
LSSE=∣∣Xw−y∣∣22=(Xw−y)T(Xw−y)=((Xw)T−yT)(Xw−y)=(wTXT−yT)(Xw−y)=wTXTXw−wTXTy−yTXw+yTy=wTMw−(Xw)Ty−yTXw+yTy(M=XTX)=wTMw−2yTXw+yTy(ATB=BTA)=wTMw−2zTw+yTy(zT=yTX,z=XTy)\begin{aligned} \mathcal{L}_{SSE}&=||X\mathbf{w}-y||_2^2 = (X\mathbf{w}-y)^T(X\mathbf{w}-y)\\ &=((X\mathbf{w})^T-y^T)(X\mathbf{w}-y) =(\mathbf{w}^TX^T-y^T)(X\mathbf{w}-y) \\ &=\mathbf{w}^TX^T X\mathbf{w} - \mathbf{w}^T X^Ty -y^TX\mathbf{w} + y^Ty\\ &=\mathbf{w}^T M\mathbf{w} - (X\mathbf{w})^Ty -y^TX\mathbf{w} + y^Ty \qquad {(M=X^T X)}\\ &=\mathbf{w}^T M\mathbf{w} - 2y^TX\mathbf{w} + y^Ty \qquad\qquad{(A^TB=B^TA)}\\ &=\mathbf{w}^T M\mathbf{w} - 2z^T\mathbf{w} + y^Ty \qquad\qquad{(z^T=y^TX, z=X^Ty)} \end{aligned}

We Know that (See Matrix Calculus in Wikipedia):

∂yTx∂x=∂xTy∂x=y\frac{\partial y^Tx}{\partial x}=\frac{\partial x^Ty}{\partial x}=y
∂Mx∂x=M\frac{\partial Mx}{\partial x}=M

and if MM be a symmetric matrix:

∂xTMx∂x=2Mx\frac{\partial x^TMx}{\partial x}=2Mx

Hence:

∂LSSE∂w=∂(wTMw−2zTw+yTy)∂w=2Mw−2z=2XTXw−2XTy\begin{aligned} \frac{\partial \mathcal{L}_{SSE}}{\partial \mathbf{w}} &= \frac{\partial (\mathbf{w}^T M\mathbf{w} - 2z^T\mathbf{w} + y^Ty)}{\partial \mathbf{w}} \\ &= 2M\mathbf{w}-2z = 2X^TX\mathbf{w}-2X^T y \end{aligned}

Set the derivative equal to zero:

∂LSSE∂w=0⇒2XTXw−2XTy=0⇒XTXw=XTy⇒w=(XTX)−1XTy\begin{aligned} &\frac{\partial \mathcal{L}_{SSE}}{\partial \mathbf{w}}=0 \\ \Rightarrow & 2 X^TX\mathbf{w} - 2X^T y = 0\\ \Rightarrow & X^TX\mathbf{w} = X^Ty \\ \Rightarrow & \mathbf{w} = (X^TX)^{-1}X^Ty \\ \end{aligned}

Some notes about Closed-Form Solution

The unique closed-form solution:

w∗=(XTX)−1XTy\mathbf{w}^{*} = (X^{T}X)^{-1} X^T \mathbf{y}

Where X has nn rows, pp features, hence XTXX^{T}X has dimensionality p⋅pp \cdot p

Notes:

  • Slow. Time complexity is quadratic in number of features: O(p2n)\mathcal{O}(p^2n)

  • Only works if n>pn>p, XTX X^T X is Singular When n<p n < p , making OLS’s (XTX)−1 (X^T X)^{-1} undefined.

  • The closed-form solution of Ordinary Least Squares (OLS) is highly prone to overfitting, especially when applied to small or highly correlated datasets.

  • Large coefficients: In the absence of regularization, weights w w can grow excessively, leading to unstable predictions.

  • Sensitive to input variations: Small changes in x x may result in disproportionately large shifts in the output y y , making the model unreliable.

  • No direct hyperparameter control: Unlike Gradient Descent, OLS lacks tuning mechanisms such as learning rate or regularization strength.

Gradient Descent

  • More efficient for large-scale or high-dimensional datasets.

  • Preferred when computing XTX X^{T}X is infeasible or excessively time-consuming due to large p p or n n .

  • Offers multiple tunable settings to control the learning process, including:

    • Learning Rate: Adjusts update speed to balance stability and convergence.

    • Regularization: Options like L1, L2, or Elastic Net mitigate overfitting.

    • Batch Size: Influences computational efficiency (Stochastic, Mini-batch, Full-batch).

    • Iterations: Determines the number of passes over the dataset.

    • Momentum & Decay: Helps stabilize and refine the learning trajectory.


Source
X (design matrix):
[[1 2 3]
 [4 5 6]]

X^T X (Gram matrix):
[[17 22 27]
 [22 29 36]
 [27 36 45]]

Rank of X: 2
Rank of X^T X: 2
Is X^T X singular? True

Error: X^T X is singular and cannot be inverted (as expected when n < p).

Gradient Descent

  • Start with an initial, random set of weights: w0\mathbf{w}^0

  • Given a differentiable loss function L\mathcal{L} (e.g. LSSE\mathcal{L}_{SSE}), compute ∇L\nabla \mathcal{L}

  • For least squares: ∂LSSE∂wi(w)=−2∑n=1N(yn−y^n)xn,i\frac{\partial \mathcal{L}_{SSE}}{\partial w_i}(\mathbf{w}) = -2\sum_{n=1}^{N} (y_n-\hat{y}_n) x_{n,i}

    • If feature X:,iX_{:,i} is associated with big errors, the gradient wrt wiw_i will be large

  • Update all weights slightly (by step size or learning rate η\eta) in ‘downhill’ direction.

  • Basic update rule (step s):

    ws+1=ws−η∇L(ws)\mathbf{w}^{s+1} = \mathbf{w}^s-\eta\nabla \mathcal{L}(\mathbf{w}^s)
  • Important hyperparameters

    • Learning rate

      • Too small: slow convergence. Too large: possible divergence

    • Maximum number of iterations

      • Too small: no convergence. Too large: wastes resources

    • Learning rate decay with decay rate kk

      • E.g. exponential (ηs+1=η0e−ks\eta^{s+1} = \eta^{0} e^{-ks}), inverse-time (ηs+1=ηs1+ks\eta^{s+1} = \frac{\eta^{s}}{1+ks}),...

    • Many more advanced ways to control learning rate (see later)

      • Adaptive techniques: depend on how much loss improved in previous step

Source
Output
Loading...
Loading...
Source
Loading...
Source
Source
Source

Effect of learning rate

Source
Loading...
Loading...
Loading...

Effect of learning rate decay

Source
Loading...
Loading...
Loading...

In two dimensions:

  • You can get stuck in local minima (if the loss is not fully convex)

    • If you have many model parameters, this is less likely

    • You always find a way down in some direction

    • Models with many parameters typically find good local minima

  • Intuition: walking downhill using only the slope you “feel” nearby

(Image by A. Karpathy)

Stochastic Gradient Descent (SGD)

  • Compute gradients not on the entire dataset, but on a single data point ii at a time

    • Gradient descent: ws+1=ws−η∇L(ws)=ws−ηn∑i=1n∇Li(ws)\mathbf{w}^{s+1} = \mathbf{w}^s-\eta\nabla \mathcal{L}(\mathbf{w}^s) = \mathbf{w}^s-\frac{\eta}{n} \sum_{i=1}^{n} \nabla \mathcal{L_i}(\mathbf{w}^s)

    • Stochastic Gradient Descent: ws+1=ws−η∇Li(ws)\mathbf{w}^{s+1} = \mathbf{w}^s-\eta\nabla \mathcal{L_i}(\mathbf{w}^s)

  • Many smoother variants, e.g.

    • Minibatch SGD: compute gradient on batches of data: ws+1=ws−ηB∑i=1B∇Li(ws)\mathbf{w}^{s+1} = \mathbf{w}^s-\frac{\eta}{B} \sum_{i=1}^{B} \nabla \mathcal{L_i}(\mathbf{w}^s)

    • Stochastic Average Gradient Descent (SAG). With is∈[1,n]i_s \in [1,n] randomly chosen per iteration:

      • Incremental gradient: ws+1=ws−ηn∑i=1nvis\mathbf{w}^{s+1} = \mathbf{w}^s-\frac{\eta}{n} \sum_{i=1}^{n} v_i^s with vis={∇Li(ws)i=isvis−1otherwisev_i^s = \begin{cases}\nabla \mathcal{L_i}(\mathbf{w}^s) & i = i_s \\ v_i^{s-1} & \text{otherwise} \end{cases}

In practice

  • Linear regression can be found in sklearn.linear_model. We’ll evaluate it on the Boston Housing dataset.

    • LinearRegression uses closed form solution, SGDRegressor with loss='squared_loss' uses Stochastic Gradient Descent

    • Large coefficients signal overfitting

    • Test score is much lower than training score

Source
Source
Weights (coefficients): [ -412.711   -52.243  -131.899   -12.004   -15.511    28.716    54.704
   -49.535    26.582    37.062   -11.828   -18.058   -19.525    12.203
  2980.781  1500.843   114.187   -16.97     40.961   -24.264    57.616
  1278.121 -2239.869   222.825    -2.182    42.996   -13.398   -19.389
    -2.575   -81.013     9.66      4.914    -0.812    -7.647    33.784
   -11.446    68.508   -17.375    42.813     1.14 ]
Bias (intercept): 30.934563673643545
Source
Training set score (R^2): 0.95
Test set score (R^2): 0.61

Ridge regression

  • Adds a penalty term to the least squares loss function:

LRidge=∑n=1N(yn−(wxn+w0))2+α∑i=1pwi2\mathcal{L}_{Ridge} = \sum_{n=1}^{N} (y_n-(\mathbf{w}\mathbf{x_n} + w_0))^2 + \alpha \sum_{i=1}^{p} w_i^2
  • Model is penalized if it uses large coefficients (ww)

    • Each feature should have as little effect on the outcome as possible

    • We don’t want to penalize w0w_0, so we leave it out

  • Regularization: explicitly restrict a model to avoid overfitting.

    • Called L2 regularization because it uses the L2 norm: ∑wi2\sum w_i^2

  • The strength of the regularization can be controlled with the α\alpha hyperparameter.

    • Increasing α\alpha causes more regularization (or shrinkage). Default is 1.0.

  • Still convex. Can be optimized in different ways:

    • Closed form solution (a.k.a. Cholesky): w∗=(XTX+αI)−1XTyw^{*} = (X^{T}X + \alpha I)^{-1} X^T \mathbf{y}

    • Gradient descent and variants, e.g. Stochastic Average Gradient (SAG,SAGA)

      • Conjugate gradient (CG): each new gradient is influenced by previous ones

    • Use Cholesky for smaller datasets, Gradient descent for larger ones

Ridge Regression Derivation

We want to minimize the Ridge loss function with respect to w\mathbf{w}:

∣∣Xw−y∣∣22+α∣∣w∣∣22||X\mathbf{w} - \mathbf{y}||_2^2 + \alpha ||\mathbf{w}||_2^2

Expanding:

LRidge=∣∣Xw−y∣∣22+α∣∣w∣∣22=(Xw−y)T(Xw−y)+αwTw=wTXTXw−2yTXw+yTy+αwTw\begin{aligned} \mathcal{L}_{Ridge} &= ||X\mathbf{w} - \mathbf{y}||_2^2 + \alpha ||\mathbf{w}||_2^2\\ &= (X\mathbf{w} - \mathbf{y})^T (X\mathbf{w} - \mathbf{y}) + \alpha \mathbf{w}^T \mathbf{w} \\ &= \mathbf{w}^T X^T X \mathbf{w} - 2 \mathbf{y}^T X \mathbf{w} + \mathbf{y}^T \mathbf{y} + \alpha \mathbf{w}^T \mathbf{w} \end{aligned}

Taking the derivative with respect to w\mathbf{w}:

∂LRidge∂w=2XTXw−2XTy+2αw\begin{aligned} \frac{\partial \mathcal{L}_{Ridge}}{\partial \mathbf{w}} &= 2 X^T X \mathbf{w} - 2 X^T \mathbf{y} + 2 \alpha \mathbf{w} \end{aligned}

Setting the derivative equal to zero:

2XTXw−2XTy+2αw=0⇒XTXw+αw=XTy⇒(XTX+αI)w=XTy⇒w=(XTX+αI)−1XTy\begin{aligned} &2 X^T X \mathbf{w} - 2 X^T \mathbf{y} + 2 \alpha \mathbf{w} = 0\\ \Rightarrow & X^T X \mathbf{w} + \alpha \mathbf{w} = X^T \mathbf{y}\\ \Rightarrow & (X^T X + \alpha I) \mathbf{w} = X^T \mathbf{y}\\ \Rightarrow & \mathbf{w} = (X^T X + \alpha I)^{-1} X^T \mathbf{y} \end{aligned}

In practice

from sklearn.linear_model import Ridge
lr = Ridge().fit(X_train, y_train)
Source
Weights (coefficients): [-1.414 -1.557 -1.465 -0.127 -0.079  8.332  0.255 -4.941  3.899 -1.059
 -1.584  1.051 -4.012  0.334  0.004 -0.849  0.745 -1.431 -1.63  -1.405
 -0.045 -1.746 -1.467 -1.332 -1.692 -0.506  2.622 -2.092  0.195 -0.275
  5.113 -1.671 -0.098  0.634 -0.61   0.04  -1.277 -2.913  3.395  0.792]
Bias (intercept): 21.390525958610052
Training set score: 0.89
Test set score: 0.75

Test set score is higher and training set score lower: less overfitting!

  • We can plot the weight values for differents levels of regularization to explore the effect of α\alpha.

  • Increasing regularization decreases the values of the coefficients, but never to 0.

Source
Output
Loading...
Loading...
Source
Loading...
Loading...
  • When we plot the train and test scores for every α\alpha value, we see a sweet spot around α=0.2\alpha=0.2

    • Models with smaller α\alpha are overfitting

    • Models with larger α\alpha are underfitting

Source
Loading...

Other ways to reduce overfitting

  • Add more training data: with enough training data, regularization becomes less important

    • Ridge and ordinary least squares will have the same performance

  • Use fewer features: remove unimportant ones or find a low-dimensional embedding (e.g. PCA)

    • Fewer coefficients to learn, reduces the flexibility of the model

  • Scaling the data typically helps (and changes the optimal α\alpha value)

Source
Loading...

Lasso (Least Absolute Shrinkage and Selection Operator)

  • Adds a different penalty term to the least squares sum:

LLasso=∑n=1N(yn−(wxn+w0))2+α∑i=1p∣wi∣\mathcal{L}_{Lasso} = \sum_{n=1}^{N} (y_n-(\mathbf{w}\mathbf{x_n} + w_0))^2 + \alpha \sum_{i=1}^{p} |w_i|
  • Called L1 regularization because it uses the L1 norm

    • Will cause many weights to be exactly 0

  • Same parameter α\alpha to control the strength of regularization.

    • Will again have a ‘sweet spot’ depending on the data

  • No closed-form solution

  • Convex, but no longer strictly convex, and not differentiable

    • Weights can be optimized using coordinate descent

Analyze what happens to the weights:

  • L1 prefers coefficients to be exactly zero (sparse models)

  • Some features are ignored entirely: automatic feature selection

  • How can we explain this?

Source
Output
Loading...
Loading...
Source
Loading...
Loading...

Coordinate descent

  • Alternative for gradient descent, supports non-differentiable convex loss functions (e.g. LLasso\mathcal{L}_{Lasso})

  • In every iteration, optimize a single coordinate wiw_i (find minimum in direction of xix_i)

    • Continue with another coordinate, using a selection rule (e.g. round robin)

  • Faster iterations. No need to choose a step size (learning rate).

  • May converge more slowly. Can’t be parallellized.


Coordinate descent with Lasso (Further Reading)

  • Remember that LLasso=LSSE+α∑i=1p∣wi∣\mathcal{L}_{Lasso} = \mathcal{L}_{SSE} + \alpha \sum_{i=1}^{p} |w_i|

  • For one wiw_i: LLasso(wi)=LSSE(wi)+α∣wi∣\mathcal{L}_{Lasso}(w_i) = \mathcal{L}_{SSE}(w_i) + \alpha |w_i|

  • The L1 term is not differentiable but convex: we can compute the subgradient

    • Unique at points where L\mathcal{L} is differentiable, a range of all possible slopes [a,b] where it is not

    • For ∣wi∣|w_i|, the subgradient ∂wi∣wi∣\partial_{w_i} |w_i| = {−1wi<0[−1,1]wi=01wi>0\begin{cases}-1 & w_i<0\\ [-1,1] & w_i=0 \\ 1 & w_i>0 \\ \end{cases}

    • Subdifferential ∂(f+g)=∂f+∂g\partial(f+g) = \partial f + \partial g if ff and gg are both convex

  • To find the optimum for Lasso wi∗w_i^{*}, solve

    ∂wiLLasso(wi)=∂wiLSSE(wi)+∂wiα∣wi∣0=(wi−ρi)+α⋅∂wi∣wi∣wi=ρi−α⋅∂wi∣wi∣\begin{aligned} \partial_{w_i} \mathcal{L}_{Lasso}(w_i) &= \partial_{w_i} \mathcal{L}_{SSE}(w_i) + \partial_{w_i} \alpha |w_i| \\ 0 &= (w_i - \rho_i) + \alpha \cdot \partial_{w_i} |w_i| \\ w_i &= \rho_i - \alpha \cdot \partial_{w_i} |w_i| \end{aligned}
    • In which ρi\rho_i is the part of ∂wiLSSE(wi)\partial_{w_i} \mathcal{L}_{SSE}(w_i) excluding wiw_i (assume zi=1z_i=1 for now)

      • ρi\rho_i can be seen as the LSSE\mathcal{L}_{SSE} ‘solution’: wi=ρiw_i = \rho_i if ∂wiLSSE(wi)=0\partial_{w_i} \mathcal{L}_{SSE}(w_i) = 0

    ∂wiLSSE(wi)=∂wi∑n=1N(yn−(wxn+w0))2=ziwi−ρi\partial_{w_i} \mathcal{L}_{SSE}(w_i) = \partial_{w_i} \sum_{n=1}^{N} (y_n-(\mathbf{w}\mathbf{x_n} + w_0))^2 = z_i w_i -\rho_i
  • We found: wi=ρi−α⋅∂wi∣wi∣w_i = \rho_i - \alpha \cdot \partial_{w_i} |w_i|

  • The Lasso solution has the form of a soft thresholding function SS

    wi∗=S(ρi,α)={ρi+α,ρi<−α0,−α<ρi<αρi−α,ρi>αw_i^* = S(\rho_i,\alpha) = \begin{cases} \rho_i + \alpha, & \rho_i < -\alpha \\ 0, & -\alpha < \rho_i < \alpha \\ \rho_i - \alpha, & \rho_i > \alpha \\ \end{cases}
    • Small weights become 0: sparseness!

    • If the data is not normalized, wi∗=1ziS(ρi,α)w_i^* = \frac{1}{z_i}S(\rho_i,\alpha) with constant zi=∑n=1Nxni2z_i = \sum_{n=1}^{N} x_{ni}^2

  • Ridge solution: wi=ρi−α⋅∂wiwi2=ρi−2α⋅wiw_i = \rho_i - \alpha \cdot \partial_{w_i} w_i^2 = \rho_i - 2\alpha \cdot w_i, thus wi∗=ρi1+2αw_i^* = \frac{\rho_i}{1 + 2\alpha}

  • For mor information see Rashidabadi (2016)

Notebook Cell
Source
Output
Loading...
Loading...
Notebook Cell
Source
Loading...

Interpreting L1 and L2 loss

Notebook Cell
Notebook Cell
Notebook Cell
Source
Output
Loading...
Loading...
Notebook Cell
Source
Loading...

  • In 2D (for 2 model weights w1w_1 and w2w_2)

    • The least squared loss is a 2D convex function in this space

    • For illustration, assume that L1 loss = L2 loss = 1

      • L1 loss (Σ∣wi∣\Sigma |w_i|): every {w1,w2w_1, w_2} falls on the diamond

      • L2 loss (Σwi2\Sigma w_i^2): every {w1,w2w_1, w_2} falls on the circle

    • For L1, the loss is minimized if w1w_1 or w2w_2 is 0 (rarely so for L2)

Source
Loading...

Comparing Ridge and LASSO for Prediction and Feature Selection

The following code trains and compares Linear Regression, Ridge (L2), and LASSO (L1) regression models. We’ll examine their predictive performance using Mean Squared Error (MSE) and observe how LASSO can be used for feature selection by shrinking some feature coefficients to zero.

Source
Linear Regression MSE: 32.06913512158206
Ridge MSE: 18.386795859109146
LASSO MSE: 19.145582778836758

LASSO selected 33 features from total 104 features.

Elastic-Net

  • Adds both L1 and L2 regularization:

LElastic=∑n=1N(yn−(wxn+w0))2+αρ∑i=1p∣wi∣+α(1−ρ)∑i=1pwi2\mathcal{L}_{Elastic} = \sum_{n=1}^{N} (y_n-(\mathbf{w}\mathbf{x_n} + w_0))^2 + \alpha \rho \sum_{i=1}^{p} |w_i| + \alpha (1 - \rho) \sum_{i=1}^{p} w_i^2
  • ρ\rho is the L1 ratio

    • With ρ=1\rho=1, LElastic=LLasso\mathcal{L}_{Elastic} = \mathcal{L}_{Lasso}

    • With ρ=0\rho=0, LElastic=LRidge\mathcal{L}_{Elastic} = \mathcal{L}_{Ridge}

    • 0<ρ<10 < \rho < 1 sets a trade-off between L1 and L2.

  • Allows learning sparse models (like Lasso) while maintaining L2 regularization benefits

    • E.g. if 2 features are correlated, Lasso likely picks one randomly, Elastic-Net keeps both

  • Weights can be optimized using coordinate descent (similar to Lasso)

Sparse Optimization: Theory and Applications

Sparse optimization is a fundamental paradigm in mathematical modeling that seeks solutions with few non-zero elements, often formalized through ℓ₁-norm regularization or non-convex penalties. This framework is grounded in the Compressed Sensing (CS) theory Donoho (2006), which guarantees exact signal recovery from sub-Nyquist measurements if the signal is sparse in some basis. Key applications include:

  1. Medical Imaging: CS enables faster MRI scans by reconstructing images from limited k-space samples (Lustig et al., 2007), as highlighted in the CUHK lecture notes on CS (p. 13).

  2. Signal Processing: Sparse methods underpin denoising (e.g., wavelet shrinkage) and inpainting, where total variation minimization preserves edges while removing noise (Figueiredo, 2021, slides p. 8).

  3. Machine Learning: Sparse regression (e.g., LASSO; Tibshirani, 1996) and robust PCA (Candès et al., 2011) are critical for feature selection and anomaly detection. The Ghent tutorial (p. 5) further links sparsity to deep network pruning.

  4. Statistics: High-dimensional inference (e.g., genomics) benefits from sparsity-induced interpretability (Bühlmann & Van de Geer, 2011).

The field continues to evolve with non-convex penalties (e.g., SCAD) and greedy algorithms (OMP), balancing computational efficiency and statistical guarantees. For a unified perspective, see the cited references and tutorials.


Sparse Signal Denoising via Weighted Lasso in DCT Domain

Given a noisy 1D signal:

y(t)=f(t)+ϵ(t)y(t) = f(t) + \epsilon(t)

where:

  • f(t) is the clean signal (sparse in frequency domain)

  • ϵ(t) is Gaussian noise (non-sparse in any basis)

We solve the weighted Lasso problem:

min⁡x∥y−IDCT(x)∥22+α∑i>nfreq∣xi∣\min_x \|y - \text{IDCT}(x)\|^2_2 + \alpha \sum_{i>n_{freq}} |x_i|
Notebook Cell

Noise-Sparsity Dichotomy

  • Signal: Sparse in DCT domain (few dominant coefficients)

  • Noise: Non-sparse (energy spread across all frequencies)

Weighted ℓ₁ Magic

Effective penalty=α∑i>nfreq∣xi∣\text{Effective penalty} = \alpha \sum_{i>n_{freq}} |x_i|
  • Preserves signal structure (low frequencies)

  • Aggressively truncates noise (high frequencies)

Performance Analysis

Theoretical Guarantees

  • Exact Recovery: Possible if:

    • Signal truly sparse in DCT basis

    • Noise level below threshold (Donoho et al., 2006)

  • Stability: Weighted Lasso provides better coefficient preservation than standard Lasso

Limitations

  • Assumes signal sparsity in chosen basis

  • Requires tuning for each application

  • Computationally heavier than simple filtering

Signal Denoising using LASSO

Source
Total number of coefficients: 1000
Number of non-zero coefficients (NNZ): 25
<Figure size 800x400 with 1 Axes>

Orthogonal Matching Pursuit (OMP) for Sparse Recovery

Orthogonal Matching Pursuit (OMP) is a greedy algorithm that solves the sparse approximation problem:

Problem Statement: Given a design matrix X∈Rn×pX \in \mathbb{R}^{n \times p} (where typically n≪pn \ll p) and observations y∈Rn\mathbf{y} \in \mathbb{R}^n, find the sparsest vector w∈Rp\mathbf{w} \in \mathbb{R}^p such that y≈Xw\mathbf{y} \approx X\mathbf{w}.

Key characteristics:

  • Iterative approach that selects one feature per iteration based on maximum correlation

  • Provides exact recovery guarantees under Restricted Isometry Property (RIP) conditions

  • Computationally efficient (O(knp)O(knp) complexity) compared to ℓ0\ell_0-norm minimization

  • Widely used in compressed sensing, signal processing, and feature selection

  • Preserves interpretability through explicit feature selection

This method complements LASSO by offering an alternative approach to sparse recovery with distinct theoretical guarantees and computational trade-offs.

While LASSO solves the ℓ1\ell_1-regularized problem:

min⁡w12n∥y−Xw∥22+α∥w∥1\min_{\mathbf{w}} \frac{1}{2n} \|\mathbf{y} - X\mathbf{w}\|_2^2 + \alpha \|\mathbf{w}\|_1

OMP provides a greedy alternative for sparse approximation, solving:

min⁡w∥w∥0subject to∥y−Xw∥2≤ϵ\min_{\mathbf{w}} \|\mathbf{w}\|_0 \quad \text{subject to} \quad \|\mathbf{y} - X\mathbf{w}\|_2 \leq \epsilon

OMP algorithm

Given:

  • Design matrix X∈Rn×pX \in \mathbb{R}^{n \times p}

  • Response vector y∈Rn\mathbf{y} \in \mathbb{R}^n

  • Target sparsity level kk

At each iteration:

  1. Select most correlated feature: j=arg⁡max⁡j∉A∣xj⊤r∣j = \arg\max_{j \notin \mathcal{A}} |\mathbf{x}_j^\top \mathbf{r}|, where r\mathbf{r} is the current residual and A\mathcal{A} is the active feature set.

  2. Update support: A←A∪{j}\mathcal{A} \leftarrow \mathcal{A} \cup \{j\}

  3. Solve least squares: w=arg⁡min⁡w∥XAw−y∥22\mathbf{w} = \arg\min_{\mathbf{w}} \|X_{\mathcal{A}}\mathbf{w} - \mathbf{y}\|_2^2

  4. Update residual: r←XAw−y\mathbf{r} \leftarrow X_{\mathcal{A}}\mathbf{w} - \mathbf{y}

Termination: After kk iterations or when ∥r∥2<ϵ\|\mathbf{r}\|_2 < \epsilon

Figure 10.2 of Theodoridis (2020):

(A) In the case of an orthogonal matrix, the observations vector y will be orthogonal to any inactive column, here, x3cx_3^c. (B) In the more general case, it is expected to “lean” closer (form smaller angles) to the active than to the inactive columns.

Figure 2.3 of Bakhshali (2018)

Comparison with LASSO

PropertyOMPLASSO
Objectiveℓ0\ell_0 constraintℓ1\ell_1 regularization
SolutionGreedy approximationConvex optimization
ComputationalFaster for small kkSlower but more stable
TheoreticalExact recovery possibleConsistent estimation

For further information see Asaran (2016).

Practice

Source

Ground Truth Non-zero Coefficients: 1.50, -0.80, 1.20

Performance Comparison:
Method     Test MSE     Support Error   ℓ2 Error   Non-zero Coefficients         
---------------------------------------------------------------------------
OMP        1.6293e-02    0               0.0296     [1.51, -0.80, 1.17]
LASSO      5.5046e-02    0               0.2214     [1.39, -0.68, 1.05]
Notebook Cell
Loading...

A Simple Example

Source
Dictionary matrix A (shape (3, 4)):
[[1 0 0 1]
 [0 1 0 1]
 [0 0 1 0]]

Target vector b: [2 3 0]

Running OMP with k=2...

=== Orthogonal Matching Pursuit ===
Target vector y: [2 3 0]
Initial residual norm: 3.6056

Iteration 1:
  Selected index: 3
  Active set: [np.int64(3)]
  Coefficients: [2.5]
  Residual norm: 0.7071

  (3, 1), (1, 3), (1,)

Iteration 2:
  Selected index: 1
  Active set: [np.int64(3), np.int64(1)]
  Coefficients: [2. 1.]
  Residual norm: 0.0000

  (3, 2), (2, 3), (2,)

Stopping early: residual norm 0.0000 < tolerance 1e-06

=== Final Result ===
Non-zero coefficients at indices: [1 3]
Coefficient values: [1. 2.]

Reconstruction: [2. 3. 0.]
Target: [2 3 0]
Reconstruction error: 6.280369834735101e-16

When to Use OMP

  1. Exactly sparse signals – OMP is ideal when the underlying signal truly has only a few non-zero coefficients, making it a strong choice for enforcing strict sparsity.

  2. Small-scale problems – Works efficiently when the number of non-zero elements k k is much smaller than the total features p p (i.e., k≪p k \ll p ), preventing unnecessary computational overhead.

  3. Interpretable solutions – Since OMP selects features iteratively, the stepwise approach makes it easier to analyze which features contribute to the model, often simpler than interpreting LASSO’s continuous shrinkage.

  4. Dictionary learning – Frequently used in sparse coding applications, where signals are represented as a sparse combination of dictionary elements, making it valuable for feature selection in compressed sensing.

Similarities and Differences in Solving Ax=b A\mathbf{x} = \mathbf{b} in Regression and Sparse Representation

Similarities

  1. Core Equation: Both domains solve the linear system Ax=b A\mathbf{x} = \mathbf{b} .

  2. Matrix-Vector Structure:

    • A A is a matrix, x \mathbf{x} is a vector of unknowns, and b \mathbf{b} is a vector of observations/targets.

  3. Optimization Goal: Both aim to find x \mathbf{x} such that Ax A\mathbf{x} approximates b \mathbf{b} , often with a minimization objective (e.g., least squares or sparsity constraints).


Differences in Specification of A,x,b A, \mathbf{x}, \mathbf{b}

AspectRegressionSparse Representation
Role of A A Design matrix: Rows = samples, columns = features.
- Each row is a data sample (e.g., patient measurements).
- Each column is a feature (e.g., age, blood pressure).
Dictionary matrix: Columns = atoms/basis vectors.
- Each column is a pre-defined basis (e.g., wavelets, image patches).
- Typically overcomplete (more columns than rows).
Role of x \mathbf{x} Coefficient vector: Represents weights for features.
- xj x_j = weight for the j j -th feature.
- Usually dense (all entries non-zero).
Sparse coefficient vector: Represents activations of atoms.
- xj x_j = activation of the j j -th atom.
- Must be sparse (most entries zero).
Role of b \mathbf{b} Target vector: Observed responses for samples.
- bi b_i = target value for the i i -th sample (e.g., house price).
Signal vector: Input signal to be represented.
- bi b_i = value at the i i -th dimension (e.g., pixel intensity).
Problem GoalModel relationships: Predict b \mathbf{b} from features in A A .Compress/denoise signals: Represent b \mathbf{b} as a sparse combination of atoms in A A .
Solution MethodLeast squares: Minimize ∣Ax−b∣22 |A\mathbf{x} - \mathbf{b}|_2^2 .
- Closed-form: x=(ATA)−1ATb \mathbf{x} = (A^T A)^{-1} A^T \mathbf{b} .
Sparsity-constrained optimization: Minimize ∣Ax−b∣22+λ∣x∣1 |A\mathbf{x} - \mathbf{b}|_2^2 + \lambda |\mathbf{x}|_1 (LASSO) or ∣x∣0 |\mathbf{x}|_0 (non-convex).
Key AssumptionFeatures are independent/linearly related.Signal can be represented by few atoms from A A .
Example Use CasePredicting house prices from features (size, location).Denoising an image using a dictionary of edges/textures.

Key Differences Explained

  1. Structure of A A :

    • Regression: A A is tall/square (rows ≥ columns). Rows = samples, columns = features.
      Example: 100 patients (rows) × 5 features (columns).

    • Sparse Representation: A A is fat (columns > rows). Columns = atoms, rows = signal dimensions.
      Example: 1000 pixels (rows) × 5000 atoms (columns).

  2. Sparsity of x \mathbf{x} :

    • Regression: x \mathbf{x} is dense (all entries non-zero). Every feature contributes to predictions.

    • Sparse Representation: x \mathbf{x} must be sparse (most entries zero). Only a few atoms are activated.

  3. Interpretation:

    • Regression: x \mathbf{x} quantifies feature importance (e.g., “size” has weight 0.8).

    • Sparse Representation: x \mathbf{x} identifies active atoms (e.g., “edge #42” is activated for a line in an image).

  4. Optimization:

    • Regression: Unconstrained least squares (closed-form or iterative solvers).

    • Sparse Representation: Constrained optimization (L1/L0 regularization) to enforce sparsity (e.g., LASSO, OMP).


Example: House Price Prediction (Regression)

  • A A : 100 houses (rows) × 3 features: [size, bedrooms, age].

  • b \mathbf{b} : House prices (e.g., [300k, 450k, ...]).

  • x \mathbf{x} : Weights (e.g., [size: 0.2, bedrooms: 0.1, age: -0.05]).

  • Solution: x=(ATA)−1ATb \mathbf{x} = (A^T A)^{-1} A^T \mathbf{b} (dense).


Example: Image Denoising (Sparse Representation)

  • A A : Dictionary of 10,000 image patches (atoms).

  • b \mathbf{b} : Noisy 50×50 image vectorized (2500 rows).

  • x \mathbf{x} : Sparse vector activating 20 atoms (e.g., only 20 non-zero entries).

  • Solution: Minimize ∥Ax−b∥22+λ∥x∥1 \|A\mathbf{x} - \mathbf{b}\|_2^2 + \lambda \|\mathbf{x}\|_1 (sparse).


Summary

  • Regression: A A = samples × features, x \mathbf{x} = dense weights, b \mathbf{b} = targets. Focus on prediction.

  • Sparse Representation: A A = signal × atoms, x \mathbf{x} = sparse activations, b \mathbf{b} = signal. Focus on compression/denoising.

  • Shared Core: Both solve Ax≈b A\mathbf{x} \approx \mathbf{b} , but with different constraints on x \mathbf{x} and interpretations of A A .

Connection Between Sparse Learning and Functional Analysis (Further Reading)

Sparse recovery techniques like OMP and LASSO are deeply rooted in functional analysis, which explains why terms like Hilbert spaces and Banach spaces frequently appear in machine learning research. These mathematical frameworks provide the theoretical foundation for understanding sparsity-inducing methods.

Hilbert Spaces and Orthogonal Projections

Hilbert spaces (complete inner product spaces) are essential for analyzing orthogonal projections and basis expansions. For example:

  • OMP iteratively projects the residual onto the span of selected basis vectors, leveraging the orthogonality principle to minimize error at each step.

  • The inner product structure of Hilbert spaces enables efficient computation of correlations between residuals and dictionary atoms (columns of X X ).

Banach Spaces and ℓ1 \ell_1 -Regularization

LASSO operates in the context of Banach spaces (complete normed vector spaces) due to its reliance on the ℓ1 \ell_1 -norm:

  • The ℓ1 \ell_1 -norm’s non-smoothness at the origin induces sparsity, a property studied in Banach space geometry.

  • Unlike Hilbert spaces, Banach spaces generalize optimization techniques to non-Euclidean settings, crucial for sparse regularization.

Fourier, Wavelet, and Other Representations

Sparse learning often exploits transform domains (e.g., Fourier, wavelet, or learned dictionaries) where signals admit concise representations: - These domains provide structured bases where only a few coefficients are significant. - The connection to functional analysis arises because such bases typically form frames or Riesz bases in Hilbert spaces, ensuring stable sparse approximations.

From Fixed Bases to Learned Representations

  1. Classical Sparse Coding:

    • Relies on predefined bases (e.g., Fourier, wavelets) where signals admit sparse representations.

    • These bases often form frames or Riesz bases in Hilbert spaces, ensuring stable approximations.

  2. Convolutional Neural Networks (CNNs):

    • Learn adaptive bases/filters from data, implicitly constructing sparse-like representations through:

      • Local connectivity: Filters act as localized basis functions.

      • Activation sparsity: ReLU promotes de facto sparsity in feature maps.

    • While CNNs lack explicit ℓ0 \ell_0 /ℓ1 \ell_1 constraints, their hierarchical structure approximates multi-scale sparse decompositions, akin to wavelet analysis but data-driven.

The Evolving Role of Sparse Methods

While deep learning has reduced reliance on handcrafted sparse models in some domains, sparse methods remain relevant because:

  1. Interpretability:

    • OMP/LASSO yield explicit basis selections, whereas CNNs operate as black boxes.

    • Critical in fields like medicine or physics where model transparency is required.

  2. Data-Efficiency:

    • Sparse methods often outperform DL in low-data regimes (e.g., medical imaging with small datasets).

  3. Theoretical Guarantees:

    • Compressed sensing (OMP) and convex optimization (LASSO) provide recovery guarantees under precise conditions, unlike empirical DL results.

  4. Hybrid Approaches:

    • Modern architectures (e.g., ISTA-Net, Learned Iterative Shrinkage) blend sparse priors with deep learning, showing that sparsity remains a useful inductive bias.

Sparse learning and deep learning are complementary:

  • CNNs dominate when data is abundant and interpretability is secondary.

  • OMP/LASSO persist in scenarios requiring rigor, efficiency, or transparency.

  • Functional analysis bridges these paradigms, providing tools to analyze both fixed and learned representations.


MRI reconstruction (Further Reading)

MRI reconstruction can be formulated as an inverse problem where the goal is to recover the original image m \mathbf{m} from under-sampled k-space measurements y \mathbf{y} . This is achieved using sparse optimization techniques.

A common formulation for MRI reconstruction is:

min⁡m∥Fum−y∥22+λ∥Ψm∥p\min_{\mathbf{m}} \|\mathbf{F}_u \mathbf{m} - \mathbf{y}\|_2^2 + \lambda \|\Psi \mathbf{m}\|_p

where:

  • m \mathbf{m} represents the MRI image to be reconstructed.

  • Fu \mathbf{F}_u is the under-sampled Fourier operator, mapping the image to k-space.

  • y \mathbf{y} is the acquired k-space data (limited measurements).

  • Ψ \Psi is the sparsifying transform (e.g., wavelet or total variation).

  • ∥Ψm∥p \|\Psi \mathbf{m}\|_p represents the sparsity constraint, often chosen as ℓ1 \ell_1 (similar to LASSO) or ℓ0 \ell_0 (similar to OMP).

  • λ \lambda controls the balance between data fidelity and sparsity enforcement.

By leveraging sparsity, MRI reconstruction enables faster scans with fewer measurements while preserving essential anatomical details.

Source: Iterative reconstruction: how it works, how to apply it

PyTomography

PyTomography is an open-source Python library designed for medical image reconstruction, particularly in SPECT (Single-Photon Emission Computed Tomography) and PET (Positron Emission Tomography) imaging. Developed to address the challenges of quantitative tomographic reconstruction, PyTomography provides a flexible, modular framework for implementing advanced reconstruction algorithms, including attenuation correction, scatter correction, and resolution modeling.

Key Features

✅ Open-source & community-driven (GitHub)
✅ Supports multiple reconstruction techniques (OSEM, MLEM, deep learning-based methods)
✅ Integrates with GPU acceleration for faster computations
✅ Well-documented with tutorials and API references (ReadTheDocs)
✅ Validated in peer-reviewed research (Scientific Reports, 2024)

Why Use PyTomography?

PyTomography bridges the gap between research and clinical applications by offering:

  • Reproducible reconstruction workflows

  • Customizable forward and backward projection models

  • Seamless integration with Python’s scientific computing stack (NumPy, PyTorch)

Whether for academic research, algorithm development, or clinical prototyping, PyTomography provides a powerful, accessible toolkit for next-generation medical imaging reconstruction.

PySAP

The Python Sparse data Analysis Package (PySAP) was developed as part of COSMIC, a multi-disciplinary collaboration between NeuroSpin, experts in biomedical imaging, and CosmoStat, experts in astrophysical image processing. PySAP is designed to provide state-of-the-art signal processing tools for various imaging domains, including:

  • Astronomy

  • Electron Tomography

  • Magnetic Resonance Imaging (MRI)

One of PySAP’s core contributions lies in sparse optimization, a powerful technique widely used for reconstructing images from incomplete or noisy data. The package implements advanced compressed sensing algorithmsTheodoridis (2020), allowing efficient image restoration while preserving essential features.

In medical imaging, PySAP plays a crucial role in MRI reconstruction by leveraging sparsity-based approaches to improve scan efficiency. It enables:

  • Reduced scanning time while maintaining image quality

  • Improved reconstruction of under-sampled k-space data

  • Integration of machine learning techniques for further enhancement

The first release of PySAP was presented in Farrens et al. Gueddari et al. (2020) and continues to evolve as a robust tool for sparse signal processing.

For further exploration, visit the PySAP GitHub repository.

In our deep learning course, we will encounter additional examples of minimizing ∣∣Ax−b∣∣ ||Ax - b|| , including applications like image deblurring and super-resolution.

For valuable references on Ridge and Shrinkage methods, consider consulting Prof. Arashi’s books Saleh et al. (2019)Saleh et al. (2022).


Linear models for Classification

Aims to find a hyperplane that separates the examples of each class.
For binary classification (2 classes), we aim to fit the following function:

y^=w1∗x1+w2∗x2+...+wp∗xp+w0>0\hat{y} = w_1 * x_1 + w_2 * x_2 +... + w_p * x_p + w_0 > 0

When y^<0\hat{y}<0, predict class -1, otherwise predict class +1

Source
Loading...
  • There are many algorithms for linear classification, differing in loss function, regularization techniques, and optimization method

  • Most common techniques:

    • Convert target classes {neg,pos} to {0,1} and treat as a regression task

      • Logistic regression (Log loss)

      • Ridge Classification (Least Squares + L2 loss)

    • Find hyperplane that maximizes the margin between classes

      • Linear Support Vector Machines (Hinge loss)

    • Neural networks without activation functions

      • Perceptron (Perceptron loss)

    • SGDClassifier: can act like any of these by choosing loss function

      • Hinge, Log, Modified_huber, Squared_hinge, Perceptron

Logistic regression

  • Aims to predict the probability that a point belongs to the positive class

  • Converts target values {negative (blue), positive (red)} to {0,1}

  • Fits a logistic (or sigmoid or S curve) function through these points

    • Maps (-Inf,Inf) to a probability [0,1]

    y^=logistic(fθ(x))=11+e−fθ(x)\hat{y} = \textrm{logistic}(f_{\theta}(\mathbf{x})) = \frac{1}{1+e^{-f_{\theta}(\mathbf{x})}}
  • E.g. in 1D: logistic(x1w1+w0)=11+e−x1w1−w0 \textrm{logistic}(x_1w_1+w_0) = \frac{1}{1+e^{-x_1w_1-w_0}}

Source
Output
Loading...
Loading...
Source
Loading...
  • Fitted solution to our 2D example:

    • To get a binary prediction, choose a probability threshold (e.g. 0.5)

Source
Loading...
Source
Loading...

Loss function: Cross-entropy (Further Reading)

  • Models that return class probabilities can use cross-entropy loss

    Llog(w)=∑n=1NH(pn,qn)=−∑n=1N∑c=1Cpn,clog(qn,c)\mathcal{L_{log}}(\mathbf{w}) = \sum_{n=1}^{N} H(p_n,q_n) = - \sum_{n=1}^{N} \sum_{c=1}^{C} p_{n,c} log(q_{n,c})
    • Also known as log loss, logistic loss, or maximum likelihood

    • Based on true probabilities pp (0 or 1) and predicted probabilities qq over NN instances and CC classes

      • Binary case (C=2): Llog(w)=−∑n=1N[ynlog(y^n)+(1−yn)log(1−y^n)]\mathcal{L_{log}}(\mathbf{w}) = - \sum_{n=1}^{N} \big[ y_n log(\hat{y}_n) + (1-y_n) log(1-\hat{y}_n) \big]

    • Penalty (or surprise) grows exponentially as difference between pp and qq increases

    • Often used together with L2 (or L1) loss: Llog′(w)=Llog(w)+α∑iwi2\mathcal{L_{log}}'(\mathbf{w}) = \mathcal{L_{log}}(\mathbf{w}) + \alpha \sum_{i} w_i^2

  • We will see this loss function in Deep Learning Course

Notebook Cell
Source
Loading...

Optimization methods (solvers) for cross-entropy loss

  • Gradient descent (only supports L2 regularization)

    • Log loss is differentiable, so we can use (stochastic) gradient descent

    • Variants thereof, e.g. Stochastic Average Gradient (SAG, SAGA)

  • Coordinate descent (supports both L1 and L2 regularization)

    • Faster iteration, but may converge more slowly, has issues with saddlepoints

    • Called liblinear in sklearn. Can’t run in parallel.

  • Newton-Rhapson or Newton Conjugate Gradient (only L2):

    • Uses the Hessian H=[∂2L∂xi∂xj]H = \big[\frac{\partial^2 \mathcal{L}}{\partial x_i \partial x_j} \big]: ws+1=ws−ηH−1(ws)∇L(ws)\mathbf{w}^{s+1} = \mathbf{w}^s-\eta H^{-1}(\mathbf{w}^s) \nabla \mathcal{L}(\mathbf{w}^s)

    • Slow for large datasets. Works well if solution space is (near) convex

  • Quasi-Newton methods (only L2)

    • Approximate, faster to compute

    • E.g. Limited-memory Broyden–Fletcher–Goldfarb–Shanno (lbfgs)

      • Default in sklearn for Logistic Regression

  • For further information about conjugate gradients, see Nemati (2018)

  • You will see many of these solvers in Optimization course taught by Dr. Ghanbari.

In practice

  • Logistic regression can also be found in sklearn.linear_model.

    • C hyperparameter is the inverse regularization strength: C=α−1C=\alpha^{-1}

    • penalty: type of regularization: L1, L2 (default), Elastic-Net, or None

    • solver: newton-cg, lbfgs (default), liblinear, sag, saga

  • Increasing C: less regularization, tries to overfit individual points

from sklearn.linear_model import LogisticRegression
lr = LogisticRegression(C=1).fit(X_train, y_train)
Source
Output
Loading...
Loading...
Source
Loading...
Loading...
  • Analyze behavior on the breast cancer dataset

    • Underfitting if C is too small, some overfitting if C is too large

    • We use cross-validation because the dataset is small

Source
Loading...
  • Again, choose between L1 or L2 regularization (or elastic-net)

  • Small C overfits, L1 leads to sparse models

Source
Output
Loading...
Loading...
Loading...
Source
Loading...
Loading...
Loading...

Note: Data scaling helps convergence, minimizes differences between solvers

newton-cg  → Iterations: 19 (unscaled)
lbfgs      → Iterations: 43 (unscaled)
liblinear  → Iterations: 14 (unscaled)
sag        → Iterations: 1000 (unscaled)
saga       → Iterations: 1000 (unscaled)
newton-cg  → Iterations: 5 (scaled)
lbfgs      → Iterations: 7 (scaled)
liblinear  → Iterations: 5 (scaled)
sag        → Iterations: 21 (scaled)
saga       → Iterations: 12 (scaled)

Ridge Classification

  • Instead of log loss, we can also use ridge loss:

    LRidge=∑n=1N(yn−(wxn+w0))2+α∑i=1pwi2\mathcal{L}_{Ridge} = \sum_{n=1}^{N} (y_n-(\mathbf{w}\mathbf{x_n} + w_0))^2 + \alpha \sum_{i=1}^{p} w_i^2
  • In this case, target values {negative, positive} are converted to {-1,1}

  • Can be solved similarly to Ridge regression:

    • Closed form solution (a.k.a. Cholesky)

    • Gradient descent and variants

      • E.g. Conjugate Gradient (CG) or Stochastic Average Gradient (SAG,SAGA)

    • Use Cholesky for smaller datasets, Gradient descent for larger ones

Linear Models for multiclass classification

one-vs-rest (aka one-vs-all)

  • Learn a binary model for each class vs. all other classes

  • Create as many binary models as there are classes

Source
Loading...
  • Every binary classifiers makes a prediction, the one with the highest score (>0) wins

Source
Loading...

one-vs-one

  • An alternative is to learn a binary model for every combination of two classes

    • For CC classes, this results in C(C−1)2\frac{C(C-1)}{2} binary models

    • Each point is classified according to a majority vote amongst all models

    • Can also be a ‘soft vote’: sum up the probabilities (or decision values) for all models. The class with the highest sum wins.

  • Requires more models than one-vs-rest, but training each one is faster

    • Only the examples of 2 classes are included in the training data

  • Recommended for algorithms than learn well on small datasets

    • Especially SVMs and Gaussian Processes

Loading...
Source
Loading...

Linear models overview

NameRepresentationLoss functionOptimizationRegularization
Least squaresLinear function (R)SSECFS or SGDNone
RidgeLinear function (R)SSE + L2CFS or SGDL2 strength (α\alpha)
LassoLinear function (R)SSE + L1Coordinate descentL1 strength (α\alpha)
Elastic-NetLinear function (R)SSE + L1 + L2Coordinate descentα\alpha, L1 ratio (ρ\rho)
SGDRegressorLinear function (R)SSE, Huber, ϵ\epsilon-ins,... + L1/L2SGDL1/L2, α\alpha
Logistic regressionLinear function (C)Log + L1/L2SGD, coordinate descent,...L1/L2, α\alpha
Ridge classificationLinear function (C)SSE + L2CFS or SGDL2 strength (α\alpha)
Linear SVMSupport VectorsHinge(1)Quadratic programming or SGDCost (C)
Least Squares SVMSupport VectorsSquared HingeLinear equations or SGDCost (C)
PerceptronLinear function (C)Hinge(0)SGDNone
SGDClassifierLinear function (C)Log, (Sq.) Hinge, Mod. Huber,...SGDL1/L2, α\alpha
  • SSE: Sum of Squared Errors

  • CFS: Closed-form solution

  • SGD: (Stochastic) Gradient Descent and variants

  • (R)egression, (C)lassification

Summary

  • Linear models

    • Good for very large datasets (scalable)

    • Good for very high-dimensional data (not for low-dimensional data)

  • Can be used to fit non-linear or low-dim patterns as well (see later)

    • Preprocessing: e.g. Polynomial or Poisson transformations

    • Generalized linear models (kernel trick)

  • Regularization is important. Tune the regularization strength (α\alpha)

    • Ridge (L2): Good fit, sometimes sensitive to outliers

    • Lasso (L1): Sparse models: fewer features, more interpretable, faster

    • Elastic-Net: Trade-off between both, e.g. for correlated features

  • Most can be solved by different optimizers (solvers)

    • Closed form solutions or quadratic/linear solvers for smaller datasets

    • Gradient descent variants (SGD,CD,SAG,CG,...) for larger ones

  • Multi-class classification can be done using a one-vs-all approach

References
  1. Rashidabadi, F. (2016). Image Matting [Mathesis, Hakim Sabzevari University, Faculty of Mathematics]. http://hcloud.hsu.ac.ir/index.php/s/OaHkkTSsO8mNrk0
  2. Donoho, D. L. (2006). Compressed Sensing. IEEE Transactions on Information Theory, 52(4), 1289–1306. 10.1109/TIT.2006.871582
  3. Theodoridis, S. (2020). Machine Learning: A Bayesian and Optimization Perspective. Academic Press. https://books.google.com/books?id=l-nEDwAAQBAJ
  4. Bakhshali, M. (2018). The subspace pursuit method in sparse optimization [Mathesis, Hakim Sabzevari University, Faculty of Mathematics]. http://hcloud.hsu.ac.ir/index.php/s/jacmnZiPfNFpYfk
  5. Asaran, A. (2016). Super Resolution Via SparseRepresentation [Mathesis, Hakim Sabzevari University, Faculty of Mathematics]. http://hcloud.hsu.ac.ir/index.php/s/W9ImIzeV6C1mqZo
  6. Gueddari, L. E., Giliyar Radhakrishna, C., Ramzi, Z., Farrens, S., Starck, S., Grigis, A., Starck, J.-L., & Ciuciu, P. (2020, January). PySAP-MRI: a Python Package for MR Image Reconstruction. ISMRM Workshop on Data Sampling and Image Reconstruction. https://inria.hal.science/hal-02399267
  7. Saleh, A. K. M. E., Arashi, M., & Kibria, B. M. G. (2019). Theory of Ridge Regression Estimation with Applications. Wiley. https://books.google.com/books?id=v0KCDwAAQBAJ
  8. Saleh, A. K. M. E., Arashi, M., Saleh, R. A., & Norouzirad, M. (2022). Rank-Based Methods for Shrinkage and Selection: With Application to Machine Learning. Wiley. https://books.google.com/books?id=f8p6EAAAQBAJ
  9. Nemati, M. (2018). A Gradient Based Method For TheSpectral Graph Partitioning [Mathesis, Hakim Sabzevari University, Faculty of Mathematics]. https://hcloud.hsu.ac.ir/index.php/s/tR53d9306yZSAc7