KHEIREDDINE RIAHI

Machine Learning: basic algorithms

MACHINE LEARNING · BASIC ALGORITHMS

This page brings together the basic notions of Machine Learning, useful formulas, examples of algorithms and comments on the 17 visualizations. The explanations are grouped by topic to avoid repetition.

Overview of Machine Learning families, from the field of artificial intelligence to neural networks and LLMs
Overview of Machine Learning families and their relationships.

1. Benchmarks and families of Machine Learning

A general map locates artificial intelligence (AI), Machine Learning (ML), Deep Learning (DL), deep neural networks, then Transformers and large language models (LLM). Artificial neural networks (ANN) form a family of models; those that have several hidden layers generally fall under Deep Learning.

1.1 The three main categories of learning

ApproachPrincipleExample
SupervisedLearn from data accompanied by labels.Predict churn.
UnsupervisedFind structures in unlabeled data.Segment customers.
ReinforcementLearn a strategy from the rewards received.Control an autonomous robot.

1.2 Classification of algorithms

FamilyAlgorithmsObjective
RegressionLinear, Ridge, LassoPredict a value.
ClassificationLogistic, SVM, KNN, Naive BayesPredict a class.
Trees and SetsDecision Tree, Random Forest, XGBoostPredict from rules or sets of models.
ClusteringK-Means, DBSCAN, GMMIdentify groups.
Dimensional reductionPCA, t-SNE, UMAPProject or reduce variables.
Deep LearningANN, CNN, RNN, LSTMLearn complex representations.
GenerativeGAN, VAE, TransformersGenerate data or content.
ReinforcementQ-Learning, PPOLearn an action strategy.
Illustrated summary of Machine Learning families and uses
References to Machine Learning families.

2. Fundamental mathematical functions

2.1 Linear function

f(x) = ax + b

Example: Prix = 2 000 × Surface + 15 000. For an area of ​​50 m², the estimated price is 115,000.

2.2 Cost functions

MSE = (1/n) Σᵢ (yᵢ − ŷᵢ)²

MAE = (1/n) Σᵢ |yᵢ − ŷᵢ|

Binary Cross-Entropy = −(1/n) Σᵢ [yᵢ ln(pᵢ) + (1−yᵢ) ln(1−pᵢ)]

The MSE strongly penalizes large errors; the MAE is less sensitive to extreme values; cross-entropy evaluates the predicted probabilities.

2.3 Gradient descent

θₜ₊₁ = θₜ − α∇J(θₜ)

θ represents the parameters, α the learning rate (*learning rate*) and ∇J the gradient. Variants include Batch, SGD, Mini-batch, Momentum, RMSProp and Adam.

2.4 Activation functions

FunctionFormulaCommonly used
Sigmoid1/(1+e⁻ˣ)Binary classification.
Tanhtanh(x)Recurrent networks.
ReLUmax(0,x)Hidden layers.
Leaky ReLUmax(0.01x,x)Limit inactive neurons.
Softmaxeᶻⁱ / ΣⱼeᶻʲMulticlass classification.
GELUxΦ(x)Transformers.

3. Supervised algorithms

3.1 Linear regression

Linear regression predicts a numerical value, such as price, consumption or sales.

ŷ = w₁x₁ + … + wₙxₙ + b

We minimize the MSE. Ridge adds an L2 penalty, Lasso an L1 penalty, and Elastic Net combines L1 and L2.

3.2 Logistic regression

Logistic regression is used for classification, for example to detect spam or predict churn. It transforms a score into probability: z = wᵀx+b ; P(y=1|x) = 1/(1+e⁻ᶻ). It generally uses Binary Cross-Entropy and a decision threshold, for example 0.5.

3.3 Decision tree

A tree chains rules for classification or regression. The Gini index and entropy measure the impurity of the nodes: Gini = 1 − Σₖpₖ² and H = −Σₖpₖ log₂(pₖ). The information gain compares the entropy of the parent to that of its children; in regression, we can use variance reduction or MSE.

3.4 Random Forest

