3  Machine Learning handbook

3.1 Intro

3.1.1 Références

3.1.2 Algebra 101

Notation

  • \(x \in \mathbb R\) scalar value
  • \(\mathbf x = (x_i)_{i=1:d} \in \mathbb R^d\) vector of dimension \(d\)
  • \(\mathbf X = \left[x_{ij}\right]_{i=1:n}^{j=1:p} \in \mathbb R^{n \times p}\) matrix of dimension \(n \times p\)

\[\mathbf X_{n \times p} = \left[ \begin{array}{c|c|c|c|c|c|c} \ \ \ & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \\ \hline \ & \ & \ & x_{ij} & \ & \ & \ \\ \hline \ & \ & \ & \ & \ & \ & \ \end{array} \right] = \left[\begin{array}{c} \mathbf x_1 \\ \vdots \\ \mathbf x_i \\ \vdots \\ \mathbf x_n \end{array}\right] = \left[ \begin{array}{ccccc} \mathbf x^1 & \cdots & \mathbf x^j & \cdots & \mathbf x^p \end{array} \right]\]

  • \(n\) rows \(\mathbf x_i \in\mathbb R^p\)
  • \(p\) columns \(\mathbf x^j \in\mathbb R^n\)

Vectors are by default considered as column vectors:

\[\mathbf x = (x_i)_{i=1:d} = (x_1,\dots,x_i,\dots,x_d)^t = \left(\begin{array}{c} x_1 \\ \vdots \\ x_i \\ \vdots \\ x_d \end{array}\right) \in \mathbb R^d\]

Operations

Say we have two matrices \(\mathbf A = [a_{ij}]_{n\times p} \in \mathbb R^{n\times p}\) and \(\mathbf B = [b_{jk}]_{p\times q}\in \mathbb R^{p\times q}\) and two vectors \(\mathbf c = (c_j)_{j=1:p} \in \mathbb R^p\) and \(\mathbf d = (d_j)_{j=1:p} \in \mathbb R^p\)

  • transpose: \(\mathbf A^t = [a_{ji}]_{p\times n}\) (transpose of a column vector = identical row vector)
  • scalar product: \(\langle \mathbf c, \mathbf d \rangle = \mathbf c^t\,\mathbf d = \sum_{j=1}^p c_j\,d_j\)
  • \(\ell_2\) norm: \(\Vert \mathbf c \Vert_2 = \sqrt{\langle \mathbf c, \mathbf c \rangle} = \sqrt{\mathbf c^t\,\mathbf c} = \sqrt{\sum_{j=1}^p c_j^{\,2}}\)
  • Euclidean distance: \(d(\mathbf c, \mathbf d) = \Vert \mathbf c - \mathbf d \Vert_2\)
  • matrix product: \(\mathbf A\,\mathbf B = \left[ \sum_{j=1}^p a_{ij}\,b_{jk} \right]_{n \times q}\) (caution with dimension concordance), c.f. Figure 3.1.

Figure 3.1: Illustration of the matrix multiplication computation [Credit: Bilou CC BY-SA 3.0 (wikimedia)]

3.1.3 Optimization 101

Scalar function \(f : \mathbb R \to \mathbb R\) such that \(x \in \mathbb R \mapsto y = f(x) \in \mathbb R\)

Optimization: find optimal value (min or max) of a function

  • Global minimum: find \(x^*\in \mathbb R\) such that \(f(x^*) \leq f(x)\) for any \(x \in \mathbb R\)
    • \(x^*\in \mathbb R\) is called the argmin
    • \(y = f(x^*) \in \mathbb R\) is called the min
  • Global minimum: find \(x^*\in \mathbb R\) such that \(f(x^*) \geq f(x)\) for any \(x \in \mathbb R\)
    • \(x^*\in \mathbb R\) is called the argmax
    • \(y = f(x^*) \in \mathbb R\) is called the max

Some characterisitcs of the function simplifies the optimization process, in particular regarding its smnoothness (regularity):

  • convexity
  • continuity
  • derivability

See Figure 3.2 for some example of minimization and maximization of convex, resp. concave, functions.

Global minimum for a convex function

Global maximum for a concave function

Figure 3.2: Global Min/Argmin (left) and Max/Argmax (right) definition for a convex (left) and concave (right) function

Under some regularity assumptions, finding optima candidates can be done by deriving the function and finding coordinate of points for which the derivative is null

