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.
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
What is important for optimization?
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
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\)
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
How to group data ?
Based on object (dis)similarity
Possible to use distances between objects (what kind of distances?)
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 \]
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.
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)]
Load the data
import pandas as pdfrom palmerpenguins import load_penguinspenguins = 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
Data visualization: pairwise representation of numerical variables colored by penguin species
import seaborn as snsg = 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()
Why using clustering in this case?
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)
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)
use dimension reduction technique, c.f. Section 3.4.1
How can we asses the clustering quality?
We can check the clustering inertia (a.k.a within-cluster sum of squares), the lower, the better.
kmeans_res.inertia_
28761673.86622378
How can we compare the clustering partition to the species partition?
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 metricsmetrics.adjusted_rand_score(penguins["species"], penguins["cluster"])
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
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)\)
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]
How can we get a partition with a given number of clusters based on hierarchical clustering?
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.
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.
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).
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}\)
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\))
What can we do?
Investigate the possible relationship or association between \(X\) and \(Y\) (-> statistical analysis), e.g. for interpretability consideration
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\):
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
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\)
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
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.
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
Empirical risk minimization formulation?
\(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
\(\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.
Model formulation?
Linear model: \[\mathbf y = \mathbf X\boldsymbol\beta + \boldsymbol\varepsilon\]
Why using a single multiple linear regression model including the \(p\) predictors? and not \(p\) different simple linear regression of the response on each predictor separately?
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 datasetsX, y = datasets.fetch_california_housing(return_X_y=True)
What is the dimension of the data set
X.shapey.shape
(20640,)
Run a linear regression
from sklearn import linear_modellinreg = linear_model.LinearRegression()linreg.fit(X, y)linreg.coef_
from sklearn.metrics import mean_squared_error, r2_scorey_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
/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
\(\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}\]
from sklearn import datasetsX,y = datasets.load_breast_cancer(return_X_y =True)
Define train and test sets:
from sklearn.model_selection import train_test_splitX_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 StandardScalerscaler = 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 valuelambd =2# trainingclf_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.
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.
Many machine learning methods/algorithms depends on some hyper-parameters. How to choose their value?
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.
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 leukemiadataset 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.
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.
A possible strategy to remplace hyper-parameter calibration: aggregate results from model trained with different hyper-parameter values.
Géron, Aurélien. 2022. Hands-OnMachineLearning with Scikit-Learn, Keras, and TensorFlow. "O’Reilly Media, Inc.". https://github.com/ageron/handson-ml3.
Hastie, T., R. Tibshirani, and J. Friedman. 2013. The Elements of Statistical Learning: Data Mining, Inference, and Prediction. Springer Series in Statistics. Springer New York. https://hastie.su.domains/ElemStatLearn/.
Horst, Allison Marie, Alison Presmanes Hill, and Kristen B Gorman. 2020. Palmerpenguins: Palmer Archipelago (Antarctica) Penguin Data. https://doi.org/10.5281/zenodo.3960218.
We need to specify a different optimizer with the solver parameter as the default one does not handle \(\ell_1\) penalty. See scikit-learndocumentation.↩︎