Random Forest aggregates trees trained on bootstrap samples and subsets of variables. In regression, the tree predictions are averaged; in classification, they are combined by majority vote. This aggregation reduces the variance compared to an isolated tree.

3.5 Gradient Boosting, XGBoost and LightGBM

Gradient boosting successively adds trees to correct previous errors: Fₘ(x) = F₀(x) + Σₘ ηhₘ(x). XGBoost exploits the gradient, the Hessian and the regularization; LightGBM promotes speed; CatBoost supports categorical variables.

3.6 K-Nearest Neighbors (KNN)

KNN classifies an observation according to its K nearest neighbors. The Euclidean distance is written d(x,y) = √[Σᵢ(xᵢ−yᵢ)²]. Classification uses a majority vote and regression uses an average. Standardization of variables is important.

3.7 Support Vector Machine (SVM)

SVM searches for a separator hyperplane with maximum margin. The linear boundary is described by wᵀx+b=0 ; an RBF kernel can model non-linear separations: K(x,x′)=exp(−γ||x−x′||²).

3.8 Naive Bayes

Naive Bayes performs probabilistic classification assuming conditional independence of variables: P(A|B)=P(B|A)P(A)/P(B). Common variants are Gaussian, Multinomial and Bernoulli.

4. Unsupervised algorithms, dimension reduction and anomalies

4.1 K-Means

K-Means chooses K centroids, assigns each point to the nearest centroid, recalculates the centers and repeats these steps until stabilization. It minimizes the sum of quadratic distances: J = Σₖ Σₓᵢ∈Cₖ ||xᵢ−μₖ||². The number of groups can in particular be chosen using the elbow method. K-Means is sensitive to outliers and is less suitable for groups of non-convex shapes.

The visualizations show partitions into three, four, and six groups. The crosses indicate the centroids and the borders represent the zones of allocation to the nearest center. Cluster labels identify groups without ranking them by quality.

Example of K-Means clustering into four clusters
K-Means with four clusters.
Visualization of groups and their K-Means labels
Labels of K-Means clusters.
Example of clustering with isolated observations and centroids
Clusters, isolated observations and centroids.

4.2 DBSCAN

DBSCAN forms clusters from sufficiently dense areas. Its parameters are ε, the neighborhood radius, and MinPts, the minimum number of points. A point is central if |Nε(p)| ≥ MinPts, with Nε(p) = {q ∈ D : d(p,q) ≤ ε}. A border point is close to a central point without being central itself; isolated points are considered noise or outliers.

DBSCAN can detect groups of complex shapes and isolated points without fixing the number of clusters in advance. Unlike K-Means, it does not represent groups by centroids.

4.3 Hierarchical clustering

A dendrogram represents successive mergers between observations or groups. The vertical axis indicates the distance or dissimilarity at the time of the merger. A horizontal cut chosen at a given height determines the number of clusters: the lower branches indicate observations merged at a short distance, while the higher branches bring together more dissimilar sets.

Hierarchical clustering dendrogram
Hierarchical groupings and choice of cut.

Other methods include GMM, Mean Shift, OPTICS, and Spectral Clustering.

4.4 PCA — principal component analysis

PCA transforms the initial variables into orthogonal principal components, ordered according to the variance explained. The steps include centering, calculating the covariance, finding the eigenvectors, choosing the components and projecting: Xc = X − X̄ ; Σ = XcᵀXc/(n−1) ; Σv = λv ; Z = XcW.

The visualizations compare the data before and after their projection onto two components, and show that a separation between classes can become more readable. PCA transforms variables and does not create classes.

4.5 UMAP and t-SNE

UMAP and t-SNE project many-dimensional data into a 2D map. Close groups suggest neighboring observations in the original space, but the projected axes do not necessarily have a direct business interpretation. t-SNE seeks above all to preserve local neighborhoods; distances between distant groups do not precisely measure their overall dissimilarity.

A visualization combines UMAP and K-Means: UMAP first reduces the dimension, then K-Means assigns the points to six groups. The projection facilitates inspection, but does not replace analysis in the original space.

4.6 Anomaly detection

Autoencoder