\[f'(x^*) = \frac{\partial}{\partial x} f(x^*) = 0\]

See Figure 3.3.

Figure 3.3: The derivative at the optimal point \(f(x^*)\) is null (which corresponds to an horizonatal tangent)

Local optima: when the function is not convex/concav, sometimes only local optima exists, i.e. optimum points on a subset of the space of definition of the function. See Figure 3.4.

Figure 3.4: Multiple local optima for a function that is not convex
Optimization for functions on vector space?

The previous concepts can be generalized to functions \(f : \mathbb R^d \to \mathbb R\) such that \(\mathbf x \in \mathbb R^d \mapsto y = f(\mathbf x) \in \mathbb R\).

In this context, for regular functions, the gradient will be the vector of partial derivatives regarding each parameter and will be null for optimal points.

3.2 Unsupervised learning

3.2.1 What kind of data?

generallyobservations of numerical (or possibly discrete) features/variables without labels nor annotations (either categorical, discrete or numerical)

Data matrix: \(\mathbf X = \left[x_{ij}\right]_{i=1:n}^{j=1:p} \in \mathbb R^{n \times p}\) where \(x_{ij} \in \mathbb R\) = observation \(i\) for variable \(j\)

\[\mathbf X_{n \times p} = \left[ \begin{array}{c|c|c|c|c|c|c} \ \ \ & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \\ \hline \ & \ & \ & x_{ij} & \ & \ & \ \\ \hline \ & \ & \ & \ & \ & \ & \ \end{array} \right] = \left[\begin{array}{c} \mathbf x_1 \\ \vdots \\ \mathbf x_i \\ \vdots \\ \mathbf x_n \end{array}\right] = \left[ \begin{array}{ccccc} \mathbf x^1 & \cdots & \mathbf x^j & \cdots & \mathbf x^p \end{array} \right]\]

  • \(n\) individuals/observations in rows where row \(\mathbf x_i \in\mathbb R^p\) corresponds to individual \(i\)
  • \(p\) features/variables in columns where column \(\mathbf x^j \in\mathbb R^n\) corresponds to variable \(j\)
  1. Data exploration (what can we find in the data)
  • Group observations/individuals that are similar
  • investigate possible relationship (correlation/dependencies) between variables/features
  1. Data generation (c.f. Chapter 6)
  1. And more…
  • Data visualization
  • Clustering

Example: (biology) Single-cell expression data (scRNA-seq) visualization and clustering followed by cell type identification in cluster based on marker genes (c.f. Figure 3.5).

Figure 3.5: Clustering (left) of single cell expression data (PBMC3K scRNA-seq dataset) and identification of cell types (right) [Credit: scanpy]

In the previous example, clustering is directly used to infer biological relevant groups of cells (according to their cell types). The labels are not available beforehand (so we cannot use a supervised learning technique, c.f. Section 3.3), but information can be extracted from the data in an unsupervised way and then used to label the data.

3.2.2 Clustering

Clustering can be applied to:

  • individuals/observations in the feature/variable space
  • features/variables in the individual/observation space
  • Based on object (dis)similarity
  • Possible to use distances between objects (what kind of distances?)
Many different algorithms

See examples in Figure 3.6.

You can also refer to the dedicated page in the scikit-learn documentation.

Figure 3.6: Different clustering algorithms on different 2dimensional datasets [Credit: scikit-learn] [Source code]

K-means

Objective: find a partition of the data points, e.g. of the \(n\) observations \(\mathbf x_1,\dots,\mathbf x_i,\dots,\mathbf x_n\in\mathbb R^p\), into \(K \leq n\) groups, c.f. Figure 3.7

Figure 3.7: Example of K-means clustering (with \(K=10\)) on two-dimensional data points (centroids are marked with white crosses) [Credit: scikit-learn] [Source code]

Optimization problem:

\[\underset{\mathcal S =\{S_k\}_{k=1:K}}{\text{argmin}}\ \sum_{k=1}^K\ \sum_{\mathbf x\in S_k} \left\Vert \mathbf x - \boldsymbol \mu_k \right\Vert^2\]

  • Partition of the data point: \(\mathcal S =\{S_k\}_{k=1:K}\)

  • Centroid of cluster \(S_k\) (a.k.a. mean of points in \(S_k\)): \[\boldsymbol \mu_k = \frac{1}{\vert S_k\vert} \sum_{\mathbf x\in S_k} \mathbf x\]

Minimization of the within-cluster sum of squares (WCSS), a.k.a. within-cluster (or intra-cluster) variance or intertia

Equivalent formulation:

\[\underset{\mathcal S =\{S_k\}_{k=1:K}}{\text{argmin}}\ \sum_{k=1}^K\ \frac{1}{\vert S_k\vert}\sum_{\mathbf x,\mathbf y\in S_k} \left\Vert \mathbf x - \mathbf y \right\Vert^2 \]

Iterative algorithm: see Figure 3.8 or this animation (wikimedia)

Initialization: \(K\) initial centroids (circles) are generated (with \(K=3\))

Step 2: Data points are assigned to the cluster with the nearest centroid

Step 3: The cluster centroids are recalculted

Repeat step 2 and 3 until convergence

Figure 3.8: Illustration of the K-means clustering algorithm steps (with \(K=3\)) on two-dimensional data points [Credit: Weston.pace CC BY-SA 3.0 (wikimedia)]

You can refer to the dedicated page in the scikit-learn documentation.

Application 1 (palmerpenguin dataset)

The palmerpenguins dataset (Horst, Hill, and Gorman 2020) is available for R and Python (PyPI). This is a toy dataset that can be used to study some statistics and machine learning related concepts.

“Data were collected and made available by Dr. Kristen Gorman and the Palmer Station, Antarctica LTER, a member of the Long Term Ecological Research Network.” [https://allisonhorst.github.io/palmerpenguins/]

Figure 3.9: [Credit: Artwork by @allison_horst (CC BY-4.0)]

“The culmen is the upper ridge of a bird’s bill. In the simplified penguins data, culmen length and depth are renamed as variables bill_length_mm and bill_depth_mm to be more intuitive.” [https://allisonhorst.github.io/palmerpenguins/]

Figure 3.10: [Credit: Artwork by @allison_horst (CC BY-4.0)]
  1. Load the data
import pandas as pd
from palmerpenguins import load_penguins
penguins = load_penguins()
penguins
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex year
0 Adelie Torgersen 39.1 18.7 181.0 3750.0 male 2007
1 Adelie Torgersen 39.5 17.4 186.0 3800.0 female 2007
2 Adelie Torgersen 40.3 18.0 195.0 3250.0 female 2007
3 Adelie Torgersen NaN NaN NaN NaN NaN 2007
4 Adelie Torgersen 36.7 19.3 193.0 3450.0 female 2007
... ... ... ... ... ... ... ... ...
339 Chinstrap Dream 55.8 19.8 207.0 4000.0 male 2009
340 Chinstrap Dream 43.5 18.1 202.0 3400.0 female 2009
341 Chinstrap Dream 49.6 18.2 193.0 3775.0 male 2009
342 Chinstrap Dream 50.8 19.0 210.0 4100.0 male 2009
343 Chinstrap Dream 50.2 18.7 198.0 3775.0 female 2009

344 rows × 8 columns

  1. Data visualization: pairwise representation of numerical variables colored by penguin species
import seaborn as sns
g = sns.PairGrid(
    penguins, hue="species", 
    vars=["bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g"]
)
g.map_diag(sns.histplot)
g.map_offdiag(sns.scatterplot)
g.add_legend()

  • to investigate if the physical characteristics of the penguins allow to define a partition of the data that is different than the natural ones (e.g. species, sex, island of origin)
  1. Run a K-Means algorithm on the physical characteristics of the penguins (we will use \(K = 3\) to compare it with the partition by species)

We can use the sklearn.cluster.KMeans() function from scikit-learn.

We will remove rows with missing values since the K-means algorithm cannot manage them.

penguins.shape
penguins = penguins.dropna()
penguins.shape
(333, 8)
  • Extract the physical features
# extract physical features
penguins_phys = penguins[["bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g"]]
  • Run the K-means
from sklearn.cluster import KMeans
kmeans_model = KMeans(n_clusters=3, random_state=0, n_init="auto")
kmeans_res = kmeans_model.fit(penguins_phys)
  • 2-dimensional pairwise scatterplot
penguins.loc[:,"cluster"] = kmeans_res.labels_
g = sns.PairGrid(
    penguins, hue="cluster", 
    vars=["bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g"]
)
g.map_diag(sns.histplot)
g.map_offdiag(sns.scatterplot)
g.add_legend()

  • We can check the clustering inertia (a.k.a within-cluster sum of squares), the lower, the better.
kmeans_res.inertia_
28761673.86622378
  • We can compute the adjusted Rand Index between the two partition. It lies between 0 and 1, the closer to 1, the higher accordance between the two partitions.
from sklearn import metrics

metrics.adjusted_rand_score(penguins["species"], penguins["cluster"])
0.31263458431294716

More details in Section 3.2.2.4.

Hierarchical clustering

Objective: build a hierarchy of clusters

  • agglomerative/ascendant: bottom-up approach where each observations start in a single cluster and then pairs of clusters are iteratively merged based on a between-cluster linkage criterion
  • divisive/descendant: top-down approach where all observations start in the same cluster and then clusters are iteratively split based on a between-cluster linkage criterion

Data points [Credit: CC0 (wikimedia)]

Agglomerative clustering [Credit: Mhbrugman CC BY-SA 3.0 (wikimedia)]

Figure 3.11: Illustration of hierarchical clustering algorithm

Clusters are merged are split based on a between-cluster linkage criterion, a.k.a. a dissimilarity measure between pairs of clusters (based on their data point composition), e.g. for two clusters \(\mathcal A\) and \(\mathcal{B}\):

  • max distance: \(\underset{x\in\mathcal A, y \in \mathcal{B}}{\text{max}}\ d(a,b)\)

  • min distance: \(\underset{x\in\mathcal A, y \in \mathcal{B}}{\text{min}}\ d(a,b)\)

  • average distance: \(\frac{1}{\vert\mathcal{A}\vert\times\vert\mathcal{B}\vert} \sum_{x\in\mathcal A}\sum_{y \in \mathcal{B}} d(a,b)\)

  • and more… (see here for a more exhaustive list)

where \(d(\cdot,\cdot)\) is a distance/metric in the data point space.

Different linkage strategy yield different clustering results, c.f. Figure 3.12.

Figure 3.12: Different clustering algorithms on different 2dimensional datasets [Credit: scikit-learn] [Source code]

The metric used to compute the linkage also matters, see this example (from scikit-learn documentation).

Visualization with a dendrogram = tree built from cluster merging where branch height depends on the linkage value, c.f. Figure 3.13 (example of application to the palmerpenguins dataset).

Figure 3.13: Output of agglomerative hierarchical clustering on the palmerpenguins dataset (leafs are colored according to the individual species) [Source code]

We can “cut” the dendrogram at the chosen number of clusters.

You can refer to the dedicated page in the scikit-learn documentation.

Clustering performance evaluation

In unsupervised setting, it can be difficult to assess the performance of a method since we have no “ground truth” to compare to the results.

In clustering setting, we can compute quantities like:

  • the within-cluster sum of squares to quantify the homogeneity within each cluster
  • the between-cluster sum of squares to quantity the heterogeneity between clusters.
  • the silhouette-coefficient
  • and more.

These quantities can be useful to compare different clustering results.

For benchmark or evaluation purpose, we can compare blind clustering of data with existing labels/annotations that can be used as “ground truth”.

In that case, we can evaluate if the clustering if able to recover the partition of the data points defined by the labels/classes/groups of observations known a priori for instance by using the adjusted Rand Index previously mentioned.

See scikit-learn clustering performance evaluation article for a detail review of various clustering evaluation criteria with or without ground truth.

Choice of the number of clusters

In unsupervised setting, we do not know the “true” number of groups (if it exists) but we generally have to choose the number of clusters that will be infer by the clustering algorithm (e.g. \(K\) for the K-means algorithm).

We can use a clustering evaluation criterion mentioned in Section 3.2.2.4 that does not require a ground truth to tune the number of clusters.

See this example based on the *silhouette coefficient**. (from scikit-learn documentation).

3.2.3 Data visualization

c.f. Section 3.4.1

3.3 Supervised learning

3.3.1 What kind of data?

generally observations of numerical, discrete (or sometimes categorical) features/variables with one or multiple labels or annotations (either categorical, discrete or numerical)

Data: observations of pairs \((\mathbf x_i, y_i)_{i=1:n}\)

  • input variables/covariates/predictors/features: \(\mathbf x_i \in \mathbb R^p\)
  • output variable/response: \(y_i \in \mathbb R\)

Matrix notation:

  • input variables/features: \[\mathbf X = \left[x_{ij}\right]_{i=1:n}^{j=1:p} = \left[\begin{array}{c} \mathbf x_1 \\ \vdots \\ \mathbf x_i \\ \vdots \\ \mathbf x_n \end{array}\right] \in \mathbb R^{n \times p}\] where \(x_{ij} \in \mathbb R\) = observation \(i\) for variable \(j\)
  • output variable/response: \[\mathbf y = \left(\begin{array}{c} y_1 \\ \vdots \\ y_i \\ \vdots \\ y_n \end{array}\right)\in \mathbb R^n\]
Multivariate response

Sometime the response is also multivariate (i.e. with multiple response variables):

\[\mathbf Y = \left[y_{i\ell}\right]_{i=1:n}^{\ell=1:q} = \left[\begin{array}{c} \mathbf y_1 \\ \vdots \\ \mathbf y_i \\ \vdots \\ \mathbf y_n \end{array}\right] \in \mathbb R^{n \times q}\] where \(y_{i\ell} \in \mathbb R\) = observation \(i\) for output variable \(\ell\) and \(\mathbf y_i \in \mathbb R^q\) = observation \(i\) of the various response variables

Abstract notation

The set of input variables is generally denoted \(X\) and the response \(Y\) when referring to them as random variables that are observed on a sample.

With our notations, \(\mathbf X_{n\times p}\) collects the observations of \(X\) and \(\mathbf Y_{n \times q}\) the observations of \(Y\) on the observed samples.

Sometimes \(\mathcal X\) also refers to the input space (i.e. the space of possible values for the input variable \(X\)) and \(\mathcal Y\) refers to the output space (i.e. the space of possible values for the output variable \(Y\))

  1. Investigate the possible relationship or association between \(X\) and \(Y\) (-> statistical analysis), e.g. for interpretability consideration

  2. Predict \(Y\) by observing \(X\)

  3. And more…

  • spam detector in a mail system
  • image content segmentation/detection
  • conversational agent (ChatBot, vocal assistant)
  • protein folding
  • disease occurrence/survival (from physiological, genomic data, etc.)
  • and more…

Many different algorithms for different tasks: see scikit-learn related [documentation] for instance.

3.3.2 A little bit of theory

Objective
  • find the best function \(f^* : \mathcal X \to \mathcal Y\) in a given function space \(\mathcal F\) such that conceptually \(f^*(X)\) can be used to “approximate” \(Y\)

To do so, we can only use:

  • the training set, i.e. the observed data \((\mathbf x_i, y_i)_{i=1:n}\), what is called
  • a loss function \(L: \mathcal Y \times \mathcal Y \to \mathbb R\) that “quantify” how “good” a candidate function \(f \in \mathcal F\) to “approximate” \(Y\) by \(f(X)\)
Empirical risk minimization

Most of supervised machine learning methods can be defined by specifying:

  • a family of candidate functions \(\mathcal F\) such that \(f(X)\) “approximate” \(Y\)
  • a loss/objective function \(L\)

Then \(f^*\) is computed by minimizing the empirical risk, i.e. the empirical gap between \(Y\) and \(f(X)\) quantified by \(L\):

\[\underset{f\in\mathcal F}{\text{argmin}} \sum_i L(y_i, f(\mathbf x_i))\]

Prediction/Inferrence

Once \(f^*\) is learned thanks to the previous optimization procedure, we can use it to predict the response value corresponding to a new (potentially unlabeled/annotated) observation \(\mathbf x_{n+1}\).

The predicted value \(\widehat{y}_{n+1}\) for the potentially unknown \(y_{n+1}\) will be given by \(f^*(\mathbf x_{n+1})\).

The statistical point of view
  1. We define a probabilistic model \(\mathcal M\), i.e. a probabilistic distribution, \(p_{\mathcal M}(Y \vert g(X))\) for a given function \(g(.)\) of the input variable quantifying the randomness of the values taken by \(Y\) knowing \(X\)

  2. Then we estimate the model \(p_{\mathcal M}\) parameter by maximizing its likelihood knowing the data, which can be viewed as an empirical risk minimization.

Note: some statistical approaches, e.g. Bayesian statistics, use different paradigms (beyond the scope of this training).

3.3.3 Regression

Application case: the response \(Y\) is a numerical variable

Linear regression

Empirical risk minimization: \(\underset{f\in\mathcal F}{\text{argmin}} \sum_i L(y_i, f(\mathbf x_i))\)

  • loss function \(L\) = Euclidean distance
  • candidate functions \(f\in\mathcal F\) = linear functions

Simple linear regression

We consider the specific case where \(p=1\).

Dataset: \((x_i, y_i)_{i=1:n}\) with \(x_i,y_i\in\mathbb R\)

  • \(f_{\beta_0,\beta_1}(x_i) = \beta_0 + \beta_1 x_i\) with the intercept \(\beta_0\in\mathbb R\) and the slope \(\beta_1\in\mathbb R\)
  • \(\underset{\beta_0,\beta_1\in\mathbb R}{\text{argmin}} \sum_i \left(y_i - f_{\beta_0,\beta_1}(x_i)\right)^2\)
  • Linear model: \[y_i = \beta_0 + \beta_1 x_i + \varepsilon_i\]
  • Error term, a.k.a. residuals: \(\varepsilon_i\)
  • Objective: \(\underset{\beta_0,\beta_1\in\mathbb R}{\text{argmin}}\sum_i \varepsilon_i^{\,2}\)

This is called Ordinary Least Squares (OLS) regression, see Figure 3.14 for an illustration.

Figure 3.14: Ordinary Least Squares (OLS) regression [Credit: Mirko Stojiljković (realpython.com)]

Regular (convex and derivable) objective function so we can find the values for \(\beta_0\) and \(\beta_1\) such that the gradient (\(\approx\) derivative regarding these parameters) is null.

Closed-form solution?

  • \(\widehat{\beta}_1 = \frac{\sum_i (x_i - \bar{x})(y_i - \bar{y})}{\sum_i (x_i - \bar{x})^2}\)
  • \(\widehat{\beta}_0 = \bar{y} - \beta_1\bar{x}\)

where \(\bar{x} = \frac{1}{n} \sum_i x_i\) and \(\bar{y} = \frac{1}{n} \sum_i y_i\) are the respective empirical means for \(X\) and \(Y\)

Mulitple linear regression

What happens when \(p>1\), i.e. when we have more than

  • \(f_{\boldsymbol\beta}:\mathbb R^p \to \mathbb R\) is a linear function \[f_{\boldsymbol\beta}(\mathbf x_{i}) = f_{\boldsymbol\beta}(x_{i1},\dots,x_{ip}) = \beta_0 + \left( \sum_{j=1}^p x_{ij}\,\beta_j \right)\] with \(\beta_0\) the intercept, \((\beta_j)_{j=1:p}\) the linear coefficients
  • notation: \(\boldsymbol\beta = (\beta_j)_{j=0:p} \in \mathbb R^{p+1}\)
  • \(\underset{\boldsymbol\beta\in\mathbb R^{p+1}}{\text{argmin}} \sum_i \left(y_i - f_{\boldsymbol\beta}(\mathbf x_{i})\right)^2\)

Matrix notation:

  • \(\underset{\boldsymbol\beta\in\mathbb R^{p+1}}{\text{argmin}} \left\Vert \mathbf y - \mathbf X\boldsymbol\beta\right\Vert_2^{\,2}\)

Where did \(\beta_0\) go? we can replace \(\mathbf X\) by a matrix \(\left[\boldsymbol 1, \mathbf X\right]_{n\times (p+1)}\) and not consider the intercept, which is equivalent.

  • Linear model: \[\mathbf y = \mathbf X\boldsymbol\beta + \boldsymbol\varepsilon\]
  • Error term, a.k.a. residuals: \(\boldsymbol\varepsilon = (\varepsilon_i)_{i=1:n} \in\mathbb R^n\)
  • Objective: \(\underset{\beta_0,\beta_1\in\mathbb R}{\text{argmin}}\ \Vert \boldsymbol\varepsilon\Vert_2^{\,2}\)

Regular (convex and derivable) objective function so we can find the values for \(\boldsymbol\beta\in\mathbb R^{p+1}\) such that the gradient is null.

Closed-form solution?

\[\widehat{\boldsymbol\beta} = \left( \mathbf X^t \mathbf X \right)^{-1} \mathbf X^t \mathbf y\]

  • Combination of predictors can potentially give better performance for prediction
  • Summarized view of the data in a single model
  • \(p\) can be large (e.g. up to \(10000\) when analyzing genomes), do we want to fit and interpret \(p\) model in this case?

Application 2 (California housing dataset)

California housing dataset: predict median house value for California districts based on various numerical district attributes.

To load the dataset:

from sklearn import datasets

X, y = datasets.fetch_california_housing(return_X_y=True)
X.shape
y.shape
(20640,)
Run a linear regression
from sklearn import linear_model

linreg = linear_model.LinearRegression()
linreg.fit(X, y)
linreg.coef_
array([ 4.36693293e-01,  9.43577803e-03, -1.07322041e-01,  6.45065694e-01,
       -3.97638942e-06, -3.78654265e-03, -4.21314378e-01, -4.34513755e-01])

More details can be found here (in scikit-learn documentation).

Regression model performance evaluation

Various metrics exist for linear model evaluation, including:

from sklearn.metrics import mean_squared_error, r2_score

y_pred = linreg.predict(X)
r2_score(y, y_pred)
mean_squared_error(y, y_pred)
0.5243209861846072

In this example, we use the same data for the training and the evaluation (since the prediction is done on the training set), which is not a very good idea as we will see in ?sec-validation.

3.3.4 Classification

Application case: the response \(Y\) is a categorical variable

We aim at predicting the class/label/category of the observed data.

  • Binary case: \(Y \in \{0,1\}\)
  • Multicategorical case \(Y \in \{0,1,\dots,G-1\}\) with G groups

Example: handwritten digits classification, c.f. Figure 3.15.

Figure 3.15: MNIST dataset [Credit: Suvanjanprasai (CC BY-SA 4.0)]

Figure 3.16: ?(caption)

Logistic regression

Generalization of linear regression to binary classification

Empirical risk minimization: \(\underset{f\in\mathcal F}{\text{argmin}} \sum_i L(y_i, f(\mathbf x_i))\)

  • loss function \(L\) = log-likelihood
  • candidate functions \(f\in\mathcal F\) = linear functions

\[\underset{f\in\mathcal F}{\text{argmin}} \sum_i L(y_i, f(\mathbf x_i))\]

Generalized linear model

  • \(Y_i \sim \mathcal{B}(\pi)\)

\[\underset{f\in\mathcal F}{\text{argmin}} \sum_i p_{\pi_i}\left(y_i \vert f(\mathbf x_i)\right)\]

  • Linear function: \[f(\mathbf x) = \mathbf x^t\boldsymbol\beta\]

  • Predict the probability \(\pi\in[0,1] = \mathbb P(Y_i = 1)\)

Example with the “Breast cancer” dataset:

from sklearn import datasets

breast_cancer = datasets.load_breast_cancer()

breast_cancer.target

breast_cancer.data.shape

X,y = datasets.load_breast_cancer(return_X_y = True)

from sklearn.linear_model import LogisticRegression

clf = LogisticRegression(penalty = None)
clf.fit(X, y)
clf.predict_proba(X)
/home/fradav/.conda/envs/formation-env/lib/python3.10/site-packages/sklearn/linear_model/_logistic.py:458: ConvergenceWarning:

lbfgs failed to converge (status=1):
STOP: TOTAL NO. of ITERATIONS REACHED LIMIT.

Increase the number of iterations (max_iter) or scale the data as shown in:
    https://scikit-learn.org/stable/modules/preprocessing.html
Please also refer to the documentation for alternative solver options:
    https://scikit-learn.org/stable/modules/linear_model.html#logistic-regression
array([[1.00000000e+00, 3.02161572e-15],
       [9.99999986e-01, 1.44511136e-08],
       [9.99999881e-01, 1.19007002e-07],
       ...,
       [9.92906449e-01, 7.09355116e-03],
       [1.00000000e+00, 1.24978434e-10],
       [1.19744128e-02, 9.88025587e-01]])

Logistic regression can be viewed as a nonlinear regression, hence the awkward “regression” term for a “classifier”.

Generalist approaches

For regression and classification:

Figure 3.17: Illustration of Support Vector Machine [Credit: Larhmam CC BY-SA 4.0 (wikimedia)]

Figure 3.18: Illustration of \(k\)-nearest neighbor algorithm [Credit: Antti Ajanki AnAj CC BY-SA 4.0 (wikimedia)]

Regression and classification performance evaluation

See the “metrics and scoring quantifying the quality of predictions” section in scikit-learn documentation and tomorrow.

3.4 The curse of dimensionality

  • Large dimension: large number of variables \(p\)
  • Large scale: large number of observations \(n\)
  • high dimensional data: \(p > n\)
Issue with large dimension (large \(p\)) and high dimension (\(p>n\))?
  • “Everyone is far from everyone in large dimension” (the curse of dimensionality)
  • Numerical, algebraic or geometric singularities

Example in Figure 3.19

Figure 3.19: Average distance between 500 points of dimension \(d\) uniformly sampled from the Hypercube [0,1]

3.4.1 Dimension reduction

Feature projection, embedding, latent space representation, data decomposition

Purpose:

  • Solve dimensionality issue
  • visualization
  • compression (example with MNIST)

Unsupervised dimension reduction:

\[\begin{array}{ccc} \mathbf X_{n\times p} = \left[ \begin{array}{c|c|c|c|c} \ \ \ & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \\ \hline & & & & \\ \hline & & x_{ij} & & \\ \hline & & & & \\ \hline & & & & \\ \end{array} \right] & \longrightarrow & \mathbf U_{n\times K} = \left[ \begin{array}{c|c|c} \ \ \ & \ \ \ \, & \ \ \ \\ \hline & & \\ \hline & u_{ik} & \\ \hline & & \\ \hline & & \\ \end{array} \right] \\ & & \\ \begin{array}{cccc} & & & \Big\downarrow \end{array} & & \\ \\ \mathbf V^t_{K\times p} = \left[ \begin{array}{c|c|c|c|c} \ \ \ & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, \\ \hline & & v_{kj} & & \\ \hline & & & & \\ \end{array} \right] \end{array}\]

  • Latent dimension \(= K\)
  • Latent space representation of observations = \(\mathbf U_{n\times K}\)
  • Latent space representation of features = \(\mathbf V_{p\times K}\)

Dimension reduction for supervised learning:

\[\begin{array}{ccc} \mathbf X_{n\times p} = \left[ \begin{array}{c|c|c|c|c|c} \ \ \ & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \, & \ \ \ \\ \hline & & x_{ij} & & & \\ \hline & & & & & \\ \end{array} \right] & \longrightarrow & \mathbf U_{n\times K} = \left[ \begin{array}{c|c|c} \ \ \ & \ \ \ \, & \ \ \ \\ \hline & u_{ik} & \\ \hline & & \\ \end{array} \right]\\ \\ && \text{predict} \ \ \Big\downarrow \\ \\ & & \ \ \ \ \ \ \ Y = \left[\begin{array}{c} \vdots \\ y_i \\ \vdots \end{array}\right] \end{array}\]

Principal Component Analysis (PCA)

\[\mathbf T_{n\times K} = \mathbf X_{n\times K} \ \mathbf W_{p\times k}\]

  • \(\mathbf W_{p\times k}\) and then \(\mathbf T_{n\times K}\) are computed to maximize the variance of components \(\mathbf X\mathbf w_j\) where \(\mathbf w_j\) is row \(j\) of \(\mathbf W_{p\times k}\)
  • Optimization problem: \[\underset{\mathbf w\in \mathbb R}{\text{argmax}}\ \mathbf w^t \tilde{\mathbf X}^t \tilde{\mathbf X} \mathbf w\] where \(\tilde{\mathbf X}\) is the centered version of \(\mathbf X\)

Matrix factorization

\[\underset{\mathbf U\in\mathbb R^{n\times K},\mathbf V\in\mathbb R^{p\times K}}{\text{argmin}}\ \left\Vert \mathbf X - \mathbf U \mathbf V^t \right\Vert_{F}^{\,2}\]

Non linear

Application 3

Penguin dataset:

import pandas as pd
from palmerpenguins import load_penguins
penguins = load_penguins().dropna()
penguins
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g sex year
0 Adelie Torgersen 39.1 18.7 181.0 3750.0 male 2007
1 Adelie Torgersen 39.5 17.4 186.0 3800.0 female 2007
2 Adelie Torgersen 40.3 18.0 195.0 3250.0 female 2007
4 Adelie Torgersen 36.7 19.3 193.0 3450.0 female 2007
5 Adelie Torgersen 39.3 20.6 190.0 3650.0 male 2007
... ... ... ... ... ... ... ... ...
339 Chinstrap Dream 55.8 19.8 207.0 4000.0 male 2009
340 Chinstrap Dream 43.5 18.1 202.0 3400.0 female 2009
341 Chinstrap Dream 49.6 18.2 193.0 3775.0 male 2009
342 Chinstrap Dream 50.8 19.0 210.0 4100.0 male 2009
343 Chinstrap Dream 50.2 18.7 198.0 3775.0 female 2009

333 rows × 8 columns

Scaling:

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaled_penguins = scaler.fit_transform(
    penguins[["bill_length_mm","bill_depth_mm","flipper_length_mm","body_mass_g"]].values
    )

PCA fit:

from sklearn.decomposition import PCA
pca = PCA(n_components=2)
penguins_T = pca.fit_transform(scaled_penguins)

Visualization:

import pandas as pd
penguins_T = pd.DataFrame(penguins_T, columns = ['PC1','PC2'])
penguins_T["species"] = penguins["species"]

import seaborn as sns
sns.scatterplot(penguins_T, x="PC1", y="PC2", hue="species")
<Axes: xlabel='PC1', ylabel='PC2'>

Model evaluation:

  • explained variance:
pca.explained_variance_
array([2.75362487, 0.7804609 ])
  • Percentage of explained variance
pca.explained_variance_ratio_
array([0.68633893, 0.19452929])

3.4.2 Regularization

Penalized risk minimization:

\[\underset{\boldsymbol\theta\in\mathbb R^p}{\text{argmin}}\ \sum_i R_{\boldsymbol\theta}(y_i, \mathbf x_i)) + \lambda\, \text{Pen}(\boldsymbol\theta)\]

  • \(R_{\boldsymbol\theta}(y_i, \mathbf x_i)\) = risk that is parametrized by the vector \(\boldsymbol\theta = (\theta_j)_{j=1:p}\)

  • \(\text{Pen}(\boldsymbol\theta)\) is a regularization term based on a penalty

Different type of regularization:

  • Ridge: \(\text{Pen}(\boldsymbol\theta) = \sum_{j=1}^p (\theta_j)^2 = \Vert \boldsymbol\theta \Vert_2^{\,2}\)

  • Lasso: \(\text{Pen}(\boldsymbol\theta) = \sum_{j=1}^p \vert \theta_j \vert = \Vert \boldsymbol\theta \Vert_1\)

Figure 3.20: Coefficients estimation with OLS, Ridge and Lasso regression (data where \(n = 50\), \(p = 100\))

Example

from sklearn import datasets

X,y = datasets.load_breast_cancer(return_X_y = True)
  • Define train and test sets:
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
  • Scaling (we use X_train as reference for scaling):
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(X_train)

X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)
  • Ridge logistic regression (\(\ell_2\) penalty):
from sklearn.linear_model import LogisticRegression

# hyper-parameter value
lambd = 2

# training
clf_l2 = LogisticRegression(penalty = "l2", C = 1/lambd)
clf_l2.fit(X_train, y_train)
LogisticRegression(C=0.5)
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
  • Lasso logistic regression1 (\(\ell_1\) penalty):
# hyper-parameter value
lambd = 2

# training
clf_l1 = LogisticRegression(penalty = "l1", C = 1/lambd, solver = "liblinear")
clf_l1.fit(X_train, y_train)
LogisticRegression(C=0.5, penalty='l1', solver='liblinear')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
  • Prediction on test set:
# Ridge
y_pred_l2 = clf_l2.predict(X_test)
# Lasso
y_pred_l1 = clf_l1.predict(X_test)
  • Compare prediction performance (using accuracy = 1 - error of prediction):
from sklearn.metrics import accuracy_score

# Ridge
acc_l2 = accuracy_score(y_test, y_pred_l2)

# Lasso
acc_l1 = accuracy_score(y_test, y_pred_l1)

# print
print(f"Ridge logistic regression accuray = {acc_l2}")
print(f"Lasso logistic regression accuray = {acc_l1}")
Ridge logistic regression accuray = 0.9736842105263158
Lasso logistic regression accuray = 0.9649122807017544

How to choose the hyper-parameter \(\lambda\)?

3.5 Hyper-parameter calibration

We need to use a calibration or tuning procedure to choose the best value for each hyper-parameter, i.e. the values giving the best performance result (c.f. #fig-hyperparam-tuning)

Figure 3.21: Hyper-parameter tuning process [Credit: scikit-learn]

Two levels:

  • the grid of candidates values for each hyper-parameters (dimension scales with the number of hyper-parameters)

  • the procedure to evaluate the performance for given values for each hyper-parameter

Standard procedure for hyper-parameter calibration: cross-validation based on a split of the data in a training set for training the model and a test set to evaluate the model performance.

*Purpose:** avoid risk of overfitting (bad generalization ability) and dependency to train/test split choice.

Different cross-validation procedures:

  • \(K\)-fold: c.f. #fig-cross-valid
  • Leave-one-out (LOO) or Leave-p-out (LPO): repetition of random train/test split leaving one or \(p\) observations out of the training in the test set
  • repeated random train/test split
  • specific procedures for grouped data or for classification with unbalanced classes

Figure 3.22: K-fold cross-validation process [Credit: scikit-learn]

Example with the leukemia dataset containing images of tumors partitionned in two different classes.

  • Load the data
from sklearn import datasets

# X,y = datasets.load_breast_cancer(return_X_y = True)

X, y = leukemia = datasets.fetch_openml('leukemia', return_X_y = True)

X.shape
/home/fradav/.conda/envs/formation-env/lib/python3.10/site-packages/sklearn/datasets/_openml.py:301: UserWarning:

Multiple active versions of the dataset matching the name leukemia exist. Versions may be fundamentally different, returning version 1.

/home/fradav/.conda/envs/formation-env/lib/python3.10/site-packages/sklearn/datasets/_openml.py:968: FutureWarning:

The default value of `parser` will change from `'liac-arff'` to `'auto'` in 1.4. You can set `parser='auto'` to silence this warning. Therefore, an `ImportError` will be raised from 1.4 if the dataset is dense and pandas is not installed. Note that the pandas parser may return different data types. See the Notes Section in fetch_openml's API doc for details.
(72, 7129)
  • 5-fold cross-validation
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.linear_model import RidgeClassifier
from sklearn.linear_model import LogisticRegression

# method = scaling + Lasso logistic regression
make_pipeline(StandardScaler(), LogisticRegression(penalty = "l1", solver = "liblinear")).get_params()

# 5-fold cross-validation
params = {'logisticregression__C': [0.1, 0.5, 1, 5, 10]}
grid_search = GridSearchCV(
    make_pipeline(
        StandardScaler(), 
        LogisticRegression(penalty = "l1", solver = "liblinear")
    ), 
    params,
    scoring = "accuracy",
    cv = 5
)
grid_search.fit(X, y)
GridSearchCV(cv=5,
             estimator=Pipeline(steps=[('standardscaler', StandardScaler()),
                                       ('logisticregression',
                                        LogisticRegression(penalty='l1',
                                                           solver='liblinear'))]),
             param_grid={'logisticregression__C': [0.1, 0.5, 1, 5, 10]},
             scoring='accuracy')
In a Jupyter environment, please rerun this cell to show the HTML representation or trust the notebook.
On GitHub, the HTML representation is unable to render, please try loading this page with nbviewer.org.
  • CV results
import pandas as pd

pd.DataFrame(grid_search.cv_results_)
mean_fit_time std_fit_time mean_score_time std_score_time param_logisticregression__C params split0_test_score split1_test_score split2_test_score split3_test_score split4_test_score mean_test_score std_test_score rank_test_score
0 0.414928 0.062642 0.115114 0.004353 0.1 {'logisticregression__C': 0.1} 1.000000 0.866667 1.0 0.928571 0.785714 0.916190 0.082071 5
1 0.385337 0.059155 0.110978 0.000341 0.5 {'logisticregression__C': 0.5} 0.933333 0.933333 1.0 1.000000 0.857143 0.944762 0.052992 4
2 0.385803 0.058738 0.110503 0.000173 1 {'logisticregression__C': 1} 1.000000 0.933333 1.0 1.000000 0.928571 0.972381 0.033860 1
3 0.389688 0.057354 0.110990 0.000900 5 {'logisticregression__C': 5} 1.000000 0.933333 1.0 1.000000 0.928571 0.972381 0.033860 1
4 0.396852 0.065786 0.111278 0.000519 10 {'logisticregression__C': 10} 1.000000 0.933333 1.0 1.000000 0.928571 0.972381 0.033860 1
grid_search.best_params_
{'logisticregression__C': 1}
  • Comparison with calibration on a single train/test split
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import pandas as pd

# train/test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

# scaling
scaler = StandardScaler()
scaler.fit(X_train)
X_train = scaler.transform(X_train)
X_test = scaler.transform(X_test)

# calibration
calib_res = []
for param_val in [0.1, 0.5, 1, 5, 10]:
    tmp_clf = make_pipeline(
        StandardScaler(), 
        LogisticRegression(penalty = "l1", solver = "liblinear", C = param_val)
    )
    tmp_clf.fit(X_train, y_train)
    calib_res.append([param_val, accuracy_score(tmp_clf.predict(X_test), y_test)])
    
pd.DataFrame(calib_res, columns = ['Param', 'Accuracy'])
Param Accuracy
0 0.1 1.0
1 0.5 1.0
2 1.0 1.0
3 5.0 1.0
4 10.0 1.0

3.6 Ensemble methods

Combines weak predictors results (average in regression and voting in classification) to get a better predictor

See scikit-learn documentation for more details.

Different strategies and combination:

  • feed different randomly sub-sampled observations to each predictor (e.g. bagging)
  • feed different randomly sub-sampled observations and use a subset of the variables to each predictor (e.g. boosting)

Example of random forest:

Figure 3.23: Decision tree and random forest [Credit: Jeremy Beauchamp CC BY-SA 4.0 (wikimedia)]

A possible strategy to remplace hyper-parameter calibration: aggregate results from model trained with different hyper-parameter values.


  1. We need to specify a different optimizer with the solver parameter as the default one does not handle \(\ell_1\) penalty. See scikit-learn documentation.↩︎