Commit 0ad9b6

2026-07-10 12:03:30 lugonthier: Remove "07 Regularization and high-dimensional inference" chapter and add "07 Support Vector Machines" and "08 Decision trees and ensemble methods" chapters with corresponding images.
en/Deep Learning.md ..
@@ 2,7 2,7 @@
Neural networks from the single perceptron to modern transformers: how depth, the right activations, and gradient-based training let a model learn its own features instead of hand-crafted ones.
- **Prerequisites:** the [Machine Learning](/en/Machine%20Learning) course (especially the perceptron in [Linear classification](/en/Machine%20Learning/06%20Linear%20classification)), basic Python, calculus, and linear algebra.
+ **Prerequisites:** the [Machine Learning](/en/Machine%20Learning) course (especially the perceptron in [Linear classification](/en/Machine%20Learning/05%20Linear%20classification)), basic Python, calculus, and linear algebra.
## Syllabus
@@ 22,7 22,6 @@
14. [LSTM and GRU](/en/Deep%20Learning/14%20LSTM%20and%20GRU)
15. [Attention](/en/Deep%20Learning/15%20Attention)
16. [Transformers](/en/Deep%20Learning/16%20Transformers)
- 17. [Deep learning in practice](/en/Deep%20Learning/17%20Deep%20learning%20in%20practice)
---
[Machine Learning](/en/Machine%20Learning) · [MLOps](/en/MLOps) · [Home](/en)
en/Deep Learning/01 Introduction.md ..
@@ 1,6 1,6 @@
# 1. Introduction
- This course continues directly from the Machine Learning course, which closed the [Linear classification](/en/Machine%20Learning/06%20Linear%20classification) part with a key remark: a perceptron is a single unit, and stacked into layers it becomes a neural network. This lesson makes that bridge explicit. It recalls what one unit can do, shows the concrete task (XOR) where a single unit fails, and fixes the notation used throughout the rest of the course.
+ This course continues directly from the Machine Learning course, which closed the [Linear classification](/en/Machine%20Learning/05%20Linear%20classification) part with a key remark: a perceptron is a single unit, and stacked into layers it becomes a neural network. This lesson makes that bridge explicit. It recalls what one unit can do, shows the concrete task (XOR) where a single unit fails, and fixes the notation used throughout the rest of the course.
**Objectives**
- Recall the perceptron as a single unit with a step activation and a linear boundary.
en/Deep Learning/16 Transformers.md ..
@@ 109,7 109,7 @@
*Remark:* an encoder-only model sees the whole sequence at once, which suits labelling and retrieval. A decoder-only model masks the future so it can predict the next token, which is exactly the setup for text generation.
- *With attention and the Transformer in hand, the final lesson turns to using these models in practice: frameworks, the training loop, transfer learning, and the pitfalls that most often trip up applied work.*
+ *With attention and the Transformer in hand, the arc of this course is complete: from a single perceptron to the architecture behind today's foundation models. To take a trained model from a notebook to a reliable production service, continue with the [MLOps](/en/MLOps) course.*
---
- Next: [Deep learning in practice](/en/Deep%20Learning/17%20Deep%20learning%20in%20practice) · [Course overview](/en/Deep%20Learning)
+ Next: [Course overview](/en/Deep%20Learning)
en/Deep Learning/17 Deep learning in practice.md .. /dev/null
@@ 1,104 0,0 @@
- # 17. Deep learning in practice
-
- Every lesson so far derived the mechanics of neural networks by hand: forward pass, loss, backpropagation, and the optimizer. In practice you write almost none of that. Modern frameworks store data as tensors, record the operations you perform, and differentiate them automatically, so the training loop you code is short and the gradients come for free. This capstone connects the theory to the tools, the hardware, and the habits that make a model actually train.
-
- **Objectives**
- - Explain what a tensor and automatic differentiation give you, and how autograd implements backpropagation.
- - Write a framework-agnostic training loop from memory.
- - Reason about batch size, accelerators, and mixed precision as practical trade-offs.
- - Apply transfer learning: reuse a pretrained backbone, freeze early layers, fine-tune the rest.
- - Recognize and fix the common failure modes that quietly wreck a run.
- - Place the models from this course on a single map and hand them off to production.
-
- ## 17.1 Frameworks, tensors, and autograd
-
- The two dominant stacks are **PyTorch** and **TensorFlow**, with **JAX** a fast-growing third that pairs a NumPy-like API with function transformations. All three share two ideas.
-
- A **tensor** is an n-dimensional array that lives on a device (CPU or accelerator) and carries a data type. A scalar is a 0-D tensor, a vector 1-D, a matrix 2-D, and a batch of RGB images is typically a 4-D tensor of shape (batch, channels, height, width). Every activation $a^{[l]}$, weight $W^{[l]}$, and bias $b^{[l]}$ from the earlier lessons is a tensor.
-
- **Automatic differentiation** (autograd) is what saves you from coding backprop. As the forward pass runs, the framework records each primitive operation into a computation graph. Calling `backward()` walks that graph in reverse and applies the chain rule, giving $\partial J / \partial W^{[l]}$ and $\partial J / \partial b^{[l]}$ for every parameter. This is exactly the backpropagation you derived earlier, executed for you:
-
- $$\boxed{ \frac{\partial J}{\partial z^{[l]}} = \left( W^{[l+1]} \right)^{T} \frac{\partial J}{\partial z^{[l+1]}} \odot g'^{[l]}\!\left(z^{[l]}\right) }$$
-
- *Remark:* PyTorch builds the graph dynamically on each forward pass (define-by-run), which makes debugging feel like ordinary Python. TensorFlow and JAX can trace and compile the graph ahead of time for speed. You rarely call the gradient math yourself, but knowing the formula above is why you can diagnose a vanishing or exploding gradient when a deep network refuses to learn.
-
- ## 17.2 The training loop
-
- Underneath every framework the loop is the same. You iterate over epochs, and within each epoch over mini-batches, running four steps per batch: forward pass, loss, backward pass, optimizer step. One detail trips up newcomers: gradients accumulate by default, so you must clear them each iteration.
-
- ```python
- for epoch in range(num_epochs):
- for x_batch, y_batch in dataloader: # mini-batches, shuffled
- optimizer.zero_grad() # clear accumulated gradients
- yhat = model(x_batch) # forward pass a[L] = model(x)
- loss = loss_fn(yhat, y_batch) # per-batch cost J
- loss.backward() # autograd: backpropagation
- optimizer.step() # update W[l], b[l]
- validate(model, val_loader) # track generalization
- ```
-
- *Remark:* the order matters. Zero the gradients before `backward()`, and never call `optimizer.step()` before the backward pass has populated the gradients. In TensorFlow the same four steps live inside a `GradientTape` context, but the structure is identical.
-
- ## 17.3 Hardware and batching
-
- Neural networks are dense linear algebra, which maps perfectly onto **GPUs** and other accelerators (TPUs). A GPU runs thousands of matrix multiplications in parallel, so moving both the model and the data to the device is usually the single largest speedup you will get.
-
- ### 17.3.1 Mini-batch size
-
- The batch size is a core trade-off, not a detail.
-
- | Batch size | Gradient quality | Hardware use | Generalization |
- | --- | --- | --- | --- |
- | Small (8 to 32) | noisy estimate | underuses the GPU | noise can help escape sharp minima |
- | Large (256+) | smooth, accurate estimate | saturates the GPU | may converge to sharp minima, needs a warmup |
-
- *Remark:* a common rule of thumb is to pick the largest batch that fits in memory, then tune the learning rate to match, since a larger batch usually needs a larger (or warmed-up) learning rate.
-
- ### 17.3.2 Mixed precision
-
- Storing activations and weights in 16-bit floats (`float16` or `bfloat16`) instead of 32-bit halves the memory and speeds up the matrix multiplies, while a master copy of the weights and the loss stay in 32-bit for numerical stability. This is **mixed precision**, and on modern accelerators it is close to free performance.
-
- ## 17.4 Transfer learning and fine-tuning
-
- Training a large network from scratch needs a lot of data and compute. **Transfer learning** sidesteps that by reusing a model already trained on a large corpus. You keep its **backbone** (the feature-extracting layers), replace the final task-specific head, and train on your smaller dataset.
-
- The usual recipe:
-
- 1. **Freeze** the early layers, whose features (edges, textures, generic token patterns) transfer across tasks.
- 2. **Replace the head** with one sized for your classes or outputs.
- 3. **Fine-tune** the later layers, and optionally unfreeze the rest at a small learning rate once the head has settled.
-
- ![Transfer learning pipeline from a pretrained backbone to deploy](/en/Deep%20Learning/17%20Deep%20learning%20in%20practice/a/transfer-learning.svg)
-
- *Transfer learning reuses a pretrained backbone, replaces the head, and fine-tunes the later layers on the new task.*
-
- *Remark:* this is where **self-supervised pretraining** pays off. A model pretrained BERT-style or GPT-style on huge unlabelled text already encodes rich language structure, so fine-tuning it on a small labelled set beats training a fresh model many times over. The same holds for vision backbones pretrained on large image collections.
-
- ## 17.5 Common pitfalls
-
- Most failed runs are not exotic. They come from a short list of mistakes, and each has a direct fix.
-
- | Pitfall | Symptom | Fix |
- | --- | --- | --- |
- | Overfitting | train loss drops, validation loss rises | regularize, add dropout, augment, or stop early |
- | Bad learning rate | loss diverges or is flat | sweep the rate, use a scheduler or warmup |
- | Data leakage | great validation score, poor in production | split before preprocessing, keep test data unseen |
- | Forgetting to shuffle | loss plateaus or cycles | shuffle the training set every epoch |
- | Not normalizing inputs | slow or unstable training | standardize features to zero mean, unit variance |
-
- *Remark:* data leakage is the most dangerous because it hides as success. If you fit a scaler or select features using the whole dataset before splitting, information about the test set bleeds into training, and the reported score is a mirage.
-
- ## 17.6 A map of the field
-
- The models across this course form a lineage. Fully connected multilayer perceptrons gave the core mechanics. Convolutions added spatial structure for images. Recurrent networks and LSTMs handled sequences. Attention removed the sequential bottleneck, transformers scaled it, and pretraining transformers at scale produced the foundation models that now anchor most applications.
-
- ![Course map from MLP to foundation models](/en/Deep%20Learning/17%20Deep%20learning%20in%20practice/a/field-map.svg)
-
- *A map of the course: from the multilayer perceptron through convolutional and recurrent networks to attention, Transformers, and foundation models.*
-
- A trained model is only half the job. Serving it reliably, monitoring for drift, versioning data, and automating retraining are their own discipline.
-
- *To take any of these models from a notebook to a reliable production service, continue with the [MLOps](/en/MLOps) course.*
-
- ---
- Next: [Course overview](/en/Deep%20Learning)
en/Deep Learning/17 Deep learning in practice/field-map.svg .. /dev/null
@@ 1,1 0,0 @@
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1030 300" width="1030" height="300" font-family="Helvetica, Arial, sans-serif"><defs><marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker><marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker></defs><rect width="1030" height="300" fill="#ffffff"/><text x="515.0" y="22.0" font-family="Helvetica, Arial, sans-serif" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">A map of the course: from the MLP to foundation models</text><rect x="40.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/><text x="105.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">MLP</text><rect x="204.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e4f5f4" stroke="#2a9d9a" stroke-width="1.6"/><text x="269.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">CNN</text><rect x="368.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/><text x="433.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">RNN and LSTM</text><rect x="532.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/><text x="597.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Attention</text><rect x="696.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/><text x="761.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Transformers</text><rect x="860.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#fdecec" stroke="#d1495b" stroke-width="1.6"/><text x="925.0" y="171.8" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Foundation</text><text x="925.0" y="187.1" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">models</text><line x1="170.0" y1="175.0" x2="204.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="334.0" y1="175.0" x2="368.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="498.0" y1="175.0" x2="532.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="662.0" y1="175.0" x2="696.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="826.0" y1="175.0" x2="860.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><text x="105.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">core mechanics</text><text x="351.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">structure for images and sequences</text><text x="761.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">attention, scaling, and pretraining</text></svg>
\ No newline at end of file
en/Deep Learning/17 Deep learning in practice/transfer-learning.svg .. /dev/null
@@ 1,1 0,0 @@
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 340" width="880" height="340" font-family="Helvetica, Arial, sans-serif"><defs><marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker><marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker></defs><rect width="880" height="340" fill="#ffffff"/><text x="440.0" y="22.0" font-family="Helvetica, Arial, sans-serif" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Transfer learning: reuse the backbone, replace the head, fine-tune</text><rect x="60" y="90" width="470" height="150" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/><text x="295.0" y="78.0" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">pretrained backbone</text><rect x="90.0" y="130.0" width="190.0" height="72.0" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/><text x="185.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">early layers</text><text x="185.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">frozen</text><rect x="310.0" y="130.0" width="190.0" height="72.0" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/><text x="405.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">later layers</text><text x="405.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">fine-tune</text><line x1="280.0" y1="166.0" x2="310.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><rect x="590.0" y="130.0" width="150.0" height="72.0" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/><text x="665.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">new task head</text><text x="665.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">replaced</text><line x1="500.0" y1="166.0" x2="590.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><rect x="780.0" y="130.0" width="78.0" height="72.0" rx="8" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/><text x="819.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">deploy</text><line x1="740.0" y1="166.0" x2="780.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><path d="M596.0 126.0 Q545.0 60.0 490.0 126.0" fill="none" stroke="#5b6b7b" stroke-width="1.7" marker-end="url(#arrowmuted)" stroke-dasharray="5 4"/><text x="543.0" y="121.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">fine-tune signal</text></svg>
\ No newline at end of file
en/Machine Learning.md ..
@@ 8,14 8,12 @@
1. [Introduction](/en/Machine%20Learning/01%20Introduction)
2. [General concepts](/en/Machine%20Learning/02%20General%20concepts)
- 3. [Model evaluation and validation](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation)
- 4. [Probabilistic formulation](/en/Machine%20Learning/04%20Probabilistic%20formulation)
- 5. [Linear regression](/en/Machine%20Learning/05%20Linear%20regression)
- 6. [Linear classification](/en/Machine%20Learning/06%20Linear%20classification)
- 7. [Regularization and high-dimensional inference](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference)
- 8. [Multilayer neural networks](/en/Machine%20Learning/08%20Multilayer%20neural%20networks)
- 9. [Support Vector Machines](/en/Machine%20Learning/09%20Support%20Vector%20Machines)
- 10. [Decision trees and ensemble methods](/en/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods)
+ 3. [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation)
+ 4. [Linear regression](/en/Machine%20Learning/04%20Linear%20regression)
+ 5. [Linear classification](/en/Machine%20Learning/05%20Linear%20classification)
+ 6. [Multilayer neural networks](/en/Machine%20Learning/06%20Multilayer%20neural%20networks)
+ 7. [Support Vector Machines](/en/Machine%20Learning/07%20Support%20Vector%20Machines)
+ 8. [Decision trees and ensemble methods](/en/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods)
---
[MLOps](/en/MLOps) · [Home](/en)
en/Machine Learning/01 Introduction.md ..
@@ 2,27 2,53 @@
Machine learning builds models that learn patterns from data instead of being explicitly programmed with rules. This module fixes the notation used throughout the course and maps the landscape of problems and models, so later modules can stay terse and formula-first.
- ## 1.1 Types of learning
-
- - **Supervised**: learn from labelled examples (regression, classification).
- - **Unsupervised**: find structure in unlabelled data (clustering, dimensionality reduction).
- - **Reinforcement**: learn from feedback by interacting with an environment.
-
- ## 1.2 The workflow
-
- 1. Define the problem and gather data.
- 2. Explore and preprocess the data.
- 3. Train candidate models.
- 4. Evaluate and compare them.
- 5. Deploy and monitor (see the [MLOps](/en/MLOps) course).
-
**Objectives**
+ - Distinguish supervised, unsupervised, and reinforcement learning by their feedback signal.
+ - Situate the stages of a machine learning project and its feedback loops.
- Fix the notation used across the whole course.
- Define the training set, the hypothesis, and the design matrix.
- Adopt the intercept convention $x_0 = 1$.
- Classify a supervised problem by the type of its output.
- Distinguish discriminative from generative models.
+ ## 1.1 Types of learning
+
+ Machine learning problems are usually sorted into three paradigms. What separates them is not the algorithm but the feedback available during training: a label for every example, no labels at all, or a reward that arrives through interaction.
+
+ ![The three types of learning](/en/Machine%20Learning/01%20Introduction/a/types-of-learning.svg)
+
+ *Supervised learning fits a mapping from labelled examples, unsupervised learning finds structure in unlabelled data, and reinforcement learning improves a policy through interaction with an environment.*
+
+ **Supervised learning.** Each training example pairs an input $x$ with the answer $y$ the model should produce, and the goal is a mapping $x \mapsto y$ that generalizes to inputs never seen in training. Predicting the price of a house from its features (regression) and deciding whether an email is spam (classification) are the canonical tasks. Labels make the objective explicit and progress measurable, which is why the theory is most developed here. Almost all of this course lives in this setting.
+
+ **Unsupervised learning.** Only the inputs $x$ are available, and no label says what the right answer is. The goal shifts from prediction to description: group similar customers into segments (clustering), compress many correlated features into a few informative directions (dimensionality reduction), or estimate which regions of the input space are likely (density estimation). Success is harder to quantify, because there is no ground truth to compare against.
+
+ **Reinforcement learning.** There is no fixed dataset at all. An agent takes an action, the environment returns a new state and a reward, and the reward may arrive long after the action that earned it. The goal is a policy, a rule for choosing actions that maximizes the cumulative reward. Game playing and robotics are the typical examples. It is a field of its own and sits outside the scope of this course.
+
+ | Paradigm | Data | Feedback signal | What is learned | Canonical tasks |
+ | --- | --- | --- | --- | --- |
+ | Supervised | pairs $(x, y)$ | the label $y$ | a mapping $h : x \mapsto y$ | regression, classification |
+ | Unsupervised | inputs $x$ only | none | structure in the data | clustering, dimensionality reduction |
+ | Reinforcement | interaction | reward, often delayed | a policy for acting | control, game playing |
+
+ *Remark:* the boundaries are not rigid. Semi-supervised learning mixes a few labelled examples with many unlabelled ones, and self-supervised learning manufactures labels from the data itself, for example by hiding a word and predicting it. Both reuse the supervised machinery introduced in this course.
+
+ ## 1.2 The workflow
+
+ A machine learning project is not a straight line from data to model. It runs as a loop: every evaluation reveals something that sends the work back to an earlier stage, and once deployed, a model faces new data that eventually restarts the cycle.
+
+ ![The machine learning workflow](/en/Machine%20Learning/01%20Introduction/a/ml-workflow.svg)
+
+ *The solid path is the nominal order. The dashed arrows are where real projects spend most of their time: reworking features and models after evaluation, and retraining after monitoring.*
+
+ 1. **Define the problem and gather data.** Turn the question into a prediction task by fixing the input $x$, the target $y$, and the metric that counts as success. The choices made here bound everything downstream, because no model can recover information the data does not contain.
+ 2. **Explore and preprocess the data.** Inspect distributions, missing values, and outliers, then clean, encode, and scale the features. Set aside a test set before tuning anything against it, so the final performance estimate stays honest.
+ 3. **Train candidate models.** Start with a simple baseline, then fit richer families by minimizing a loss over the parameters $\theta$ ([General concepts](/en/Machine%20Learning/02%20General%20concepts)).
+ 4. **Evaluate and compare.** Measure each candidate on data it has never seen, with validation and cross-validation ([General concepts](/en/Machine%20Learning/02%20General%20concepts)) and a metric matched to the problem. The verdict usually points back to step 2 or 3: better features, another model family, or more data.
+ 5. **Deploy and monitor.** In production the incoming data drifts away from the training distribution, so performance must be watched and retraining planned. That discipline has its own course: [MLOps](/en/MLOps).
+
+ *Remark:* in practice most of the effort goes into steps 1, 2, and 4. Training itself is often the cheapest step, and the ceiling on model quality is set by the data.
+
## 1.3 Notation and setup
### 1.3.1 Training set
@@ 109,7 135,7 @@
E -->|"generative"| G["GDA, naive Bayes"]
```
- *With the problem framed and the notation fixed, the next part introduces the tools used to fit a model to data: loss functions, gradient descent, and maximum likelihood.*
+ *With the problem framed and the notation fixed, the next part turns to what learning really demands: minimizing a loss is easy, generalizing beyond the training set is the challenge.*
---
Next: [General concepts](/en/Machine%20Learning/02%20General%20concepts) · [Course overview](/en/Machine%20Learning)
/dev/null .. en/Machine Learning/01 Introduction/ml-workflow.svg
@@ 0,0 1,40 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 270" width="880" height="270" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker>
+ </defs>
+ <rect width="880" height="270" fill="#ffffff"/>
+ <text x="440" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">The machine learning workflow</text>
+
+ <path d="M772 150 Q440 -10 108 150" fill="none" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="5 4" marker-end="url(#arrowmuted)"/>
+ <text x="440" y="62" font-size="11" fill="#5b6b7b" text-anchor="middle">monitoring restarts the cycle: new data, drift, retraining</text>
+ <path d="M606 150 Q440 55 274 150" fill="none" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="5 4" marker-end="url(#arrowmuted)"/>
+ <text x="440" y="95" font-size="11" fill="#5b6b7b" text-anchor="middle">evaluation sends you back: better features, other models</text>
+
+ <rect x="40" y="150" width="136" height="64" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="108" y="177" font-size="12" fill="#1f2933" text-anchor="middle">define the problem</text>
+ <text x="108" y="194" font-size="12" fill="#1f2933" text-anchor="middle">and gather data</text>
+ <rect x="206" y="150" width="136" height="64" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="274" y="177" font-size="12" fill="#1f2933" text-anchor="middle">explore and</text>
+ <text x="274" y="194" font-size="12" fill="#1f2933" text-anchor="middle">preprocess</text>
+ <rect x="372" y="150" width="136" height="64" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="440" y="177" font-size="12" fill="#1f2933" text-anchor="middle">train candidate</text>
+ <text x="440" y="194" font-size="12" fill="#1f2933" text-anchor="middle">models</text>
+ <rect x="538" y="150" width="136" height="64" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="606" y="177" font-size="12" fill="#1f2933" text-anchor="middle">evaluate and</text>
+ <text x="606" y="194" font-size="12" fill="#1f2933" text-anchor="middle">compare</text>
+ <rect x="704" y="150" width="136" height="64" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <text x="772" y="177" font-size="12" fill="#1f2933" text-anchor="middle">deploy and</text>
+ <text x="772" y="194" font-size="12" fill="#1f2933" text-anchor="middle">monitor</text>
+
+ <line x1="176" y1="182" x2="206" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="342" y1="182" x2="372" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="508" y1="182" x2="538" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="674" y1="182" x2="704" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+
+ <text x="191" y="234" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">data</text>
+ <text x="523" y="234" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">modelling</text>
+ <text x="772" y="234" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">production</text>
+
+ <text x="440" y="258" font-size="11" fill="#5b6b7b" text-anchor="middle">the solid path reads left to right, the dashed loops are where a real project spends most of its time</text>
+ </svg>
/dev/null .. en/Machine Learning/01 Introduction/types-of-learning.svg
@@ 0,0 1,62 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 840 320" width="840" height="320" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ </defs>
+ <rect width="840" height="320" fill="#ffffff"/>
+ <text x="420" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Three learning paradigms, three feedback signals</text>
+
+ <text x="142" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Supervised</text>
+ <text x="407" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Unsupervised</text>
+ <text x="685" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Reinforcement</text>
+
+ <rect x="20" y="68" width="245" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+ <rect x="285" y="68" width="245" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+ <rect x="550" y="68" width="270" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+
+ <line x1="85" y1="90" x2="235" y2="180" stroke="#1f2933" stroke-width="1.7"/>
+ <circle cx="85" cy="175" r="5.5" fill="#3b6fb6"/>
+ <circle cx="105" cy="155" r="5.5" fill="#3b6fb6"/>
+ <circle cx="75" cy="145" r="5.5" fill="#3b6fb6"/>
+ <circle cx="120" cy="180" r="5.5" fill="#3b6fb6"/>
+ <circle cx="140" cy="165" r="5.5" fill="#3b6fb6"/>
+ <circle cx="100" cy="190" r="5.5" fill="#3b6fb6"/>
+ <circle cx="160" cy="110" r="5.5" fill="#e0872e"/>
+ <circle cx="185" cy="125" r="5.5" fill="#e0872e"/>
+ <circle cx="205" cy="100" r="5.5" fill="#e0872e"/>
+ <circle cx="220" cy="120" r="5.5" fill="#e0872e"/>
+ <circle cx="175" cy="95" r="5.5" fill="#e0872e"/>
+ <circle cx="195" cy="140" r="5.5" fill="#e0872e"/>
+
+ <circle cx="350" cy="175" r="5.5" fill="#9aa7b2"/>
+ <circle cx="370" cy="155" r="5.5" fill="#9aa7b2"/>
+ <circle cx="340" cy="145" r="5.5" fill="#9aa7b2"/>
+ <circle cx="385" cy="180" r="5.5" fill="#9aa7b2"/>
+ <circle cx="405" cy="165" r="5.5" fill="#9aa7b2"/>
+ <circle cx="365" cy="190" r="5.5" fill="#9aa7b2"/>
+ <circle cx="425" cy="110" r="5.5" fill="#9aa7b2"/>
+ <circle cx="450" cy="125" r="5.5" fill="#9aa7b2"/>
+ <circle cx="470" cy="100" r="5.5" fill="#9aa7b2"/>
+ <circle cx="485" cy="120" r="5.5" fill="#9aa7b2"/>
+ <circle cx="440" cy="95" r="5.5" fill="#9aa7b2"/>
+ <circle cx="460" cy="140" r="5.5" fill="#9aa7b2"/>
+ <ellipse cx="369" cy="168" rx="46" ry="36" fill="none" stroke="#3b6fb6" stroke-width="1.6" stroke-dasharray="5 4"/>
+ <ellipse cx="455" cy="115" rx="45" ry="34" fill="none" stroke="#e0872e" stroke-width="1.6" stroke-dasharray="5 4"/>
+
+ <rect x="565" y="118" width="100" height="50" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="615" y="147" font-size="13" fill="#1f2933" text-anchor="middle">agent</text>
+ <rect x="705" y="118" width="105" height="50" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="757" y="147" font-size="13" fill="#1f2933" text-anchor="middle">environment</text>
+ <path d="M645 113 Q686 79 727 113" fill="none" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="686" y="90" font-size="11" fill="#5b6b7b" text-anchor="middle">action</text>
+ <path d="M727 173 Q686 207 645 173" fill="none" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="686" y="204" font-size="11" fill="#5b6b7b" text-anchor="middle">state, reward</text>
+
+ <text x="142" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">labelled examples (x, y)</text>
+ <text x="407" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">unlabelled examples x</text>
+ <text x="685" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">interaction and reward</text>
+ <text x="142" y="256" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">learn to predict y from x</text>
+ <text x="407" y="256" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">discover structure (clusters)</text>
+ <text x="685" y="256" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">learn a policy for acting</text>
+
+ <text x="420" y="302" font-size="11" fill="#5b6b7b" text-anchor="middle">what changes across paradigms is the feedback: a label for every example, no labels at all, or a delayed reward</text>
+ </svg>
en/Machine Learning/02 General concepts.md ..
@@ 1,16 1,25 @@
# 2. General concepts
- The building blocks shared by every supervised model: how a loss measures a single prediction and aggregates into a cost, how iterative optimization minimizes that cost, and how the probabilistic view (likelihood) recovers the same objectives. We close with Newton's method, a second-order alternative to gradient descent.
+ The introduction fixed the notation and named the learning paradigms. Before fitting any particular model, this module covers what learning actually means. Making a model fit the data it has seen is easy, making it perform on data it has never seen is the whole game. Polynomial regression serves as the running example, and the module closes with the reason geometric intuition fails in high dimension.
**Objectives**
- - Define a loss function and aggregate per-example losses into a single cost to minimize.
- - State the gradient descent update rule and contrast its batch and stochastic variants.
- - Define the likelihood and the MLE objective, and link it to minimizing a cost.
- - State Newton's update in one and several dimensions and compare it with gradient descent.
+ - Contrast supervised and unsupervised learning through what each one optimizes.
+ - Define a loss function and aggregate per-example losses into a cost to minimize.
+ - Fit polynomial regression and read its degree as a capacity knob.
+ - Distinguish training performance from generalization, and diagnose underfitting and overfitting.
+ - Control capacity continuously with a regularization penalty.
+ - Select hyperparameters with validation and cross-validation without contaminating the test set.
+ - State the curse of dimensionality and its consequences for learning.
- ## 2.1 Loss functions and cost
+ ## 2.1 Supervised versus unsupervised learning
- ### 2.1.1 Loss function
+ The [Introduction](/en/Machine%20Learning/01%20Introduction) named the paradigms by their feedback signal. Formally, supervised learning starts from labelled pairs $\{(x^{(i)}, y^{(i)})\}_{i=1}^{m}$ and searches a family of hypotheses for the $h_\theta$ whose predictions sit closest to the targets, closeness being measured by a loss function. Unsupervised learning has only the inputs $x^{(i)}$, so its objectives are built from the inputs alone: compact groups, informative directions, regions of high density.
+
+ Everything in this module is stated for the supervised case, which occupies the rest of the course. The questions it answers (how well does this model generalize, how complex should it be, how do I choose between candidates) arise unchanged in the unsupervised setting.
+
+ ## 2.2 Minimizing a loss: polynomial regression
+
+ ### 2.2.1 Loss function
A loss function $L(z, y)$ is defined as a scalar penalty comparing a raw model score $z$ (or a predicted probability $\phi$) against the target $y$. Smaller is better. Each family of models is characterized by its loss.
@@ 23,111 32,131 @@
*Remark:* $z$ denotes a raw score such as $\theta^T x$, whereas $\phi \in (0,1)$ denotes a predicted probability. The cross-entropy row takes a probability $\phi$, not a raw score.
- ### 2.1.2 Cost function
+ ![Margin-based loss functions](/en/Machine%20Learning/02%20General%20concepts/a/loss-functions.png)
+
+ *Margin-based losses, each a convex surrogate for the 0-1 loss that penalizes small or negative margins.*
+
+ ### 2.2.2 Cost function
The cost $J(\theta)$ is defined as the sum of the per-example losses over the whole training set of $m$ examples:
$$\boxed{\,J(\theta)=\sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right)\,}$$
- Training a model means choosing $\theta$ to minimize $J(\theta)$. The next lesson shows how.
+ Training a model means choosing $\theta$ to minimize $J(\theta)$. The algorithms that carry out this minimization (closed forms, gradient descent) arrive with the model modules. This module asks a different question: what does a low value of $J(\theta)$ actually prove?
*Remark:* the factor $\tfrac{1}{2}$ in the squared error is a convention that cancels with the exponent when differentiating, leaving a clean gradient.
- ![Margin-based loss functions](/en/Machine%20Learning/02%20General%20concepts/a/loss-functions.png)
+ ### 2.2.3 The running example: polynomial regression
- *Margin-based losses, each a convex surrogate for the 0-1 loss that penalizes small or negative margins.*
+ To make everything concrete, take a single input $x$ and fit a polynomial of degree $d$ under the squared loss:
- ## 2.2 Gradient descent
+ $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{d} \theta_j\, x^{j}, \qquad \phi(x) = (1, x, x^2, \dots, x^d) }$$
- ### 2.2.1 Update rule
+ The model stays linear in $\theta$, so least squares applies unchanged (the closed form is derived in [Linear regression](/en/Machine%20Learning/04%20Linear%20regression)). The degree $d$ is not fitted along with $\theta$: it is fixed before fitting and decides how flexible the curve is allowed to be. A knob of that kind, chosen rather than learned, is called a hyperparameter, and $d$ is our first one.
- Gradient descent iteratively moves the parameters $\theta$ against the gradient of the cost, scaled by a learning rate $\alpha > 0$:
+ ![Polynomial fits of degree 1, 3, and 9](/en/Machine%20Learning/02%20General%20concepts/a/polynomial-fits.png)
- $$\boxed{\,\theta \leftarrow \theta - \alpha\,\nabla_\theta J(\theta)\,}$$
+ *The same noisy sample fitted three ways. Degree 1 is too rigid to follow the trend, degree 3 captures it, and degree 9 weaves through every training point.*
- The gradient points in the direction of steepest increase, so stepping opposite to it decreases $J$. The step size $\alpha$ controls how far each update moves.
+ ## 2.3 Training performance versus generalization
- *Remark:* if $\alpha$ is too large the iterates can diverge, if too small convergence is slow.
+ ### 2.3.1 Generalization error
- ### 2.2.2 Batch versus stochastic
+ The quantity we care about is the generalization error, the expected loss on a fresh draw from the same population:
- The two variants differ in how many examples contribute to one update.
+ $$\boxed{ R(h) = \mathbb{E}_{(x, y)}\left[ L\!\left(h(x), y\right) \right] }$$
- | Variant | Examples per update | Update |
- | --- | --- | --- |
- | Batch | All $m$ | $\theta \leftarrow \theta - \alpha\,\nabla_\theta J(\theta)$ |
- | Stochastic (SGD) | One $(x^{(i)}, y^{(i)})$ | $\theta \leftarrow \theta - \alpha\,\nabla_\theta L\!\left(h_\theta(x^{(i)}), y^{(i)}\right)$ |
+ We cannot observe it, so we estimate it. The tempting estimate is the training error, the average loss on the data used to fit $h$. It is biased downward: the model has already adapted to that particular sample, so it scores itself too kindly.
- Batch gives a smooth descent but reads the whole set per step. SGD updates after each example, so it is cheap per step and noisy.
+ $$\boxed{ \hat{R}_{\text{train}}(h) = \frac{1}{m}\sum_{i=1}^{m} L\!\left(h(x^{(i)}), y^{(i)}\right) \;\le\; R(h) \ \text{(in expectation)} }$$
- ### 2.2.3 LMS (Widrow-Hoff) update
+ ### 2.3.2 Underfitting and overfitting
- For the least squared error, the per-coordinate stochastic update is defined as:
+ Back to the polynomials. The degree-1 fit underfits: it lacks the capacity to represent the trend, so it scores badly on the training points and on new points alike. The degree-9 fit overfits: it has capacity to spare, drives the training error to zero by weaving through the noise, and pays for it on fresh data. It has the lowest training error of the three fits and is also the worst model. The good model sits in between.
- $$\boxed{\,\theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)}\,}$$
+ ![Training versus validation error as capacity grows](/en/Machine%20Learning/02%20General%20concepts/a/train-vs-validation.png)
- The correction is proportional to the residual $y^{(i)} - h_\theta(x^{(i)})$ times the feature $x_j^{(i)}$.
+ *As the degree grows, the training error falls monotonically while the validation error falls, bottoms out, and rises again. The best degree sits at the bottom of the U.*
- *Remark:* a large residual produces a large step, a correct prediction produces no update.
+ This is the bias-variance trade-off. A rigid model is biased: it is systematically off, whichever sample it is trained on. A flexible model has high variance: its fit swings with every resample of the noise. Raising capacity trades bias for variance, and generalization is best where the two balance.
- ![Gradient descent path](/en/Machine%20Learning/02%20General%20concepts/a/gradient-descent.png)
+ *Remark:* training error is not evidence of quality. Past the sweet spot it is evidence of memorization, and only performance on unseen data can tell the difference.
- *Gradient descent steps downhill toward the minimum (star).*
+ ## 2.4 Regularization
- ## 2.3 Likelihood and maximum likelihood estimation
+ Choosing the degree is a coarse dial: capacity jumps by whole integers. A finer control keeps a flexible family but makes complexity expensive inside the cost itself, by adding a penalty $\Omega(\theta)$ scaled by a strength $\lambda \ge 0$:
- ### 2.3.1 Likelihood
+ $$\boxed{\,J_\lambda(\theta)=\sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right) + \lambda\,\Omega(\theta)\,}$$
- The likelihood $L(\theta)$ is defined as the probability of the observed targets under the model, viewed as a function of the parameters $\theta$. Assuming examples are independent, it factorizes:
+ The classic choice is the squared norm $\Omega(\theta) = \lVert \theta \rVert_2^2$, the ridge penalty. The degree-9 fit only weaves through every point by using huge coefficients that cancel each other between the training points. The penalty makes those coefficients costly, so the minimizer trades a little training error for a much smoother curve. At $\lambda = 0$ the overfitted fit returns, as $\lambda \to \infty$ the curve flattens toward underfitting: $\lambda$ sweeps the same bias-variance dial as the degree, but continuously.
- $$\boxed{\,L(\theta)=\prod_{i=1}^{m} p\!\left(y^{(i)} \mid x^{(i)}; \theta\right)\,}$$
+ *Remark:* regularization does not decide the right complexity for you, it converts a discrete choice ($d$) into a continuous one ($\lambda$) that is easier to tune. $\lambda$ is a hyperparameter like the degree, chosen by the validation machinery of the next section. Where the penalty comes from (a prior on $\theta$, via maximum a posteriori) and what the L1 variant adds are the subjects of [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation) and [Linear regression](/en/Machine%20Learning/04%20Linear%20regression).
- ### 2.3.2 Log-likelihood
+ ## 2.5 Hyperparameters, validation, and cross-validation
- Products are awkward to optimize, so we take the logarithm. The log-likelihood $\ell(\theta)$ is defined as:
+ ### 2.5.1 Training, validation, and test sets
- $$\boxed{\,\ell(\theta)=\sum_{i=1}^{m} \log p\!\left(y^{(i)} \mid x^{(i)}; \theta\right)\,}$$
+ Hyperparameters cannot be chosen on the training error, which only rewards more capacity. The fix is to keep data the model never touched during fitting. The standard split has three disjoint roles:
- The $\log$ is monotone, so it has the same maximizer as $L(\theta)$ while turning the product into a sum.
+ | Set | Used for | Touched |
+ | --- | --- | --- |
+ | Training | fitting the model parameters | every fit |
+ | Validation | choosing the model and its hyperparameters | many times |
+ | Test | reporting one honest final estimate | exactly once |
- ### 2.3.3 Maximum likelihood estimation
+ *Remark:* the test set is sacred. Every time a choice is guided by test performance, the test set quietly becomes part of training and its estimate turns optimistic.
- The MLE is defined as the parameter value that makes the data most probable:
+ ### 2.5.2 Cross-validation
- $$\boxed{\,\theta_{\mathrm{MLE}}=\arg\max_\theta\,\ell(\theta)\,}$$
+ Samples are often small, and a single train/validation split both wastes data and gives a noisy estimate. k-fold cross-validation reuses the data: partition it into $K$ folds, and for each fold train on the other $K-1$ and validate on the held-out fold. The cross-validation error averages the $K$ rounds:
- *Remark:* maximizing the log-likelihood is equivalent to minimizing the cost $J(\theta) = -\ell(\theta)$. This is exactly the cost-minimization view of the previous lessons, so likelihood and cost are two faces of one objective.
+ $$\boxed{ \text{CV}_K = \frac{1}{K}\sum_{k=1}^{K} \frac{1}{|F_k|}\sum_{i \in F_k} L\!\left(h^{(-k)}(x^{(i)}), y^{(i)}\right) }$$
- ## 2.4 Newton's algorithm
+ where $h^{(-k)}$ is trained on all folds except $F_k$. Taking $K = m$ gives leave-one-out cross-validation. Common choices are $K = 5$ or $K = 10$, trading computation against a lower-variance estimate.
- ### 2.4.1 One-dimensional update
+ ![k-fold cross-validation](/en/Machine%20Learning/02%20General%20concepts/a/cross-validation.svg)
- To find a stationary point of the log-likelihood, Newton's method follows the local quadratic approximation. The scalar update is defined as:
+ *Each round holds out one fold for validation and trains on the rest, and the reported score is the average across folds.*
- $$\boxed{\,\theta \leftarrow \theta - \frac{\ell'(\theta)}{\ell''(\theta)}\,}$$
+ ### 2.5.3 Model and hyperparameter selection
- It divides the first derivative by the second, so the step automatically adapts to the curvature.
+ Cross-validation is how we tune. Fit each candidate (a model family, a tree depth, the polynomial degree $d$, or the penalty $\lambda$) and keep the one with the lowest validation or CV error. Only then, once the choice is frozen, do we touch the test set to report a final number.
- ### 2.4.2 Multivariate update
+ *Remark:* choosing the winner on the test set inflates the estimate. With enough candidates one will look good by chance alone, the winner's curse, so selection and final evaluation must use different data.
- With a parameter vector $\theta \in \mathbb{R}^{n+1}$, the second derivative becomes the Hessian matrix $H$, with $H_{jk}=\dfrac{\partial^2 \ell}{\partial\theta_j\,\partial\theta_k}$. The update is defined as:
+ ## 2.6 Common validation pitfalls
- $$\boxed{\,\theta \leftarrow \theta - H^{-1}\,\nabla_\theta \ell(\theta)\,}$$
+ Honest validation is harder than it looks, and real data often breaks the usual assumptions in three ways.
- *Remark:* each step solves a linear system in $H$, an $O(n^3)$ operation, so Newton's method is costly when the number of features $n$ is large.
+ - **Data leakage.** Information about the target leaks into the features. Standardizing with statistics computed on the full sample, or including a variable realized after the outcome, lets the model peek at the answer. Any preprocessing must be fit on the training folds only.
+ - **Look-ahead bias.** Using information that was not yet available at the moment of prediction, which arises whenever the data is time-ordered, produces backtests that cannot be reproduced live.
+ - **Dependence.** Many datasets are serially correlated (time series) or grouped (several observations that share a unit). Shuffling them into random folds mixes near-identical neighbours across train and validation, so the estimate is far too optimistic.
- ### 2.4.3 Newton versus gradient descent
+ For time series, use a rolling-origin (blocked) scheme so the model is only ever tested on data that comes after its training window. For grouped data, hold out whole units (grouped cross-validation) so no unit appears on both sides.
- | Property | Newton's algorithm | Gradient descent |
- | --- | --- | --- |
- | Order | Second (uses curvature $H$) | First (uses gradient only) |
- | Per-step cost | High ($O(n^3)$, inverts $H$) | Low ($O(n)$ per example) |
- | Convergence | Quadratic near the optimum, few steps | Linear, many steps |
- | Tuning | No learning rate | Needs a learning rate $\alpha$ |
+ ![Time-series cross-validation](/en/Machine%20Learning/02%20General%20concepts/a/time-series-cv.svg)
+
+ *In a rolling-origin scheme the training window grows forward in time and the model is validated on the next block, never on shuffled data.*
+
+ *Remark:* the honest question behind every split is the same. Would this have been knowable at the time, from data the model actually had?
+
+ ## 2.7 The curse of dimensionality
+
+ Everything above rests on the sample standing in for the population near the points that matter. In high dimension that assumption degrades, and it degrades fast. Suppose the inputs fill the unit hypercube $[0,1]^d$ and we want a neighbourhood around a point that captures a fraction $r$ of the data. A sub-cube containing a fraction $r$ of the volume must have edge length:
+
+ $$\boxed{ e_d(r) = r^{1/d} }$$
+
+ In one dimension, capturing 1% of the volume takes 1% of the axis. In $d = 10$ dimensions it takes $0.01^{1/10} \approx 0.63$, so 63% of the range of every feature, and in $d = 100$ dimensions 95%. A neighbourhood that sees any reasonable share of the data stops being local, and methods that rely on nearby examples lose their footing. Filling space directly is hopeless too: covering each axis with just 10 bins already produces $10^d$ cells, so the sample size needed to populate them grows exponentially with $d$.
+
+ ![The curse of dimensionality](/en/Machine%20Learning/02%20General%20concepts/a/curse-dimensionality.png)
+
+ *The edge length needed to capture a fixed fraction of the volume shoots toward 1 as the dimension grows: in high dimension, a "local" neighbourhood spans most of every axis.*
+
+ Two more symptoms follow from the same geometry. Almost all of the volume of a high-dimensional cube sits near its boundary, so a typical point has no interior around it. And pairwise distances concentrate: the nearest and the farthest neighbour end up almost equally far, so distance itself becomes less informative.
- *Remark:* Newton's method converges in very few iterations but pays a high per-step cost, so gradient descent is preferred when $n$ is large.
+ *Remark:* this is why learning in high dimension leans on structure rather than raw proximity: linear models, regularization pulling toward simple fits, and features or embeddings that compress the inputs. Real data usually concentrates near a much lower-dimensional structure, and that is what makes learning possible at all.
- *These tools are model-agnostic. The next part puts them to work on the simplest hypothesis class, where the prediction is a linear function of the features: linear models.*
+ *The concepts are in place: fitting minimizes a loss, generalizing is the goal, validation measures it, and regularization with hyperparameter tuning controls it. The next module builds the probabilistic language (Bayes' rule, entropy, likelihood) behind the first concrete models.*
---
- Next: [Model evaluation and validation](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation) · [Course overview](/en/Machine%20Learning)
+ Next: [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/03 Model evaluation and validation/cross-validation.svg .. en/Machine Learning/02 General concepts/cross-validation.svg
/dev/null .. en/Machine Learning/02 General concepts/curse-dimensionality.png
en/Machine Learning/02 General concepts/gradient-descent.png .. /dev/null
/dev/null .. en/Machine Learning/02 General concepts/polynomial-fits.png
en/Machine Learning/03 Model evaluation and validation/time-series-cv.svg .. en/Machine Learning/02 General concepts/time-series-cv.svg
/dev/null .. en/Machine Learning/02 General concepts/train-vs-validation.png
en/Machine Learning/03 Model evaluation and validation.md .. /dev/null
@@ 1,73 0,0 @@
- # 3. Model evaluation and validation
-
- Any model can be made to fit the data it was trained on. What matters is how it performs on data it has never seen. This module makes evaluation a first-class skill: how to estimate out-of-sample error honestly, how to use it to choose models, and the traps that make it easy to fool yourself, especially with small or dependent datasets.
-
- **Objectives**
- - Distinguish in-sample from out-of-sample error and see why training error is optimistic.
- - Split data into training, validation, and test sets and know the role of each.
- - Estimate generalization error with k-fold cross-validation.
- - Use validation to select models and hyperparameters without contaminating the test set.
- - Avoid data leakage and look-ahead bias, and validate dependent data with time-series or grouped schemes.
-
- ## 3.1 In-sample versus out-of-sample error
-
- The quantity we care about is the generalization error, the expected loss on a fresh draw from the same population:
-
- $$\boxed{ R(h) = \mathbb{E}_{(x, y)}\left[ L\!\left(h(x), y\right) \right] }$$
-
- We cannot observe it, so we estimate it. The tempting estimate is the training error, the average loss on the data used to fit $h$. It is biased downward: the model has already adapted to that particular sample, so it scores itself too kindly.
-
- $$\boxed{ \hat{R}_{\text{train}}(h) = \frac{1}{m}\sum_{i=1}^{m} L\!\left(h(x^{(i)}), y^{(i)}\right) \;\le\; R(h) \ \text{(in expectation)} }$$
-
- *Remark:* a flexible model driven to near-zero training error has usually memorized noise. That is overfitting, the high-variance end of the bias-variance trade-off introduced in [General concepts](/en/Machine%20Learning/02%20General%20concepts).
-
- ## 3.2 Training, validation, and test sets
-
- The fix is to keep data the model never touched during fitting. The standard split has three disjoint roles:
-
- | Set | Used for | Touched |
- | --- | --- | --- |
- | Training | fitting the model parameters | every fit |
- | Validation | choosing the model and its hyperparameters | many times |
- | Test | reporting one honest final estimate | exactly once |
-
- *Remark:* the test set is sacred. Every time a choice is guided by test performance, the test set quietly becomes part of training and its estimate turns optimistic.
-
- ## 3.3 Cross-validation
-
- Samples are often small, and a single train/validation split both wastes data and gives a noisy estimate. k-fold cross-validation reuses the data: partition it into $K$ folds, and for each fold train on the other $K-1$ and validate on the held-out fold. The cross-validation error averages the $K$ rounds:
-
- $$\boxed{ \text{CV}_K = \frac{1}{K}\sum_{k=1}^{K} \frac{1}{|F_k|}\sum_{i \in F_k} L\!\left(h^{(-k)}(x^{(i)}), y^{(i)}\right) }$$
-
- where $h^{(-k)}$ is trained on all folds except $F_k$. Taking $K = m$ gives leave-one-out cross-validation. Common choices are $K = 5$ or $K = 10$, trading computation against a lower-variance estimate.
-
- ![k-fold cross-validation](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation/a/cross-validation.svg)
-
- *Each round holds out one fold for validation and trains on the rest, and the reported score is the average across folds.*
-
- ## 3.4 Model and hyperparameter selection
-
- Cross-validation is how we tune. Fit each candidate (a model family, a tree depth, or the penalty $\lambda$ of the next module) and keep the one with the lowest validation or CV error. Only then, once the choice is frozen, do we touch the test set to report a final number.
-
- *Remark:* choosing the winner on the test set inflates the estimate. With enough candidates one will look good by chance alone, the winner's curse, so selection and final evaluation must use different data.
-
- ## 3.5 Common validation pitfalls
-
- Honest validation is harder than it looks, and real data often breaks the usual assumptions in three ways.
-
- - **Data leakage.** Information about the target leaks into the features. Standardizing with statistics computed on the full sample, or including a variable realized after the outcome, lets the model peek at the answer. Any preprocessing must be fit on the training folds only.
- - **Look-ahead bias.** Using information that was not yet available at the moment of prediction, which arises whenever the data is time-ordered, produces backtests that cannot be reproduced live.
- - **Dependence.** Many datasets are serially correlated (time series) or grouped (several observations that share a unit). Shuffling them into random folds mixes near-identical neighbours across train and validation, so the estimate is far too optimistic.
-
- For time series, use a rolling-origin (blocked) scheme so the model is only ever tested on data that comes after its training window. For grouped data, hold out whole units (grouped cross-validation) so no unit appears on both sides.
-
- ![Time-series cross-validation](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation/a/time-series-cv.svg)
-
- *In a rolling-origin scheme the training window grows forward in time and the model is validated on the next block, never on shuffled data.*
-
- *Remark:* the honest question behind every split is the same. Would this have been knowable at the time, from data the model actually had?
-
- *With a way to measure generalization in hand, the next module fits our first models, and the one after controls their complexity with regularization tuned by exactly this cross-validation.*
-
- ---
- Next: [Probabilistic formulation](/en/Machine%20Learning/04%20Probabilistic%20formulation) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/04 Probabilistic formulation.md .. en/Machine Learning/03 Probabilistic formulation.md
@@ 1,4 1,4 @@
- # 4. Probabilistic formulation
+ # 3. Probabilistic formulation
Probability is the language machine learning uses to handle uncertainty. This module sets out the rules for discrete and continuous variables, takes a first look at information theory, shows the Bayesian way of turning probabilities into decisions, and defines the two estimation principles the course returns to again and again: maximum likelihood and maximum a posteriori.
@@ 9,7 9,7 @@
- Make the decision that minimizes expected loss, and recover the maximum-a-posteriori classifier.
- Define the maximum-likelihood and maximum-a-posteriori estimators.
- ## 4.1 Probability, discrete and continuous
+ ## 3.1 Probability, discrete and continuous
A random variable takes values with probabilities that are non-negative and sum or integrate to one. A discrete variable has a probability mass function, a continuous one a probability density function:
@@ 17,7 17,7 @@
For a continuous variable, probability attaches to intervals through an integral, $P(a \le X \le b) = \int_a^b p(x)\, dx$, not to single points.
- ## 4.2 Joint, conditional, and Bayes
+ ## 3.2 Joint, conditional, and Bayes
Two variables have a joint distribution $p(x, y)$. Summing (or integrating) out one variable gives the marginal, the sum rule, and the joint factors into a conditional times a marginal, the product rule:
@@ 29,13 29,13 @@
Two variables are independent when the joint is the product of the marginals, $p(x, y) = p(x)\, p(y)$.
- ## 4.3 A little information theory
+ ## 3.3 A little information theory
The entropy of a distribution measures its uncertainty, the average number of bits needed to describe an outcome:
$$\boxed{ H(X) = -\sum_x p(x)\log p(x) }$$
- ![Binary entropy](/en/Machine%20Learning/04%20Probabilistic%20formulation/a/entropy.png)
+ ![Binary entropy](/en/Machine%20Learning/03%20Probabilistic%20formulation/a/entropy.png)
*For a two-outcome variable the entropy is largest at $p = 0.5$, where the outcome is hardest to predict, and zero when one outcome is certain.*
@@ 45,31 45,37 @@
*Remark:* minimizing the cross-entropy between the true labels and a model's predictions is the same as maximizing the likelihood of those labels. This is why classification networks minimize cross-entropy, a thread picked up in later modules.
- ## 4.4 Bayesian decision theory
+ ## 3.4 Bayesian decision theory
To classify an input $x$, the Bayesian rule uses the posterior over classes. Under the 0-1 loss, the decision that minimizes the expected loss is simply the most probable class, and because the posterior is proportional to the class-conditional density times the prior, it can be computed either way:
$$\boxed{ \hat{y} = \arg\max_y \; p(y \mid x) = \arg\max_y \; p(x \mid y)\, p(y) }$$
- ![Bayesian decision between two classes](/en/Machine%20Learning/04%20Probabilistic%20formulation/a/bayes-decision.png)
+ ![Bayesian decision between two classes](/en/Machine%20Learning/03%20Probabilistic%20formulation/a/bayes-decision.png)
*Each class contributes its density scaled by its prior, and the decision boundary falls where the two are equal. On each side the class with the larger posterior wins.*
*Remark:* this is the optimal classifier, called the Bayes classifier. Every method later in the course is, in effect, an attempt to approximate these posteriors from data.
- ## 4.5 Maximum likelihood and maximum a posteriori
+ ## 3.5 Maximum likelihood and maximum a posteriori
We rarely know the true distribution, so we estimate its parameters $\theta$ from data. Maximum likelihood picks the $\theta$ that makes the observed data most probable, usually maximized as a sum of log-likelihoods over the $m$ examples:
$$\boxed{ \theta_{\mathrm{MLE}} = \arg\max_\theta \sum_{i=1}^{m} \log p(x^{(i)} \mid \theta) }$$
+ In supervised learning the model parameterizes the conditional $p(y \mid x; \theta)$, so the same principle applies to the conditional likelihood of the targets:
+
+ $$\boxed{ \ell(\theta) = \sum_{i=1}^{m} \log p\!\left(y^{(i)} \mid x^{(i)}; \theta\right) }$$
+
+ Maximizing $\ell$ is the same as minimizing the cost $J(\theta) = -\ell(\theta)$, so the likelihood view and the cost-minimization view of [General concepts](/en/Machine%20Learning/02%20General%20concepts) are two faces of one objective.
+
Maximum a posteriori instead maximizes the posterior, which multiplies the likelihood by a prior on $\theta$:
$$\boxed{ \theta_{\mathrm{MAP}} = \arg\max_\theta \; p(D \mid \theta)\, p(\theta) }$$
- *Remark:* maximum a posteriori is maximum likelihood plus a prior. A Gaussian prior on $\theta$ becomes an L2 penalty and a Laplace prior an L1 penalty, which is exactly the regularization of a later module. With abundant data the prior washes out and the two estimators agree.
+ *Remark:* maximum a posteriori is maximum likelihood plus a prior. A Gaussian prior on $\theta$ becomes an L2 penalty and a Laplace prior an L1 penalty, which is exactly the regularization of the next module. With abundant data the prior washes out and the two estimators agree.
- *The next module turns these principles into concrete loss functions and the gradient descent that minimizes them.*
+ *The next module turns these principles into a first concrete model: linear regression, where maximum likelihood and maximum a posteriori both land on closed-form fits.*
---
- Next: [Linear regression](/en/Machine%20Learning/05%20Linear%20regression) · [Course overview](/en/Machine%20Learning)
+ Next: [Linear regression](/en/Machine%20Learning/04%20Linear%20regression) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/04 Probabilistic formulation/bayes-decision.png .. en/Machine Learning/03 Probabilistic formulation/bayes-decision.png
en/Machine Learning/04 Probabilistic formulation/entropy.png .. en/Machine Learning/03 Probabilistic formulation/entropy.png
/dev/null .. en/Machine Learning/04 Linear regression.md
@@ 0,0 1,138 @@
+ # 4. Linear regression
+
+ Linear regression predicts a continuous target from a linear score. This module follows one thread from end to end: pose the model, fit it to noisy data by least squares, justify that objective by maximum likelihood, regularize it by maximum a posteriori (ridge, then its selecting cousin the lasso), then widen the model with basis functions and multiple outputs, where the same two closed forms return unchanged.
+
+ **Objectives**
+ - Write the linear model and read its prediction as a line, a plane, or a hyperplane.
+ - Pose the fitting problem on noisy data and state the least-squares objective.
+ - Show that maximum likelihood under Gaussian noise is exactly least squares, and derive the normal equation.
+ - Derive ridge regression (weight decay) from maximum a posteriori, in closed form.
+ - Contrast the ridge and lasso penalties: shrinking versus selecting.
+ - Generalize the model with basis functions and to multiple outputs, keeping the same closed forms.
+
+ ## 4.1 The linear model
+
+ The hypothesis is linear in the augmented input $x \in \mathbb{R}^{n+1}$ with $x_0 = 1$, the convention of the [Introduction](/en/Machine%20Learning/01%20Introduction):
+
+ $$\boxed{ h_\theta(x) = \theta^T x = \theta_0 + \theta_1 x_1 + \dots + \theta_n x_n }$$
+
+ $\theta_0$ is the bias (the intercept) and the remaining coordinates are the weights, and folding the bias into the dot product is exactly what the $x_0 = 1$ convention buys. Geometrically, the prediction is a line for $n = 1$, a plane for $n = 2$, and a hyperplane beyond.
+
+ ![The prediction is a line, then a plane](/en/Machine%20Learning/04%20Linear%20regression/a/line-and-plane.png)
+
+ *With one feature the model draws a line through the data, with two a plane, and beyond that a hyperplane that can no longer be drawn.*
+
+ ## 4.2 The problem to solve
+
+ Given the training set $\{(x^{(i)}, y^{(i)})\}_{i=1}^{m}$, ideally we would have $h_\theta(x^{(i)}) = y^{(i)}$ at every point. Real targets are noisy (measurement error, unmodelled factors), so no line passes through them all, and the goal becomes to make the smallest total error. Least squares takes the squared residual as the error and sums it over the training set:
+
+ $$\boxed{ \theta^{*} = \arg\min_\theta \; \sum_{i=1}^{m}\left(\theta^T x^{(i)} - y^{(i)}\right)^2 }$$
+
+ ![Ideal versus noisy targets](/en/Machine%20Learning/04%20Linear%20regression/a/ideal-vs-noisy.png)
+
+ *Left: if the targets were noise-free, the model could pass through every point. Right: real targets scatter around the trend, so each point leaves a residual between $y^{(i)}$ and the prediction $h_\theta(x^{(i)})$, and the fit minimizes their sum of squares (grey segments).*
+
+ *Remark:* why the square rather than, say, the absolute value? Because this choice is provably optimal when the noise is Gaussian, a classic interview question that the next section unpacks.
+
+ ## 4.3 Maximum likelihood: least squares justified
+
+ Give the data a generative story, using the estimation principle of [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation): each target is the linear prediction plus independent Gaussian noise,
+
+ $$\boxed{ y^{(i)} = \theta^T x^{(i)} + \varepsilon^{(i)}, \quad \varepsilon^{(i)} \sim \mathcal{N}(0, \sigma^2) }$$
+
+ so $p(y^{(i)} \mid x^{(i)}; \theta) = \mathcal{N}(\theta^T x^{(i)}, \sigma^2)$. The log-likelihood of the $m$ i.i.d. examples separates into a constant and the sum of squares:
+
+ $$\ell(\theta) = \sum_{i=1}^{m} \log \mathcal{N}\!\left(y^{(i)} \mid \theta^T x^{(i)}, \sigma^2\right) = -\frac{m}{2}\log(2\pi\sigma^2) \;-\; \frac{1}{2\sigma^2}\sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2$$
+
+ Neither the constant nor the positive factor $\tfrac{1}{2\sigma^2}$ moves the argmax, so:
+
+ $$\boxed{ \arg\max_\theta \; \ell(\theta) = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 }$$
+
+ *Remark:* this equivalence is the most important fact of the module. Least squares is not a convenient convention, it is the maximum-likelihood estimate under Gaussian noise.
+
+ The maximizer has a closed form. Writing the objective with the design matrix $X$ and setting the gradient to zero,
+
+ $$\nabla_\theta\, \lVert X\theta - y \rVert^2 = 2\,X^T(X\theta - y) = 0$$
+
+ $$\boxed{ \theta_{\mathrm{MLE}} = (X^T X)^{-1}X^T y }$$
+
+ the normal equation, one matrix solve away from the data.
+
+ ## 4.4 Maximum a posteriori: ridge regression
+
+ Maximum likelihood can overfit, especially when the model is flexible. The maximum a posteriori estimate maximizes the posterior instead, which by Bayes' rule is the likelihood times a prior on the parameters, here a zero-mean Gaussian:
+
+ $$\theta_{\mathrm{MAP}} = \arg\max_\theta \; p(y \mid X, \theta)\, p(\theta), \qquad \theta \sim \mathcal{N}(0, \tau^2 I)$$
+
+ Taking logarithms adds $-\lVert \theta \rVert^2 / 2\tau^2$ to the log-likelihood, and dropping the constants leaves a penalized least squares:
+
+ $$\boxed{ \theta_{\mathrm{MAP}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_2^2, \quad \lambda = \frac{\sigma^2}{\tau^2} }$$
+
+ with, by the same zero-gradient computation, the closed form:
+
+ $$\boxed{ \theta_{\mathrm{MAP}} = (X^T X + \lambda I)^{-1}X^T y }$$
+
+ This is ridge regression, and the penalty is often called weight decay. The Gaussian prior became the L2 penalty of [General concepts](/en/Machine%20Learning/02%20General%20concepts), exactly the prior-to-penalty link of [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation).
+
+ *Remark:* $\lambda \to 0$ recovers maximum likelihood, and a growing $\lambda$ shrinks $\theta$ toward zero and fights overfitting. A stronger prior (small $\tau$) means a larger $\lambda$. Note also that $X^T X + \lambda I$ is always invertible for $\lambda > 0$, which rescues least squares exactly where it breaks down: strongly correlated features, or more features than examples.
+
+ ## 4.5 The lasso: a penalty that selects
+
+ The ridge penalty came from a Gaussian prior. A Laplace prior yields the L1 penalty instead, the link noted in [Probabilistic formulation](/en/Machine%20Learning/03%20Probabilistic%20formulation):
+
+ $$\boxed{ \theta_{\mathrm{lasso}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_1 }$$
+
+ The change looks small and its consequence is large: the lasso drives some coefficients to exactly zero, so it selects variables while it fits. Unlike ridge it has no closed form (the penalty is not differentiable at zero), so it is fitted by convex solvers. The reason for the selection is geometric. The constraint region $\lVert \theta \rVert_1 \le t$ is a diamond with corners on the axes, and the elliptical contours of the squared error tend to touch it first at a corner, where a coordinate is zero. The rounded L2 ball has no corners, so ridge shrinks every coefficient smoothly but never zeroes one: ridge stabilizes, the lasso selects.
+
+ ![L1 versus L2 constraint geometry](/en/Machine%20Learning/04%20Linear%20regression/a/l1-l2-geometry.png)
+
+ *The rounded L2 ball is touched off the axes, keeping every coefficient nonzero, while the L1 diamond is touched at a corner, setting a coefficient to exactly zero.*
+
+ As $\lambda$ grows, more coefficients cross to zero, tracing the regularization path from the full model down to the empty one.
+
+ ![Lasso regularization path](/en/Machine%20Learning/04%20Linear%20regression/a/regularization-path.png)
+
+ *Each coefficient shrinks as $\lambda$ increases and then hits exactly zero, so the lasso yields a compact, interpretable subset of regressors.*
+
+ *Remark:* the elastic net blends the two penalties, $\lambda\left(\alpha \lVert \theta \rVert_1 + (1-\alpha)\lVert \theta \rVert_2^2\right)$, keeping the lasso's selection with the ridge's stability under correlated features. As always, $\lambda$ is chosen by the cross-validation of [General concepts](/en/Machine%20Learning/02%20General%20concepts), often taking the largest $\lambda$ within one standard error of the best for a simpler model.
+
+ *Remark:* prediction is not inference. Selecting variables with the lasso and then reporting textbook standard errors on the same data is invalid, the winner's curse again: the intervals ignore that the data already chose the variables. Honest inference needs sample splitting or a debiased estimator, the doorway to causal machine learning.
+
+ ## 4.6 Basis functions: nonlinear in $x$, linear in $\theta$
+
+ A straight line is often too rigid: the underfitting of [General concepts](/en/Machine%20Learning/02%20General%20concepts) appeared precisely when a low-capacity model met a curved trend. The fix is not to abandon the linear machinery but to project the input into a larger space, where the relationship is linear:
+
+ $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{M-1} \theta_j\, \phi_j(x), \qquad \phi_0(x) = 1 }$$
+
+ The $\phi_j$ are basis functions, fixed before training. With $\phi(x) = (1, x, x^2, \dots, x^d)$ they give polynomial regression, the running example of [General concepts](/en/Machine%20Learning/02%20General%20concepts), and the identity $\phi(x) = x$ recovers everything above. The model can now be wildly nonlinear in $x$ yet stays linear in $\theta$, so nothing changes in the fit: stack the $\phi(x^{(i)})^T$ as the rows of the design matrix $\Phi \in \mathbb{R}^{m \times M}$ and the two closed forms return verbatim:
+
+ $$\boxed{ \theta_{\mathrm{MLE}} = (\Phi^T \Phi)^{-1}\Phi^T y, \qquad \theta_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T y }$$
+
+ *Remark:* the basis (its family and its size $M$) is a hyperparameter, chosen before training, while $\theta$ is learned. Choosing $M$ and $\lambda$ is the model-selection problem settled by the cross-validation of [General concepts](/en/Machine%20Learning/02%20General%20concepts).
+
+ ## 4.7 Multiple outputs
+
+ Nothing restricts the target to a single number. To predict $K$ values at once (say a house's price, heating cost, and property tax from the same features), let $y^{(i)} \in \mathbb{R}^K$ and give each output its own parameter column, gathered in a matrix $W \in \mathbb{R}^{M \times K}$:
+
+ $$\boxed{ h_W(x) = W^T \phi(x) \in \mathbb{R}^{K} }$$
+
+ Stacking the targets as the rows of $Y \in \mathbb{R}^{m \times K}$, the same derivations give the same closed forms, now solving all $K$ regressions at once:
+
+ $$\boxed{ W_{\mathrm{MLE}} = (\Phi^T \Phi)^{-1}\Phi^T Y, \qquad W_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T Y }$$
+
+ *Remark:* the expensive factor $(\Phi^T \Phi)^{-1}$ does not depend on the targets, so it is computed once and shared by all $K$ outputs.
+
+ ## 4.8 Summary
+
+ | | Formula |
+ | --- | --- |
+ | Model | $h_\theta(x) = \theta^T \phi(x)$ |
+ | Maximum likelihood (least squares) | $\theta_{\mathrm{MLE}} = (\Phi^T \Phi)^{-1}\Phi^T y$ |
+ | Maximum a posteriori (ridge) | $\theta_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T y$ |
+ | Parameters, learned | $\theta$ (or $W$ for $K$ outputs) |
+ | Hyperparameters, chosen by validation | the basis $\phi$ and its size $M$, the penalty $\lambda$ |
+
+ *The same linear score, passed through a squashing function instead of read directly, turns regression into classification, the subject of the next module.*
+
+ ---
+ Next: [Linear classification](/en/Machine%20Learning/05%20Linear%20classification) · [Course overview](/en/Machine%20Learning)
/dev/null .. en/Machine Learning/04 Linear regression/ideal-vs-noisy.png
en/Machine Learning/07 Regularization and high-dimensional inference/l1-l2-geometry.png .. en/Machine Learning/04 Linear regression/l1-l2-geometry.png
/dev/null .. en/Machine Learning/04 Linear regression/line-and-plane.png
en/Machine Learning/07 Regularization and high-dimensional inference/regularization-path.png .. en/Machine Learning/04 Linear regression/regularization-path.png
/dev/null .. en/Machine Learning/05 Linear classification.md
@@ 0,0 1,187 @@
+ # 5. Linear classification
+
+ Classification predicts a discrete label from the same linear score $\theta^T x$. This module surveys the classical linear classifiers as one menu: least squares, which assumes Gaussian-shaped classes and admits a closed form, and the perceptron and logistic regression, which assume nothing about the distribution and are fitted by gradient descent. Regularization closes the module.
+
+ **Objectives**
+ - Read a linear classifier as a separating hyperplane whose score tells the side, making prediction one dot product.
+ - Situate the classical methods by their assumption (Gaussian or none) and their fit (closed form or gradient descent).
+ - Classify by least squares, binary and multiclass, and see where it breaks.
+ - Train the perceptron from its criterion, and know its convergence guarantee and its limits.
+ - Distinguish batch from stochastic gradient descent, and know that fancier optimizers exist.
+ - Fit logistic regression by gradient descent on the cross-entropy, binary and multiclass.
+ - Regularize any of these fits with a penalty, the maximum a posteriori view.
+
+ ## 5.1 The linear separator
+
+ A linear classifier assigns the class from the sign of the linear score, and the set of inputs scoring zero is the decision boundary:
+
+ $$\boxed{ h_\theta(x) = \mathrm{sign}(\theta^T x), \qquad \theta^T x = 0 \ \text{is the boundary} }$$
+
+ The boundary is a hyperplane: a line with two features, a plane with three. The sign of the score says on which side of the hyperplane the input falls, and its magnitude how far from the boundary it sits. With $\theta = (-4, 1, 2)$ (bias first, on the augmented input), the point $x = (3, 2)$ scores $-4 + 3 + 4 = 3$ and falls in front of the hyperplane, while $x = (1, 1)$ scores $-4 + 1 + 2 = -1$ and falls behind it.
+
+ *Remark:* two practical advantages follow. Once training is done the training set can be thrown away, and predicting costs a single dot product.
+
+ ## 5.2 A menu of methods
+
+ The classical methods fit that hyperplane, and they split cleanly by what they assume about the data and how they are solved.
+
+ | Method | Assumption on the data | How it is fitted |
+ | --- | --- | --- |
+ | Least squares | Gaussian-shaped classes | closed form (matrix inversion) |
+ | Perceptron | none | gradient descent |
+ | Logistic regression | none | gradient descent |
+
+ Least squares inherits the closed-form comfort of [Linear regression](/en/Machine%20Learning/04%20Linear%20regression) and pays for it with a distributional assumption. The other two assume nothing and pay with iterative optimization.
+
+ ## 5.3 Least squares as a classifier
+
+ Code the two classes as $y \in \{-1, +1\}$, treat them as regression targets, and everything from [Linear regression](/en/Machine%20Learning/04%20Linear%20regression) applies verbatim, closed form included:
+
+ $$\boxed{ \theta = (X^T X)^{-1}X^T y, \qquad h_\theta(x) = \mathrm{sign}(\theta^T x) }$$
+
+ For $K > 2$ classes, code each label as a one-hot row of $Y \in \mathbb{R}^{m \times K}$ and reuse the multiple-output regression of [Linear regression](/en/Machine%20Learning/04%20Linear%20regression), predicting the class with the highest score:
+
+ $$\boxed{ W = (X^T X)^{-1}X^T Y, \qquad \hat{y} = \arg\max_k \; (W^T x)_k }$$
+
+ It can work, but the squared loss penalizes large scores even deep on the correct side, so the points least in doubt pull on the boundary. That is the Gaussian assumption at work: least squares treats the labels as Gaussian targets, and data far from that story breaks it.
+
+ ![Least squares versus logistic regression with outliers](/en/Machine%20Learning/05%20Linear%20classification/a/least-squares-outliers.png)
+
+ *Without outliers least squares and logistic regression agree. Adding distant, correctly classified points tilts the least-squares boundary into errors, while logistic regression barely moves.*
+
+ ## 5.4 The perceptron
+
+ ### 5.4.1 Model, loss, and update
+
+ The first assumption-free method takes the definition of a linear classifier at face value, a dot product followed by a hard activation, the historical neuron:
+
+ $$\boxed{ h_\theta(x) = \mathrm{sign}(\theta^T x), \qquad y \in \{-1, +1\} }$$
+
+ ![The perceptron as a neuron](/en/Machine%20Learning/05%20Linear%20classification/a/perceptron-neuron.svg)
+
+ *Left: the perceptron is a single neuron, the weighted inputs summed into the score $\theta^T x$ and passed through a hard sign activation. Right: that sign splits the input space along the hyperplane $\theta^T x = 0$.*
+
+ Fitting needs a loss, and counting mistakes does not work: the count is piecewise constant, so its gradient is zero almost everywhere. The perceptron criterion instead penalizes each misclassified point by how far it sits on the wrong side. A mistake means $y^{(i)}\,\theta^T x^{(i)} < 0$, so over the set $\mathcal{M}$ of misclassified points:
+
+ $$\boxed{ E(\theta) = -\sum_{i \in \mathcal{M}} y^{(i)}\, \theta^T x^{(i)} }$$
+
+ always positive and piecewise linear. Minimizing it introduces the workhorse of everything in this course that lacks a closed form, gradient descent: repeatedly step the parameters against the gradient of the loss, scaled by a learning rate $\alpha > 0$:
+
+ $$\boxed{\,\theta \leftarrow \theta - \alpha\,\nabla_\theta E(\theta)\,}$$
+
+ The batch variant computes the gradient over the whole training set before each step, a smooth descent that reads every example every time. The stochastic variant (SGD) steps on one example at a time, cheap and noisy, and is the default on large datasets. If $\alpha$ is too large the iterates can diverge, if too small convergence crawls.
+
+ *Remark:* fancier optimizers exist, momentum, Adam and their cousins, refinements of this same rule that matter for deep networks ([Optimization](/en/Deep%20Learning/06%20Optimization) in the Deep Learning course). Everything in this module needs only the plain version.
+
+ On a single misclassified example the gradient of the criterion is $-y^{(i)} x^{(i)}$, so the stochastic step is the perceptron update: on a mistake,
+
+ $$\boxed{ \theta \leftarrow \theta + \alpha\, y^{(i)} x^{(i)} }$$
+
+ and no update otherwise. In the $\{0, 1\}$ coding this is the residual-times-input update $\theta_j \leftarrow \theta_j + \alpha\,(y^{(i)} - h_\theta(x^{(i)}))\,x_j^{(i)}$.
+
+ ![Perceptron decision boundary](/en/Machine%20Learning/05%20Linear%20classification/a/perceptron.png)
+
+ *The perceptron finds one separating hyperplane, not necessarily the maximum-margin one the support vector machine will choose.*
+
+ ### 5.4.2 Multiclass perceptron
+
+ With $k$ classes, keep one weight vector $\theta_c$ per class and predict the highest-scoring one. On a mistake, reward the true class and penalize the predicted one:
+
+ $$\boxed{ \hat{y} = \arg\max_c \theta_c^T x, \qquad \theta_{y} \mathrel{+}= \alpha x, \quad \theta_{\hat{y}} \mathrel{-}= \alpha x }$$
+
+ The network view extends naturally: one score neuron per class, and an argmax where the binary perceptron had a sign. Gathering the $\theta_c$ as the columns of a matrix $W \in \mathbb{R}^{(n+1) \times k}$, one product $W^T x$ computes every score at once, and the scores carve the input space into $k$ regions, each claimed by the class whose score is largest.
+
+ ![The multiclass perceptron](/en/Machine%20Learning/05%20Linear%20classification/a/multiclass-neuron.svg)
+
+ *One score neuron per class and an argmax on top. Each column of $W$ (each row of $W^T$) is the hyperplane, normal and bias, of one class.*
+
+ A worked example with $k = 3$ classes and the input $x = (1.1, -2.0)$, augmented with $x_0 = 1$:
+
+ $$ W^T x = \begin{bmatrix} -2 & -4 & 1 \\ -4 & 2 & 4 \\ -6 & 4 & -5 \end{bmatrix}\begin{bmatrix} 1 \\ 1.1 \\ -2.0 \end{bmatrix} = \begin{bmatrix} -8.4 \\ -9.8 \\ 8.4 \end{bmatrix} $$
+
+ The third score wins, so the input is assigned to class 3. Reading off the third row, that score is $\theta_3^T x = -6 + 4 \times 1.1 + (-5) \times (-2.0) = 8.4$.
+
+ ### 5.4.3 Convergence and limits
+
+ If the data is linearly separable the perceptron converges in a finite number of updates, otherwise the weights oscillate forever. And since the criterion is zero on every separating hyperplane, all of them count as "optimal", including those that graze the data.
+
+ *Remark:* three upgrades fix these limits, and each one opens a module. A smooth activation and loss give logistic regression, next section. Margins and basis functions lead to the [Support Vector Machine](/en/Machine%20Learning/07%20Support%20Vector%20Machines). Stacking neurons into layers gives [multilayer neural networks](/en/Machine%20Learning/06%20Multilayer%20neural%20networks), the starting point of the Deep Learning course.
+
+ ## 5.5 Logistic regression
+
+ ### 5.5.1 A smooth activation
+
+ Logistic regression keeps the neuron but replaces the hard step with the smooth sigmoid, so the output is the probability of the positive class ($y \in \{0, 1\}$):
+
+ $$\boxed{ \phi = p(y = 1 \mid x; \theta) = \sigma(\theta^T x) = \frac{1}{1 + e^{-\theta^T x}} }$$
+
+ ![Logistic regression as a neuron](/en/Machine%20Learning/05%20Linear%20classification/a/logistic-neuron.svg)
+
+ *The same neuron with the step swapped for the sigmoid: the output becomes the probability $\phi = p(y = 1 \mid x)$, and thresholding it at $\tfrac{1}{2}$ recovers the same boundary $\theta^T x = 0$.*
+
+ *Remark:* the sigmoid is not an arbitrary squashing choice. Writing the posterior with Bayes' rule gives $p(C_1 \mid x) = 1/(1 + e^{-a})$ with $a = \ln \frac{p(x \mid C_1)\,p(C_1)}{p(x \mid C_0)\,p(C_0)}$, so a well-trained logistic output is exactly a posterior probability.
+
+ ### 5.5.2 Cross-entropy and its gradient
+
+ The likelihood of Bernoulli labels, taken through $-\log$, gives the cross-entropy loss:
+
+ $$\boxed{ L(\theta) = -\sum_{i=1}^{m}\left[ y^{(i)}\log \phi^{(i)} + (1 - y^{(i)})\log(1 - \phi^{(i)}) \right] }$$
+
+ Unlike least squares, this loss has no closed-form minimizer: the sigmoid makes the stationarity equations transcendental, so the fit falls to the same gradient descent as the perceptron. Differentiating the cross-entropy through the sigmoid rewards the effort: almost everything cancels and the gradient collapses to the residual times the input:
+
+ $$\boxed{ \theta_j \leftarrow \theta_j - \alpha \sum_{i=1}^{m}\left(\phi^{(i)} - y^{(i)}\right)x_j^{(i)} }$$
+
+ *Remark:* unlike the perceptron, the gradient involves every training point, not only the misclassified ones: each point pulls in proportion to its residual $\phi^{(i)} - y^{(i)}$. That is what makes logistic regression more stable than the perceptron and usable on non-separable data.
+
+ ![Sigmoid and logistic decision boundary](/en/Machine%20Learning/05%20Linear%20classification/a/logistic-regression.png)
+
+ *Left: the sigmoid maps any score into the interval (0, 1). Right: the decision boundary and the predicted probability.*
+
+ ### 5.5.3 Multiclass: the softmax
+
+ For $k$ classes the sigmoid generalizes to the softmax, one weight vector per class, normalized into a distribution:
+
+ $$\boxed{ p(y = c \mid x; \theta) = \frac{\exp(\theta_c^T x)}{\sum_{j=1}^{k}\exp(\theta_j^T x)} }$$
+
+ With one-hot labels the loss is the categorical cross-entropy $L = -\sum_i \log p(y^{(i)} \mid x^{(i)})$, whose gradient keeps the same residual-times-input form.
+
+ | | sigmoid | softmax |
+ | --- | --- | --- |
+ | classes | 2 | $k$ |
+ | output | one probability $\phi$ | a distribution over $k$ classes |
+ | relation | the $k = 2$ softmax reduces to the sigmoid | generalizes the sigmoid |
+
+ ## 5.6 Regularized classification
+
+ Nothing pins down the scale of $\theta$: doubling it moves no perceptron boundary and only sharpens the probabilities of logistic regression, and different weight vectors can produce identical scores. The maximum a posteriori recipe of [Linear regression](/en/Machine%20Learning/04%20Linear%20regression) applies verbatim, adding a penalty to whichever loss is being minimized:
+
+ $$\boxed{ J_\lambda(\theta) = \sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right) + \lambda\,\Omega(\theta), \qquad \Omega(\theta) = \lVert \theta \rVert_2^2 \ \text{or} \ \lVert \theta \rVert_1 }$$
+
+ For the cross-entropy with the L2 penalty, the gradient simply gains a pull toward zero, $\sum_i (\phi^{(i)} - y^{(i)})\,x^{(i)} + 2\lambda\theta$.
+
+ *Remark:* libraries expose exactly this menu, a loss plus a penalty (scikit-learn's `SGDClassifier` takes a `loss` and a `penalty` argument). The strength $\lambda$ is chosen by the validation of [General concepts](/en/Machine%20Learning/02%20General%20concepts), and the lasso's selecting behaviour is covered in [Linear regression](/en/Machine%20Learning/04%20Linear%20regression).
+
+ ## 5.7 Summary
+
+ The assumption-free methods share one update, the residual times the input:
+
+ | Model | Activation | Update (one example) |
+ | --- | --- | --- |
+ | Perceptron | step | $\theta_j \leftarrow \theta_j + \alpha\,(y - h_\theta(x))\,x_j$ (mistakes only) |
+ | Linear regression | identity | $\theta_j \leftarrow \theta_j + \alpha\,(y - \theta^T x)\,x_j$ |
+ | Logistic regression | sigmoid or softmax | $\theta_j \leftarrow \theta_j + \alpha\,(y - \phi)\,x_j$ |
+
+ *Remark:* only the activation differs (step, identity, sigmoid or softmax). The Deep Learning course picks up exactly this thread, stacking such units into layers.
+
+ And the losses at a glance:
+
+ | Loss | Penalizes | Used by |
+ | --- | --- | --- |
+ | Perceptron criterion | misclassified points only | perceptron |
+ | Hinge $\max(0,\,1 - y\,\theta^T x)$ | mistakes and small margins | [SVM](/en/Machine%20Learning/07%20Support%20Vector%20Machines) |
+ | Cross-entropy | every point, by its residual | logistic regression |
+
+ *With linear models covered, the next module stacks these building blocks into multilayer neural networks.*
+
+ ---
+ Next: [Multilayer neural networks](/en/Machine%20Learning/06%20Multilayer%20neural%20networks) · [Course overview](/en/Machine%20Learning)
/dev/null .. en/Machine Learning/05 Linear classification/least-squares-outliers.png
/dev/null .. en/Machine Learning/05 Linear classification/logistic-neuron.svg
@@ 0,0 1,40 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 300" width="620" height="300" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowgreen" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#38a05a"/></marker>
+ </defs>
+ <rect width="620" height="300" fill="#ffffff"/>
+ <text x="310" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Logistic regression: the same neuron, a smooth activation</text>
+
+ <circle cx="70" cy="95" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="100" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="70" cy="155" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="160" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="70" cy="215" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="220" font-size="13" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="70" y="251" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="88" y1="95" x2="226" y2="146" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="155" x2="225" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="215" x2="226" y2="164" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="150" y="112" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="150" y="148" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">2</tspan></text>
+ <text x="150" y="184" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">0</tspan></text>
+
+ <circle cx="255" cy="155" r="28" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="255" y="160" font-size="13" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="-5" font-size="9">T</tspan><tspan dy="5" font-size="13">x</tspan></text>
+
+ <line x1="283" y1="155" x2="330" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+
+ <circle cx="360" cy="155" r="28" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <path d="M342 166 C 355 166, 358 144, 378 144" fill="none" stroke="#38a05a" stroke-width="2.2"/>
+
+ <line x1="388" y1="155" x2="485" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="449" y="140" font-size="12" fill="#1f2933" text-anchor="middle">&#966; = p(y = 1 | x)</text>
+ <text x="449" y="176" font-size="11" fill="#5b6b7b" text-anchor="middle">&#8712; (0, 1)</text>
+
+ <line x1="360" y1="222" x2="360" y2="190" stroke="#38a05a" stroke-width="1.7" marker-end="url(#arrowgreen)"/>
+ <text x="360" y="240" font-size="11" fill="#5b6b7b" text-anchor="middle">sigmoid activation</text>
+
+ <text x="310" y="282" font-size="11" fill="#5b6b7b" text-anchor="middle">thresholding at &#966; = 0.5 recovers the same boundary &#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x = 0</tspan></text>
+ </svg>
en/Machine Learning/06 Linear classification/logistic-regression.png .. en/Machine Learning/05 Linear classification/logistic-regression.png
/dev/null .. en/Machine Learning/05 Linear classification/multiclass-neuron.svg
@@ 0,0 1,71 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 320" width="860" height="320" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ </defs>
+ <rect width="860" height="320" fill="#ffffff"/>
+ <text x="430" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">The multiclass perceptron: one score per class, then an argmax</text>
+
+ <circle cx="55" cy="95" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="100" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="55" cy="155" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="160" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="55" cy="215" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="220" font-size="12" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="55" y="248" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="71" y1="95" x2="214" y2="93" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="95" x2="216" y2="147" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="95" x2="218" y2="205" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="216" y2="101" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="214" y2="155" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="216" y2="209" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="218" y2="105" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="216" y2="163" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="214" y2="215" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+
+ <circle cx="240" cy="95" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="100" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">1</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+ <circle cx="240" cy="155" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="160" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">2</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+ <circle cx="240" cy="215" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="220" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">3</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+
+ <ellipse cx="405" cy="155" rx="45" ry="22" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/>
+ <text x="405" y="160" font-size="12" fill="#1f2933" text-anchor="middle">argmax</text>
+ <line x1="264" y1="95" x2="367" y2="146" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+ <line x1="264" y1="155" x2="356" y2="155" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+ <line x1="264" y1="215" x2="367" y2="164" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+
+ <line x1="450" y1="155" x2="510" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="485" y="142" font-size="13" fill="#1f2933" text-anchor="middle">&#375;</text>
+
+ <polygon points="695,160 695,55 555,55 555,210" fill="#e8f0fe"/>
+ <polygon points="695,160 555,210 555,255 805,255" fill="#e7f5ea"/>
+ <polygon points="695,160 805,255 835,255 835,55 695,55" fill="#fff1e0"/>
+ <line x1="695" y1="160" x2="695" y2="55" stroke="#5b6b7b" stroke-width="1.2"/>
+ <line x1="695" y1="160" x2="555" y2="210" stroke="#5b6b7b" stroke-width="1.2"/>
+ <line x1="695" y1="160" x2="805" y2="255" stroke="#5b6b7b" stroke-width="1.2"/>
+ <rect x="555" y="55" width="280" height="200" rx="8" fill="none" stroke="#9aa7b2" stroke-width="1.4"/>
+
+ <circle cx="610" cy="90" r="5" fill="#3b6fb6"/>
+ <circle cx="640" cy="120" r="5" fill="#3b6fb6"/>
+ <circle cx="600" cy="140" r="5" fill="#3b6fb6"/>
+ <circle cx="660" cy="95" r="5" fill="#3b6fb6"/>
+ <circle cx="625" cy="105" r="5" fill="#3b6fb6"/>
+ <circle cx="610" cy="225" r="5" fill="#38a05a"/>
+ <circle cx="650" cy="235" r="5" fill="#38a05a"/>
+ <circle cx="700" cy="230" r="5" fill="#38a05a"/>
+ <circle cx="590" cy="240" r="5" fill="#38a05a"/>
+ <circle cx="660" cy="215" r="5" fill="#38a05a"/>
+ <circle cx="760" cy="120" r="5" fill="#e0872e"/>
+ <circle cx="790" cy="160" r="5" fill="#e0872e"/>
+ <circle cx="740" cy="90" r="5" fill="#e0872e"/>
+ <circle cx="780" cy="210" r="5" fill="#e0872e"/>
+ <circle cx="730" cy="140" r="5" fill="#e0872e"/>
+
+ <text x="568" y="74" font-size="11" fill="#3b6fb6" text-anchor="start">&#952;<tspan dy="3" font-size="8">1</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+ <text x="572" y="223" font-size="11" fill="#38a05a" text-anchor="start">&#952;<tspan dy="3" font-size="8">2</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+ <text x="828" y="74" font-size="11" fill="#e0872e" text-anchor="end">&#952;<tspan dy="3" font-size="8">3</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+
+ <text x="405" y="300" font-size="11" fill="#5b6b7b" text-anchor="middle">each class scores the input with its own hyperplane, and the largest score claims the region</text>
+ </svg>
/dev/null .. en/Machine Learning/05 Linear classification/perceptron-neuron.svg
@@ 0,0 1,63 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 300" width="860" height="300" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowgreen" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#38a05a"/></marker>
+ </defs>
+ <rect width="860" height="300" fill="#ffffff"/>
+ <text x="430" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">The perceptron: one neuron, a hard activation</text>
+
+ <circle cx="70" cy="85" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="90" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="70" cy="145" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="150" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="70" cy="205" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="210" font-size="13" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="70" y="241" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="88" y1="85" x2="226" y2="136" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="145" x2="225" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="205" x2="226" y2="154" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="150" y="102" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="150" y="138" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">2</tspan></text>
+ <text x="150" y="174" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">0</tspan></text>
+
+ <circle cx="255" cy="145" r="28" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="255" y="150" font-size="13" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="-5" font-size="9">T</tspan><tspan dy="5" font-size="13">x</tspan></text>
+
+ <line x1="283" y1="145" x2="330" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+
+ <circle cx="360" cy="145" r="28" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <text x="360" y="150" font-size="13" fill="#1f2933" text-anchor="middle">sign</text>
+
+ <line x1="388" y1="145" x2="485" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="445" y="131" font-size="12" fill="#1f2933" text-anchor="middle">h<tspan dy="4" font-size="9">&#952;</tspan><tspan dy="-4">(x) &#8712; {&#8722;1, +1}</tspan></text>
+
+ <line x1="360" y1="212" x2="360" y2="180" stroke="#38a05a" stroke-width="1.7" marker-end="url(#arrowgreen)"/>
+ <text x="360" y="230" font-size="11" fill="#5b6b7b" text-anchor="middle">activation function</text>
+
+ <line x1="560" y1="250" x2="835" y2="250" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="560" y1="250" x2="560" y2="55" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="828" y="268" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="543" y="64" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+
+ <line x1="580" y1="95" x2="820" y2="230" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="6 5"/>
+ <text x="772" y="192" font-size="11" fill="#5b6b7b" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x = 0</tspan></text>
+
+ <line x1="700" y1="162" x2="727" y2="114" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="736" y="112" font-size="12" fill="#1f2933" text-anchor="start">&#952;</text>
+
+ <circle cx="600" cy="78" r="5.5" fill="#3b6fb6"/>
+ <circle cx="632" cy="96" r="5.5" fill="#3b6fb6"/>
+ <circle cx="662" cy="112" r="5.5" fill="#3b6fb6"/>
+ <circle cx="692" cy="128" r="5.5" fill="#3b6fb6"/>
+ <circle cx="612" cy="100" r="5.5" fill="#3b6fb6"/>
+ <text x="590" y="62" font-size="11" fill="#3b6fb6" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x &gt; 0</tspan></text>
+
+ <circle cx="650" cy="180" r="5.5" fill="#e0872e"/>
+ <circle cx="700" cy="210" r="5.5" fill="#e0872e"/>
+ <circle cx="740" cy="190" r="5.5" fill="#e0872e"/>
+ <circle cx="780" cy="225" r="5.5" fill="#e0872e"/>
+ <circle cx="720" cy="195" r="5.5" fill="#e0872e"/>
+ <circle cx="760" cy="205" r="5.5" fill="#e0872e"/>
+ <text x="608" y="237" font-size="11" fill="#e0872e" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x &lt; 0</tspan></text>
+ </svg>
en/Machine Learning/06 Linear classification/perceptron.png .. en/Machine Learning/05 Linear classification/perceptron.png
en/Machine Learning/05 Linear regression.md .. /dev/null
@@ 1,62 0,0 @@
- # 5. Linear regression
-
- Linear regression predicts a continuous target from a linear score $\theta^T x$. This module presents it probabilistically, building on the [Probabilistic formulation](/en/Machine%20Learning/04%20Probabilistic%20formulation) module: the model (extended to polynomial features), fitting by maximum likelihood, which turns out to be ordinary least squares, and fitting by maximum a posteriori, which adds a prior and yields a regularized fit.
-
- **Objectives**
- - Write the linear and polynomial regression model and fit it by least squares.
- - Give regression a probabilistic formulation with Gaussian noise.
- - See that maximum likelihood under that model is exactly least squares.
- - Add a prior and fit by maximum a posteriori, recovering a regularized fit.
-
- ## 5.1 The linear and polynomial model
-
- The hypothesis is linear in the augmented input $x \in \mathbb{R}^{n+1}$ with $x_0 = 1$ and parameters $\theta$:
-
- $$\boxed{ h_\theta(x) = \theta^T x }$$
-
- Polynomial regression is the same model applied to a feature map. Replacing $x$ by $\phi(x) = (1, x, x^2, \dots, x^d)$ fits a degree-$d$ polynomial while staying linear in the parameters:
-
- $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{d} \theta_j\, x^{j} }$$
-
- so everything below applies unchanged once the design matrix $X$ stacks the transformed inputs $\phi(x^{(i)})$ as its rows.
-
- ## 5.2 Least squares
-
- The cost is half the sum of squared residuals over the $m$ examples:
-
- $$\boxed{ J(\theta) = \tfrac{1}{2}\sum_{i=1}^{m}\left(h_\theta(x^{(i)}) - y^{(i)}\right)^2 }$$
-
- Setting $\nabla_\theta J = 0$ gives the closed-form normal equation, and gradient descent gives the equivalent iterative update:
-
- $$\boxed{ \theta = (X^T X)^{-1}X^T y \qquad \theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)} }$$
-
- ![Linear regression fit](/en/Machine%20Learning/05%20Linear%20regression/a/linear-regression.png)
-
- *Least squares fits the curve that minimizes the squared residuals (grey segments).*
-
- ## 5.3 Probabilistic formulation: maximum likelihood
-
- Give the data a generative story: each target is the linear prediction plus independent Gaussian noise,
-
- $$\boxed{ y^{(i)} = \theta^T x^{(i)} + \varepsilon^{(i)}, \quad \varepsilon^{(i)} \sim \mathcal{N}(0, \sigma^2) }$$
-
- so $p(y^{(i)} \mid x^{(i)}; \theta) = \mathcal{N}(\theta^T x^{(i)}, \sigma^2)$. Maximizing the log-likelihood over the $m$ i.i.d. examples drops every term that does not depend on $\theta$ and leaves the least-squares cost:
-
- $$\boxed{ \arg\max_\theta \ell(\theta) = \arg\min_\theta \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 }$$
-
- *Remark:* this is why least squares is a principled objective and not merely a convenient one. Ordinary least squares is the maximum-likelihood estimate under Gaussian noise, exactly the maximum-likelihood principle from the previous module.
-
- ## 5.4 Maximum a posteriori
-
- Maximum likelihood can overfit, especially at high polynomial degree. Placing a zero-mean Gaussian prior on the parameters, $\theta \sim \mathcal{N}(0, \tau^2 I)$, and maximizing the posterior instead adds a penalty on their size:
-
- $$\boxed{ \theta_{\mathrm{MAP}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_2^2, \quad \lambda = \frac{\sigma^2}{\tau^2} }$$
-
- This is regularized (ridge) regression: the Gaussian prior becomes an L2 penalty, exactly the prior-to-penalty link noted in the previous module.
-
- *Remark:* a stronger prior (small $\tau$) means a larger $\lambda$ and more shrinkage toward zero. With abundant data the likelihood dominates the prior and the maximum-a-posteriori fit approaches the maximum-likelihood one. Choosing the degree $d$ and the penalty $\lambda$ is a model-selection problem, settled by cross-validation from the [evaluation module](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation), and taken further in the [regularization module](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference).
-
- *The same linear score, passed through a squashing function instead of read directly, turns regression into classification, the subject of the next module.*
-
- ---
- Next: [Linear classification](/en/Machine%20Learning/06%20Linear%20classification) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/05 Linear regression/linear-regression.png .. /dev/null
en/Machine Learning/06 Linear classification.md .. /dev/null
@@ 1,83 0,0 @@
- # 6. Linear classification
-
- Classification predicts a discrete label from the same linear score $\theta^T x$. This module starts from the idea of treating classification as regression, then builds the two classical linear classifiers: the perceptron, binary and multiclass, and logistic regression, binary with the sigmoid and multiclass with the softmax, all trained by gradient descent on the cross-entropy loss.
-
- **Objectives**
- - See why regressing the labels directly is a poor classifier, and how a squashing function fixes it.
- - Classify with the perceptron, binary and multiclass, and know when it converges.
- - Fit binary logistic regression with the sigmoid and the cross-entropy loss.
- - Extend to many classes with the softmax, and relate the sigmoid and the softmax.
- - Train these models by gradient descent.
-
- ## 6.1 Classification as a regression problem
-
- One could fit least squares to the labels $y \in \{0, 1\}$ directly, but the linear output is unbounded, is pulled around by outliers, and does not read as a probability. The fix is to keep the linear score and pass it through a squashing function that maps it to a class or a probability. The rest of the module is two choices of that function.
-
- ## 6.2 The perceptron
-
- ### 6.2.1 Binary perceptron
-
- The perceptron passes the score through a hard step, so the output is a class label:
-
- $$\boxed{ h_\theta(x) = g(\theta^T x), \quad g(z) = \begin{cases} 1 & \text{if } z \ge 0 \\ 0 & \text{otherwise} \end{cases} }$$
-
- It is trained online, correcting $\theta$ only on a misclassified point:
-
- $$\boxed{ \theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)} }$$
-
- ![Perceptron decision boundary](/en/Machine%20Learning/06%20Linear%20classification/a/perceptron.png)
-
- *The perceptron finds one separating hyperplane, not necessarily the maximum-margin one the support vector machine will choose.*
-
- ### 6.2.2 Multiclass perceptron
-
- With $k$ classes, keep one weight vector $\theta_c$ per class and predict the highest-scoring one. On a mistake, reward the true class and penalize the predicted one:
-
- $$\boxed{ \hat{y} = \arg\max_c \theta_c^T x, \qquad \theta_{y} \mathrel{+}= \alpha x, \quad \theta_{\hat{y}} \mathrel{-}= \alpha x }$$
-
- ### 6.2.3 Convergence
-
- If the data is linearly separable the perceptron converges in a finite number of updates, otherwise the weights oscillate forever.
-
- *Remark:* the perceptron stops at the first separating hyperplane, which motivates the support vector machine (widest margin) and, stacked into layers, the neural network. A perceptron is a single unit, and stacked into layers it becomes a neural network, the starting point of the Deep Learning course.
-
- ## 6.3 Logistic regression, binary
-
- Logistic regression replaces the hard step with the smooth sigmoid, so the output is the probability of the positive class:
-
- $$\boxed{ \phi = p(y = 1 \mid x; \theta) = g(\theta^T x) = \frac{1}{1 + e^{-\theta^T x}} }$$
-
- It is fit by minimizing the cross-entropy loss, the negative log-likelihood of the Bernoulli labels:
-
- $$\boxed{ L(\theta) = -\sum_{i=1}^{m}\left[ y^{(i)}\log \phi^{(i)} + (1 - y^{(i)})\log(1 - \phi^{(i)}) \right] }$$
-
- ![Sigmoid and logistic decision boundary](/en/Machine%20Learning/06%20Linear%20classification/a/logistic-regression.png)
-
- *Left: the sigmoid maps any score into the interval (0, 1). Right: the decision boundary and the predicted probability.*
-
- ## 6.4 Logistic regression, multiclass
-
- For $k$ classes the sigmoid generalizes to the softmax, one weight vector per class, normalized into a distribution:
-
- $$\boxed{ p(y = c \mid x; \theta) = \frac{\exp(\theta_c^T x)}{\sum_{j=1}^{k}\exp(\theta_j^T x)} }$$
-
- trained by the categorical cross-entropy $L = -\sum_i \log p(y^{(i)} \mid x^{(i)})$.
-
- | | sigmoid | softmax |
- | --- | --- | --- |
- | classes | 2 | $k$ |
- | output | one probability $\phi$ | a distribution over $k$ classes |
- | relation | the $k = 2$ softmax reduces to the sigmoid | generalizes the sigmoid |
-
- ## 6.5 Gradient descent
-
- Both models are fit by gradient descent on the cross-entropy. The gradient takes the same clean form as the least-squares update, the residual times the input:
-
- $$\boxed{ \theta_j \leftarrow \theta_j - \alpha \sum_{i=1}^{m}\left(\phi^{(i)} - y^{(i)}\right)x_j^{(i)} }$$
-
- *Remark:* the perceptron, linear regression, and logistic regression share one update, the residual times the input. Only the activation differs (step, identity, sigmoid or softmax). The Deep Learning course picks up exactly this thread, stacking such units into layers.
-
- *With linear models covered, the next module controls their complexity: regularization and inference when the regressors are many.*
-
- ---
- Next: [Regularization and high-dimensional inference](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/08 Multilayer neural networks.md .. en/Machine Learning/06 Multilayer neural networks.md
@@ 1,4 1,4 @@
- # 8. Multilayer neural networks
+ # 6. Multilayer neural networks
A single linear unit only draws a straight boundary. Stacking many simple units with a nonlinearity between them gives a multilayer neural network, which fits curved boundaries and learns its own features. This module is a compact tour of neural networks, from architecture to training, and the gateway to the [Deep Learning](/en/Deep%20Learning) course, which develops every topic here in depth.
@@ 10,15 10,15 @@
- Train by the chain rule and backpropagation, with mini-batches, good initialization, and dropout.
- Guard the implementation with gradient checking and vectorization.
- ## 8.1 Linear versus nonlinear
+ ## 6.1 Linear versus nonlinear
- The linear classifiers of the [previous module](/en/Machine%20Learning/06%20Linear%20classification) separate classes with a single straight boundary, so a problem like XOR, which is not linearly separable, is out of reach. Composing units through a nonlinear activation $g$ bends the boundary. The nonlinearity is essential: without it, a stack of linear layers collapses back to a single linear map,
+ The linear classifiers of the [linear classification module](/en/Machine%20Learning/05%20Linear%20classification) separate classes with a single straight boundary, so a problem like XOR, which is not linearly separable, is out of reach. Composing units through a nonlinear activation $g$ bends the boundary. The nonlinearity is essential: without it, a stack of linear layers collapses back to a single linear map,
$$\boxed{ W^{[2]}\!\left(W^{[1]} x + b^{[1]}\right) + b^{[2]} = W' x + b' }$$
so depth would add nothing. The nonlinear activation is what makes stacking worthwhile.
- ## 8.2 Layers: input, hidden, output
+ ## 6.2 Layers: input, hidden, output
A single neuron computes $a = g(w^T x + b)$. A layer stacks many neurons, and a network stacks layers. Layer $l$ transforms the previous activations into new ones:
@@ 26,19 26,19 @@
The input layer holds $x$, the hidden layers learn intermediate features, and the output layer produces the prediction $\hat{y}$.
- ![Input, hidden, and output layers](/en/Machine%20Learning/08%20Multilayer%20neural%20networks/a/mlp-layers.svg)
+ ![Input, hidden, and output layers](/en/Machine%20Learning/06%20Multilayer%20neural%20networks/a/mlp-layers.svg)
*Each edge carries a weight in $W^{[l]}$ and each unit adds a bias then applies the activation.*
*Remark:* the bias is now written out explicitly and each layer has its own weight matrix $W^{[l]}$, unlike the earlier convention of folding the bias into $\theta^T x$ with $x_0 = 1$. This is the notation the Deep Learning course uses throughout.
- ## 8.3 Output layer: binary and multiclass
+ ## 6.3 Output layer: binary and multiclass
- The output layer matches the task, reusing the losses from the previous module. For two classes, a sigmoid output with the binary cross-entropy; for $k$ classes, a softmax output with the categorical cross-entropy:
+ The output layer matches the task, reusing the losses from [Linear classification](/en/Machine%20Learning/05%20Linear%20classification). For two classes, a sigmoid output with the binary cross-entropy, and for $k$ classes, a softmax output with the categorical cross-entropy:
$$\boxed{ \hat{y} = \frac{1}{1 + e^{-z}} \quad\text{(binary)} \qquad \hat{y}_c = \frac{e^{z_c}}{\sum_{j} e^{z_j}} \quad\text{(multiclass)} }$$
- ## 8.4 Activation functions and the zero-centered problem
+ ## 6.4 Activation functions and the zero-centered problem
The hidden activation is usually the sigmoid, the hyperbolic tangent, or the rectified linear unit:
@@ 46,28 46,28 @@
The sigmoid saturates in its tails, and its outputs are never negative, so a unit's incoming weights all receive gradients of the same sign and the updates zig-zag. The zero-centered $\tanh$ removes that bias, and ReLU avoids positive-side saturation altogether, which is why it is the common default.
- ![Activation functions](/en/Machine%20Learning/08%20Multilayer%20neural%20networks/a/activations.png)
+ ![Activation functions](/en/Machine%20Learning/06%20Multilayer%20neural%20networks/a/activations.png)
*The tanh is zero-centered while the sigmoid is not, and ReLU stays linear for positive inputs.*
- ## 8.5 Chain rule and backpropagation
+ ## 6.5 Chain rule and backpropagation
Training minimizes the loss by gradient descent, which needs its gradient with respect to every weight. Backpropagation computes all of them in one forward and one backward sweep: the forward pass caches each $z^{[l]}$ and $a^{[l]}$, then the backward pass applies the chain rule from the loss back to the first layer, reusing the cache. With the layer error $\delta^{[l]} = \partial L / \partial z^{[l]}$,
$$\boxed{ \delta^{[l]} = \left((W^{[l+1]})^T \delta^{[l+1]}\right) \odot g'^{[l]}\!\left(z^{[l]}\right), \qquad \frac{\partial L}{\partial W^{[l]}} = \delta^{[l]} (a^{[l-1]})^T }$$
- ![Forward and backward passes](/en/Machine%20Learning/08%20Multilayer%20neural%20networks/a/backprop.svg)
+ ![Forward and backward passes](/en/Machine%20Learning/06%20Multilayer%20neural%20networks/a/backprop.svg)
*The [Backpropagation](/en/Deep%20Learning/05%20Backpropagation) lesson of the Deep Learning course derives this step by step.*
- ## 8.6 Training in practice
+ ## 6.6 Training in practice
- **Mini-batches.** Estimate the gradient on a small batch of examples at a time, a middle ground between the full batch (accurate but slow) and one example (noisy but cheap).
- **Vanishing gradient.** Through many saturating layers the backpropagated gradient is a product of small factors and shrinks toward zero, so early layers barely learn. ReLU activations and careful initialization keep it alive.
- **Initialization.** Start the weights small and random to break symmetry, scaling the variance by the number of inputs (Xavier or He), so signals neither vanish nor explode through depth.
- - **Dropout.** Randomly zero a fraction of units during training. This prevents units from co-adapting and acts as a regularizer, in the spirit of the [regularization module](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference).
+ - **Dropout.** Randomly zero a fraction of units during training. This prevents units from co-adapting and acts as a regularizer, in the spirit of the regularization of [General concepts](/en/Machine%20Learning/02%20General%20concepts).
- ## 8.7 Sanity checks and vectorization
+ ## 6.7 Sanity checks and vectorization
Backpropagation is error-prone, so check the analytic gradient against a numerical finite-difference estimate:
@@ 80,4 80,4 @@
*This module is the doorway to the [Deep Learning](/en/Deep%20Learning) course, which develops architectures, optimizers, initialization, normalization, and regularization in full. The next module returns to linear models from a new angle, the maximum-margin classifier.*
---
- Next: [Support Vector Machines](/en/Machine%20Learning/09%20Support%20Vector%20Machines) · [Course overview](/en/Machine%20Learning)
+ Next: [Support Vector Machines](/en/Machine%20Learning/07%20Support%20Vector%20Machines) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/08 Multilayer neural networks/activations.png .. en/Machine Learning/06 Multilayer neural networks/activations.png
en/Machine Learning/08 Multilayer neural networks/backprop.svg .. en/Machine Learning/06 Multilayer neural networks/backprop.svg
en/Machine Learning/08 Multilayer neural networks/mlp-layers.svg .. en/Machine Learning/06 Multilayer neural networks/mlp-layers.svg
en/Machine Learning/07 Regularization and high-dimensional inference.md .. /dev/null
@@ 1,75 0,0 @@
- # 7. Regularization and high-dimensional inference
-
- You often do not have a handful of clean regressors. There can be many candidate predictors, sometimes more than observations, and they are correlated. Ordinary least squares overfits or breaks down in that regime. Regularization tames it by shrinking the coefficients, and this is where regularized regression meets classical statistics most directly. It also carries a warning: selecting variables and then doing inference on the same data invalidates the classical standard errors, which matters whenever the goal is a causal estimate rather than a prediction.
-
- Throughout we write the regression coefficients as $\beta$, the parameters $\theta$ of the linear model from the [linear regression module](/en/Machine%20Learning/05%20Linear%20regression).
-
- **Objectives**
- - See why ordinary least squares fails with many correlated regressors.
- - Define ridge (L2) and lasso (L1) regression and the role of the penalty $\lambda$.
- - Understand why the lasso produces sparse, variable-selecting solutions.
- - Choose the penalty $\lambda$ by cross-validation.
- - Recognize why naive post-selection inference is invalid, and know the standard corrections.
-
- ## 7.1 Why regularize
-
- When the number of regressors $p$ is large relative to the sample size $n$, the least-squares fit chases noise and its coefficients have huge variance. With correlated regressors the matrix $X^T X$ is nearly singular, so small data changes swing the estimates wildly, and when $p > n$ it is singular and OLS has no unique solution at all. Regularization accepts a little bias in exchange for a large cut in variance, the trade-off from [General concepts](/en/Machine%20Learning/02%20General%20concepts).
-
- ## 7.2 Ridge regression (L2)
-
- Ridge adds a squared-norm penalty on the coefficients to the least-squares objective:
-
- $$\boxed{ \hat{\beta}_{\text{ridge}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda \|\beta\|_2^2 }$$
-
- It has a closed form that is always invertible for $\lambda > 0$, which is exactly what rescues the collinear and $p > n$ cases:
-
- $$\boxed{ \hat{\beta}_{\text{ridge}} = \left(X^T X + \lambda I\right)^{-1} X^T y }$$
-
- Ridge shrinks all coefficients smoothly toward zero but never sets them exactly to zero, so it stabilizes rather than selects.
-
- ## 7.3 Lasso regression (L1)
-
- The lasso replaces the squared penalty with an absolute-value penalty:
-
- $$\boxed{ \hat{\beta}_{\text{lasso}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda \|\beta\|_1 }$$
-
- This small change has a large consequence: the lasso drives some coefficients to exactly zero, so it performs variable selection while it fits. The reason is geometric. The constraint region $\|\beta\|_1 \le t$ is a diamond with corners on the axes, and the elliptical loss contours tend to first touch it at a corner, where one coordinate is zero.
-
- ![L1 versus L2 constraint geometry](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference/a/l1-l2-geometry.png)
-
- *The rounded L2 ball is touched off the axes, keeping every coefficient nonzero, while the L1 diamond is touched at a corner, setting a coefficient to exactly zero.*
-
- As the penalty grows, more coefficients cross to zero, tracing the regularization path from the full model to the empty one.
-
- ![Lasso regularization path](/en/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference/a/regularization-path.png)
-
- *Each coefficient shrinks as $\lambda$ increases and then hits exactly zero, so the lasso yields a compact, interpretable subset of regressors.*
-
- ## 7.4 Elastic net
-
- The elastic net blends the two penalties, keeping the lasso's selection while borrowing the ridge's stability with correlated regressors:
-
- $$\boxed{ \hat{\beta}_{\text{en}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda\left(\alpha \|\beta\|_1 + (1 - \alpha)\|\beta\|_2^2\right) }$$
-
- with $\alpha \in [0, 1]$ mixing selection ($\alpha = 1$, lasso) and shrinkage ($\alpha = 0$, ridge).
-
- ## 7.5 Choosing the penalty
-
- The penalty $\lambda$ is a hyperparameter, so it is chosen by cross-validation from the [previous module](/en/Machine%20Learning/03%20Model%20evaluation%20and%20validation): fit over a grid of $\lambda$ values and keep the one with the lowest cross-validated error, or the largest $\lambda$ within one standard error of the best for a simpler model. Larger $\lambda$ means more shrinkage, more bias, and less variance.
-
- ## 7.6 The inference caveat
-
- Prediction is not inference, and this is the point that is easy to miss. Suppose you select regressors with the lasso and then run ordinary least squares on the chosen subset and report textbook standard errors. Those standard errors are wrong. They ignore that the data was already used to pick the variables, so the confidence intervals are too narrow and the p-values are not valid, a form of the winner's curse. Three corrections are standard:
-
- - **Sample splitting.** Select the variables on one part of the data and estimate and do inference on another, so the selection does not contaminate the standard errors.
- - **Debiased (desparsified) lasso.** Add a correction term to the lasso estimate that removes the shrinkage bias and restores an asymptotically valid confidence interval for each coefficient.
- - **Post-double-selection** (Belloni, Chernozhukov, and Hansen). To estimate the effect of a treatment with many controls, select the controls that predict the outcome and the controls that predict the treatment, then estimate the effect on the union of both sets.
-
- $$\boxed{ \text{select for prediction} \;\ne\; \text{valid inference on a coefficient} }$$
-
- *Remark:* these ideas are the doorway to causal machine learning, where flexible learners estimate nuisance functions while a correction preserves valid inference on the parameter of interest. Regularization is superb for prediction, but for a causal parameter you need one of these corrections, not the raw penalized coefficients.
-
- *With shrinkage and selection covered, the next module stacks these linear building blocks into multilayer neural networks.*
-
- ---
- Next: [Multilayer neural networks](/en/Machine%20Learning/08%20Multilayer%20neural%20networks) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/09 Support Vector Machines.md .. en/Machine Learning/07 Support Vector Machines.md
@@ 1,4 1,4 @@
- # 9. Support Vector Machines
+ # 7. Support Vector Machines
Support vector machines are large-margin linear classifiers. They pick the boundary that
maximizes the distance to the nearest points, control overfitting with the hinge loss and a
@@ 11,11 11,11 @@
- Define kernels, the kernel trick, and the Mercer condition.
- Form the Lagrangian, derive the dual and KKT conditions, and define support vectors.
- ## 9.1 Optimal margin classifier
+ ## 7.1 Optimal margin classifier
Labels are $y \in \{-1,+1\}$, with weight vector $w \in \mathbb{R}^{n}$ and bias $b$.
- ### 9.1.1 Hypothesis and boundary
+ ### 7.1.1 Hypothesis and boundary
The hypothesis is defined as the sign of the raw score $z = w^T x - b$:
@@ 27,7 27,7 @@
*Remark:* $w$ is orthogonal to the boundary, so it sets the orientation, and $b$ sets the offset.
- ### 9.1.2 Geometric margin
+ ### 7.1.2 Geometric margin
The geometric margin of example $i$ is defined as its signed distance to the boundary, made
positive by the label:
@@ 40,7 40,7 @@
*Remark:* dividing by $\lVert w \rVert$ makes the margin invariant to rescaling $(w,b)$, unlike
the raw score $z$.
- ### 9.1.3 Hard-margin primal
+ ### 7.1.3 Hard-margin primal
Fixing the scale so the closest points satisfy $y^{(i)}(w^T x^{(i)} - b) = 1$, maximizing the
margin is equivalent to minimizing $\lVert w \rVert^2$ subject to a unit functional margin:
@@ 52,15 52,15 @@
*Remark:* it requires the data to be linearly separable. The next lesson relaxes that with slack
variables.
- ![SVM margin and support vectors](/en/Machine%20Learning/09%20Support%20Vector%20Machines/a/svm-margin.png)
+ ![SVM margin and support vectors](/en/Machine%20Learning/07%20Support%20Vector%20Machines/a/svm-margin.png)
*The optimal hyperplane (solid) maximizes the margin (dashed). Circled points are the support vectors.*
- ## 9.2 Hinge loss
+ ## 7.2 Hinge loss
The raw score is $z = w^T x - b$ and labels are $y \in \{-1,+1\}$.
- ### 9.2.1 Hinge loss
+ ### 7.2.1 Hinge loss
The hinge loss is defined as the amount by which the margin $yz$ falls short of $1$, clipped at zero:
@@ 72,7 72,7 @@
*Remark:* the hinge loss is convex but not differentiable at $yz = 1$, so it is optimized with
subgradients.
- ### 9.2.2 Soft-margin primal
+ ### 7.2.2 Soft-margin primal
Introduce a slack $\xi_i \ge 0$ per example to allow margin violations, penalized by $C > 0$:
@@ 86,7 86,7 @@
This is regularization plus hinge loss: the $\tfrac{1}{2}\lVert w \rVert^2$ term widens the margin
and the sum penalizes violations.
- ### 9.2.3 Role of $C$
+ ### 7.2.3 Role of $C$
| $C$ | Penalty on violations | Margin | Behaviour |
| --- | --- | --- | --- |
@@ 95,9 95,9 @@
*Remark:* as $C \to \infty$ no violation is tolerated, which recovers the hard-margin classifier.
- ## 9.3 Kernels
+ ## 7.3 Kernels
- ### 9.3.1 Kernel definition
+ ### 7.3.1 Kernel definition
A kernel is defined as the inner product of a feature map $\phi$ applied to two inputs:
@@ 106,7 106,7 @@
A valid kernel computes this inner product directly, so $\phi$ never has to be formed (it may even
be infinite-dimensional).
- ### 9.3.2 Kernel trick
+ ### 7.3.2 Kernel trick
The SVM dual depends on the data only through inner products $\langle x^{(i)}, x^{(j)} \rangle$.
The kernel trick replaces each inner product with a kernel:
@@ 120,7 120,7 @@
$$\boxed{ K(x,z) = \exp\!\left( -\frac{\lVert x - z \rVert^2}{2\sigma^2} \right) }$$
- ### 9.3.3 Mercer condition
+ ### 7.3.3 Mercer condition
A function $K$ is a valid kernel if and only if, for every finite sample, its Gram matrix is
symmetric positive semidefinite:
@@ 130,7 130,7 @@
*Remark:* this is the Mercer condition. It guarantees a feature map $\phi$ exists, so the dual stays
convex.
- ### 9.3.4 Common kernels
+ ### 7.3.4 Common kernels
| Kernel | $K(x,z)$ | Note |
| --- | --- | --- |
@@ 141,13 141,13 @@
*Remark:* a small $\sigma$ makes the RBF kernel very local, which can overfit. It trades off against
$C$.
- ![RBF kernel decision boundary](/en/Machine%20Learning/09%20Support%20Vector%20Machines/a/svm-kernel.png)
+ ![RBF kernel decision boundary](/en/Machine%20Learning/07%20Support%20Vector%20Machines/a/svm-kernel.png)
*An RBF kernel separates classes that are not linearly separable, with a nonlinear boundary in the input space.*
- ## 9.4 Lagrangian and duality
+ ## 7.4 Lagrangian and duality
- ### 9.4.1 Lagrangian
+ ### 7.4.1 Lagrangian
For a primal objective $f(w)$ with inequality constraints $g_i(w) \le 0$ and multipliers
$\beta_i \ge 0$, the Lagrangian is defined as:
@@ 162,16 162,16 @@
So the optimal $w$ is a linear combination of the training inputs weighted by $\beta_i y^{(i)}$.
- ### 9.4.2 Dual problem
+ ### 7.4.2 Dual problem
Substituting these back eliminates $w$ and $b$, leaving a problem in $\beta$ that depends on the
data only through inner products:
$$\boxed{ \max_{\beta} \ \sum_{i=1}^{m}\beta_i - \tfrac{1}{2}\sum_{i,j}\beta_i \beta_j\, y^{(i)} y^{(j)} \langle x^{(i)}, x^{(j)} \rangle \quad \text{s.t.} \quad \beta_i \ge 0, \ \ \sum_{i}\beta_i y^{(i)} = 0 }$$
- The inner products are exactly where a kernel $K$ is substituted (see [Kernels](/en/Machine%20Learning/09%20Support%20Vector%20Machines#93-kernels)).
+ The inner products are exactly where a kernel $K$ is substituted (see [Kernels](/en/Machine%20Learning/07%20Support%20Vector%20Machines#73-kernels)).
- ### 9.4.3 KKT and support vectors
+ ### 7.4.3 KKT and support vectors
At the optimum, complementary slackness ties each multiplier to its constraint:
@@ 183,7 183,7 @@
These are the points exactly on the margin. All others have $\beta_i = 0$ and do not affect $w$.
- ### 9.4.4 Kernelized decision
+ ### 7.4.4 Kernelized decision
Replacing the inner product by a kernel gives a decision rule expressed only through support vectors:
@@ 192,7 192,7 @@
*Remark:* only support vectors ($\beta_i > 0$) contribute, so prediction cost scales with their
count, not with $m$.
- ### 9.4.5 From primal to decision
+ ### 7.4.5 From primal to decision
```mermaid
flowchart TD
@@ 212,4 212,4 @@
*Support vector machines draw a single, possibly kernelized, boundary. The final part takes a different route: split the feature space with simple rules and combine many such models into an ensemble.*
---
- Next: [Decision trees and ensemble methods](/en/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods) · [Course overview](/en/Machine%20Learning)
+ Next: [Decision trees and ensemble methods](/en/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods) · [Course overview](/en/Machine%20Learning)
en/Machine Learning/09 Support Vector Machines/svm-kernel.png .. en/Machine Learning/07 Support Vector Machines/svm-kernel.png
en/Machine Learning/09 Support Vector Machines/svm-margin.png .. en/Machine Learning/07 Support Vector Machines/svm-margin.png
en/Machine Learning/10 Decision trees and ensemble methods.md .. en/Machine Learning/08 Decision trees and ensemble methods.md
@@ 1,4 1,4 @@
- # 10. Decision trees and ensemble methods
+ # 8. Decision trees and ensemble methods
Tree models partition the input space into axis-aligned regions and fit a constant per region, giving interpretable but high-variance predictors. Ensemble methods combine many trees: bagging and random forests average independently grown trees to cut variance, while boosting grows trees sequentially to cut bias.
@@ 9,9 9,9 @@
- Estimate generalization error for free with out-of-bag samples.
- Build a strong predictor as an additive sum of weak learners (AdaBoost, gradient boosting).
- ## 10.1 CART decision trees
+ ## 8.1 CART decision trees
- ### 10.1.1 Tree as a partition
+ ### 8.1.1 Tree as a partition
A CART tree partitions the input space into $M$ disjoint regions $R_1,\dots,R_M$ (the leaves) and predicts a constant $c_m$ on each. The prediction is defined as
@@ 21,7 21,7 @@
*Remark:* the regions are axis-aligned boxes, so the decision boundary is a staircase. A single tree has low bias but high variance.
- ### 10.1.2 Impurity and split selection
+ ### 8.1.2 Impurity and split selection
For a region with class proportions $\hat p_k$, impurity measures how mixed the labels are. The Gini index is defined as
@@ 44,7 44,7 @@
*Remark:* the two criteria almost always pick the same split. Gini is the default in most implementations because it avoids the logarithm.
- ### 10.1.3 Regression trees
+ ### 8.1.3 Regression trees
For regression the leaf value is the mean of the targets in the region, defined as
@@ 52,7 52,7 @@
and splits minimize the within-region squared error instead of a classification impurity.
- ### 10.1.4 Pruning
+ ### 8.1.4 Pruning
An unpruned tree fits the training set exactly and overfits. Cost-complexity pruning trades fit against tree size $|T|$ (the number of leaves) through a penalty $\alpha\ge0$:
@@ 68,13 68,13 @@
B -->|"no"| E["leaf R2"]
```
- ![Decision tree regions](/en/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods/a/tree-boundary.png)
+ ![Decision tree regions](/en/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods/a/tree-boundary.png)
*A tree carves the input space into axis-aligned regions, each with a constant prediction.*
- ## 10.2 Random forests
+ ## 8.2 Random forests
- ### 10.2.1 Bagging
+ ### 8.2.1 Bagging
Bagging (bootstrap aggregating) trains $B$ trees on $B$ bootstrap resamples of the data and averages them. The bagged predictor is defined as
@@ 84,7 84,7 @@
A bootstrap sample draws $N$ examples with replacement from $N$ examples. The probability that a given example is never drawn is $(1-\tfrac1N)^N\to e^{-1}\approx0.37$, so about 37% of the data is left out of each tree. These are its out-of-bag (OOB) examples.
- ### 10.2.2 Variance of an average
+ ### 8.2.2 Variance of an average
If the $B$ trees each have variance $\sigma^2$ and pairwise correlation $\rho$, the variance of their average is
@@ 92,7 92,7 @@
The second term vanishes as $B$ grows, but the first, $\rho\sigma^2$, does not. Reducing the correlation $\rho$ between trees is therefore the key lever, and that is what random forests target.
- ### 10.2.3 Random forests
+ ### 8.2.3 Random forests
A random forest is bagging plus feature subsampling: at each split only a random subset of $m_{\text{try}}$ features is considered as split candidates. The usual choices are
@@ 122,13 122,13 @@
T3 --> AGG
```
- ![Single tree versus random forest](/en/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods/a/forest-vs-tree.png)
+ ![Single tree versus random forest](/en/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods/a/forest-vs-tree.png)
*(a) A single deep tree overfits with a jagged boundary. (b) A random forest averages many trees for a smoother boundary.*
- ## 10.3 Boosting
+ ## 8.3 Boosting
- ### 10.3.1 Additive model
+ ### 8.3.1 Additive model
Boosting builds a predictor as a weighted sum of $T$ weak learners $h_t$ (typically shallow trees), fitted one at a time. The additive model is defined as
@@ 136,7 136,7 @@
Each stage corrects the errors of the running sum, so the ensemble is built sequentially and reduces bias rather than variance.
- ### 10.3.2 AdaBoost
+ ### 8.3.2 AdaBoost
With labels $y\in\{-1,+1\}$, AdaBoost keeps example weights $w^{(i)}$ that concentrate on the currently misclassified points. At round $t$ the weak learner has weighted error $\varepsilon_t$, and its coefficient is defined as
@@ 148,7 148,7 @@
and renormalized. Misclassified examples ($y^{(i)}h_t(x^{(i)})<0$) gain weight, so the next learner focuses on them.
- ### 10.3.3 Gradient boosting
+ ### 8.3.3 Gradient boosting
Gradient boosting generalizes the idea to any differentiable loss $L$. At stage $t$ it fits the next learner to the negative gradient of the loss evaluated at the current model, the pseudo-residual defined as
en/Machine Learning/10 Decision trees and ensemble methods/forest-vs-tree.png .. en/Machine Learning/08 Decision trees and ensemble methods/forest-vs-tree.png
en/Machine Learning/10 Decision trees and ensemble methods/tree-boundary.png .. en/Machine Learning/08 Decision trees and ensemble methods/tree-boundary.png
fr/Deep Learning.md ..
@@ 2,7 2,7 @@
Les réseaux de neurones, du simple perceptron aux transformeurs modernes : comment la profondeur, les bonnes fonctions d'activation et l'entraînement par gradient permettent à un modèle d'apprendre ses propres caractéristiques au lieu de les concevoir à la main.
- **Prérequis :** le cours [Machine Learning](/fr/Machine%20Learning) (en particulier le perceptron dans [Classification linéaire](/fr/Machine%20Learning/06%20Linear%20classification)), Python de base, calcul différentiel et algèbre linéaire.
+ **Prérequis :** le cours [Machine Learning](/fr/Machine%20Learning) (en particulier le perceptron dans [Classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification)), Python de base, calcul différentiel et algèbre linéaire.
## Programme
@@ 22,7 22,6 @@
14. [LSTM et GRU](/fr/Deep%20Learning/14%20LSTM%20and%20GRU)
15. [Attention](/fr/Deep%20Learning/15%20Attention)
16. [Transformeurs](/fr/Deep%20Learning/16%20Transformers)
- 17. [Le deep learning en pratique](/fr/Deep%20Learning/17%20Deep%20learning%20in%20practice)
---
[Machine Learning](/fr/Machine%20Learning) · [MLOps](/fr/MLOps) · [Accueil](/fr)
fr/Deep Learning/01 Introduction.md ..
@@ 1,6 1,6 @@
# 1. Introduction
- Ce cours prolonge directement le cours de Machine Learning, qui concluait la partie [Classification linéaire](/fr/Machine%20Learning/06%20Linear%20classification) sur une remarque clé : un perceptron est une unité unique, et empilé en couches il devient un réseau de neurones. Cette leçon rend ce pont explicite. Elle rappelle ce qu'une seule unité peut faire, montre la tâche concrète (XOR) où une unité unique échoue, et fixe la notation utilisée dans tout le reste du cours.
+ Ce cours prolonge directement le cours de Machine Learning, qui concluait la partie [Classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification) sur une remarque clé : un perceptron est une unité unique, et empilé en couches il devient un réseau de neurones. Cette leçon rend ce pont explicite. Elle rappelle ce qu'une seule unité peut faire, montre la tâche concrète (XOR) où une unité unique échoue, et fixe la notation utilisée dans tout le reste du cours.
**Objectifs**
- Rappeler le perceptron comme une unité unique avec une activation en marche d'escalier et une frontière linéaire.
fr/Deep Learning/16 Transformers.md ..
@@ 109,7 109,7 @@
*Remarque :* un modèle encodeur seul voit toute la séquence d'un coup, ce qui convient à l'étiquetage et à la recherche d'information. Un modèle décodeur seul masque le futur afin de pouvoir prédire le token suivant, ce qui correspond exactement au cadre de la génération de texte.
- *L'attention et le Transformeur étant maintenant acquis, la dernière leçon se tourne vers l'usage de ces modèles en pratique : les frameworks, la boucle d'entraînement, l'apprentissage par transfert et les pièges qui font le plus souvent trébucher le travail appliqué.*
+ *L'attention et le Transformeur étant maintenant acquis, l'arc du cours est complet : du simple perceptron à l'architecture derrière les modèles de fondation d'aujourd'hui. Pour faire passer un modèle entraîné du notebook à un service de production fiable, poursuivez avec le cours [MLOps](/fr/MLOps).*
---
- Suivant : [Le deep learning en pratique](/fr/Deep%20Learning/17%20Deep%20learning%20in%20practice) · [Vue d'ensemble du cours](/fr/Deep%20Learning)
+ Suivant : [Vue d'ensemble du cours](/fr/Deep%20Learning)
fr/Deep Learning/17 Deep learning in practice.md .. /dev/null
@@ 1,104 0,0 @@
- # 17. Le deep learning en pratique
-
- Jusqu'ici, chaque leçon dérivait à la main les mécanismes des réseaux de neurones : passe avant, fonction de coût, rétropropagation et optimiseur. En pratique, vous n'écrivez presque rien de tout cela. Les frameworks modernes stockent les données sous forme de tenseurs, enregistrent les opérations que vous effectuez et les différencient automatiquement, si bien que la boucle d'entraînement que vous codez est courte et que les gradients viennent gratuitement. Cette leçon de synthèse relie la théorie aux outils, au matériel et aux habitudes qui permettent à un modèle de réellement s'entraîner.
-
- **Objectifs**
- - Expliquer ce qu'un tenseur et la différentiation automatique vous apportent, et comment l'autograd implémente la rétropropagation.
- - Écrire de mémoire une boucle d'entraînement indépendante du framework.
- - Raisonner sur la taille de batch, les accélérateurs et la précision mixte comme des compromis pratiques.
- - Appliquer l'apprentissage par transfert : réutiliser un backbone préentraîné, geler les premières couches, affiner le reste.
- - Reconnaître et corriger les modes de défaillance courants qui sabotent discrètement un entraînement.
- - Situer les modèles de ce cours sur une même carte et les transmettre à la production.
-
- ## 17.1 Frameworks, tenseurs et autograd
-
- Les deux piles logicielles dominantes sont **PyTorch** et **TensorFlow**, avec **JAX** comme troisième en forte croissance, qui associe une API à la NumPy à des transformations de fonctions. Les trois partagent deux idées.
-
- Un **tenseur** est un tableau à n dimensions qui réside sur un périphérique (CPU ou accélérateur) et porte un type de données. Un scalaire est un tenseur 0-D, un vecteur 1-D, une matrice 2-D, et un lot d'images RVB est typiquement un tenseur 4-D de forme (batch, canaux, hauteur, largeur). Chaque activation $a^{[l]}$, poids $W^{[l]}$ et biais $b^{[l]}$ des leçons précédentes est un tenseur.
-
- La **différentiation automatique** (autograd) est ce qui vous évite de coder la rétropropagation. Pendant l'exécution de la passe avant, le framework enregistre chaque opération primitive dans un graphe de calcul. L'appel à `backward()` parcourt ce graphe à l'envers et applique la règle de la chaîne, donnant $\partial J / \partial W^{[l]}$ et $\partial J / \partial b^{[l]}$ pour chaque paramètre. C'est exactement la rétropropagation que vous avez dérivée plus tôt, exécutée pour vous :
-
- $$\boxed{ \frac{\partial J}{\partial z^{[l]}} = \left( W^{[l+1]} \right)^{T} \frac{\partial J}{\partial z^{[l+1]}} \odot g'^{[l]}\!\left(z^{[l]}\right) }$$
-
- *Remarque :* PyTorch construit le graphe dynamiquement à chaque passe avant (define-by-run), ce qui fait que le débogage ressemble à du Python ordinaire. TensorFlow et JAX peuvent tracer et compiler le graphe à l'avance pour la vitesse. Vous appelez rarement vous-même les calculs de gradient, mais connaître la formule ci-dessus est la raison pour laquelle vous pouvez diagnostiquer un gradient qui s'évanouit ou explose lorsqu'un réseau profond refuse d'apprendre.
-
- ## 17.2 La boucle d'entraînement
-
- Sous chaque framework, la boucle est la même. Vous itérez sur les époques, et au sein de chaque époque sur les mini-lots, en exécutant quatre étapes par lot : passe avant, fonction de coût, passe arrière, pas de l'optimiseur. Un détail piège les débutants : les gradients s'accumulent par défaut, vous devez donc les remettre à zéro à chaque itération.
-
- ```python
- for epoch in range(num_epochs):
- for x_batch, y_batch in dataloader: # mini-batches, shuffled
- optimizer.zero_grad() # clear accumulated gradients
- yhat = model(x_batch) # forward pass a[L] = model(x)
- loss = loss_fn(yhat, y_batch) # per-batch cost J
- loss.backward() # autograd: backpropagation
- optimizer.step() # update W[l], b[l]
- validate(model, val_loader) # track generalization
- ```
-
- *Remarque :* l'ordre compte. Remettez les gradients à zéro avant `backward()`, et n'appelez jamais `optimizer.step()` avant que la passe arrière n'ait rempli les gradients. Dans TensorFlow, ces mêmes quatre étapes vivent à l'intérieur d'un contexte `GradientTape`, mais la structure est identique.
-
- ## 17.3 Matériel et batching
-
- Les réseaux de neurones sont de l'algèbre linéaire dense, qui se projette parfaitement sur les **GPU** et autres accélérateurs (TPU). Un GPU exécute des milliers de multiplications matricielles en parallèle, si bien que déplacer à la fois le modèle et les données sur le périphérique est en général la plus grande accélération que vous obtiendrez.
-
- ### 17.3.1 Taille de mini-lot
-
- La taille de batch est un compromis central, pas un détail.
-
- | Taille de batch | Qualité du gradient | Utilisation du matériel | Généralisation |
- | --- | --- | --- | --- |
- | Petite (8 à 32) | estimation bruitée | sous-utilise le GPU | le bruit peut aider à échapper aux minima aigus |
- | Grande (256+) | estimation lisse et précise | sature le GPU | peut converger vers des minima aigus, nécessite un warmup |
-
- *Remarque :* une règle empirique courante consiste à choisir le plus grand batch qui tient en mémoire, puis à régler le taux d'apprentissage en conséquence, puisqu'un batch plus grand nécessite en général un taux d'apprentissage plus élevé (ou progressif via un warmup).
-
- ### 17.3.2 Précision mixte
-
- Stocker les activations et les poids en flottants 16 bits (`float16` ou `bfloat16`) plutôt qu'en 32 bits divise la mémoire par deux et accélère les multiplications matricielles, tandis qu'une copie maîtresse des poids et de la fonction de coût reste en 32 bits pour la stabilité numérique. C'est la **précision mixte**, et sur les accélérateurs modernes elle offre des gains de performance quasi gratuits.
-
- ## 17.4 Apprentissage par transfert et fine-tuning
-
- Entraîner un grand réseau à partir de zéro nécessite beaucoup de données et de calcul. L'**apprentissage par transfert** contourne cela en réutilisant un modèle déjà entraîné sur un grand corpus. Vous conservez son **backbone** (les couches d'extraction de caractéristiques), remplacez la tête finale spécifique à la tâche, et entraînez sur votre plus petit jeu de données.
-
- La recette habituelle :
-
- 1. **Geler** les premières couches, dont les caractéristiques (contours, textures, motifs génériques de tokens) se transfèrent d'une tâche à l'autre.
- 2. **Remplacer la tête** par une tête dimensionnée pour vos classes ou vos sorties.
- 3. **Affiner** les couches ultérieures, et éventuellement dégeler le reste avec un faible taux d'apprentissage une fois que la tête s'est stabilisée.
-
- ![Pipeline d'apprentissage par transfert, d'un backbone préentraîné jusqu'au déploiement](/fr/Deep%20Learning/17%20Deep%20learning%20in%20practice/a/transfer-learning.svg)
-
- *L'apprentissage par transfert réutilise un backbone préentraîné, remplace la tête et affine les couches ultérieures sur la nouvelle tâche.*
-
- *Remarque :* c'est là que le **préentraînement auto-supervisé** porte ses fruits. Un modèle préentraîné à la manière de BERT ou de GPT sur d'énormes quantités de texte non étiqueté encode déjà une riche structure du langage, si bien que l'affiner sur un petit ensemble étiqueté surpasse de loin l'entraînement d'un modèle neuf. Il en va de même pour les backbones de vision préentraînés sur de vastes collections d'images.
-
- ## 17.5 Pièges courants
-
- La plupart des entraînements ratés n'ont rien d'exotique. Ils proviennent d'une courte liste d'erreurs, et chacune a une correction directe.
-
- | Piège | Symptôme | Correction |
- | --- | --- | --- |
- | Surapprentissage | le coût d'entraînement baisse, le coût de validation monte | régulariser, ajouter du dropout, augmenter les données ou arrêter tôt |
- | Mauvais taux d'apprentissage | le coût diverge ou reste plat | balayer le taux, utiliser un scheduler ou un warmup |
- | Fuite de données | excellent score de validation, mauvaise performance en production | séparer avant le prétraitement, garder les données de test invisibles |
- | Oubli de mélanger | le coût plafonne ou oscille en cycle | mélanger l'ensemble d'entraînement à chaque époque |
- | Absence de normalisation des entrées | entraînement lent ou instable | standardiser les caractéristiques à moyenne nulle et variance unitaire |
-
- *Remarque :* la fuite de données est la plus dangereuse car elle se déguise en succès. Si vous ajustez un scaler ou sélectionnez des caractéristiques en utilisant l'ensemble complet des données avant de le séparer, une information sur l'ensemble de test s'infiltre dans l'entraînement, et le score rapporté n'est qu'un mirage.
-
- ## 17.6 Une carte du domaine
-
- Les modèles de ce cours forment une lignée. Les perceptrons multicouches entièrement connectés ont fourni les mécanismes de base. Les convolutions ont ajouté la structure spatiale pour les images. Les réseaux récurrents et les LSTM ont géré les séquences. L'attention a supprimé le goulot d'étranglement séquentiel, les transformers l'ont mise à l'échelle, et le préentraînement des transformers à grande échelle a produit les modèles de fondation qui ancrent aujourd'hui la plupart des applications.
-
- ![Carte du cours, du MLP aux modèles de fondation](/fr/Deep%20Learning/17%20Deep%20learning%20in%20practice/a/field-map.svg)
-
- *Une carte du cours : du perceptron multicouche aux réseaux convolutifs et récurrents, en passant par l'attention, les Transformers et les modèles de fondation.*
-
- Un modèle entraîné ne représente que la moitié du travail. Le servir de façon fiable, surveiller la dérive, versionner les données et automatiser le réentraînement constituent une discipline à part entière.
-
- *Pour amener n'importe lequel de ces modèles d'un notebook à un service de production fiable, poursuivez avec le cours [MLOps](/fr/MLOps).*
-
- ---
- Suivant : [Vue d'ensemble du cours](/fr/Deep%20Learning)
fr/Deep Learning/17 Deep learning in practice/field-map.svg .. /dev/null
@@ 1,1 0,0 @@
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1030 300" width="1030" height="300" font-family="Helvetica, Arial, sans-serif"><defs><marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker><marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker></defs><rect width="1030" height="300" fill="#ffffff"/><text x="515.0" y="22.0" font-family="Helvetica, Arial, sans-serif" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">A map of the course: from the MLP to foundation models</text><rect x="40.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/><text x="105.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">MLP</text><rect x="204.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e4f5f4" stroke="#2a9d9a" stroke-width="1.6"/><text x="269.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">CNN</text><rect x="368.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/><text x="433.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">RNN and LSTM</text><rect x="532.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/><text x="597.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Attention</text><rect x="696.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/><text x="761.0" y="179.4" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Transformers</text><rect x="860.0" y="142.0" width="130.0" height="66.0" rx="8" fill="#fdecec" stroke="#d1495b" stroke-width="1.6"/><text x="925.0" y="171.8" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">Foundation</text><text x="925.0" y="187.1" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#1f2933" text-anchor="middle">models</text><line x1="170.0" y1="175.0" x2="204.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="334.0" y1="175.0" x2="368.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="498.0" y1="175.0" x2="532.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="662.0" y1="175.0" x2="696.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><line x1="826.0" y1="175.0" x2="860.0" y2="175.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><text x="105.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">core mechanics</text><text x="351.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">structure for images and sequences</text><text x="761.0" y="236.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">attention, scaling, and pretraining</text></svg>
\ No newline at end of file
fr/Deep Learning/17 Deep learning in practice/transfer-learning.svg .. /dev/null
@@ 1,1 0,0 @@
- <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 340" width="880" height="340" font-family="Helvetica, Arial, sans-serif"><defs><marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker><marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker></defs><rect width="880" height="340" fill="#ffffff"/><text x="440.0" y="22.0" font-family="Helvetica, Arial, sans-serif" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Transfer learning: reuse the backbone, replace the head, fine-tune</text><rect x="60" y="90" width="470" height="150" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/><text x="295.0" y="78.0" font-family="Helvetica, Arial, sans-serif" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">pretrained backbone</text><rect x="90.0" y="130.0" width="190.0" height="72.0" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/><text x="185.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">early layers</text><text x="185.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">frozen</text><rect x="310.0" y="130.0" width="190.0" height="72.0" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/><text x="405.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">later layers</text><text x="405.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">fine-tune</text><line x1="280.0" y1="166.0" x2="310.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><rect x="590.0" y="130.0" width="150.0" height="72.0" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/><text x="665.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">new task head</text><text x="665.0" y="224.0" font-family="Helvetica, Arial, sans-serif" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">replaced</text><line x1="500.0" y1="166.0" x2="590.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><rect x="780.0" y="130.0" width="78.0" height="72.0" rx="8" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/><text x="819.0" y="170.4" font-family="Helvetica, Arial, sans-serif" font-size="13" fill="#1f2933" text-anchor="middle">deploy</text><line x1="740.0" y1="166.0" x2="780.0" y2="166.0" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/><path d="M596.0 126.0 Q545.0 60.0 490.0 126.0" fill="none" stroke="#5b6b7b" stroke-width="1.7" marker-end="url(#arrowmuted)" stroke-dasharray="5 4"/><text x="543.0" y="121.0" font-family="Helvetica, Arial, sans-serif" font-size="11" fill="#5b6b7b" text-anchor="middle">fine-tune signal</text></svg>
\ No newline at end of file
fr/Machine Learning.md ..
@@ 8,14 8,12 @@
1. [Introduction](/fr/Machine%20Learning/01%20Introduction)
2. [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts)
- 3. [Évaluation et validation des modèles](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation)
- 4. [Formulation probabiliste](/fr/Machine%20Learning/04%20Probabilistic%20formulation)
- 5. [Régression linéaire](/fr/Machine%20Learning/05%20Linear%20regression)
- 6. [Classification linéaire](/fr/Machine%20Learning/06%20Linear%20classification)
- 7. [Régularisation et inférence en grande dimension](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference)
- 8. [Réseaux de neurones multi-couches](/fr/Machine%20Learning/08%20Multilayer%20neural%20networks)
- 9. [Machines à vecteurs de support](/fr/Machine%20Learning/09%20Support%20Vector%20Machines)
- 10. [Arbres de décision et méthodes d'ensemble](/fr/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods)
+ 3. [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation)
+ 4. [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression)
+ 5. [Classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification)
+ 6. [Réseaux de neurones multi-couches](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks)
+ 7. [Machines à vecteurs de support](/fr/Machine%20Learning/07%20Support%20Vector%20Machines)
+ 8. [Arbres de décision et méthodes d'ensemble](/fr/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods)
---
[MLOps](/fr/MLOps) · [Accueil](/fr)
fr/Machine Learning/01 Introduction.md ..
@@ 2,27 2,53 @@
Le machine learning construit des modèles qui apprennent des motifs à partir de données, au lieu d'être programmés explicitement avec des règles. Ce module fixe la notation utilisée tout au long du cours et cartographie l'éventail des problèmes et des modèles, afin que les modules suivants restent concis et centrés sur les formules.
- ## 1.1 Types d'apprentissage
-
- - **Supervisé** : apprendre à partir d'exemples étiquetés (régression, classification).
- - **Non supervisé** : trouver une structure dans des données non étiquetées (clustering, réduction de dimension).
- - **Par renforcement** : apprendre via des retours en interagissant avec un environnement.
-
- ## 1.2 Le déroulé
-
- 1. Définir le problème et rassembler les données.
- 2. Explorer et préparer les données.
- 3. Entraîner des modèles candidats.
- 4. Les évaluer et les comparer.
- 5. Déployer et surveiller (voir le cours [MLOps](/fr/MLOps)).
-
**Objectifs**
+ - Distinguer apprentissage supervisé, non supervisé et par renforcement selon leur signal de retour.
+ - Situer les étapes d'un projet de machine learning et ses boucles de rétroaction.
- Fixer la notation utilisée dans tout le cours.
- Définir l'ensemble d'entraînement, l'hypothèse et la matrice de conception.
- Adopter la convention d'ordonnée à l'origine $x_0 = 1$.
- Classer un problème supervisé selon le type de sa sortie.
- Distinguer les modèles discriminatifs des modèles génératifs.
+ ## 1.1 Types d'apprentissage
+
+ Les problèmes de machine learning se rangent d'ordinaire en trois paradigmes. Ce qui les sépare n'est pas l'algorithme mais le retour disponible pendant l'entraînement : une étiquette pour chaque exemple, aucune étiquette, ou une récompense obtenue en interagissant.
+
+ ![Les trois types d'apprentissage](/fr/Machine%20Learning/01%20Introduction/a/types-of-learning.svg)
+
+ *L'apprentissage supervisé ajuste une correspondance à partir d'exemples étiquetés, l'apprentissage non supervisé trouve une structure dans des données non étiquetées, et l'apprentissage par renforcement améliore une politique en interagissant avec un environnement.*
+
+ **Apprentissage supervisé.** Chaque exemple d'entraînement associe une entrée $x$ à la réponse $y$ que le modèle doit produire, et le but est une correspondance $x \mapsto y$ qui généralise à des entrées jamais vues à l'entraînement. Prédire le prix d'une maison à partir de ses caractéristiques (régression) et décider si un courriel est un spam (classification) sont les tâches canoniques. Les étiquettes rendent l'objectif explicite et le progrès mesurable, ce qui explique que la théorie soit la plus développée ici. Presque tout ce cours se place dans ce cadre.
+
+ **Apprentissage non supervisé.** Seules les entrées $x$ sont disponibles, et aucune étiquette ne dit quelle est la bonne réponse. Le but passe de la prédiction à la description : regrouper des clients similaires en segments (clustering), compresser de nombreuses caractéristiques corrélées en quelques directions informatives (réduction de dimension), ou estimer quelles régions de l'espace d'entrée sont probables (estimation de densité). Le succès est plus difficile à quantifier, faute de vérité terrain à laquelle se comparer.
+
+ **Apprentissage par renforcement.** Il n'y a pas de jeu de données fixe. Un agent choisit une action, l'environnement renvoie un nouvel état et une récompense, et cette récompense peut arriver longtemps après l'action qui l'a produite. Le but est une politique, une règle de choix des actions qui maximise la récompense cumulée. Le jeu et la robotique en sont les exemples typiques. C'est un domaine à part entière, hors du périmètre de ce cours.
+
+ | Paradigme | Données | Signal de retour | Ce qui est appris | Tâches canoniques |
+ | --- | --- | --- | --- | --- |
+ | Supervisé | paires $(x, y)$ | l'étiquette $y$ | une correspondance $h : x \mapsto y$ | régression, classification |
+ | Non supervisé | entrées $x$ seules | aucun | une structure dans les données | clustering, réduction de dimension |
+ | Par renforcement | interaction | récompense, souvent différée | une politique d'action | contrôle, jeu |
+
+ *Remarque :* les frontières ne sont pas rigides. L'apprentissage semi-supervisé mélange quelques exemples étiquetés à beaucoup d'exemples non étiquetés, et l'apprentissage auto-supervisé fabrique des étiquettes à partir des données elles-mêmes, par exemple en masquant un mot pour le prédire. Les deux réutilisent la machinerie supervisée introduite dans ce cours.
+
+ ## 1.2 Le déroulé
+
+ Un projet de machine learning n'est pas une ligne droite des données au modèle. Il fonctionne en boucle : chaque évaluation révèle quelque chose qui renvoie le travail à une étape antérieure, et une fois déployé, le modèle affronte de nouvelles données qui finissent par relancer le cycle.
+
+ ![Le déroulé d'un projet de machine learning](/fr/Machine%20Learning/01%20Introduction/a/ml-workflow.svg)
+
+ *Le chemin plein est l'ordre nominal. Les flèches en pointillé sont là où les vrais projets passent le plus clair de leur temps : retravailler caractéristiques et modèles après l'évaluation, et réentraîner après la surveillance.*
+
+ 1. **Définir le problème et rassembler les données.** Traduire la question en tâche de prédiction en fixant l'entrée $x$, la cible $y$ et la métrique qui compte comme succès. Les choix faits ici bornent tout ce qui suit, car aucun modèle ne peut retrouver une information absente des données.
+ 2. **Explorer et préparer les données.** Inspecter les distributions, les valeurs manquantes et les valeurs aberrantes, puis nettoyer, encoder et mettre à l'échelle les caractéristiques. Mettre de côté un ensemble de test avant tout réglage, pour que l'estimation finale des performances reste honnête.
+ 3. **Entraîner des modèles candidats.** Commencer par une base de référence simple, puis ajuster des familles plus riches en minimisant une perte sur les paramètres $\theta$ ([Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts)).
+ 4. **Les évaluer et les comparer.** Mesurer chaque candidat sur des données jamais vues, avec la validation et la validation croisée ([Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts)) et une métrique adaptée au problème. Le verdict renvoie le plus souvent à l'étape 2 ou 3 : de meilleures caractéristiques, une autre famille de modèles, ou plus de données.
+ 5. **Déployer et surveiller.** En production les données entrantes dérivent de la distribution d'entraînement, il faut donc surveiller les performances et planifier le réentraînement. Cette discipline a son propre cours : [MLOps](/fr/MLOps).
+
+ *Remarque :* en pratique l'essentiel de l'effort va aux étapes 1, 2 et 4. L'entraînement lui-même est souvent l'étape la moins coûteuse, et le plafond de qualité d'un modèle est fixé par les données.
+
## 1.3 Notation et mise en place
### 1.3.1 Ensemble d'entraînement
@@ 109,7 135,7 @@
E -->|"generatif"| G["ADG, Bayes naif"]
```
- *Le problème étant posé et la notation fixée, la partie suivante introduit les outils qui servent à ajuster un modèle aux données : fonctions de perte, descente de gradient et maximum de vraisemblance.*
+ *Le problème étant posé et la notation fixée, la partie suivante aborde ce que l'apprentissage exige vraiment : minimiser une perte est facile, généraliser au-delà de l'ensemble d'entraînement est le défi.*
---
Suivant : [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
/dev/null .. fr/Machine Learning/01 Introduction/ml-workflow.svg
@@ 0,0 1,40 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 880 270" width="880" height="270" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowmuted" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#5b6b7b"/></marker>
+ </defs>
+ <rect width="880" height="270" fill="#ffffff"/>
+ <text x="440" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Le déroulé d'un projet de machine learning</text>
+
+ <path d="M772 150 Q440 -10 108 150" fill="none" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="5 4" marker-end="url(#arrowmuted)"/>
+ <text x="440" y="62" font-size="11" fill="#5b6b7b" text-anchor="middle">la surveillance relance le cycle : nouvelles données, dérive, réentraînement</text>
+ <path d="M606 150 Q440 55 274 150" fill="none" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="5 4" marker-end="url(#arrowmuted)"/>
+ <text x="440" y="95" font-size="11" fill="#5b6b7b" text-anchor="middle">l'évaluation renvoie en arrière : autres caractéristiques, autres modèles</text>
+
+ <rect x="40" y="150" width="136" height="64" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="108" y="177" font-size="12" fill="#1f2933" text-anchor="middle">définir le problème</text>
+ <text x="108" y="194" font-size="12" fill="#1f2933" text-anchor="middle">réunir les données</text>
+ <rect x="206" y="150" width="136" height="64" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="274" y="177" font-size="12" fill="#1f2933" text-anchor="middle">explorer et</text>
+ <text x="274" y="194" font-size="12" fill="#1f2933" text-anchor="middle">préparer les données</text>
+ <rect x="372" y="150" width="136" height="64" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="440" y="177" font-size="12" fill="#1f2933" text-anchor="middle">entraîner des</text>
+ <text x="440" y="194" font-size="12" fill="#1f2933" text-anchor="middle">modèles candidats</text>
+ <rect x="538" y="150" width="136" height="64" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="606" y="177" font-size="12" fill="#1f2933" text-anchor="middle">évaluer et</text>
+ <text x="606" y="194" font-size="12" fill="#1f2933" text-anchor="middle">comparer</text>
+ <rect x="704" y="150" width="136" height="64" rx="8" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <text x="772" y="177" font-size="12" fill="#1f2933" text-anchor="middle">déployer et</text>
+ <text x="772" y="194" font-size="12" fill="#1f2933" text-anchor="middle">surveiller</text>
+
+ <line x1="176" y1="182" x2="206" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="342" y1="182" x2="372" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="508" y1="182" x2="538" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="674" y1="182" x2="704" y2="182" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+
+ <text x="191" y="234" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">données</text>
+ <text x="523" y="234" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">modélisation</text>
+ <text x="772" y="234" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">production</text>
+
+ <text x="440" y="258" font-size="11" fill="#5b6b7b" text-anchor="middle">le chemin plein se lit de gauche à droite, les boucles en pointillé sont là où un projet passe le plus clair de son temps</text>
+ </svg>
/dev/null .. fr/Machine Learning/01 Introduction/types-of-learning.svg
@@ 0,0 1,62 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 840 320" width="840" height="320" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ </defs>
+ <rect width="840" height="320" fill="#ffffff"/>
+ <text x="420" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Trois paradigmes d'apprentissage, trois signaux de retour</text>
+
+ <text x="142" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Supervisé</text>
+ <text x="407" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Non supervisé</text>
+ <text x="685" y="58" font-size="13" font-weight="600" fill="#5b6b7b" text-anchor="middle">Par renforcement</text>
+
+ <rect x="20" y="68" width="245" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+ <rect x="285" y="68" width="245" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+ <rect x="550" y="68" width="270" height="204" rx="12" fill="none" stroke="#9aa7b2" stroke-width="1.4" stroke-dasharray="6 5"/>
+
+ <line x1="85" y1="90" x2="235" y2="180" stroke="#1f2933" stroke-width="1.7"/>
+ <circle cx="85" cy="175" r="5.5" fill="#3b6fb6"/>
+ <circle cx="105" cy="155" r="5.5" fill="#3b6fb6"/>
+ <circle cx="75" cy="145" r="5.5" fill="#3b6fb6"/>
+ <circle cx="120" cy="180" r="5.5" fill="#3b6fb6"/>
+ <circle cx="140" cy="165" r="5.5" fill="#3b6fb6"/>
+ <circle cx="100" cy="190" r="5.5" fill="#3b6fb6"/>
+ <circle cx="160" cy="110" r="5.5" fill="#e0872e"/>
+ <circle cx="185" cy="125" r="5.5" fill="#e0872e"/>
+ <circle cx="205" cy="100" r="5.5" fill="#e0872e"/>
+ <circle cx="220" cy="120" r="5.5" fill="#e0872e"/>
+ <circle cx="175" cy="95" r="5.5" fill="#e0872e"/>
+ <circle cx="195" cy="140" r="5.5" fill="#e0872e"/>
+
+ <circle cx="350" cy="175" r="5.5" fill="#9aa7b2"/>
+ <circle cx="370" cy="155" r="5.5" fill="#9aa7b2"/>
+ <circle cx="340" cy="145" r="5.5" fill="#9aa7b2"/>
+ <circle cx="385" cy="180" r="5.5" fill="#9aa7b2"/>
+ <circle cx="405" cy="165" r="5.5" fill="#9aa7b2"/>
+ <circle cx="365" cy="190" r="5.5" fill="#9aa7b2"/>
+ <circle cx="425" cy="110" r="5.5" fill="#9aa7b2"/>
+ <circle cx="450" cy="125" r="5.5" fill="#9aa7b2"/>
+ <circle cx="470" cy="100" r="5.5" fill="#9aa7b2"/>
+ <circle cx="485" cy="120" r="5.5" fill="#9aa7b2"/>
+ <circle cx="440" cy="95" r="5.5" fill="#9aa7b2"/>
+ <circle cx="460" cy="140" r="5.5" fill="#9aa7b2"/>
+ <ellipse cx="369" cy="168" rx="46" ry="36" fill="none" stroke="#3b6fb6" stroke-width="1.6" stroke-dasharray="5 4"/>
+ <ellipse cx="455" cy="115" rx="45" ry="34" fill="none" stroke="#e0872e" stroke-width="1.6" stroke-dasharray="5 4"/>
+
+ <rect x="565" y="118" width="100" height="50" rx="8" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="615" y="147" font-size="13" fill="#1f2933" text-anchor="middle">agent</text>
+ <rect x="705" y="118" width="105" height="50" rx="8" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="757" y="147" font-size="13" fill="#1f2933" text-anchor="middle">environnement</text>
+ <path d="M645 113 Q686 79 727 113" fill="none" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="686" y="90" font-size="11" fill="#5b6b7b" text-anchor="middle">action</text>
+ <path d="M727 173 Q686 207 645 173" fill="none" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="686" y="204" font-size="11" fill="#5b6b7b" text-anchor="middle">état, récompense</text>
+
+ <text x="142" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">exemples étiquetés (x, y)</text>
+ <text x="407" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">exemples non étiquetés x</text>
+ <text x="685" y="234" font-size="11" fill="#5b6b7b" text-anchor="middle">interaction et récompense</text>
+ <text x="142" y="256" font-size="12" font-weight="600" fill="#3b6fb6" text-anchor="middle">apprendre à prédire y depuis x</text>
+ <text x="407" y="256" font-size="12" font-weight="600" fill="#e0872e" text-anchor="middle">découvrir une structure (groupes)</text>
+ <text x="685" y="256" font-size="12" font-weight="600" fill="#38a05a" text-anchor="middle">apprendre une politique d'action</text>
+
+ <text x="420" y="302" font-size="11" fill="#5b6b7b" text-anchor="middle">ce qui change d'un paradigme à l'autre, c'est le retour : une étiquette par exemple, aucune étiquette, ou une récompense différée</text>
+ </svg>
fr/Machine Learning/02 General concepts.md ..
@@ 1,16 1,25 @@
# 2. Concepts généraux
- Les briques communes à tout modèle supervisé : comment une perte mesure une prédiction isolée puis s'agrège en un coût, comment l'optimisation itérative minimise ce coût, et comment le point de vue probabiliste (la vraisemblance) retrouve les mêmes objectifs. On termine par l'algorithme de Newton, une alternative du second ordre à la descente de gradient.
+ L'introduction a fixé la notation et nommé les paradigmes d'apprentissage. Avant d'ajuster le moindre modèle particulier, ce module couvre ce qu'apprendre veut dire. Faire coller un modèle aux données qu'il a vues est facile, le faire performer sur des données qu'il n'a jamais vues est tout l'enjeu. La régression polynomiale sert d'exemple fil rouge, et le module se termine par la raison pour laquelle l'intuition géométrique s'effondre en grande dimension.
**Objectifs**
- - Définir une fonction de perte et agréger les pertes par exemple en un unique coût à minimiser.
- - Énoncer la règle de mise à jour de la descente de gradient et opposer ses variantes par lots et stochastique.
- - Définir la vraisemblance et l'objectif du maximum de vraisemblance, et le relier à la minimisation d'un coût.
- - Énoncer la mise à jour de Newton en une et plusieurs dimensions et la comparer à la descente de gradient.
+ - Opposer apprentissage supervisé et non supervisé par ce que chacun optimise.
+ - Définir une fonction de perte et agréger les pertes par exemple en un coût à minimiser.
+ - Ajuster une régression polynomiale et lire son degré comme un bouton de capacité.
+ - Distinguer performance d'entraînement et généralisation, et diagnostiquer sous-apprentissage et surapprentissage.
+ - Contrôler la capacité de façon continue avec une pénalité de régularisation.
+ - Sélectionner les hyperparamètres par validation et validation croisée sans contaminer l'ensemble de test.
+ - Énoncer la malédiction de la dimensionnalité et ses conséquences pour l'apprentissage.
- ## 2.1 Fonctions de perte et coût
+ ## 2.1 Apprentissage supervisé et non supervisé
- ### 2.1.1 Fonction de perte
+ L'[Introduction](/fr/Machine%20Learning/01%20Introduction) a nommé les paradigmes par leur signal de retour. Formellement, l'apprentissage supervisé part de paires étiquetées $\{(x^{(i)}, y^{(i)})\}_{i=1}^{m}$ et cherche dans une famille d'hypothèses le $h_\theta$ dont les prédictions collent le mieux aux cibles, la proximité étant mesurée par une fonction de perte. L'apprentissage non supervisé ne dispose que des entrées $x^{(i)}$, ses objectifs se construisent donc à partir des entrées seules : des groupes compacts, des directions informatives, des régions de forte densité.
+
+ Tout ce module est énoncé pour le cas supervisé, qui occupe le reste du cours. Les questions qu'il traite (ce modèle généralise-t-il bien, quelle complexité lui donner, comment départager des candidats) se posent à l'identique dans le cadre non supervisé.
+
+ ## 2.2 Minimiser une perte : la régression polynomiale
+
+ ### 2.2.1 Fonction de perte
Une fonction de perte $L(z, y)$ est définie comme une pénalité scalaire comparant un score brut $z$ du modèle (ou une probabilité prédite $\phi$) à la cible $y$. Plus elle est petite, mieux c'est. Chaque famille de modèles se caractérise par sa perte.
@@ 23,111 32,131 @@
*Remarque :* $z$ désigne un score brut tel que $\theta^T x$, tandis que $\phi \in (0,1)$ désigne une probabilité prédite. La ligne d'entropie croisée prend une probabilité $\phi$, non un score brut.
- ### 2.1.2 Fonction de coût
+ ![Fonctions de perte basées sur la marge](/fr/Machine%20Learning/02%20General%20concepts/a/loss-functions.png)
+
+ *Pertes basées sur la marge, chacune un substitut convexe de la perte 0-1 qui pénalise les marges faibles ou négatives.*
+
+ ### 2.2.2 Fonction de coût
Le coût $J(\theta)$ est défini comme la somme des pertes par exemple sur tout l'ensemble d'entraînement de $m$ exemples :
$$\boxed{\,J(\theta)=\sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right)\,}$$
- Entraîner un modèle, c'est choisir $\theta$ qui minimise $J(\theta)$. La leçon suivante montre comment.
+ Entraîner un modèle, c'est choisir $\theta$ qui minimise $J(\theta)$. Les algorithmes qui effectuent cette minimisation (formes fermées, descente de gradient) arrivent avec les modules de modèles. Ce module pose une autre question : que prouve réellement une petite valeur de $J(\theta)$ ?
*Remarque :* le facteur $\tfrac{1}{2}$ de l'erreur quadratique est une convention qui s'annule avec l'exposant lors de la dérivation, laissant un gradient propre.
- ![Fonctions de perte basées sur la marge](/fr/Machine%20Learning/02%20General%20concepts/a/loss-functions.png)
+ ### 2.2.3 L'exemple fil rouge : la régression polynomiale
- *Pertes basées sur la marge, chacune un substitut convexe de la perte 0-1 qui pénalise les marges faibles ou négatives.*
+ Pour rendre tout cela concret, prenons une entrée unique $x$ et ajustons un polynôme de degré $d$ sous la perte quadratique :
- ## 2.2 Descente de gradient
+ $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{d} \theta_j\, x^{j}, \qquad \phi(x) = (1, x, x^2, \dots, x^d) }$$
- ### 2.2.1 Règle de mise à jour
+ Le modèle reste linéaire en $\theta$, les moindres carrés s'appliquent donc tels quels (la forme fermée est dérivée dans [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression)). Le degré $d$ n'est pas ajusté avec $\theta$ : il est fixé avant l'ajustement et décide de la flexibilité permise à la courbe. Un tel bouton, choisi plutôt qu'appris, s'appelle un hyperparamètre, et $d$ est notre premier.
- La descente de gradient déplace itérativement les paramètres $\theta$ à l'opposé du gradient du coût, mis à l'échelle par un taux d'apprentissage $\alpha > 0$ :
+ ![Ajustements polynomiaux de degré 1, 3 et 9](/fr/Machine%20Learning/02%20General%20concepts/a/polynomial-fits.png)
- $$\boxed{\,\theta \leftarrow \theta - \alpha\,\nabla_\theta J(\theta)\,}$$
+ *Le même échantillon bruité ajusté de trois façons. Le degré 1 est trop rigide pour suivre la tendance, le degré 3 la capture, et le degré 9 se faufile par chaque point d'entraînement.*
- Le gradient pointe dans la direction de plus forte croissance, donc avancer à son opposé fait décroître $J$. Le pas $\alpha$ contrôle l'ampleur de chaque mise à jour.
+ ## 2.3 Performance d'entraînement et généralisation
- *Remarque :* si $\alpha$ est trop grand les itérés peuvent diverger, s'il est trop petit la convergence est lente.
+ ### 2.3.1 Erreur de généralisation
- ### 2.2.2 Par lots ou stochastique
+ La quantité qui nous intéresse est l'erreur de généralisation, la perte espérée sur un nouveau tirage de la même population :
- Les deux variantes diffèrent par le nombre d'exemples contribuant à une mise à jour.
+ $$\boxed{ R(h) = \mathbb{E}_{(x, y)}\left[ L\!\left(h(x), y\right) \right] }$$
- | Variante | Exemples par mise à jour | Mise à jour |
- | --- | --- | --- |
- | Par lots | Tous les $m$ | $\theta \leftarrow \theta - \alpha\,\nabla_\theta J(\theta)$ |
- | Stochastique (SGD) | Un seul $(x^{(i)}, y^{(i)})$ | $\theta \leftarrow \theta - \alpha\,\nabla_\theta L\!\left(h_\theta(x^{(i)}), y^{(i)}\right)$ |
+ On ne peut pas l'observer, il faut donc l'estimer. L'estimation tentante est l'erreur d'entraînement, la perte moyenne sur les données ayant servi à ajuster $h$. Elle est biaisée vers le bas : le modèle s'est déjà adapté à cet échantillon précis, il se juge donc trop favorablement.
- Le mode par lots donne une descente lisse mais lit tout l'ensemble à chaque pas. SGD met à jour après chaque exemple, donc peu coûteux par pas et bruité.
+ $$\boxed{ \hat{R}_{\text{train}}(h) = \frac{1}{m}\sum_{i=1}^{m} L\!\left(h(x^{(i)}), y^{(i)}\right) \;\le\; R(h) \ \text{(en espérance)} }$$
- ### 2.2.3 Mise à jour LMS (Widrow-Hoff)
+ ### 2.3.2 Sous-apprentissage et surapprentissage
- Pour l'erreur quadratique, la mise à jour stochastique par coordonnée est définie comme :
+ Revenons aux polynômes. L'ajustement de degré 1 sous-apprend : il n'a pas la capacité de représenter la tendance, il est donc mauvais sur les points d'entraînement comme sur les nouveaux. L'ajustement de degré 9 surapprend : il a de la capacité à revendre, pousse l'erreur d'entraînement à zéro en épousant le bruit, et le paie sur des données fraîches. Il a la plus petite erreur d'entraînement des trois ajustements et c'est aussi le pire modèle. Le bon modèle se situe entre les deux.
- $$\boxed{\,\theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)}\,}$$
+ ![Erreur d'entraînement et de validation quand la capacité croît](/fr/Machine%20Learning/02%20General%20concepts/a/train-vs-validation.png)
- La correction est proportionnelle au résidu $y^{(i)} - h_\theta(x^{(i)})$ multiplié par la composante $x_j^{(i)}$.
+ *Quand le degré croît, l'erreur d'entraînement décroît de façon monotone tandis que l'erreur de validation descend, atteint un creux, puis remonte. Le bon degré est au fond du U.*
- *Remarque :* un grand résidu produit un grand pas, une prédiction correcte ne produit aucune mise à jour.
+ C'est le compromis biais-variance. Un modèle rigide est biaisé : il se trompe systématiquement, quel que soit l'échantillon d'entraînement. Un modèle flexible a une forte variance : son ajustement change à chaque nouveau tirage du bruit. Augmenter la capacité échange du biais contre de la variance, et la généralisation est la meilleure là où les deux s'équilibrent.
- ![Trajectoire de la descente de gradient](/fr/Machine%20Learning/02%20General%20concepts/a/gradient-descent.png)
+ *Remarque :* l'erreur d'entraînement n'est pas une preuve de qualité. Passé le point d'équilibre, c'est une preuve de mémorisation, et seule la performance sur des données jamais vues fait la différence.
- *La descente de gradient descend la pente vers le minimum (étoile).*
+ ## 2.4 Régularisation
- ## 2.3 Vraisemblance et estimation du maximum de vraisemblance
+ Choisir le degré est un réglage grossier : la capacité saute d'entier en entier. Un contrôle plus fin garde une famille flexible mais rend la complexité coûteuse dans le coût lui-même, en ajoutant une pénalité $\Omega(\theta)$ mise à l'échelle par une intensité $\lambda \ge 0$ :
- ### 2.3.1 Vraisemblance
+ $$\boxed{\,J_\lambda(\theta)=\sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right) + \lambda\,\Omega(\theta)\,}$$
- La vraisemblance $L(\theta)$ est définie comme la probabilité des cibles observées sous le modèle, vue comme une fonction des paramètres $\theta$. En supposant les exemples indépendants, elle se factorise :
+ Le choix classique est la norme au carré $\Omega(\theta) = \lVert \theta \rVert_2^2$, la pénalité ridge. L'ajustement de degré 9 ne se faufile par chaque point qu'à l'aide de coefficients énormes qui se compensent entre les points d'entraînement. La pénalité rend ces coefficients coûteux, le minimiseur échange donc un peu d'erreur d'entraînement contre une courbe bien plus lisse. À $\lambda = 0$ le surapprentissage revient, quand $\lambda \to \infty$ la courbe s'aplatit vers le sous-apprentissage : $\lambda$ parcourt le même cadran biais-variance que le degré, mais continûment.
- $$\boxed{\,L(\theta)=\prod_{i=1}^{m} p\!\left(y^{(i)} \mid x^{(i)}; \theta\right)\,}$$
+ *Remarque :* la régularisation ne décide pas de la bonne complexité à votre place, elle convertit un choix discret ($d$) en un choix continu ($\lambda$) plus facile à régler. $\lambda$ est un hyperparamètre comme le degré, choisi par la machinerie de validation de la section suivante. D'où vient la pénalité (un a priori sur $\theta$, via le maximum a posteriori) et ce qu'apporte la variante L1 sont les sujets de [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation) et de la [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression).
- ### 2.3.2 Log-vraisemblance
+ ## 2.5 Hyperparamètres, validation et validation croisée
- Les produits sont malcommodes à optimiser, on prend donc le logarithme. La log-vraisemblance $\ell(\theta)$ est définie comme :
+ ### 2.5.1 Ensembles d'entraînement, de validation et de test
- $$\boxed{\,\ell(\theta)=\sum_{i=1}^{m} \log p\!\left(y^{(i)} \mid x^{(i)}; \theta\right)\,}$$
+ Les hyperparamètres ne peuvent pas être choisis sur l'erreur d'entraînement, qui ne récompense que davantage de capacité. La parade consiste à garder des données que le modèle n'a jamais vues pendant l'ajustement. La séparation standard a trois rôles disjoints :
- Le $\log$ est monotone, il a donc le même maximiseur que $L(\theta)$ tout en transformant le produit en somme.
+ | Ensemble | Sert à | Consulté |
+ | --- | --- | --- |
+ | Entraînement | ajuster les paramètres du modèle | à chaque ajustement |
+ | Validation | choisir le modèle et ses hyperparamètres | plusieurs fois |
+ | Test | fournir une estimation finale honnête | une seule fois |
- ### 2.3.3 Estimation du maximum de vraisemblance
+ *Remarque :* l'ensemble de test est sacré. Chaque fois qu'un choix est guidé par la performance de test, celui-ci devient discrètement partie de l'entraînement et son estimation devient optimiste.
- Le maximum de vraisemblance est défini comme la valeur des paramètres qui rend les données les plus probables :
+ ### 2.5.2 Validation croisée
- $$\boxed{\,\theta_{\mathrm{MLE}}=\arg\max_\theta\,\ell(\theta)\,}$$
+ Les jeux de données sont souvent petits, et une unique séparation entraînement/validation gaspille des données tout en donnant une estimation bruitée. La validation croisée à $K$ blocs réutilise les données : on partitionne en $K$ blocs, et pour chaque bloc on entraîne sur les $K-1$ autres et on valide sur le bloc mis de côté. L'erreur de validation croisée moyenne les $K$ tours :
- *Remarque :* maximiser la log-vraisemblance équivaut à minimiser le coût $J(\theta) = -\ell(\theta)$. C'est exactement la vue par minimisation du coût des leçons précédentes, vraisemblance et coût sont donc deux faces d'un même objectif.
+ $$\boxed{ \text{VC}_K = \frac{1}{K}\sum_{k=1}^{K} \frac{1}{|F_k|}\sum_{i \in F_k} L\!\left(h^{(-k)}(x^{(i)}), y^{(i)}\right) }$$
- ## 2.4 Algorithme de Newton
+ où $h^{(-k)}$ est entraîné sur tous les blocs sauf $F_k$. Prendre $K = m$ donne la validation croisée « un contre tous ». Les choix courants sont $K = 5$ ou $K = 10$, un compromis entre calcul et variance de l'estimation.
- ### 2.4.1 Mise à jour unidimensionnelle
+ ![Validation croisée à k blocs](/fr/Machine%20Learning/02%20General%20concepts/a/cross-validation.svg)
- Pour trouver un point stationnaire de la log-vraisemblance, l'algorithme de Newton suit l'approximation quadratique locale. La mise à jour scalaire est définie comme :
+ *Chaque tour met un bloc de côté pour la validation et entraîne sur le reste, et le score rapporté est la moyenne sur les blocs.*
- $$\boxed{\,\theta \leftarrow \theta - \frac{\ell'(\theta)}{\ell''(\theta)}\,}$$
+ ### 2.5.3 Sélection du modèle et des hyperparamètres
- Elle divise la dérivée première par la dérivée seconde, donc le pas s'adapte automatiquement à la courbure.
+ La validation croisée est notre outil de réglage. On ajuste chaque candidat (une famille de modèles, une profondeur d'arbre, le degré polynomial $d$, ou la pénalité $\lambda$) et on garde celui dont l'erreur de validation est la plus faible. Ce n'est qu'ensuite, une fois le choix figé, que l'on consulte l'ensemble de test pour rapporter un chiffre final.
- ### 2.4.2 Mise à jour multivariée
+ *Remarque :* choisir le gagnant sur l'ensemble de test gonfle l'estimation. Avec assez de candidats, l'un paraîtra bon par pur hasard, c'est la malédiction du vainqueur, donc sélection et évaluation finale doivent utiliser des données différentes.
- Avec un vecteur de paramètres $\theta \in \mathbb{R}^{n+1}$, la dérivée seconde devient la matrice hessienne $H$, avec $H_{jk}=\dfrac{\partial^2 \ell}{\partial\theta_j\,\partial\theta_k}$. La mise à jour est définie comme :
+ ## 2.6 Pièges courants de la validation
- $$\boxed{\,\theta \leftarrow \theta - H^{-1}\,\nabla_\theta \ell(\theta)\,}$$
+ Une validation honnête est plus difficile qu'il n'y paraît, et les données réelles brisent souvent les hypothèses habituelles de trois façons.
- *Remarque :* chaque pas résout un système linéaire en $H$, une opération en $O(n^3)$, donc l'algorithme de Newton est coûteux quand le nombre de variables $n$ est grand.
+ - **Fuite de données.** De l'information sur la cible se glisse dans les variables. Standardiser avec des statistiques calculées sur tout l'échantillon, ou inclure une variable réalisée après le résultat, laisse le modèle entrevoir la réponse. Tout prétraitement doit être ajusté sur les seuls blocs d'entraînement.
+ - **Biais d'anticipation.** Utiliser une information qui n'était pas encore disponible au moment de la prédiction, ce qui survient dès que les données sont ordonnées dans le temps, produit des backtests irreproductibles en conditions réelles.
+ - **Dépendance.** De nombreux jeux de données sont autocorrélés (séries temporelles) ou groupés (plusieurs observations partageant une même unité). Les mélanger en blocs aléatoires met des voisins quasi identiques de part et d'autre, et l'estimation devient bien trop optimiste.
- ### 2.4.3 Newton ou descente de gradient
+ Pour les séries temporelles, on utilise un schéma à origine glissante (par blocs) de sorte que le modèle ne soit testé que sur des données postérieures à sa fenêtre d'entraînement. Pour les données groupées, on met de côté des unités entières (validation croisée groupée) afin qu'aucune unité n'apparaisse des deux côtés.
- | Propriété | Algorithme de Newton | Descente de gradient |
- | --- | --- | --- |
- | Ordre | Second (utilise la courbure $H$) | Premier (utilise le gradient seul) |
- | Coût par pas | Élevé ($O(n^3)$, inverse $H$) | Faible ($O(n)$ par exemple) |
- | Convergence | Quadratique près de l'optimum, peu de pas | Linéaire, beaucoup de pas |
- | Réglage | Aucun taux d'apprentissage | Nécessite un taux $\alpha$ |
+ ![Validation croisée temporelle](/fr/Machine%20Learning/02%20General%20concepts/a/time-series-cv.svg)
+
+ *Dans un schéma à origine glissante, la fenêtre d'entraînement s'étend dans le temps et le modèle est validé sur le bloc suivant, jamais sur des données mélangées.*
+
+ *Remarque :* la question honnête derrière toute séparation est toujours la même. Cela aurait-il été connaissable à l'époque, à partir des données dont le modèle disposait réellement ?
+
+ ## 2.7 La malédiction de la dimensionnalité
+
+ Tout ce qui précède suppose que l'échantillon représente la population au voisinage des points qui comptent. En grande dimension, cette hypothèse se dégrade, et vite. Supposons que les entrées remplissent l'hypercube unité $[0,1]^d$ et que l'on veuille un voisinage autour d'un point qui capture une fraction $r$ des données. Un sous-cube contenant une fraction $r$ du volume doit avoir une arête de longueur :
+
+ $$\boxed{ e_d(r) = r^{1/d} }$$
+
+ En dimension un, capturer 1 % du volume demande 1 % de l'axe. En dimension $d = 10$ il faut $0{,}01^{1/10} \approx 0{,}63$, soit 63 % de l'étendue de chaque variable, et en dimension $d = 100$, 95 %. Un voisinage qui voit une part raisonnable des données cesse d'être local, et les méthodes qui s'appuient sur les exemples proches perdent pied. Remplir l'espace directement est tout aussi désespéré : couvrir chaque axe avec seulement 10 cases produit déjà $10^d$ cellules, la taille d'échantillon nécessaire pour les peupler croît donc exponentiellement avec $d$.
+
+ ![La malédiction de la dimensionnalité](/fr/Machine%20Learning/02%20General%20concepts/a/curse-dimensionality.png)
+
+ *L'arête nécessaire pour capturer une fraction fixe du volume file vers 1 quand la dimension croît : en grande dimension, un voisinage « local » couvre l'essentiel de chaque axe.*
+
+ Deux autres symptômes découlent de la même géométrie. La quasi-totalité du volume d'un cube en grande dimension se trouve près de son bord, un point typique n'a donc aucun intérieur autour de lui. Et les distances se concentrent : le voisin le plus proche et le plus lointain finissent presque à égale distance, la distance elle-même devient donc peu informative.
- *Remarque :* l'algorithme de Newton converge en très peu d'itérations mais paie un coût élevé par pas, donc la descente de gradient est préférée quand $n$ est grand.
+ *Remarque :* c'est pourquoi l'apprentissage en grande dimension s'appuie sur de la structure plutôt que sur la proximité brute : modèles linéaires, régularisation tirant vers des ajustements simples, et variables ou plongements qui compressent les entrées. Les données réelles se concentrent en général près d'une structure de dimension bien plus faible, et c'est ce qui rend l'apprentissage possible.
- *Ces outils sont indépendants du modèle. La partie suivante les applique à la classe d'hypothèses la plus simple, où la prédiction est une fonction linéaire des variables : les modèles linéaires.*
+ *Les concepts sont en place : ajuster minimise une perte, généraliser est le but, la validation le mesure, et la régularisation avec le réglage des hyperparamètres le contrôle. Le module suivant construit le langage probabiliste (règle de Bayes, entropie, vraisemblance) derrière les premiers modèles concrets.*
---
- Suivant : [Évaluation et validation des modèles](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
+ Suivant : [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/03 Model evaluation and validation/cross-validation.svg .. fr/Machine Learning/02 General concepts/cross-validation.svg
/dev/null .. fr/Machine Learning/02 General concepts/curse-dimensionality.png
fr/Machine Learning/02 General concepts/gradient-descent.png .. /dev/null
/dev/null .. fr/Machine Learning/02 General concepts/polynomial-fits.png
fr/Machine Learning/03 Model evaluation and validation/time-series-cv.svg .. fr/Machine Learning/02 General concepts/time-series-cv.svg
/dev/null .. fr/Machine Learning/02 General concepts/train-vs-validation.png
fr/Machine Learning/03 Model evaluation and validation.md .. /dev/null
@@ 1,73 0,0 @@
- # 3. Évaluation et validation des modèles
-
- On peut toujours faire coller un modèle aux données sur lesquelles il a été entraîné. Ce qui compte, c'est sa performance sur des données jamais vues. Ce module fait de l'évaluation une compétence à part entière : comment estimer honnêtement l'erreur hors échantillon, comment s'en servir pour choisir un modèle, et les pièges qui rendent facile de se tromper soi-même, surtout avec des jeux de données petits ou dépendants.
-
- **Objectifs**
- - Distinguer l'erreur en échantillon de l'erreur hors échantillon et voir pourquoi l'erreur d'entraînement est optimiste.
- - Séparer les données en ensembles d'entraînement, de validation et de test, et connaître le rôle de chacun.
- - Estimer l'erreur de généralisation par validation croisée à k blocs.
- - Utiliser la validation pour choisir modèles et hyperparamètres sans contaminer l'ensemble de test.
- - Éviter les fuites de données et le biais d'anticipation, et valider des données dépendantes par des schémas temporels ou groupés.
-
- ## 3.1 Erreur en échantillon et hors échantillon
-
- La quantité qui nous intéresse est l'erreur de généralisation, la perte espérée sur un nouveau tirage de la même population :
-
- $$\boxed{ R(h) = \mathbb{E}_{(x, y)}\left[ L\!\left(h(x), y\right) \right] }$$
-
- On ne peut pas l'observer, il faut donc l'estimer. L'estimation tentante est l'erreur d'entraînement, la perte moyenne sur les données ayant servi à ajuster $h$. Elle est biaisée vers le bas : le modèle s'est déjà adapté à cet échantillon précis, il se juge donc trop favorablement.
-
- $$\boxed{ \hat{R}_{\text{train}}(h) = \frac{1}{m}\sum_{i=1}^{m} L\!\left(h(x^{(i)}), y^{(i)}\right) \;\le\; R(h) \ \text{(en espérance)} }$$
-
- *Remarque :* un modèle flexible poussé vers une erreur d'entraînement quasi nulle a en général mémorisé le bruit. C'est le surapprentissage, l'extrémité à forte variance du compromis biais-variance introduit dans [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts).
-
- ## 3.2 Ensembles d'entraînement, de validation et de test
-
- La parade consiste à garder des données que le modèle n'a jamais vues pendant l'ajustement. La séparation standard a trois rôles disjoints :
-
- | Ensemble | Sert à | Consulté |
- | --- | --- | --- |
- | Entraînement | ajuster les paramètres du modèle | à chaque ajustement |
- | Validation | choisir le modèle et ses hyperparamètres | plusieurs fois |
- | Test | fournir une estimation finale honnête | une seule fois |
-
- *Remarque :* l'ensemble de test est sacré. Chaque fois qu'un choix est guidé par la performance de test, celui-ci devient discrètement partie de l'entraînement et son estimation devient optimiste.
-
- ## 3.3 Validation croisée
-
- Les jeux de données sont souvent petits, et une unique séparation entraînement/validation gaspille des données tout en donnant une estimation bruitée. La validation croisée à $K$ blocs réutilise les données : on partitionne en $K$ blocs, et pour chaque bloc on entraîne sur les $K-1$ autres et on valide sur le bloc mis de côté. L'erreur de validation croisée moyenne les $K$ tours :
-
- $$\boxed{ \text{VC}_K = \frac{1}{K}\sum_{k=1}^{K} \frac{1}{|F_k|}\sum_{i \in F_k} L\!\left(h^{(-k)}(x^{(i)}), y^{(i)}\right) }$$
-
- où $h^{(-k)}$ est entraîné sur tous les blocs sauf $F_k$. Prendre $K = m$ donne la validation croisée « un contre tous ». Les choix courants sont $K = 5$ ou $K = 10$, un compromis entre calcul et variance de l'estimation.
-
- ![Validation croisée à k blocs](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation/a/cross-validation.svg)
-
- *Chaque tour met un bloc de côté pour la validation et entraîne sur le reste, et le score rapporté est la moyenne sur les blocs.*
-
- ## 3.4 Sélection du modèle et des hyperparamètres
-
- La validation croisée est notre outil de réglage. On ajuste chaque candidat (une famille de modèles, une profondeur d'arbre, ou la pénalité $\lambda$ du module suivant) et on garde celui dont l'erreur de validation est la plus faible. Ce n'est qu'ensuite, une fois le choix figé, que l'on consulte l'ensemble de test pour rapporter un chiffre final.
-
- *Remarque :* choisir le gagnant sur l'ensemble de test gonfle l'estimation. Avec assez de candidats, l'un paraîtra bon par pur hasard, c'est la malédiction du vainqueur, donc sélection et évaluation finale doivent utiliser des données différentes.
-
- ## 3.5 Pièges courants de la validation
-
- Une validation honnête est plus difficile qu'il n'y paraît, et les données réelles brisent souvent les hypothèses habituelles de trois façons.
-
- - **Fuite de données.** De l'information sur la cible se glisse dans les variables. Standardiser avec des statistiques calculées sur tout l'échantillon, ou inclure une variable réalisée après le résultat, laisse le modèle entrevoir la réponse. Tout prétraitement doit être ajusté sur les seuls blocs d'entraînement.
- - **Biais d'anticipation.** Utiliser une information qui n'était pas encore disponible au moment de la prédiction, ce qui survient dès que les données sont ordonnées dans le temps, produit des backtests irreproductibles en conditions réelles.
- - **Dépendance.** De nombreux jeux de données sont autocorrélés (séries temporelles) ou groupés (plusieurs observations partageant une même unité). Les mélanger en blocs aléatoires met des voisins quasi identiques de part et d'autre, et l'estimation devient bien trop optimiste.
-
- Pour les séries temporelles, on utilise un schéma à origine glissante (par blocs) de sorte que le modèle ne soit testé que sur des données postérieures à sa fenêtre d'entraînement. Pour les données groupées, on met de côté des unités entières (validation croisée groupée) afin qu'aucune unité n'apparaisse des deux côtés.
-
- ![Validation croisée temporelle](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation/a/time-series-cv.svg)
-
- *Dans un schéma à origine glissante, la fenêtre d'entraînement s'étend dans le temps et le modèle est validé sur le bloc suivant, jamais sur des données mélangées.*
-
- *Remarque :* la question honnête derrière toute séparation est toujours la même. Cela aurait-il été connaissable à l'époque, à partir des données dont le modèle disposait réellement ?
-
- *Une fois la généralisation mesurable, le module suivant ajuste nos premiers modèles, et celui d'après contrôle leur complexité par la régularisation, réglée précisément avec cette validation croisée.*
-
- ---
- Suivant : [Formulation probabiliste](/fr/Machine%20Learning/04%20Probabilistic%20formulation) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/04 Probabilistic formulation.md .. fr/Machine Learning/03 Probabilistic formulation.md
@@ 1,4 1,4 @@
- # 4. Formulation probabiliste
+ # 3. Formulation probabiliste
La probabilité est le langage que le machine learning utilise pour traiter l'incertitude. Ce module énonce les règles pour les variables discrètes et continues, jette un premier regard sur la théorie de l'information, montre la manière bayésienne de transformer des probabilités en décisions, et définit les deux principes d'estimation auxquels le cours revient sans cesse : le maximum de vraisemblance et le maximum a posteriori.
@@ 9,7 9,7 @@
- Prendre la décision qui minimise la perte espérée, et retrouver le classifieur du maximum a posteriori.
- Définir les estimateurs du maximum de vraisemblance et du maximum a posteriori.
- ## 4.1 Probabilité, discrète et continue
+ ## 3.1 Probabilité, discrète et continue
Une variable aléatoire prend des valeurs avec des probabilités qui sont positives et qui somment ou s'intègrent à un. Une variable discrète a une fonction de masse, une variable continue une densité de probabilité :
@@ 17,7 17,7 @@
Pour une variable continue, la probabilité s'attache à des intervalles au moyen d'une intégrale, $P(a \le X \le b) = \int_a^b p(x)\, dx$, et non à des points isolés.
- ## 4.2 Conjointe, conditionnelle et Bayes
+ ## 3.2 Conjointe, conditionnelle et Bayes
Deux variables ont une distribution conjointe $p(x, y)$. Sommer (ou intégrer) une variable donne la marginale, la règle de la somme, et la conjointe se factorise en une conditionnelle fois une marginale, la règle du produit :
@@ 29,13 29,13 @@
Deux variables sont indépendantes quand la conjointe est le produit des marginales, $p(x, y) = p(x)\, p(y)$.
- ## 4.3 Un peu de théorie de l'information
+ ## 3.3 Un peu de théorie de l'information
L'entropie d'une distribution mesure son incertitude, le nombre moyen de bits nécessaires pour décrire une issue :
$$\boxed{ H(X) = -\sum_x p(x)\log p(x) }$$
- ![Entropie binaire](/fr/Machine%20Learning/04%20Probabilistic%20formulation/a/entropy.png)
+ ![Entropie binaire](/fr/Machine%20Learning/03%20Probabilistic%20formulation/a/entropy.png)
*Pour une variable à deux issues, l'entropie est maximale en $p = 0.5$, là où l'issue est la plus difficile à prévoir, et nulle quand une issue est certaine.*
@@ 45,31 45,37 @@
*Remarque :* minimiser l'entropie croisée entre les vraies étiquettes et les prédictions d'un modèle revient à maximiser la vraisemblance de ces étiquettes. C'est pourquoi les réseaux de classification minimisent l'entropie croisée, un fil repris dans les modules suivants.
- ## 4.4 Théorie de la décision bayésienne
+ ## 3.4 Théorie de la décision bayésienne
Pour classer une entrée $x$, la règle bayésienne utilise l'a posteriori sur les classes. Sous la perte 0-1, la décision qui minimise la perte espérée est simplement la classe la plus probable, et comme l'a posteriori est proportionnel à la densité conditionnelle de classe fois l'a priori, on peut la calculer des deux façons :
$$\boxed{ \hat{y} = \arg\max_y \; p(y \mid x) = \arg\max_y \; p(x \mid y)\, p(y) }$$
- ![Décision bayésienne entre deux classes](/fr/Machine%20Learning/04%20Probabilistic%20formulation/a/bayes-decision.png)
+ ![Décision bayésienne entre deux classes](/fr/Machine%20Learning/03%20Probabilistic%20formulation/a/bayes-decision.png)
*Chaque classe apporte sa densité mise à l'échelle par son a priori, et la frontière de décision tombe là où les deux sont égales. De chaque côté, la classe au plus grand a posteriori l'emporte.*
*Remarque :* c'est le classifieur optimal, appelé classifieur de Bayes. Chaque méthode plus loin dans le cours est, en pratique, une tentative d'approcher ces a posteriori à partir des données.
- ## 4.5 Maximum de vraisemblance et maximum a posteriori
+ ## 3.5 Maximum de vraisemblance et maximum a posteriori
On connaît rarement la vraie distribution, on estime donc ses paramètres $\theta$ à partir des données. Le maximum de vraisemblance choisit le $\theta$ qui rend les données observées les plus probables, maximisé en général comme une somme de log-vraisemblances sur les $m$ exemples :
$$\boxed{ \theta_{\mathrm{MV}} = \arg\max_\theta \sum_{i=1}^{m} \log p(x^{(i)} \mid \theta) }$$
+ En apprentissage supervisé le modèle paramètre la conditionnelle $p(y \mid x; \theta)$, le même principe s'applique donc à la vraisemblance conditionnelle des cibles :
+
+ $$\boxed{ \ell(\theta) = \sum_{i=1}^{m} \log p\!\left(y^{(i)} \mid x^{(i)}; \theta\right) }$$
+
+ Maximiser $\ell$ revient à minimiser le coût $J(\theta) = -\ell(\theta)$ : la vue par la vraisemblance et la vue par minimisation du coût de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts) sont deux faces d'un même objectif.
+
Le maximum a posteriori maximise plutôt l'a posteriori, qui multiplie la vraisemblance par un a priori sur $\theta$ :
$$\boxed{ \theta_{\mathrm{MAP}} = \arg\max_\theta \; p(D \mid \theta)\, p(\theta) }$$
- *Remarque :* le maximum a posteriori est le maximum de vraisemblance augmenté d'un a priori. Un a priori gaussien sur $\theta$ devient une pénalité L2 et un a priori de Laplace une pénalité L1, ce qui est exactement la régularisation d'un module ultérieur. Avec beaucoup de données l'a priori s'efface et les deux estimateurs coïncident.
+ *Remarque :* le maximum a posteriori est le maximum de vraisemblance augmenté d'un a priori. Un a priori gaussien sur $\theta$ devient une pénalité L2 et un a priori de Laplace une pénalité L1, ce qui est exactement la régularisation du module suivant. Avec beaucoup de données l'a priori s'efface et les deux estimateurs coïncident.
- *Le module suivant transforme ces principes en fonctions de perte concrètes et en la descente de gradient qui les minimise.*
+ *Le module suivant transforme ces principes en un premier modèle concret : la régression linéaire, où maximum de vraisemblance et maximum a posteriori aboutissent tous deux à des ajustements en forme close.*
---
- Suivant : [Régression linéaire](/fr/Machine%20Learning/05%20Linear%20regression) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
+ Suivant : [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/04 Probabilistic formulation/bayes-decision.png .. fr/Machine Learning/03 Probabilistic formulation/bayes-decision.png
fr/Machine Learning/04 Probabilistic formulation/entropy.png .. fr/Machine Learning/03 Probabilistic formulation/entropy.png
/dev/null .. fr/Machine Learning/04 Linear regression.md
@@ 0,0 1,138 @@
+ # 4. Régression linéaire
+
+ La régression linéaire prédit une cible continue à partir d'un score linéaire. Ce module suit un seul fil de bout en bout : poser le modèle, l'ajuster à des données bruitées par moindres carrés, justifier cet objectif par le maximum de vraisemblance, le régulariser par le maximum a posteriori (ridge, puis son cousin sélectif le lasso), puis élargir le modèle avec les fonctions de base et les prédictions multiples, où les deux mêmes formes closes reviennent inchangées.
+
+ **Objectifs**
+ - Écrire le modèle linéaire et lire sa prédiction comme une droite, un plan ou un hyperplan.
+ - Poser le problème d'ajustement sur données bruitées et énoncer l'objectif des moindres carrés.
+ - Montrer que le maximum de vraisemblance sous bruit gaussien est exactement les moindres carrés, et dériver l'équation normale.
+ - Dériver la régression ridge (weight decay) du maximum a posteriori, en forme close.
+ - Opposer les pénalités ridge et lasso : rétrécir ou sélectionner.
+ - Généraliser le modèle avec des fonctions de base et aux sorties multiples, en gardant les mêmes formes closes.
+
+ ## 4.1 Le modèle linéaire
+
+ L'hypothèse est linéaire en l'entrée augmentée $x \in \mathbb{R}^{n+1}$ avec $x_0 = 1$, la convention de l'[Introduction](/fr/Machine%20Learning/01%20Introduction) :
+
+ $$\boxed{ h_\theta(x) = \theta^T x = \theta_0 + \theta_1 x_1 + \dots + \theta_n x_n }$$
+
+ $\theta_0$ est le biais (l'ordonnée à l'origine) et les autres coordonnées sont les poids, et replier le biais dans le produit scalaire est exactement ce que la convention $x_0 = 1$ apporte. Géométriquement, la prédiction est une droite pour $n = 1$, un plan pour $n = 2$, un hyperplan au-delà.
+
+ ![La prédiction est une droite, puis un plan](/fr/Machine%20Learning/04%20Linear%20regression/a/line-and-plane.png)
+
+ *Avec une caractéristique le modèle trace une droite à travers les données, avec deux un plan, et au-delà un hyperplan que l'on ne peut plus dessiner.*
+
+ ## 4.2 Le problème à résoudre
+
+ Étant donné l'ensemble d'entraînement $\{(x^{(i)}, y^{(i)})\}_{i=1}^{m}$, on voudrait idéalement $h_\theta(x^{(i)}) = y^{(i)}$ en chaque point. Les cibles réelles sont bruitées (erreurs de mesure, facteurs non modélisés), aucune droite ne passe donc par toutes, et le but devient de commettre la plus petite erreur totale. Les moindres carrés prennent le résidu au carré comme erreur et le somment sur l'ensemble d'entraînement :
+
+ $$\boxed{ \theta^{*} = \arg\min_\theta \; \sum_{i=1}^{m}\left(\theta^T x^{(i)} - y^{(i)}\right)^2 }$$
+
+ ![Cibles idéales et cibles bruitées](/fr/Machine%20Learning/04%20Linear%20regression/a/ideal-vs-noisy.png)
+
+ *À gauche : si les cibles étaient sans bruit, le modèle pourrait passer par chaque point. À droite : les cibles réelles se dispersent autour de la tendance, chaque point laisse donc un résidu entre $y^{(i)}$ et la prédiction $h_\theta(x^{(i)})$, et l'ajustement minimise leur somme des carrés (segments gris).*
+
+ *Remarque :* pourquoi le carré plutôt que, disons, la valeur absolue ? Parce que ce choix est prouvé optimal quand le bruit est gaussien, une question d'entrevue classique que la section suivante décortique.
+
+ ## 4.3 Maximum de vraisemblance : les moindres carrés justifiés
+
+ Donnons aux données une histoire générative, avec le principe d'estimation de la [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation) : chaque cible est la prédiction linéaire plus un bruit gaussien indépendant,
+
+ $$\boxed{ y^{(i)} = \theta^T x^{(i)} + \varepsilon^{(i)}, \quad \varepsilon^{(i)} \sim \mathcal{N}(0, \sigma^2) }$$
+
+ donc $p(y^{(i)} \mid x^{(i)}; \theta) = \mathcal{N}(\theta^T x^{(i)}, \sigma^2)$. La log-vraisemblance des $m$ exemples i.i.d. se sépare en une constante et la somme des carrés :
+
+ $$\ell(\theta) = \sum_{i=1}^{m} \log \mathcal{N}\!\left(y^{(i)} \mid \theta^T x^{(i)}, \sigma^2\right) = -\frac{m}{2}\log(2\pi\sigma^2) \;-\; \frac{1}{2\sigma^2}\sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2$$
+
+ Ni la constante ni le facteur positif $\tfrac{1}{2\sigma^2}$ ne déplacent l'argmax, donc :
+
+ $$\boxed{ \arg\max_\theta \; \ell(\theta) = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 }$$
+
+ *Remarque :* cette équivalence est le fait le plus important du module. Les moindres carrés ne sont pas une convention commode, ils sont l'estimation du maximum de vraisemblance sous bruit gaussien.
+
+ Le maximiseur a une forme close. En écrivant l'objectif avec la matrice de conception $X$ et en annulant le gradient,
+
+ $$\nabla_\theta\, \lVert X\theta - y \rVert^2 = 2\,X^T(X\theta - y) = 0$$
+
+ $$\boxed{ \theta_{\mathrm{MV}} = (X^T X)^{-1}X^T y }$$
+
+ l'équation normale, une résolution matricielle entre les données et le modèle.
+
+ ## 4.4 Maximum a posteriori : la régression ridge
+
+ Le maximum de vraisemblance peut surapprendre, surtout quand le modèle est flexible. L'estimation du maximum a posteriori maximise plutôt l'a posteriori, qui par la règle de Bayes est la vraisemblance multipliée par un a priori sur les paramètres, ici une gaussienne centrée :
+
+ $$\theta_{\mathrm{MAP}} = \arg\max_\theta \; p(y \mid X, \theta)\, p(\theta), \qquad \theta \sim \mathcal{N}(0, \tau^2 I)$$
+
+ Prendre le logarithme ajoute $-\lVert \theta \rVert^2 / 2\tau^2$ à la log-vraisemblance, et éliminer les constantes laisse des moindres carrés pénalisés :
+
+ $$\boxed{ \theta_{\mathrm{MAP}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_2^2, \quad \lambda = \frac{\sigma^2}{\tau^2} }$$
+
+ avec, par le même calcul de gradient nul, la forme close :
+
+ $$\boxed{ \theta_{\mathrm{MAP}} = (X^T X + \lambda I)^{-1}X^T y }$$
+
+ C'est la régression ridge, et la pénalité est souvent appelée weight decay. L'a priori gaussien est devenu la pénalité L2 de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts), exactement le lien a priori vers pénalité de la [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation).
+
+ *Remarque :* $\lambda \to 0$ retrouve le maximum de vraisemblance, et un $\lambda$ croissant rétrécit $\theta$ vers zéro et combat le surapprentissage. Un a priori plus fort (petit $\tau$) signifie un $\lambda$ plus grand. Notons aussi que $X^T X + \lambda I$ est toujours inversible pour $\lambda > 0$, ce qui sauve les moindres carrés exactement là où ils s'effondrent : des caractéristiques fortement corrélées, ou plus de caractéristiques que d'exemples.
+
+ ## 4.5 Le lasso : une pénalité qui sélectionne
+
+ La pénalité ridge venait d'un a priori gaussien. Un a priori de Laplace donne plutôt la pénalité L1, le lien noté dans la [Formulation probabiliste](/fr/Machine%20Learning/03%20Probabilistic%20formulation) :
+
+ $$\boxed{ \theta_{\mathrm{lasso}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_1 }$$
+
+ Le changement paraît minime et sa conséquence est grande : le lasso met certains coefficients exactement à zéro, il sélectionne donc les variables tout en ajustant. Contrairement au ridge il n'a pas de forme close (la pénalité n'est pas dérivable en zéro), il s'ajuste donc par des solveurs convexes. La raison de la sélection est géométrique. La région de contrainte $\lVert \theta \rVert_1 \le t$ est un losange dont les coins sont sur les axes, et les contours elliptiques de l'erreur quadratique tendent à la toucher d'abord en un coin, où une coordonnée est nulle. La boule L2 arrondie n'a pas de coins, le ridge rétrécit donc chaque coefficient doucement sans jamais en annuler un : le ridge stabilise, le lasso sélectionne.
+
+ ![Géométrie des contraintes L1 et L2](/fr/Machine%20Learning/04%20Linear%20regression/a/l1-l2-geometry.png)
+
+ *La boule L2 arrondie est touchée hors des axes, gardant chaque coefficient non nul, tandis que le losange L1 est touché en un coin, mettant un coefficient exactement à zéro.*
+
+ À mesure que $\lambda$ grandit, davantage de coefficients passent à zéro, traçant le chemin de régularisation du modèle complet jusqu'au modèle vide.
+
+ ![Chemin de régularisation du lasso](/fr/Machine%20Learning/04%20Linear%20regression/a/regularization-path.png)
+
+ *Chaque coefficient rétrécit quand $\lambda$ augmente puis atteint exactement zéro, si bien que le lasso fournit un sous-ensemble compact et interprétable de régresseurs.*
+
+ *Remarque :* l'elastic net mêle les deux pénalités, $\lambda\left(\alpha \lVert \theta \rVert_1 + (1-\alpha)\lVert \theta \rVert_2^2\right)$, gardant la sélection du lasso avec la stabilité du ridge face aux caractéristiques corrélées. Comme toujours, $\lambda$ se choisit par la validation croisée de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts), en prenant souvent le plus grand $\lambda$ à un écart-type du meilleur pour un modèle plus simple.
+
+ *Remarque :* prédire n'est pas inférer. Sélectionner des variables par lasso puis rapporter les écarts-types des manuels sur les mêmes données est invalide, la malédiction du vainqueur encore : les intervalles ignorent que les données ont déjà choisi les variables. Une inférence honnête demande une division de l'échantillon ou un estimateur débiaisé, la porte d'entrée du machine learning causal.
+
+ ## 4.6 Fonctions de base : non linéaire en $x$, linéaire en $\theta$
+
+ Une droite est souvent trop rigide : le sous-apprentissage de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts) apparaissait précisément quand un modèle à faible capacité rencontrait une tendance courbe. La solution n'est pas d'abandonner la machinerie linéaire mais de projeter l'entrée dans un espace plus grand, là où la relation est linéaire :
+
+ $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{M-1} \theta_j\, \phi_j(x), \qquad \phi_0(x) = 1 }$$
+
+ Les $\phi_j$ sont des fonctions de base, fixées avant l'entraînement. Avec $\phi(x) = (1, x, x^2, \dots, x^d)$ elles donnent la régression polynomiale, l'exemple fil rouge de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts), et l'identité $\phi(x) = x$ retrouve tout ce qui précède. Le modèle peut désormais être follement non linéaire en $x$ tout en restant linéaire en $\theta$, rien ne change donc dans l'ajustement : on empile les $\phi(x^{(i)})^T$ comme lignes de la matrice de conception $\Phi \in \mathbb{R}^{m \times M}$ et les deux formes closes reviennent telles quelles :
+
+ $$\boxed{ \theta_{\mathrm{MV}} = (\Phi^T \Phi)^{-1}\Phi^T y, \qquad \theta_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T y }$$
+
+ *Remarque :* la base (sa famille et sa taille $M$) est un hyperparamètre, choisi avant l'entraînement, tandis que $\theta$ est appris. Choisir $M$ et $\lambda$ est le problème de sélection de modèle réglé par la validation croisée de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts).
+
+ ## 4.7 Prédictions multiples
+
+ Rien ne restreint la cible à un seul nombre. Pour prédire $K$ valeurs à la fois (disons le prix d'une maison, son coût de chauffage et ses taxes à partir des mêmes caractéristiques), on prend $y^{(i)} \in \mathbb{R}^K$ et on donne à chaque sortie sa propre colonne de paramètres, rassemblées dans une matrice $W \in \mathbb{R}^{M \times K}$ :
+
+ $$\boxed{ h_W(x) = W^T \phi(x) \in \mathbb{R}^{K} }$$
+
+ En empilant les cibles comme lignes de $Y \in \mathbb{R}^{m \times K}$, les mêmes dérivations donnent les mêmes formes closes, qui résolvent les $K$ régressions d'un coup :
+
+ $$\boxed{ W_{\mathrm{MV}} = (\Phi^T \Phi)^{-1}\Phi^T Y, \qquad W_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T Y }$$
+
+ *Remarque :* le facteur coûteux $(\Phi^T \Phi)^{-1}$ ne dépend pas des cibles, il se calcule donc une seule fois et se partage entre les $K$ sorties.
+
+ ## 4.8 Résumé
+
+ | | Formule |
+ | --- | --- |
+ | Modèle | $h_\theta(x) = \theta^T \phi(x)$ |
+ | Maximum de vraisemblance (moindres carrés) | $\theta_{\mathrm{MV}} = (\Phi^T \Phi)^{-1}\Phi^T y$ |
+ | Maximum a posteriori (ridge) | $\theta_{\mathrm{MAP}} = (\Phi^T \Phi + \lambda I)^{-1}\Phi^T y$ |
+ | Paramètres, appris | $\theta$ (ou $W$ pour $K$ sorties) |
+ | Hyperparamètres, choisis par validation | la base $\phi$ et sa taille $M$, la pénalité $\lambda$ |
+
+ *Le même score linéaire, passé dans une fonction de compression au lieu d'être lu directement, transforme la régression en classification, le sujet du module suivant.*
+
+ ---
+ Suivant : [Classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
/dev/null .. fr/Machine Learning/04 Linear regression/ideal-vs-noisy.png
fr/Machine Learning/07 Regularization and high-dimensional inference/l1-l2-geometry.png .. fr/Machine Learning/04 Linear regression/l1-l2-geometry.png
/dev/null .. fr/Machine Learning/04 Linear regression/line-and-plane.png
fr/Machine Learning/07 Regularization and high-dimensional inference/regularization-path.png .. fr/Machine Learning/04 Linear regression/regularization-path.png
/dev/null .. fr/Machine Learning/05 Linear classification.md
@@ 0,0 1,187 @@
+ # 5. Classification linéaire
+
+ La classification prédit une étiquette discrète à partir du même score linéaire $\theta^T x$. Ce module passe en revue les classifieurs linéaires classiques comme un seul menu : les moindres carrés, qui supposent des classes de forme gaussienne et admettent une forme close, et le perceptron et la régression logistique, qui ne supposent rien sur la distribution et s'ajustent par descente de gradient. La régularisation ferme le module.
+
+ **Objectifs**
+ - Lire un classifieur linéaire comme un hyperplan séparateur dont le score donne le côté, rendant la prédiction aussi rapide qu'un produit scalaire.
+ - Situer les méthodes classiques selon leur hypothèse (gaussienne ou aucune) et leur ajustement (forme close ou descente de gradient).
+ - Classer par moindres carrés, en binaire et en multiclasse, et voir où cela casse.
+ - Entraîner le perceptron à partir de son critère, et connaître sa garantie de convergence et ses limites.
+ - Distinguer la descente de gradient par lots de la stochastique, et savoir que des optimiseurs plus élaborés existent.
+ - Ajuster la régression logistique par descente de gradient sur l'entropie croisée, en binaire et en multiclasse.
+ - Régulariser n'importe lequel de ces ajustements avec une pénalité, la vue maximum a posteriori.
+
+ ## 5.1 Le séparateur linéaire
+
+ Un classifieur linéaire attribue la classe d'après le signe du score linéaire, et l'ensemble des entrées de score nul est la frontière de décision :
+
+ $$\boxed{ h_\theta(x) = \mathrm{sign}(\theta^T x), \qquad \theta^T x = 0 \ \text{est la frontière} }$$
+
+ La frontière est un hyperplan : une droite avec deux caractéristiques, un plan avec trois. Le signe du score dit de quel côté de l'hyperplan l'entrée tombe, et sa grandeur à quelle distance de la frontière elle se trouve. Avec $\theta = (-4, 1, 2)$ (biais en tête, sur l'entrée augmentée), le point $x = (3, 2)$ obtient $-4 + 3 + 4 = 3$ et tombe devant l'hyperplan, tandis que $x = (1, 1)$ obtient $-4 + 1 + 2 = -1$ et tombe derrière.
+
+ *Remarque :* deux avantages pratiques en découlent. Une fois l'entraînement terminé, l'ensemble d'entraînement peut être jeté, et prédire coûte un seul produit scalaire.
+
+ ## 5.2 Un menu de méthodes
+
+ Les méthodes classiques ajustent cet hyperplan, et elles se séparent nettement selon ce qu'elles supposent des données et la façon dont elles se résolvent.
+
+ | Méthode | Hypothèse sur les données | Ajustement |
+ | --- | --- | --- |
+ | Moindres carrés | classes de forme gaussienne | forme close (inversion de matrice) |
+ | Perceptron | aucune | descente de gradient |
+ | Régression logistique | aucune | descente de gradient |
+
+ Les moindres carrés héritent du confort de la forme close de la [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression) et le paient d'une hypothèse de distribution. Les deux autres ne supposent rien et le paient d'une optimisation itérative.
+
+ ## 5.3 Les moindres carrés comme classifieur
+
+ Codons les deux classes $y \in \{-1, +1\}$, traitons-les comme des cibles de régression, et tout le module [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression) s'applique tel quel, forme close comprise :
+
+ $$\boxed{ \theta = (X^T X)^{-1}X^T y, \qquad h_\theta(x) = \mathrm{sign}(\theta^T x) }$$
+
+ Pour $K > 2$ classes, on code chaque étiquette comme une ligne one-hot de $Y \in \mathbb{R}^{m \times K}$ et on réutilise les prédictions multiples de la [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression), en prédisant la classe au score le plus élevé :
+
+ $$\boxed{ W = (X^T X)^{-1}X^T Y, \qquad \hat{y} = \arg\max_k \; (W^T x)_k }$$
+
+ Cela peut fonctionner, mais la perte quadratique pénalise les grands scores même loin du bon côté, si bien que les points qui font le moins de doute tirent sur la frontière. C'est l'hypothèse gaussienne à l'œuvre : les moindres carrés traitent les étiquettes comme des cibles gaussiennes, et des données loin de cette histoire les cassent.
+
+ ![Moindres carrés et régression logistique avec points extrêmes](/fr/Machine%20Learning/05%20Linear%20classification/a/least-squares-outliers.png)
+
+ *Sans points extrêmes, moindres carrés et régression logistique concordent. Ajouter des points lointains et pourtant bien classés fait basculer la frontière des moindres carrés dans l'erreur, tandis que la régression logistique bouge à peine.*
+
+ ## 5.4 Le perceptron
+
+ ### 5.4.1 Modèle, perte et mise à jour
+
+ La première méthode sans hypothèse prend la définition du classifieur linéaire au pied de la lettre, un produit scalaire suivi d'une activation dure, le neurone historique :
+
+ $$\boxed{ h_\theta(x) = \mathrm{sign}(\theta^T x), \qquad y \in \{-1, +1\} }$$
+
+ ![Le perceptron comme neurone](/fr/Machine%20Learning/05%20Linear%20classification/a/perceptron-neuron.svg)
+
+ *À gauche : le perceptron est un seul neurone, les entrées pondérées sommées dans le score $\theta^T x$ puis passées dans une activation signe dure. À droite : ce signe coupe l'espace d'entrée le long de l'hyperplan $\theta^T x = 0$.*
+
+ L'ajustement demande une perte, et compter les erreurs ne fonctionne pas : le compte est constant par morceaux, son gradient est donc nul presque partout. Le critère du perceptron pénalise plutôt chaque point mal classé selon la distance à laquelle il se trouve du mauvais côté. Une erreur signifie $y^{(i)}\,\theta^T x^{(i)} < 0$, donc sur l'ensemble $\mathcal{M}$ des points mal classés :
+
+ $$\boxed{ E(\theta) = -\sum_{i \in \mathcal{M}} y^{(i)}\, \theta^T x^{(i)} }$$
+
+ toujours positif et linéaire par morceaux. Le minimiser introduit l'outil de base de tout ce qui, dans ce cours, n'a pas de forme close, la descente de gradient : avancer les paramètres à répétition à l'opposé du gradient de la perte, mis à l'échelle par un taux d'apprentissage $\alpha > 0$ :
+
+ $$\boxed{\,\theta \leftarrow \theta - \alpha\,\nabla_\theta E(\theta)\,}$$
+
+ La variante par lots calcule le gradient sur tout l'ensemble d'entraînement avant chaque pas, une descente lisse qui relit chaque exemple à chaque fois. La variante stochastique (SGD) avance sur un exemple à la fois, peu coûteuse et bruitée, et c'est le choix par défaut sur les grands jeux de données. Si $\alpha$ est trop grand les itérés peuvent diverger, s'il est trop petit la convergence se traîne.
+
+ *Remarque :* des optimiseurs plus élaborés existent, momentum, Adam et leurs cousins, des raffinements de cette même règle qui comptent pour les réseaux profonds ([Optimisation](/fr/Deep%20Learning/06%20Optimization) dans le cours de Deep Learning). Tout ce module se contente de la version simple.
+
+ Sur un seul exemple mal classé le gradient du critère vaut $-y^{(i)} x^{(i)}$, le pas stochastique est donc la mise à jour du perceptron : sur une erreur,
+
+ $$\boxed{ \theta \leftarrow \theta + \alpha\, y^{(i)} x^{(i)} }$$
+
+ et aucune mise à jour sinon. Dans le codage $\{0, 1\}$ c'est la mise à jour résidu fois l'entrée $\theta_j \leftarrow \theta_j + \alpha\,(y^{(i)} - h_\theta(x^{(i)}))\,x_j^{(i)}$.
+
+ ![Frontière de décision du perceptron](/fr/Machine%20Learning/05%20Linear%20classification/a/perceptron.png)
+
+ *Le perceptron trouve un hyperplan séparateur, pas nécessairement celui de marge maximale que la machine à vecteurs de support choisira.*
+
+ ### 5.4.2 Perceptron multiclasse
+
+ Avec $k$ classes, on garde un vecteur de poids $\theta_c$ par classe et on prédit celle au plus fort score. Sur une erreur, on récompense la vraie classe et on pénalise la classe prédite :
+
+ $$\boxed{ \hat{y} = \arg\max_c \theta_c^T x, \qquad \theta_{y} \mathrel{+}= \alpha x, \quad \theta_{\hat{y}} \mathrel{-}= \alpha x }$$
+
+ La vue en réseau s'étend naturellement : un neurone de score par classe, et un argmax là où le perceptron binaire avait un signe. En rassemblant les $\theta_c$ comme colonnes d'une matrice $W \in \mathbb{R}^{(n+1) \times k}$, un seul produit $W^T x$ calcule tous les scores à la fois, et les scores découpent l'espace d'entrée en $k$ régions, chacune revendiquée par la classe au score le plus élevé.
+
+ ![Le perceptron multiclasse](/fr/Machine%20Learning/05%20Linear%20classification/a/multiclass-neuron.svg)
+
+ *Un neurone de score par classe et un argmax au sommet. Chaque colonne de $W$ (chaque ligne de $W^T$) est l'hyperplan, normale et biais, d'une classe.*
+
+ Un exemple chiffré avec $k = 3$ classes et l'entrée $x = (1{,}1,\ -2{,}0)$, augmentée de $x_0 = 1$ :
+
+ $$ W^T x = \begin{bmatrix} -2 & -4 & 1 \\ -4 & 2 & 4 \\ -6 & 4 & -5 \end{bmatrix}\begin{bmatrix} 1 \\ 1{,}1 \\ -2{,}0 \end{bmatrix} = \begin{bmatrix} -8{,}4 \\ -9{,}8 \\ 8{,}4 \end{bmatrix} $$
+
+ Le troisième score l'emporte, l'entrée est donc affectée à la classe 3. En lisant la troisième ligne, ce score vaut $\theta_3^T x = -6 + 4 \times 1{,}1 + (-5) \times (-2{,}0) = 8{,}4$.
+
+ ### 5.4.3 Convergence et limites
+
+ Si les données sont linéairement séparables, le perceptron converge en un nombre fini de mises à jour, sinon les poids oscillent indéfiniment. Et comme le critère vaut zéro sur tout hyperplan séparateur, tous comptent comme « optimaux », y compris ceux qui frôlent les données.
+
+ *Remarque :* trois améliorations corrigent ces limites, et chacune ouvre un module. Une activation et une perte lisses donnent la régression logistique, section suivante. Les marges et les fonctions de base mènent à la [machine à vecteurs de support](/fr/Machine%20Learning/07%20Support%20Vector%20Machines). Empiler les neurones en couches donne les [réseaux de neurones multi-couches](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks), point de départ du cours de Deep Learning.
+
+ ## 5.5 La régression logistique
+
+ ### 5.5.1 Une activation lisse
+
+ La régression logistique garde le neurone mais remplace l'échelon dur par la sigmoïde lisse, si bien que la sortie est la probabilité de la classe positive ($y \in \{0, 1\}$) :
+
+ $$\boxed{ \phi = p(y = 1 \mid x; \theta) = \sigma(\theta^T x) = \frac{1}{1 + e^{-\theta^T x}} }$$
+
+ ![La régression logistique comme neurone](/fr/Machine%20Learning/05%20Linear%20classification/a/logistic-neuron.svg)
+
+ *Le même neurone avec l'échelon remplacé par la sigmoïde : la sortie devient la probabilité $\phi = p(y = 1 \mid x)$, et la seuiller à $\tfrac{1}{2}$ redonne la même frontière $\theta^T x = 0$.*
+
+ *Remarque :* la sigmoïde n'est pas un choix de compression arbitraire. Écrire l'a posteriori avec la règle de Bayes donne $p(C_1 \mid x) = 1/(1 + e^{-a})$ avec $a = \ln \frac{p(x \mid C_1)\,p(C_1)}{p(x \mid C_0)\,p(C_0)}$, donc une sortie logistique bien entraînée est exactement une probabilité a posteriori.
+
+ ### 5.5.2 L'entropie croisée et son gradient
+
+ La vraisemblance d'étiquettes de Bernoulli, passée au $-\log$, donne la perte d'entropie croisée :
+
+ $$\boxed{ L(\theta) = -\sum_{i=1}^{m}\left[ y^{(i)}\log \phi^{(i)} + (1 - y^{(i)})\log(1 - \phi^{(i)}) \right] }$$
+
+ Contrairement aux moindres carrés, cette perte n'a pas de minimiseur en forme close : la sigmoïde rend les équations de stationnarité transcendantes, l'ajustement revient donc à la même descente de gradient que le perceptron. Dériver l'entropie croisée à travers la sigmoïde récompense l'effort : presque tout se simplifie et le gradient se réduit au résidu fois l'entrée :
+
+ $$\boxed{ \theta_j \leftarrow \theta_j - \alpha \sum_{i=1}^{m}\left(\phi^{(i)} - y^{(i)}\right)x_j^{(i)} }$$
+
+ *Remarque :* contrairement au perceptron, le gradient fait intervenir chaque point d'entraînement, pas seulement les mal classés : chaque point tire proportionnellement à son résidu $\phi^{(i)} - y^{(i)}$. C'est ce qui rend la régression logistique plus stable que le perceptron et utilisable sur des données non séparables.
+
+ ![Sigmoïde et frontière de décision logistique](/fr/Machine%20Learning/05%20Linear%20classification/a/logistic-regression.png)
+
+ *À gauche : la sigmoïde envoie tout score dans l'intervalle (0, 1). À droite : la frontière de décision et la probabilité prédite.*
+
+ ### 5.5.3 Multiclasse : la softmax
+
+ Pour $k$ classes, la sigmoïde se généralise en la softmax, un vecteur de poids par classe, normalisé en une distribution :
+
+ $$\boxed{ p(y = c \mid x; \theta) = \frac{\exp(\theta_c^T x)}{\sum_{j=1}^{k}\exp(\theta_j^T x)} }$$
+
+ Avec des étiquettes one-hot, la perte est l'entropie croisée catégorielle $L = -\sum_i \log p(y^{(i)} \mid x^{(i)})$, dont le gradient garde la même forme résidu fois l'entrée.
+
+ | | sigmoïde | softmax |
+ | --- | --- | --- |
+ | classes | 2 | $k$ |
+ | sortie | une probabilité $\phi$ | une distribution sur $k$ classes |
+ | relation | la softmax à $k = 2$ se réduit à la sigmoïde | généralise la sigmoïde |
+
+ ## 5.6 La classification régularisée
+
+ Rien ne fixe l'échelle de $\theta$ : le doubler ne déplace aucune frontière du perceptron et ne fait qu'affûter les probabilités de la régression logistique, et des vecteurs de poids différents peuvent produire des scores identiques. La recette du maximum a posteriori de la [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression) s'applique telle quelle, en ajoutant une pénalité à la perte minimisée, quelle qu'elle soit :
+
+ $$\boxed{ J_\lambda(\theta) = \sum_{i=1}^{m} L\!\left(h_\theta(x^{(i)}),\,y^{(i)}\right) + \lambda\,\Omega(\theta), \qquad \Omega(\theta) = \lVert \theta \rVert_2^2 \ \text{ou} \ \lVert \theta \rVert_1 }$$
+
+ Pour l'entropie croisée avec la pénalité L2, le gradient gagne simplement une traction vers zéro, $\sum_i (\phi^{(i)} - y^{(i)})\,x^{(i)} + 2\lambda\theta$.
+
+ *Remarque :* les bibliothèques exposent exactement ce menu, une perte plus une pénalité (le `SGDClassifier` de scikit-learn prend un argument `loss` et un argument `penalty`). L'intensité $\lambda$ se choisit par la validation de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts), et le comportement sélectif du lasso est couvert dans la [Régression linéaire](/fr/Machine%20Learning/04%20Linear%20regression).
+
+ ## 5.7 Résumé
+
+ Les méthodes sans hypothèse partagent une seule mise à jour, le résidu fois l'entrée :
+
+ | Modèle | Activation | Mise à jour (un exemple) |
+ | --- | --- | --- |
+ | Perceptron | échelon | $\theta_j \leftarrow \theta_j + \alpha\,(y - h_\theta(x))\,x_j$ (erreurs seulement) |
+ | Régression linéaire | identité | $\theta_j \leftarrow \theta_j + \alpha\,(y - \theta^T x)\,x_j$ |
+ | Régression logistique | sigmoïde ou softmax | $\theta_j \leftarrow \theta_j + \alpha\,(y - \phi)\,x_j$ |
+
+ *Remarque :* seule l'activation diffère (échelon, identité, sigmoïde ou softmax). Le cours de Deep Learning reprend précisément ce fil, en empilant de telles unités en couches.
+
+ Et les pertes en un coup d'œil :
+
+ | Perte | Pénalise | Utilisée par |
+ | --- | --- | --- |
+ | Critère du perceptron | les points mal classés seulement | perceptron |
+ | Charnière $\max(0,\,1 - y\,\theta^T x)$ | les erreurs et les petites marges | [SVM](/fr/Machine%20Learning/07%20Support%20Vector%20Machines) |
+ | Entropie croisée | chaque point, selon son résidu | régression logistique |
+
+ *Les modèles linéaires étant couverts, le module suivant empile ces briques en réseaux de neurones multi-couches.*
+
+ ---
+ Suivant : [Réseaux de neurones multi-couches](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
/dev/null .. fr/Machine Learning/05 Linear classification/least-squares-outliers.png
/dev/null .. fr/Machine Learning/05 Linear classification/logistic-neuron.svg
@@ 0,0 1,40 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 620 300" width="620" height="300" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowgreen" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#38a05a"/></marker>
+ </defs>
+ <rect width="620" height="300" fill="#ffffff"/>
+ <text x="310" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">La régression logistique : le même neurone, lissé</text>
+
+ <circle cx="70" cy="95" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="100" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="70" cy="155" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="160" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="70" cy="215" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="220" font-size="13" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="70" y="251" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="88" y1="95" x2="226" y2="146" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="155" x2="225" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="215" x2="226" y2="164" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="150" y="112" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="150" y="148" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">2</tspan></text>
+ <text x="150" y="184" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">0</tspan></text>
+
+ <circle cx="255" cy="155" r="28" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="255" y="160" font-size="13" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="-5" font-size="9">T</tspan><tspan dy="5" font-size="13">x</tspan></text>
+
+ <line x1="283" y1="155" x2="330" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+
+ <circle cx="360" cy="155" r="28" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <path d="M342 166 C 355 166, 358 144, 378 144" fill="none" stroke="#38a05a" stroke-width="2.2"/>
+
+ <line x1="388" y1="155" x2="485" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="449" y="140" font-size="12" fill="#1f2933" text-anchor="middle">&#966; = p(y = 1 | x)</text>
+ <text x="449" y="176" font-size="11" fill="#5b6b7b" text-anchor="middle">&#8712; (0, 1)</text>
+
+ <line x1="360" y1="222" x2="360" y2="190" stroke="#38a05a" stroke-width="1.7" marker-end="url(#arrowgreen)"/>
+ <text x="360" y="240" font-size="11" fill="#5b6b7b" text-anchor="middle">activation sigmoïde</text>
+
+ <text x="310" y="282" font-size="11" fill="#5b6b7b" text-anchor="middle">seuiller à &#966; = 0,5 redonne la même frontière &#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x = 0</tspan></text>
+ </svg>
fr/Machine Learning/06 Linear classification/logistic-regression.png .. fr/Machine Learning/05 Linear classification/logistic-regression.png
/dev/null .. fr/Machine Learning/05 Linear classification/multiclass-neuron.svg
@@ 0,0 1,71 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 320" width="860" height="320" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ </defs>
+ <rect width="860" height="320" fill="#ffffff"/>
+ <text x="430" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Le perceptron multiclasse : un score par classe, puis un argmax</text>
+
+ <circle cx="55" cy="95" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="100" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="55" cy="155" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="160" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="55" cy="215" r="16" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="55" y="220" font-size="12" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="55" y="248" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="71" y1="95" x2="214" y2="93" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="95" x2="216" y2="147" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="95" x2="218" y2="205" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="216" y2="101" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="214" y2="155" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="155" x2="216" y2="209" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="218" y2="105" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="216" y2="163" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+ <line x1="71" y1="215" x2="214" y2="215" stroke="#1f2933" stroke-width="1.1" marker-end="url(#arrow)"/>
+
+ <circle cx="240" cy="95" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="100" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">1</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+ <circle cx="240" cy="155" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="160" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">2</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+ <circle cx="240" cy="215" r="24" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="240" y="220" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="8">3</tspan><tspan dy="-10" font-size="8">T</tspan><tspan dy="6" font-size="12">x</tspan></text>
+
+ <ellipse cx="405" cy="155" rx="45" ry="22" fill="#f2e9fd" stroke="#8257d6" stroke-width="1.6"/>
+ <text x="405" y="160" font-size="12" fill="#1f2933" text-anchor="middle">argmax</text>
+ <line x1="264" y1="95" x2="367" y2="146" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+ <line x1="264" y1="155" x2="356" y2="155" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+ <line x1="264" y1="215" x2="367" y2="164" stroke="#1f2933" stroke-width="1.4" marker-end="url(#arrow)"/>
+
+ <line x1="450" y1="155" x2="510" y2="155" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="485" y="142" font-size="13" fill="#1f2933" text-anchor="middle">&#375;</text>
+
+ <polygon points="695,160 695,55 555,55 555,210" fill="#e8f0fe"/>
+ <polygon points="695,160 555,210 555,255 805,255" fill="#e7f5ea"/>
+ <polygon points="695,160 805,255 835,255 835,55 695,55" fill="#fff1e0"/>
+ <line x1="695" y1="160" x2="695" y2="55" stroke="#5b6b7b" stroke-width="1.2"/>
+ <line x1="695" y1="160" x2="555" y2="210" stroke="#5b6b7b" stroke-width="1.2"/>
+ <line x1="695" y1="160" x2="805" y2="255" stroke="#5b6b7b" stroke-width="1.2"/>
+ <rect x="555" y="55" width="280" height="200" rx="8" fill="none" stroke="#9aa7b2" stroke-width="1.4"/>
+
+ <circle cx="610" cy="90" r="5" fill="#3b6fb6"/>
+ <circle cx="640" cy="120" r="5" fill="#3b6fb6"/>
+ <circle cx="600" cy="140" r="5" fill="#3b6fb6"/>
+ <circle cx="660" cy="95" r="5" fill="#3b6fb6"/>
+ <circle cx="625" cy="105" r="5" fill="#3b6fb6"/>
+ <circle cx="610" cy="225" r="5" fill="#38a05a"/>
+ <circle cx="650" cy="235" r="5" fill="#38a05a"/>
+ <circle cx="700" cy="230" r="5" fill="#38a05a"/>
+ <circle cx="590" cy="240" r="5" fill="#38a05a"/>
+ <circle cx="660" cy="215" r="5" fill="#38a05a"/>
+ <circle cx="760" cy="120" r="5" fill="#e0872e"/>
+ <circle cx="790" cy="160" r="5" fill="#e0872e"/>
+ <circle cx="740" cy="90" r="5" fill="#e0872e"/>
+ <circle cx="780" cy="210" r="5" fill="#e0872e"/>
+ <circle cx="730" cy="140" r="5" fill="#e0872e"/>
+
+ <text x="568" y="74" font-size="11" fill="#3b6fb6" text-anchor="start">&#952;<tspan dy="3" font-size="8">1</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+ <text x="572" y="223" font-size="11" fill="#38a05a" text-anchor="start">&#952;<tspan dy="3" font-size="8">2</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+ <text x="828" y="74" font-size="11" fill="#e0872e" text-anchor="end">&#952;<tspan dy="3" font-size="8">3</tspan><tspan dy="-7" font-size="8">T</tspan><tspan dy="4" font-size="11">x max</tspan></text>
+
+ <text x="405" y="300" font-size="11" fill="#5b6b7b" text-anchor="middle">chaque classe note l'entrée avec son propre hyperplan, et le plus grand score revendique la région</text>
+ </svg>
/dev/null .. fr/Machine Learning/05 Linear classification/perceptron-neuron.svg
@@ 0,0 1,63 @@
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 300" width="860" height="300" font-family="Helvetica, Arial, sans-serif">
+ <defs>
+ <marker id="arrow" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#1f2933"/></marker>
+ <marker id="arrowgreen" viewBox="0 0 10 10" refX="8.5" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0 0L10 5L0 10z" fill="#38a05a"/></marker>
+ </defs>
+ <rect width="860" height="300" fill="#ffffff"/>
+ <text x="430" y="22" font-size="15" font-weight="600" fill="#1f2933" text-anchor="middle">Le perceptron : un neurone, une activation dure</text>
+
+ <circle cx="70" cy="85" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="90" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <circle cx="70" cy="145" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="150" font-size="13" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+ <circle cx="70" cy="205" r="18" fill="#e8f0fe" stroke="#3b6fb6" stroke-width="1.6"/>
+ <text x="70" y="210" font-size="13" fill="#1f2933" text-anchor="middle">1</text>
+ <text x="70" y="241" font-size="10" fill="#5b6b7b" text-anchor="middle">x<tspan dy="3" font-size="8">0</tspan><tspan dy="-3"> = 1</tspan></text>
+
+ <line x1="88" y1="85" x2="226" y2="136" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="145" x2="225" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <line x1="88" y1="205" x2="226" y2="154" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="150" y="102" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="150" y="138" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">2</tspan></text>
+ <text x="150" y="174" font-size="12" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="4" font-size="9">0</tspan></text>
+
+ <circle cx="255" cy="145" r="28" fill="#fff1e0" stroke="#e0872e" stroke-width="1.6"/>
+ <text x="255" y="150" font-size="13" fill="#1f2933" text-anchor="middle">&#952;<tspan dy="-5" font-size="9">T</tspan><tspan dy="5" font-size="13">x</tspan></text>
+
+ <line x1="283" y1="145" x2="330" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+
+ <circle cx="360" cy="145" r="28" fill="#e7f5ea" stroke="#38a05a" stroke-width="1.6"/>
+ <text x="360" y="150" font-size="13" fill="#1f2933" text-anchor="middle">signe</text>
+
+ <line x1="388" y1="145" x2="485" y2="145" stroke="#1f2933" stroke-width="1.6" marker-end="url(#arrow)"/>
+ <text x="445" y="131" font-size="12" fill="#1f2933" text-anchor="middle">h<tspan dy="4" font-size="9">&#952;</tspan><tspan dy="-4">(x) &#8712; {&#8722;1, +1}</tspan></text>
+
+ <line x1="360" y1="212" x2="360" y2="180" stroke="#38a05a" stroke-width="1.7" marker-end="url(#arrowgreen)"/>
+ <text x="360" y="230" font-size="11" fill="#5b6b7b" text-anchor="middle">fonction d'activation</text>
+
+ <line x1="560" y1="250" x2="835" y2="250" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <line x1="560" y1="250" x2="560" y2="55" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="828" y="268" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">1</tspan></text>
+ <text x="543" y="64" font-size="12" fill="#1f2933" text-anchor="middle">x<tspan dy="4" font-size="9">2</tspan></text>
+
+ <line x1="580" y1="95" x2="820" y2="230" stroke="#5b6b7b" stroke-width="1.7" stroke-dasharray="6 5"/>
+ <text x="772" y="192" font-size="11" fill="#5b6b7b" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x = 0</tspan></text>
+
+ <line x1="700" y1="162" x2="727" y2="114" stroke="#1f2933" stroke-width="1.7" marker-end="url(#arrow)"/>
+ <text x="736" y="112" font-size="12" fill="#1f2933" text-anchor="start">&#952;</text>
+
+ <circle cx="600" cy="78" r="5.5" fill="#3b6fb6"/>
+ <circle cx="632" cy="96" r="5.5" fill="#3b6fb6"/>
+ <circle cx="662" cy="112" r="5.5" fill="#3b6fb6"/>
+ <circle cx="692" cy="128" r="5.5" fill="#3b6fb6"/>
+ <circle cx="612" cy="100" r="5.5" fill="#3b6fb6"/>
+ <text x="590" y="62" font-size="11" fill="#3b6fb6" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x &gt; 0</tspan></text>
+
+ <circle cx="650" cy="180" r="5.5" fill="#e0872e"/>
+ <circle cx="700" cy="210" r="5.5" fill="#e0872e"/>
+ <circle cx="740" cy="190" r="5.5" fill="#e0872e"/>
+ <circle cx="780" cy="225" r="5.5" fill="#e0872e"/>
+ <circle cx="720" cy="195" r="5.5" fill="#e0872e"/>
+ <circle cx="760" cy="205" r="5.5" fill="#e0872e"/>
+ <text x="608" y="237" font-size="11" fill="#e0872e" text-anchor="start">&#952;<tspan dy="-4" font-size="8">T</tspan><tspan dy="4">x &lt; 0</tspan></text>
+ </svg>
fr/Machine Learning/06 Linear classification/perceptron.png .. fr/Machine Learning/05 Linear classification/perceptron.png
fr/Machine Learning/05 Linear regression.md .. /dev/null
@@ 1,62 0,0 @@
- # 5. Régression linéaire
-
- La régression linéaire prédit une cible continue à partir d'un score linéaire $\theta^T x$. Ce module la présente de façon probabiliste, en prolongeant le module [Formulation probabiliste](/fr/Machine%20Learning/04%20Probabilistic%20formulation) : le modèle (étendu aux caractéristiques polynomiales), l'ajustement par maximum de vraisemblance, qui se révèle être les moindres carrés ordinaires, et l'ajustement par maximum a posteriori, qui ajoute un a priori et donne un ajustement régularisé.
-
- **Objectifs**
- - Écrire le modèle de régression linéaire et polynomiale et l'ajuster par moindres carrés.
- - Donner à la régression une formulation probabiliste avec un bruit gaussien.
- - Voir que le maximum de vraisemblance sous ce modèle est exactement les moindres carrés.
- - Ajouter un a priori et ajuster par maximum a posteriori, retrouvant un ajustement régularisé.
-
- ## 5.1 Le modèle linéaire et polynomial
-
- L'hypothèse est linéaire en l'entrée augmentée $x \in \mathbb{R}^{n+1}$ avec $x_0 = 1$ et les paramètres $\theta$ :
-
- $$\boxed{ h_\theta(x) = \theta^T x }$$
-
- La régression polynomiale est le même modèle appliqué à une transformation des caractéristiques. Remplacer $x$ par $\phi(x) = (1, x, x^2, \dots, x^d)$ ajuste un polynôme de degré $d$ tout en restant linéaire en les paramètres :
-
- $$\boxed{ h_\theta(x) = \theta^T \phi(x) = \sum_{j=0}^{d} \theta_j\, x^{j} }$$
-
- donc tout ce qui suit s'applique tel quel une fois que la matrice de conception $X$ empile les entrées transformées $\phi(x^{(i)})$ sur ses lignes.
-
- ## 5.2 Moindres carrés
-
- Le coût est la demi-somme des carrés des résidus sur les $m$ exemples :
-
- $$\boxed{ J(\theta) = \tfrac{1}{2}\sum_{i=1}^{m}\left(h_\theta(x^{(i)}) - y^{(i)}\right)^2 }$$
-
- Poser $\nabla_\theta J = 0$ donne l'équation normale sous forme close, et la descente de gradient donne la mise à jour itérative équivalente :
-
- $$\boxed{ \theta = (X^T X)^{-1}X^T y \qquad \theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)} }$$
-
- ![Ajustement par régression linéaire](/fr/Machine%20Learning/05%20Linear%20regression/a/linear-regression.png)
-
- *Les moindres carrés ajustent la courbe qui minimise les résidus au carré (segments gris).*
-
- ## 5.3 Formulation probabiliste : maximum de vraisemblance
-
- Donnons aux données une histoire générative : chaque cible est la prédiction linéaire plus un bruit gaussien indépendant,
-
- $$\boxed{ y^{(i)} = \theta^T x^{(i)} + \varepsilon^{(i)}, \quad \varepsilon^{(i)} \sim \mathcal{N}(0, \sigma^2) }$$
-
- donc $p(y^{(i)} \mid x^{(i)}; \theta) = \mathcal{N}(\theta^T x^{(i)}, \sigma^2)$. Maximiser la log-vraisemblance sur les $m$ exemples i.i.d. élimine tout terme indépendant de $\theta$ et laisse le coût des moindres carrés :
-
- $$\boxed{ \arg\max_\theta \ell(\theta) = \arg\min_\theta \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 }$$
-
- *Remarque :* c'est pourquoi les moindres carrés sont un objectif fondé et pas seulement commode. Les moindres carrés ordinaires sont l'estimation du maximum de vraisemblance sous un bruit gaussien, exactement le principe du maximum de vraisemblance du module précédent.
-
- ## 5.4 Maximum a posteriori
-
- Le maximum de vraisemblance peut surapprendre, surtout à haut degré polynomial. Placer un a priori gaussien centré sur les paramètres, $\theta \sim \mathcal{N}(0, \tau^2 I)$, et maximiser l'a posteriori ajoute une pénalité sur leur taille :
-
- $$\boxed{ \theta_{\mathrm{MAP}} = \arg\min_\theta \; \sum_{i=1}^{m}\left(y^{(i)} - \theta^T x^{(i)}\right)^2 + \lambda \lVert \theta \rVert_2^2, \quad \lambda = \frac{\sigma^2}{\tau^2} }$$
-
- C'est la régression régularisée (ridge) : l'a priori gaussien devient une pénalité L2, exactement le lien a priori vers pénalité noté au module précédent.
-
- *Remarque :* un a priori plus fort (petit $\tau$) signifie un $\lambda$ plus grand et un rétrécissement plus marqué vers zéro. Avec beaucoup de données, la vraisemblance domine l'a priori et l'ajustement du maximum a posteriori se rapproche de celui du maximum de vraisemblance. Choisir le degré $d$ et la pénalité $\lambda$ est un problème de sélection de modèle, réglé par la validation croisée du [module d'évaluation](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation), et approfondi dans le [module de régularisation](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference).
-
- *Le même score linéaire, passé dans une fonction de compression au lieu d'être lu directement, transforme la régression en classification, le sujet du module suivant.*
-
- ---
- Suivant : [Classification linéaire](/fr/Machine%20Learning/06%20Linear%20classification) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/05 Linear regression/linear-regression.png .. /dev/null
fr/Machine Learning/06 Linear classification.md .. /dev/null
@@ 1,83 0,0 @@
- # 6. Classification linéaire
-
- La classification prédit une étiquette discrète à partir du même score linéaire $\theta^T x$. Ce module part de l'idée de traiter la classification comme une régression, puis construit les deux classifieurs linéaires classiques : le perceptron, binaire et multiclasse, et la régression logistique, binaire avec la sigmoïde et multiclasse avec la softmax, tous entraînés par descente de gradient sur l'entropie croisée.
-
- **Objectifs**
- - Voir pourquoi régresser directement les étiquettes est un mauvais classifieur, et comment une fonction de compression y remédie.
- - Classer avec le perceptron, binaire et multiclasse, et savoir quand il converge.
- - Ajuster la régression logistique binaire avec la sigmoïde et l'entropie croisée.
- - Étendre à plusieurs classes avec la softmax, et relier la sigmoïde et la softmax.
- - Entraîner ces modèles par descente de gradient.
-
- ## 6.1 La classification comme un problème de régression
-
- On pourrait ajuster les moindres carrés directement aux étiquettes $y \in \{0, 1\}$, mais la sortie linéaire est non bornée, se laisse tirer par les valeurs aberrantes, et ne se lit pas comme une probabilité. La solution est de garder le score linéaire et de le passer dans une fonction de compression qui l'envoie vers une classe ou une probabilité. Le reste du module présente deux choix de cette fonction.
-
- ## 6.2 Le perceptron
-
- ### 6.2.1 Perceptron binaire
-
- Le perceptron passe le score dans un échelon dur, si bien que la sortie est une étiquette de classe :
-
- $$\boxed{ h_\theta(x) = g(\theta^T x), \quad g(z) = \begin{cases} 1 & \text{si } z \ge 0 \\ 0 & \text{sinon} \end{cases} }$$
-
- Il est entraîné en ligne, corrigeant $\theta$ seulement sur un point mal classé :
-
- $$\boxed{ \theta_j \leftarrow \theta_j + \alpha\left(y^{(i)} - h_\theta(x^{(i)})\right)x_j^{(i)} }$$
-
- ![Frontière de décision du perceptron](/fr/Machine%20Learning/06%20Linear%20classification/a/perceptron.png)
-
- *Le perceptron trouve un hyperplan séparateur, pas nécessairement celui de marge maximale que la machine à vecteurs de support choisira.*
-
- ### 6.2.2 Perceptron multiclasse
-
- Avec $k$ classes, on garde un vecteur de poids $\theta_c$ par classe et on prédit celle au plus fort score. Sur une erreur, on récompense la vraie classe et on pénalise la classe prédite :
-
- $$\boxed{ \hat{y} = \arg\max_c \theta_c^T x, \qquad \theta_{y} \mathrel{+}= \alpha x, \quad \theta_{\hat{y}} \mathrel{-}= \alpha x }$$
-
- ### 6.2.3 Convergence
-
- Si les données sont linéairement séparables, le perceptron converge en un nombre fini de mises à jour, sinon les poids oscillent indéfiniment.
-
- *Remarque :* le perceptron s'arrête au premier hyperplan séparateur, ce qui motive la machine à vecteurs de support (marge la plus large) et, empilé en couches, le réseau de neurones. Un perceptron est une unité unique, et empilé en couches il devient un réseau de neurones, le point de départ du cours de Deep Learning.
-
- ## 6.3 Régression logistique, binaire
-
- La régression logistique remplace l'échelon dur par la sigmoïde lisse, si bien que la sortie est la probabilité de la classe positive :
-
- $$\boxed{ \phi = p(y = 1 \mid x; \theta) = g(\theta^T x) = \frac{1}{1 + e^{-\theta^T x}} }$$
-
- Elle est ajustée en minimisant l'entropie croisée, la log-vraisemblance négative des étiquettes de Bernoulli :
-
- $$\boxed{ L(\theta) = -\sum_{i=1}^{m}\left[ y^{(i)}\log \phi^{(i)} + (1 - y^{(i)})\log(1 - \phi^{(i)}) \right] }$$
-
- ![Sigmoïde et frontière de décision logistique](/fr/Machine%20Learning/06%20Linear%20classification/a/logistic-regression.png)
-
- *À gauche : la sigmoïde envoie tout score dans l'intervalle (0, 1). À droite : la frontière de décision et la probabilité prédite.*
-
- ## 6.4 Régression logistique, multiclasse
-
- Pour $k$ classes, la sigmoïde se généralise en la softmax, un vecteur de poids par classe, normalisé en une distribution :
-
- $$\boxed{ p(y = c \mid x; \theta) = \frac{\exp(\theta_c^T x)}{\sum_{j=1}^{k}\exp(\theta_j^T x)} }$$
-
- entraînée par l'entropie croisée catégorielle $L = -\sum_i \log p(y^{(i)} \mid x^{(i)})$.
-
- | | sigmoïde | softmax |
- | --- | --- | --- |
- | classes | 2 | $k$ |
- | sortie | une probabilité $\phi$ | une distribution sur $k$ classes |
- | relation | la softmax à $k = 2$ se réduit à la sigmoïde | généralise la sigmoïde |
-
- ## 6.5 Descente de gradient
-
- Les deux modèles sont ajustés par descente de gradient sur l'entropie croisée. Le gradient prend la même forme épurée que la mise à jour des moindres carrés, le résidu fois l'entrée :
-
- $$\boxed{ \theta_j \leftarrow \theta_j - \alpha \sum_{i=1}^{m}\left(\phi^{(i)} - y^{(i)}\right)x_j^{(i)} }$$
-
- *Remarque :* le perceptron, la régression linéaire et la régression logistique partagent une seule mise à jour, le résidu fois l'entrée. Seule l'activation diffère (échelon, identité, sigmoïde ou softmax). Le cours de Deep Learning reprend précisément ce fil, en empilant de telles unités en couches.
-
- *Les modèles linéaires étant couverts, le module suivant contrôle leur complexité : la régularisation et l'inférence quand les régresseurs sont nombreux.*
-
- ---
- Suivant : [Régularisation et inférence en grande dimension](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/08 Multilayer neural networks.md .. fr/Machine Learning/06 Multilayer neural networks.md
@@ 1,4 1,4 @@
- # 8. Réseaux de neurones multi-couches
+ # 6. Réseaux de neurones multi-couches
Une seule unité linéaire ne trace qu'une frontière droite. Empiler de nombreuses unités simples avec une non-linéarité entre elles donne un réseau de neurones multi-couches, qui ajuste des frontières courbes et apprend ses propres caractéristiques. Ce module est un tour d'horizon compact des réseaux de neurones, de l'architecture à l'entraînement, et la porte d'entrée du cours de [Deep Learning](/fr/Deep%20Learning), qui développe en profondeur chaque sujet abordé ici.
@@ 10,15 10,15 @@
- Entraîner par la règle de dérivation en chaîne et la rétropropagation, avec des mini-lots, une bonne initialisation et le dropout.
- Protéger l'implémentation par la vérification du gradient et la vectorisation.
- ## 8.1 Linéaire contre non linéaire
+ ## 6.1 Linéaire contre non linéaire
- Les classifieurs linéaires du [module précédent](/fr/Machine%20Learning/06%20Linear%20classification) séparent les classes par une seule frontière droite, si bien qu'un problème comme XOR, non linéairement séparable, est hors de portée. Composer des unités à travers une activation non linéaire $g$ courbe la frontière. La non-linéarité est essentielle : sans elle, une pile de couches linéaires se réduit à une seule application linéaire,
+ Les classifieurs linéaires du [module de classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification) séparent les classes par une seule frontière droite, si bien qu'un problème comme XOR, non linéairement séparable, est hors de portée. Composer des unités à travers une activation non linéaire $g$ courbe la frontière. La non-linéarité est essentielle : sans elle, une pile de couches linéaires se réduit à une seule application linéaire,
$$\boxed{ W^{[2]}\!\left(W^{[1]} x + b^{[1]}\right) + b^{[2]} = W' x + b' }$$
et la profondeur n'apporterait rien. C'est l'activation non linéaire qui rend l'empilement utile.
- ## 8.2 Les couches : entrée, cachée, sortie
+ ## 6.2 Les couches : entrée, cachée, sortie
Un neurone calcule $a = g(w^T x + b)$. Une couche empile plusieurs neurones, et un réseau empile des couches. La couche $l$ transforme les activations précédentes en nouvelles :
@@ 26,19 26,19 @@
La couche d'entrée contient $x$, les couches cachées apprennent des caractéristiques intermédiaires, et la couche de sortie produit la prédiction $\hat{y}$.
- ![Couches d'entrée, cachées et de sortie](/fr/Machine%20Learning/08%20Multilayer%20neural%20networks/a/mlp-layers.svg)
+ ![Couches d'entrée, cachées et de sortie](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks/a/mlp-layers.svg)
*Chaque arête porte un poids de $W^{[l]}$ et chaque unité ajoute un biais puis applique l'activation.*
*Remarque :* le biais est désormais écrit explicitement et chaque couche a sa propre matrice de poids $W^{[l]}$, contrairement à la convention antérieure qui repliait le biais dans $\theta^T x$ avec $x_0 = 1$. C'est la notation utilisée tout au long du cours de Deep Learning.
- ## 8.3 Couche de sortie : binaire et multiclasse
+ ## 6.3 Couche de sortie : binaire et multiclasse
- La couche de sortie s'adapte à la tâche, en réutilisant les pertes du module précédent. Pour deux classes, une sortie sigmoïde avec l'entropie croisée binaire ; pour $k$ classes, une sortie softmax avec l'entropie croisée catégorielle :
+ La couche de sortie s'adapte à la tâche, en réutilisant les pertes de [Classification linéaire](/fr/Machine%20Learning/05%20Linear%20classification). Pour deux classes, une sortie sigmoïde avec l'entropie croisée binaire, et pour $k$ classes, une sortie softmax avec l'entropie croisée catégorielle :
$$\boxed{ \hat{y} = \frac{1}{1 + e^{-z}} \quad\text{(binaire)} \qquad \hat{y}_c = \frac{e^{z_c}}{\sum_{j} e^{z_j}} \quad\text{(multiclasse)} }$$
- ## 8.4 Fonctions d'activation et le problème du non-centrage en zéro
+ ## 6.4 Fonctions d'activation et le problème du non-centrage en zéro
L'activation cachée est généralement la sigmoïde, la tangente hyperbolique ou l'unité de rectification linéaire :
@@ 46,28 46,28 @@
La sigmoïde sature dans ses queues, et ses sorties ne sont jamais négatives, donc les poids entrants d'une unité reçoivent des gradients de même signe et les mises à jour zigzaguent. La $\tanh$, centrée en zéro, supprime ce biais, et ReLU évite complètement la saturation du côté positif, ce qui en fait le choix par défaut courant.
- ![Fonctions d'activation](/fr/Machine%20Learning/08%20Multilayer%20neural%20networks/a/activations.png)
+ ![Fonctions d'activation](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks/a/activations.png)
*La tanh est centrée en zéro alors que la sigmoïde ne l'est pas, et ReLU reste linéaire pour les entrées positives.*
- ## 8.5 Règle de dérivation en chaîne et rétropropagation
+ ## 6.5 Règle de dérivation en chaîne et rétropropagation
L'entraînement minimise la perte par descente de gradient, qui a besoin de son gradient par rapport à chaque poids. La rétropropagation les calcule tous en une passe avant et une passe arrière : la passe avant met en cache chaque $z^{[l]}$ et $a^{[l]}$, puis la passe arrière applique la règle de dérivation en chaîne de la perte jusqu'à la première couche, en réutilisant le cache. Avec l'erreur de couche $\delta^{[l]} = \partial L / \partial z^{[l]}$,
$$\boxed{ \delta^{[l]} = \left((W^{[l+1]})^T \delta^{[l+1]}\right) \odot g'^{[l]}\!\left(z^{[l]}\right), \qquad \frac{\partial L}{\partial W^{[l]}} = \delta^{[l]} (a^{[l-1]})^T }$$
- ![Passes avant et arrière](/fr/Machine%20Learning/08%20Multilayer%20neural%20networks/a/backprop.svg)
+ ![Passes avant et arrière](/fr/Machine%20Learning/06%20Multilayer%20neural%20networks/a/backprop.svg)
*La leçon [Rétropropagation](/fr/Deep%20Learning/05%20Backpropagation) du cours de Deep Learning la dérive pas à pas.*
- ## 8.6 L'entraînement en pratique
+ ## 6.6 L'entraînement en pratique
- **Mini-lots.** Estimer le gradient sur un petit lot d'exemples à la fois, un compromis entre le lot complet (précis mais lent) et un seul exemple (bruité mais peu coûteux).
- **Disparition du gradient.** À travers de nombreuses couches qui saturent, le gradient rétropropagé est un produit de petits facteurs et tend vers zéro, si bien que les premières couches n'apprennent presque pas. Les activations ReLU et une initialisation soignée le maintiennent vivant.
- **Initialisation.** Démarrer les poids petits et aléatoires pour briser la symétrie, en mettant la variance à l'échelle du nombre d'entrées (Xavier ou He), pour que les signaux ne s'évanouissent ni n'explosent avec la profondeur.
- - **Dropout.** Mettre à zéro au hasard une fraction des unités pendant l'entraînement. Cela empêche les unités de se co-adapter et agit comme un régulariseur, dans l'esprit du [module de régularisation](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference).
+ - **Dropout.** Mettre à zéro au hasard une fraction des unités pendant l'entraînement. Cela empêche les unités de se co-adapter et agit comme un régulariseur, dans l'esprit de la régularisation de [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts).
- ## 8.7 Tests de validité et vectorisation
+ ## 6.7 Tests de validité et vectorisation
La rétropropagation est source d'erreurs, alors on compare le gradient analytique à une estimation numérique par différences finies :
@@ 80,4 80,4 @@
*Ce module est la porte d'entrée du cours de [Deep Learning](/fr/Deep%20Learning), qui développe pleinement les architectures, les optimiseurs, l'initialisation, la normalisation et la régularisation. Le module suivant revient aux modèles linéaires sous un nouvel angle, le classifieur à marge maximale.*
---
- Suivant : [Machines à vecteurs de support](/fr/Machine%20Learning/09%20Support%20Vector%20Machines) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
+ Suivant : [Machines à vecteurs de support](/fr/Machine%20Learning/07%20Support%20Vector%20Machines) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/08 Multilayer neural networks/activations.png .. fr/Machine Learning/06 Multilayer neural networks/activations.png
fr/Machine Learning/08 Multilayer neural networks/backprop.svg .. fr/Machine Learning/06 Multilayer neural networks/backprop.svg
fr/Machine Learning/08 Multilayer neural networks/mlp-layers.svg .. fr/Machine Learning/06 Multilayer neural networks/mlp-layers.svg
fr/Machine Learning/07 Regularization and high-dimensional inference.md .. /dev/null
@@ 1,75 0,0 @@
- # 7. Régularisation et inférence en grande dimension
-
- On n'a souvent pas une poignée de régresseurs propres. Il peut y avoir de nombreux prédicteurs candidats, parfois plus que d'observations, et ils sont corrélés. Les moindres carrés ordinaires surapprennent ou s'effondrent dans ce régime. La régularisation les dompte en rétrécissant les coefficients, et c'est là que la régression régularisée rejoint le plus directement la statistique classique. Elle s'accompagne d'un avertissement : sélectionner des variables puis faire de l'inférence sur les mêmes données invalide les écarts-types classiques, ce qui compte dès que l'objectif est une estimation causale plutôt qu'une prédiction.
-
- Dans tout ce module, on note les coefficients de régression $\beta$, les paramètres $\theta$ du modèle linéaire du [module de régression linéaire](/fr/Machine%20Learning/05%20Linear%20regression).
-
- **Objectifs**
- - Voir pourquoi les moindres carrés ordinaires échouent avec de nombreux régresseurs corrélés.
- - Définir la régression ridge (L2) et lasso (L1) et le rôle de la pénalité $\lambda$.
- - Comprendre pourquoi le lasso produit des solutions parcimonieuses qui sélectionnent les variables.
- - Choisir la pénalité $\lambda$ par validation croisée.
- - Reconnaître pourquoi l'inférence naïve après sélection est invalide, et connaître les corrections standard.
-
- ## 7.1 Pourquoi régulariser
-
- Quand le nombre de régresseurs $p$ est grand par rapport à la taille d'échantillon $n$, l'ajustement par moindres carrés poursuit le bruit et ses coefficients ont une variance énorme. Avec des régresseurs corrélés, la matrice $X^T X$ est presque singulière, donc de petites variations des données font osciller fortement les estimations, et quand $p > n$ elle est singulière et les MCO n'ont aucune solution unique. La régularisation accepte un peu de biais en échange d'une forte réduction de variance, le compromis vu dans [Concepts généraux](/fr/Machine%20Learning/02%20General%20concepts).
-
- ## 7.2 Régression ridge (L2)
-
- Ridge ajoute une pénalité en norme au carré sur les coefficients à l'objectif des moindres carrés :
-
- $$\boxed{ \hat{\beta}_{\text{ridge}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda \|\beta\|_2^2 }$$
-
- Elle possède une forme close toujours inversible pour $\lambda > 0$, ce qui sauve précisément les cas de colinéarité et de $p > n$ :
-
- $$\boxed{ \hat{\beta}_{\text{ridge}} = \left(X^T X + \lambda I\right)^{-1} X^T y }$$
-
- Ridge rétrécit tous les coefficients doucement vers zéro mais ne les annule jamais exactement, elle stabilise donc plutôt qu'elle ne sélectionne.
-
- ## 7.3 Régression lasso (L1)
-
- Le lasso remplace la pénalité au carré par une pénalité en valeur absolue :
-
- $$\boxed{ \hat{\beta}_{\text{lasso}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda \|\beta\|_1 }$$
-
- Ce petit changement a une grande conséquence : le lasso met certains coefficients exactement à zéro, il effectue donc une sélection de variables tout en ajustant. La raison est géométrique. La région de contrainte $\|\beta\|_1 \le t$ est un losange dont les coins sont sur les axes, et les contours elliptiques de la perte tendent à la toucher d'abord en un coin, où une coordonnée est nulle.
-
- ![Géométrie des contraintes L1 et L2](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference/a/l1-l2-geometry.png)
-
- *La boule L2 arrondie est touchée hors des axes, gardant chaque coefficient non nul, tandis que le losange L1 est touché en un coin, mettant un coefficient exactement à zéro.*
-
- À mesure que la pénalité grandit, davantage de coefficients passent à zéro, traçant le chemin de régularisation du modèle complet jusqu'au modèle vide.
-
- ![Chemin de régularisation du lasso](/fr/Machine%20Learning/07%20Regularization%20and%20high-dimensional%20inference/a/regularization-path.png)
-
- *Chaque coefficient rétrécit quand $\lambda$ augmente puis atteint exactement zéro, si bien que le lasso fournit un sous-ensemble compact et interprétable de régresseurs.*
-
- ## 7.4 Elastic net
-
- L'elastic net mêle les deux pénalités, gardant la sélection du lasso tout en empruntant la stabilité de ridge face aux régresseurs corrélés :
-
- $$\boxed{ \hat{\beta}_{\text{en}} = \arg\min_{\beta} \; \|y - X\beta\|_2^2 + \lambda\left(\alpha \|\beta\|_1 + (1 - \alpha)\|\beta\|_2^2\right) }$$
-
- avec $\alpha \in [0, 1]$ dosant la sélection ($\alpha = 1$, lasso) et le rétrécissement ($\alpha = 0$, ridge).
-
- ## 7.5 Choisir la pénalité
-
- La pénalité $\lambda$ est un hyperparamètre, on la choisit donc par validation croisée, vue au [module précédent](/fr/Machine%20Learning/03%20Model%20evaluation%20and%20validation) : on ajuste sur une grille de valeurs de $\lambda$ et on garde celle dont l'erreur validée est la plus faible, ou le plus grand $\lambda$ à un écart-type du meilleur pour un modèle plus simple. Un $\lambda$ plus grand signifie plus de rétrécissement, plus de biais et moins de variance.
-
- ## 7.6 La mise en garde sur l'inférence
-
- Prédire n'est pas inférer, et c'est le point qu'il est facile de manquer. Supposons que vous sélectionniez des régresseurs par lasso, puis que vous fassiez des moindres carrés ordinaires sur le sous-ensemble retenu en rapportant les écarts-types des manuels. Ces écarts-types sont faux. Ils ignorent que les données ont déjà servi à choisir les variables, donc les intervalles de confiance sont trop étroits et les p-valeurs ne sont pas valides, une forme de la malédiction du vainqueur. Trois corrections sont standard :
-
- - **Division de l'échantillon.** Sélectionner les variables sur une partie des données et estimer puis inférer sur une autre, pour que la sélection ne contamine pas les écarts-types.
- - **Lasso débiaisé (dé-parcimonisé).** Ajouter un terme de correction à l'estimation lasso qui retire le biais de rétrécissement et rétablit un intervalle de confiance asymptotiquement valide pour chaque coefficient.
- - **Post-double-sélection** (Belloni, Chernozhukov et Hansen). Pour estimer l'effet d'un traitement avec de nombreux contrôles, sélectionner les contrôles qui prédisent le résultat et ceux qui prédisent le traitement, puis estimer l'effet sur l'union des deux ensembles.
-
- $$\boxed{ \text{sélectionner pour prédire} \;\ne\; \text{inférence valide sur un coefficient} }$$
-
- *Remarque :* ces idées ouvrent la porte du machine learning causal, où des apprenants flexibles estiment des fonctions de nuisance tandis qu'une correction préserve une inférence valide sur le paramètre d'intérêt. La régularisation est excellente pour prédire, mais pour un paramètre causal il faut l'une de ces corrections, pas les coefficients pénalisés bruts.
-
- *Une fois le rétrécissement et la sélection couverts, le module suivant empile ces briques linéaires en réseaux de neurones multi-couches.*
-
- ---
- Suivant : [Réseaux de neurones multi-couches](/fr/Machine%20Learning/08%20Multilayer%20neural%20networks) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/09 Support Vector Machines.md .. fr/Machine Learning/07 Support Vector Machines.md
@@ 1,4 1,4 @@
- # 9. Machines à vecteurs de support
+ # 7. Machines à vecteurs de support
Les machines à vecteurs de support sont des classifieurs linéaires à grande marge. Elles
choisissent la frontière qui maximise la distance aux points les plus proches, contrôlent le
@@ 12,11 12,11 @@
- Définir les noyaux, l'astuce du noyau et la condition de Mercer.
- Former le lagrangien, dériver le dual et les conditions KKT, et définir les vecteurs de support.
- ## 9.1 Classifieur à marge optimale
+ ## 7.1 Classifieur à marge optimale
Les étiquettes valent $y \in \{-1,+1\}$, avec un vecteur de poids $w \in \mathbb{R}^{n}$ et un biais $b$.
- ### 9.1.1 Hypothèse et frontière
+ ### 7.1.1 Hypothèse et frontière
L'hypothèse est définie comme le signe du score brut $z = w^T x - b$ :
@@ 28,7 28,7 @@
*Remarque :* $w$ est orthogonal à la frontière, il en fixe donc l'orientation, et $b$ fixe le décalage.
- ### 9.1.2 Marge géométrique
+ ### 7.1.2 Marge géométrique
La marge géométrique de l'exemple $i$ est définie comme sa distance signée à la frontière, rendue
positive par l'étiquette :
@@ 41,7 41,7 @@
*Remarque :* diviser par $\lVert w \rVert$ rend la marge invariante au rééchelonnement de $(w,b)$,
contrairement au score brut $z$.
- ### 9.1.3 Primal à marge dure
+ ### 7.1.3 Primal à marge dure
En fixant l'échelle pour que les points les plus proches vérifient $y^{(i)}(w^T x^{(i)} - b) = 1$,
maximiser la marge équivaut à minimiser $\lVert w \rVert^2$ sous une marge fonctionnelle unitaire :
@@ 53,15 53,15 @@
*Remarque :* il exige des données linéairement séparables. La leçon suivante assouplit cela avec
des variables d'écart.
- ![Marge SVM et vecteurs de support](/fr/Machine%20Learning/09%20Support%20Vector%20Machines/a/svm-margin.png)
+ ![Marge SVM et vecteurs de support](/fr/Machine%20Learning/07%20Support%20Vector%20Machines/a/svm-margin.png)
*L'hyperplan optimal (trait plein) maximise la marge (pointillés). Les points entourés sont les vecteurs de support.*
- ## 9.2 Perte charnière
+ ## 7.2 Perte charnière
Le score brut est $z = w^T x - b$ et les étiquettes valent $y \in \{-1,+1\}$.
- ### 9.2.1 Perte charnière
+ ### 7.2.1 Perte charnière
La perte charnière est définie comme l'écart par lequel la marge $yz$ tombe sous $1$, tronqué à zéro :
@@ 73,7 73,7 @@
*Remarque :* la perte charnière est convexe mais non dérivable en $yz = 1$, on l'optimise donc
avec des sous-gradients.
- ### 9.2.2 Primal à marge souple
+ ### 7.2.2 Primal à marge souple
On introduit un écart $\xi_i \ge 0$ par exemple pour autoriser les violations de marge, pénalisé
par $C > 0$ :
@@ 88,7 88,7 @@
C'est de la régularisation plus une perte charnière : le terme $\tfrac{1}{2}\lVert w \rVert^2$
élargit la marge et la somme pénalise les violations.
- ### 9.2.3 Rôle de $C$
+ ### 7.2.3 Rôle de $C$
| $C$ | Pénalité des violations | Marge | Comportement |
| --- | --- | --- | --- |
@@ 98,9 98,9 @@
*Remarque :* quand $C \to \infty$ aucune violation n'est tolérée, ce qui redonne le classifieur à
marge dure.
- ## 9.3 Noyaux
+ ## 7.3 Noyaux
- ### 9.3.1 Définition d'un noyau
+ ### 7.3.1 Définition d'un noyau
Un noyau est défini comme le produit scalaire d'une application de caractéristiques $\phi$
appliquée à deux entrées :
@@ 110,7 110,7 @@
Un noyau valide calcule ce produit scalaire directement, donc $\phi$ n'a jamais à être formée
(elle peut même être de dimension infinie).
- ### 9.3.2 Astuce du noyau
+ ### 7.3.2 Astuce du noyau
Le dual du SVM ne dépend des données qu'à travers des produits scalaires
$\langle x^{(i)}, x^{(j)} \rangle$. L'astuce du noyau remplace chaque produit scalaire par un noyau :
@@ 124,7 124,7 @@
$$\boxed{ K(x,z) = \exp\!\left( -\frac{\lVert x - z \rVert^2}{2\sigma^2} \right) }$$
- ### 9.3.3 Condition de Mercer
+ ### 7.3.3 Condition de Mercer
Une fonction $K$ est un noyau valide si et seulement si, pour tout échantillon fini, sa matrice de
Gram est symétrique semi-définie positive :
@@ 134,7 134,7 @@
*Remarque :* c'est la condition de Mercer. Elle garantit l'existence d'une application $\phi$, donc
le dual reste convexe.
- ### 9.3.4 Noyaux usuels
+ ### 7.3.4 Noyaux usuels
| Noyau | $K(x,z)$ | Note |
| --- | --- | --- |
@@ 145,13 145,13 @@
*Remarque :* un petit $\sigma$ rend le noyau RBF très local, ce qui peut surapprendre. Il se règle
en compromis avec $C$.
- ![Frontière de décision avec noyau RBF](/fr/Machine%20Learning/09%20Support%20Vector%20Machines/a/svm-kernel.png)
+ ![Frontière de décision avec noyau RBF](/fr/Machine%20Learning/07%20Support%20Vector%20Machines/a/svm-kernel.png)
*Un noyau RBF sépare des classes non linéairement séparables, par une frontière non linéaire dans l'espace d'entrée.*
- ## 9.4 Lagrangien et dualité
+ ## 7.4 Lagrangien et dualité
- ### 9.4.1 Lagrangien
+ ### 7.4.1 Lagrangien
Pour un objectif primal $f(w)$ avec contraintes d'inégalité $g_i(w) \le 0$ et multiplicateurs
$\beta_i \ge 0$, le lagrangien est défini comme :
@@ 167,16 167,16 @@
Le $w$ optimal est donc une combinaison linéaire des entrées d'apprentissage pondérées par
$\beta_i y^{(i)}$.
- ### 9.4.2 Problème dual
+ ### 7.4.2 Problème dual
En réinjectant ces relations, on élimine $w$ et $b$, ce qui laisse un problème en $\beta$ ne
dépendant des données qu'à travers des produits scalaires :
$$\boxed{ \max_{\beta} \ \sum_{i=1}^{m}\beta_i - \tfrac{1}{2}\sum_{i,j}\beta_i \beta_j\, y^{(i)} y^{(j)} \langle x^{(i)}, x^{(j)} \rangle \quad \text{s.c.} \quad \beta_i \ge 0, \ \ \sum_{i}\beta_i y^{(i)} = 0 }$$
- Les produits scalaires sont exactement l'endroit où l'on substitue un noyau $K$ (voir [Noyaux](/fr/Machine%20Learning/09%20Support%20Vector%20Machines#93-noyaux)).
+ Les produits scalaires sont exactement l'endroit où l'on substitue un noyau $K$ (voir [Noyaux](/fr/Machine%20Learning/07%20Support%20Vector%20Machines#73-noyaux)).
- ### 9.4.3 KKT et vecteurs de support
+ ### 7.4.3 KKT et vecteurs de support
À l'optimum, l'écart complémentaire lie chaque multiplicateur à sa contrainte :
@@ 189,7 189,7 @@
Ce sont les points exactement sur la marge. Tous les autres ont $\beta_i = 0$ et n'influencent pas
$w$.
- ### 9.4.4 Décision à noyau
+ ### 7.4.4 Décision à noyau
Remplacer le produit scalaire par un noyau donne une règle de décision exprimée uniquement à
travers les vecteurs de support :
@@ 199,7 199,7 @@
*Remarque :* seuls les vecteurs de support ($\beta_i > 0$) contribuent, donc le coût de prédiction
croît avec leur nombre, pas avec $m$.
- ### 9.4.5 Du primal à la décision
+ ### 7.4.5 Du primal à la décision
```mermaid
flowchart TD
@@ 219,4 219,4 @@
*Les machines à vecteurs de support tracent une seule frontière, éventuellement à noyau. La dernière partie suit une autre voie : découper l'espace des variables par des règles simples et combiner de nombreux modèles en un ensemble.*
---
- Suivant : [Arbres de décision et méthodes d'ensemble](/fr/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
+ Suivant : [Arbres de décision et méthodes d'ensemble](/fr/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods) · [Vue d'ensemble du cours](/fr/Machine%20Learning)
fr/Machine Learning/09 Support Vector Machines/svm-kernel.png .. fr/Machine Learning/07 Support Vector Machines/svm-kernel.png
fr/Machine Learning/09 Support Vector Machines/svm-margin.png .. fr/Machine Learning/07 Support Vector Machines/svm-margin.png
fr/Machine Learning/10 Decision trees and ensemble methods.md .. fr/Machine Learning/08 Decision trees and ensemble methods.md
@@ 1,4 1,4 @@
- # 10. Arbres de décision et méthodes d'ensemble
+ # 8. Arbres de décision et méthodes d'ensemble
Les modèles d'arbre partitionnent l'espace d'entrée en régions alignées sur les axes et ajustent une constante par région, ce qui donne des prédicteurs interprétables mais à forte variance. Les méthodes d'ensemble combinent plusieurs arbres : le bagging et les forêts aléatoires moyennent des arbres construits indépendamment pour réduire la variance, tandis que le boosting construit les arbres de façon séquentielle pour réduire le biais.
@@ 9,9 9,9 @@
- Estimer gratuitement l'erreur de généralisation avec les échantillons hors-sac.
- Construire un prédicteur fort comme somme additive d'apprenants faibles (AdaBoost, gradient boosting).
- ## 10.1 Arbres de décision CART
+ ## 8.1 Arbres de décision CART
- ### 10.1.1 L'arbre comme partition
+ ### 8.1.1 L'arbre comme partition
Un arbre CART partitionne l'espace d'entrée en $M$ régions disjointes $R_1,\dots,R_M$ (les feuilles) et prédit une constante $c_m$ sur chacune. La prédiction est définie par
@@ 21,7 21,7 @@
*Remarque :* les régions sont des boîtes alignées sur les axes, donc la frontière de décision est en escalier. Un arbre seul a un faible biais mais une forte variance.
- ### 10.1.2 Impureté et choix de la coupure
+ ### 8.1.2 Impureté et choix de la coupure
Pour une région de proportions de classes $\hat p_k$, l'impureté mesure le mélange des étiquettes. L'indice de Gini est défini par
@@ 44,7 44,7 @@
*Remarque :* les deux critères choisissent presque toujours la même coupure. Gini est le défaut de la plupart des implémentations car il évite le logarithme.
- ### 10.1.3 Arbres de régression
+ ### 8.1.3 Arbres de régression
En régression, la valeur de la feuille est la moyenne des cibles dans la région, définie par
@@ 52,7 52,7 @@
et les coupures minimisent l'erreur quadratique intra-région plutôt qu'une impureté de classification.
- ### 10.1.4 Élagage
+ ### 8.1.4 Élagage
Un arbre non élagué ajuste exactement l'ensemble d'entraînement et surapprend. L'élagage à complexité coûteuse arbitre entre l'ajustement et la taille de l'arbre $|T|$ (le nombre de feuilles) via une pénalité $\alpha\ge0$ :
@@ 68,13 68,13 @@
B -->|"non"| E["feuille R2"]
```
- ![Régions d'un arbre de décision](/fr/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods/a/tree-boundary.png)
+ ![Régions d'un arbre de décision](/fr/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods/a/tree-boundary.png)
*Un arbre découpe l'espace en régions alignées sur les axes, chacune à prédiction constante.*
- ## 10.2 Forêts aléatoires
+ ## 8.2 Forêts aléatoires
- ### 10.2.1 Bagging
+ ### 8.2.1 Bagging
Le bagging (bootstrap aggregating) entraîne $B$ arbres sur $B$ rééchantillons bootstrap des données et les moyenne. Le prédicteur agrégé est défini par
@@ 84,7 84,7 @@
Un échantillon bootstrap tire $N$ exemples avec remise parmi $N$ exemples. La probabilité qu'un exemple donné ne soit jamais tiré vaut $(1-\tfrac1N)^N\to e^{-1}\approx0{,}37$, donc environ 37 % des données restent hors de chaque arbre. Ce sont ses exemples hors-sac (OOB).
- ### 10.2.2 Variance d'une moyenne
+ ### 8.2.2 Variance d'une moyenne
Si les $B$ arbres ont chacun une variance $\sigma^2$ et une corrélation deux à deux $\rho$, la variance de leur moyenne vaut
@@ 92,7 92,7 @@
Le second terme s'annule quand $B$ croît, mais le premier, $\rho\sigma^2$, persiste. Réduire la corrélation $\rho$ entre les arbres est donc le levier clé, et c'est précisément ce que visent les forêts aléatoires.
- ### 10.2.3 Forêts aléatoires
+ ### 8.2.3 Forêts aléatoires
Une forêt aléatoire est du bagging avec sous-échantillonnage des variables : à chaque coupure, seul un sous-ensemble aléatoire de $m_{\text{try}}$ variables est considéré comme candidat. Les choix usuels sont
@@ 122,13 122,13 @@
T3 --> AGG
```
- ![Arbre seul et forêt aléatoire](/fr/Machine%20Learning/10%20Decision%20trees%20and%20ensemble%20methods/a/forest-vs-tree.png)
+ ![Arbre seul et forêt aléatoire](/fr/Machine%20Learning/08%20Decision%20trees%20and%20ensemble%20methods/a/forest-vs-tree.png)
*(a) Un arbre profond seul surajuste avec une frontière en escalier. (b) Une forêt aléatoire moyenne de nombreux arbres pour une frontière plus lisse.*
- ## 10.3 Boosting
+ ## 8.3 Boosting
- ### 10.3.1 Modèle additif
+ ### 8.3.1 Modèle additif
Le boosting construit un prédicteur comme une somme pondérée de $T$ apprenants faibles $h_t$ (typiquement des arbres peu profonds), ajustés un à un. Le modèle additif est défini par
@@ 136,7 136,7 @@
Chaque étape corrige les erreurs de la somme courante, donc l'ensemble est construit de façon séquentielle et réduit le biais plutôt que la variance.
- ### 10.3.2 AdaBoost
+ ### 8.3.2 AdaBoost
Avec des étiquettes $y\in\{-1,+1\}$, AdaBoost conserve des poids d'exemples $w^{(i)}$ qui se concentrent sur les points actuellement mal classés. Au tour $t$, l'apprenant faible a une erreur pondérée $\varepsilon_t$, et son coefficient est défini par
@@ 148,7 148,7 @@
puis renormalisés. Les exemples mal classés ($y^{(i)}h_t(x^{(i)})<0$) gagnent du poids, donc l'apprenant suivant se concentre sur eux.
- ### 10.3.3 Gradient boosting
+ ### 8.3.3 Gradient boosting
Le gradient boosting généralise l'idée à toute perte différentiable $L$. À l'étape $t$, il ajuste l'apprenant suivant sur l'opposé du gradient de la perte évalué au modèle courant, le pseudo-résidu défini par
fr/Machine Learning/10 Decision trees and ensemble methods/forest-vs-tree.png .. fr/Machine Learning/08 Decision trees and ensemble methods/forest-vs-tree.png
fr/Machine Learning/10 Decision trees and ensemble methods/tree-boundary.png .. fr/Machine Learning/08 Decision trees and ensemble methods/tree-boundary.png
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9