The encoder compresses the data into a latent representation called bottleneck ; the decoder attempts to reconstruct the original data. A high reconstruction error may signal an unusual observation, if the model was primarily trained on normal data.

LOF — Local Outlier Factor

LOF compares the local density of a point to that of its neighbors. A point located in an area that is much less dense than its neighborhood receives a high anomaly score. The visualizations show groups of normal observations and atypical points isolated or close to a group.

Isolation Forest

Isolation Forest builds trees using random splits. Atypical observations are generally isolated in few splits, while ordinary observations require more splits. The visualizations distinguish normal points from detected anomalies and illustrate their early isolation.

A statistical anomaly is not automatically an innovation. In technology monitoring, an expert must review the results to distinguish promising signals from false positives.

5. ANN — artificial neural networks

An ANN consists of an input layer, hidden layers and an output layer. Each neuron performs a weighted combination then applies an activation function: z = Σᵢ wᵢxᵢ + b ; a = f(z).

Example: with x₁=2, x₂=3, w₁=0,5, w₂=0,8 and b=0,1, we obtain z=3,5 and ReLU(z)=3,5.

5.1 Forward propagation

Z⁽ˡ⁾ = W⁽ˡ⁾A⁽ˡ⁻¹⁾ + b⁽ˡ⁾ ; A⁽ˡ⁾ = f(Z⁽ˡ⁾)

5.2 Backpropagation

∂L/∂w = (∂L/∂a)(∂a/∂z)(∂z/∂w)

wₜ₊₁ = wₜ − α ∂L/∂w

Backpropagation calculates the gradients using the chained derivative rule and then updates the weights. An ANN can be shallow; several hidden layers generally characterize a Deep Learning network.

6. Which algorithm to use?

ObjectivePossible methodsWhat to remember
Predict a price or valueLinear Regression, Ridge, LassoNumerical regression.
Predicting churnLogistic Regression, XGBoostSupervised classification.
Detect fraudRandom Forest, XGBoost, GNNCompare performance and data quality.
Segment observationsK-Means, DBSCANChoose according to the shape of the groups and the treatment of noise.
Explore proximities or hierarchyDendrogram, UMAP, t-SNEVisualize structure without overinterpreting projected distances.
Reduce dimensionPCA, UMAP, t-SNEProject variables to facilitate analysis.
Detect anomaliesLOF, Isolation Forest, AutoencoderIdentify observations that deviate from usual behavior.
Analyze imagesCNN, Vision TransformersLearn visual representations.
Study time seriesXGBoost, LSTM, TransformersTake order and temporal dependence into account.
Process or generate textNaive Bayes, BERT, LLMChoose according to the classification or generation task.
Query documentsRAG + LLMRetrieve document context at response time.
Exploit relationshipsGNN, GraphRAGRepresent links as a graph.
Learning from decisionsReinforcement Learning, Q-Learning, PPOLearning from rewards.

7. Machine Learning Project Stages and Metrics

An ML project typically follows the stages below, from business understanding to production monitoring.

StepDescription
1Business Understanding.
2Data Collection.
3Data Preparation.
4Feature Engineering.
5Model Selection.
6Training.
7Rating.
8Deployment.
9Monitoring.

7.1 Evaluation Metrics

Accuracy = (TP+TN)/(TP+TN+FP+FN)

Precision = TP/(TP+FP)

Recall = TP/(TP+FN)

F1 = 2×Precision×Recall/(Precision+Recall)

For classification, Accuracy, Precision, Recall, F1 and AUC-ROC can be used. For regression: MAE, MSE, RMSE and R². For clustering: Silhouette, Davies-Bouldin and Calinski-Harabasz.

8. Recommended learning path

  1. Review the basics of Python, data tables and descriptive statistics.
  2. Understand datasets, variables, labels and data preparation steps.
  3. Study linear and logistic regression, then decision trees and ensemble methods.
  4. Learn to choose suitable metrics and evaluate a model on data distinct from training data.
  5. Explore clustering and dimensionality reduction to analyze data without labels.
  6. Discover neural networks, forward propagation and backpropagation, then deep architectures.
  7. Put these concepts into practice with small projects, and document the results and limitations of the models.