SPB Git

Repository Public

neural-network-backprop.ts 35.0 KB 356 lines typescript

1import type { TemplateDef } from "../types";2import { T, pickSources } from "./shared";34const r = String.raw;56/**7 * Gradient descent on L(w) = w² from w₀ = 1: w_{t+1} = w_t − η·2w_t = (1 − 2η)·w_t, so L_t = (1 − 2η)^{2t}.8 * Exact values, rounded to 4 decimals, for t = 0…10.9 */10const lossCurve = (eta: number) => Array.from({ length: 11 }, (_, step) => ({ x: step, y: Math.round((1 - 2 * eta) ** (2 * step) * 1e4) / 1e4 }));1112const CODE = `import numpy as np1314rng = np.random.default_rng(0)15X = np.array([[0., 0.], [0., 1.], [1., 0.], [1., 1.]])   # 4 examples, 2 features16Y = np.array([[0.], [1.], [1.], [0.]])                   # targets: XOR1718W1, b1 = rng.normal(size=(2, 3)), np.zeros(3)            # layer 1: 2 -> 319W2, b2 = rng.normal(size=(3, 1)), np.zeros(1)            # layer 2: 3 -> 120sigmoid = lambda z: 1 / (1 + np.exp(-z))21eta = 0.5                                                # learning rate2223for step in range(5000):24    # 1. forward pass25    A1 = sigmoid(X @ W1 + b1)26    Yhat = sigmoid(A1 @ W2 + b2)27    loss = 0.5 * np.mean(np.sum((Yhat - Y) ** 2, axis=1))2829    # 2. backward pass (chain rule, from the output to the input)30    D2 = (Yhat - Y) * Yhat * (1 - Yhat) / len(X)         # delta of layer 231    D1 = (D2 @ W2.T) * A1 * (1 - A1)                     # delta of layer 13233    # 3. gradient descent update34    W2 -= eta * A1.T @ D235    b2 -= eta * D2.sum(axis=0)36    W1 -= eta * X.T @ D137    b1 -= eta * D1.sum(axis=0)`;3839export const neuralNetworkBackprop: TemplateDef = {40  id: "neural-network-backprop",41  category: "ai",42  title: { fr: "Réseau de neurones et rétropropagation", en: "Neural network and backpropagation" },43  description: {44    fr: "Passe avant, fonction de perte, règle de la chaîne et descente de gradient : comment un réseau calcule, mesure son erreur et se corrige.",45    en: "Forward pass, loss function, chain rule and gradient descent: how a network computes, measures its error and corrects itself.",46  },47  build: (locale) => {48    const t = T(locale);49    return {50      schemaVersion: 1,51      metadata: {52        title: t("Réseau de neurones et rétropropagation", "Neural networks and backpropagation"),53        slug: t("reseau-de-neurones-retropropagation", "neural-network-backpropagation"),54        locale,55        summary: t(56          "Un réseau de neurones apprend en répétant quatre gestes : calculer une sortie, mesurer l'erreur, remonter cette erreur couche par couche grâce à la règle de la chaîne, puis ajuster chaque poids dans le sens qui la réduit.",57          "A neural network learns by repeating four moves: compute an output, measure the error, carry that error back layer by layer with the chain rule, then nudge every weight in the direction that reduces it.",58        ),59        topics: [t("IA", "AI"), t("Apprentissage profond", "Deep Learning")],60        tags: [t("rétropropagation", "backpropagation"), t("descente de gradient", "gradient descent"), t("règle de la chaîne", "chain rule"), t("perceptron multicouche", "multilayer perceptron"), t("fonction de perte", "loss function")],61        level: "beginner",62        kind: "explainer",63        objectives: [64          t("Calculer la passe avant d'un petit réseau, couche par couche.", "Compute the forward pass of a small network, layer by layer."),65          t("Écrire les équations de la rétropropagation et dire d'où vient chaque facteur.", "Write the backpropagation equations and say where each factor comes from."),66          t("Appliquer la mise à jour par descente de gradient et expliquer le rôle du taux d'apprentissage.", "Apply the gradient descent update and explain the role of the learning rate."),67        ],68        example: true,69      },70      theme: { preset: "scientific-light", accent: "blue" },71      blocks: [72        { id: "h-title", type: "heading", level: 1, eyebrow: t("Fondements · Apprentissage profond", "Foundations · Deep Learning"), text: t("Réseau de neurones et rétropropagation", "Neural networks and backpropagation") },73        {74          id: "intro-lead", type: "paragraph", lead: true,75          text: t(76            "Un réseau de neurones est une fonction composée de couches simples, réglée par des millions de nombres appelés **poids**. L'entraîner, c'est trouver des poids qui rendent ses sorties proches des réponses attendues. La rétropropagation est la procédure qui indique, pour chaque poids, dans quel sens et de combien le modifier pour réduire l'erreur[^rumelhart1986].",77            "A neural network is a function made of simple layers, tuned by millions of numbers called **weights**. Training it means finding weights that bring its outputs close to the expected answers. Backpropagation is the procedure that tells, for every weight, in which direction and by how much to change it in order to reduce the error[^rumelhart1986].",78          ),79        },80        {81          id: "st-loop", type: "steps",82          items: [83            { icon: "arrows", title: t("Passe avant", "Forward pass"), text: t("L'entrée traverse le réseau, couche après couche, jusqu'à la sortie $\\hat{y}$.", "The input goes through the network, layer after layer, up to the output $\\hat{y}$.") },84            { icon: "target", title: t("Perte", "Loss"), text: t("Un nombre $\\mathcal{L}$ mesure l'écart entre la sortie $\\hat{y}$ et la cible $y$.", "A number $\\mathcal{L}$ measures the gap between the output $\\hat{y}$ and the target $y$.") },85            { icon: "sigma", title: t("Passe arrière", "Backward pass"), text: t("La règle de la chaîne donne la dérivée de $\\mathcal{L}$ par rapport à chaque poids, de la sortie vers l'entrée.", "The chain rule gives the derivative of $\\mathcal{L}$ with respect to every weight, from the output back to the input.") },86            { icon: "trend", title: t("Mise à jour", "Update"), text: t("Chaque poids fait un petit pas dans le sens opposé à sa dérivée. Puis on recommence.", "Every weight takes a small step in the direction opposite to its derivative. Then it all starts again.") },87          ],88        },8990        { id: "h-network", type: "heading", level: 2, text: t("Le réseau, vu d'ensemble", "The network at a glance") },91        {92          id: "d-network", type: "diagram", span: 8, kind: "graph", direction: "LR", routing: "straight",93          title: t("Un réseau à une couche cachée : le signal avance, le gradient recule", "A one-hidden-layer network: the signal goes forward, the gradient goes back"),94          caption: t(95            "Deux entrées, trois neurones cachés, une sortie. Chaque flèche pleine porte un poids ; les flèches pointillées montrent le trajet du gradient.",96            "Two inputs, three hidden neurons, one output. Every solid arrow carries a weight; dashed arrows show the path of the gradient.",97          ),98          alt: t(99            "Schéma d'un réseau de neurones. À gauche, deux entrées x1 et x2 ; au centre, trois neurones cachés h1, h2 et h3, chacun relié aux deux entrées ; à droite, un neurone de sortie relié aux trois neurones cachés. La sortie et la cible y alimentent un nœud de perte L. Des flèches pointillées rouges partent de la perte vers la sortie, puis de la sortie vers chaque neurone caché : c'est le gradient qui remonte. Un dernier nœud représente la mise à jour des poids.",100            "Diagram of a neural network. On the left, two inputs x1 and x2; in the middle, three hidden neurons h1, h2 and h3, each connected to both inputs; on the right, one output neuron connected to the three hidden neurons. The output and the target y feed a loss node L. Red dashed arrows run from the loss to the output, then from the output to each hidden neuron: this is the gradient flowing back. A last node represents the weight update.",101          ),102          groups: [103            { id: "g-input", label: t("Entrée", "Input"), tone: "neutral" },104            { id: "g-hidden", label: t("Couche cachée", "Hidden layer"), tone: "blue" },105            { id: "g-output", label: t("Sortie", "Output"), tone: "green" },106          ],107          nodes: [108            { id: "n-x1", label: "x₁", shape: "circle", tone: "neutral", group: "g-input" },109            { id: "n-x2", label: "x₂", shape: "circle", tone: "neutral", group: "g-input" },110            { id: "n-h1", label: "h₁", shape: "circle", tone: "blue", group: "g-hidden" },111            { id: "n-h2", label: "h₂", shape: "circle", tone: "blue", group: "g-hidden" },112            { id: "n-h3", label: "h₃", shape: "circle", tone: "blue", group: "g-hidden" },113            { id: "n-yhat", label: "ŷ", sublabel: t("prédiction", "prediction"), shape: "circle", tone: "green", group: "g-output" },114            { id: "n-target", label: "y", sublabel: t("cible", "target"), shape: "pill", tone: "neutral" },115            { id: "n-loss", label: t("Perte L", "Loss L"), sublabel: t("écart entre ŷ et y", "gap between ŷ and y"), shape: "hexagon", tone: "red", icon: "target" },116            { id: "n-update", label: t("Mise à jour des poids", "Weight update"), sublabel: "θ ← θ − η ∇L", shape: "rect", tone: "amber", icon: "gear" },117          ],118          edges: [119            { id: "e-x1-h1", from: "n-x1", to: "n-h1", tone: "blue" },120            { id: "e-x1-h2", from: "n-x1", to: "n-h2", tone: "blue" },121            { id: "e-x1-h3", from: "n-x1", to: "n-h3", tone: "blue" },122            { id: "e-x2-h1", from: "n-x2", to: "n-h1", tone: "blue" },123            { id: "e-x2-h2", from: "n-x2", to: "n-h2", tone: "blue" },124            { id: "e-x2-h3", from: "n-x2", to: "n-h3", tone: "blue" },125            { id: "e-h1-y", from: "n-h1", to: "n-yhat", tone: "blue" },126            { id: "e-h2-y", from: "n-h2", to: "n-yhat", tone: "blue" },127            { id: "e-h3-y", from: "n-h3", to: "n-yhat", tone: "blue" },128            { id: "e-y-loss", from: "n-yhat", to: "n-loss", tone: "neutral" },129            { id: "e-target-loss", from: "n-target", to: "n-loss", tone: "neutral" },130            { id: "e-back-y", from: "n-loss", to: "n-yhat", tone: "red", style: "dashed", label: "∂L/∂ŷ" },131            { id: "e-back-h1", from: "n-yhat", to: "n-h1", tone: "red", style: "dashed" },132            { id: "e-back-h2", from: "n-yhat", to: "n-h2", tone: "red", style: "dashed", label: "δ" },133            { id: "e-back-h3", from: "n-yhat", to: "n-h3", tone: "red", style: "dashed" },134            { id: "e-loss-update", from: "n-loss", to: "n-update", tone: "amber", style: "dotted", label: t("gradients", "gradients") },135          ],136          legend: [137            { label: t("Passe avant : chaque flèche porte un poids", "Forward pass: every arrow carries a weight"), tone: "blue", shape: "arrow" },138            { label: t("Passe arrière : le gradient remonte", "Backward pass: the gradient flows back"), tone: "red", shape: "dashed" },139            { label: t("Neurone caché", "Hidden neuron"), tone: "blue", shape: "circle" },140            { label: t("Sortie du réseau", "Network output"), tone: "green", shape: "circle" },141            { label: t("Mise à jour par descente de gradient", "Gradient descent update"), tone: "amber", shape: "square" },142          ],143          animation: {144            steps: [145              { title: t("1. De l'entrée à la couche cachée", "1. From the input to the hidden layer"), text: t("Chaque neurone caché calcule une somme pondérée des entrées, ajoute un biais, puis applique une fonction d'activation.", "Each hidden neuron computes a weighted sum of the inputs, adds a bias, then applies an activation function."), nodes: ["n-x1", "n-x2", "n-h1", "n-h2", "n-h3"], edges: ["e-x1-h1", "e-x1-h2", "e-x1-h3", "e-x2-h1", "e-x2-h2", "e-x2-h3"] },146              { title: t("2. De la couche cachée à la sortie", "2. From the hidden layer to the output"), text: t("Le neurone de sortie fait de même à partir des trois activations cachées.", "The output neuron does the same from the three hidden activations."), nodes: ["n-h1", "n-h2", "n-h3", "n-yhat"], edges: ["e-h1-y", "e-h2-y", "e-h3-y"] },147              { title: t("3. Mesurer l'erreur", "3. Measure the error"), text: t("La perte compare la prédiction à la cible et renvoie un seul nombre.", "The loss compares the prediction with the target and returns a single number."), nodes: ["n-yhat", "n-target", "n-loss"], edges: ["e-y-loss", "e-target-loss"] },148              { title: t("4. Le gradient atteint la sortie", "4. The gradient reaches the output"), text: t("On calcule comment la perte varie quand la sortie varie, ce qui donne le signal d'erreur de la dernière couche.", "We compute how the loss changes when the output changes, which gives the error signal of the last layer."), nodes: ["n-loss", "n-yhat"], edges: ["e-back-y"] },149              { title: t("5. Le gradient remonte à la couche cachée", "5. The gradient flows back to the hidden layer"), text: t("Chaque neurone caché reçoit une part de l'erreur, proportionnelle au poids qui le relie à la sortie.", "Each hidden neuron receives a share of the error, proportional to the weight linking it to the output."), nodes: ["n-yhat", "n-h1", "n-h2", "n-h3"], edges: ["e-back-h1", "e-back-h2", "e-back-h3"] },150              { title: t("6. Ajuster tous les poids", "6. Adjust all the weights"), text: t("Connaissant le gradient de chaque poids, on les déplace tous d'un petit pas dans le sens qui diminue la perte.", "Knowing the gradient of every weight, all are moved a small step in the direction that lowers the loss."), nodes: ["n-loss", "n-update"], edges: ["e-loss-update"] },151            ],152          },153        },154        {155          id: "c-vocab", type: "cards", span: 4, columns: 2,156          items: [157            { icon: "scale", tone: "blue", title: t("Poids et biais", "Weights and biases"), text: t("Les nombres que l'entraînement ajuste. Notés ensemble $\\theta$.", "The numbers training adjusts. Written together as $\\theta$.") },158            { icon: "function", tone: "violet", title: t("Activation", "Activation"), text: t("Fonction non linéaire appliquée après la somme pondérée. Sans elle, le réseau entier se réduirait à une seule transformation linéaire.", "A non-linear function applied after the weighted sum. Without it the whole network would collapse into a single linear map.") },159            { icon: "target", tone: "red", title: t("Perte", "Loss"), text: t("Mesure de l'erreur à minimiser.", "The measure of error to be minimised.") },160            { icon: "trend", tone: "amber", title: t("Gradient", "Gradient"), text: t("Vecteur des dérivées de la perte par rapport à tous les poids.", "The vector of derivatives of the loss with respect to all the weights.") },161          ],162        },163164        { id: "h-forward", type: "heading", level: 2, text: t("Passe avant et perte", "Forward pass and loss") },165        {166          id: "eq-forward", type: "equation", span: 6, label: t("Passe avant, couche par couche", "Forward pass, layer by layer"), derivation: "standard",167          latex: r`z^{(l)} = W^{(l)} a^{(l-1)} + b^{(l)}, \qquad a^{(l)} = \sigma\big(z^{(l)}\big), \qquad a^{(0)} = x, \quad \hat{y} = a^{(L)}`,168          variables: [169            { symbol: "x", meaning: t("Vecteur d'entrée", "Input vector") },170            { symbol: "W^{(l)},\\, b^{(l)}", meaning: t("Matrice de poids et vecteur de biais de la couche $l$", "Weight matrix and bias vector of layer $l$") },171            { symbol: "z^{(l)}", meaning: t("Pré-activation : somme pondérée avant la non-linéarité", "Pre-activation: weighted sum before the non-linearity") },172            { symbol: "a^{(l)}", meaning: t("Activation : sortie de la couche $l$", "Activation: output of layer $l$") },173            { symbol: r`\sigma`, meaning: t("Fonction d'activation, appliquée composante par composante", "Activation function, applied component-wise") },174            { symbol: "L", meaning: t("Nombre de couches (en exposant) ; à ne pas confondre avec la perte $\\mathcal{L}$", "Number of layers (as a superscript); not to be confused with the loss $\\mathcal{L}$") },175          ],176        },177        {178          id: "eq-loss", type: "equation", span: 6, label: t("Perte quadratique", "Squared-error loss"), derivation: "standard",179          latex: r`\mathcal{L}(\theta) = \frac{1}{2}\,\big\lVert \hat{y} - y \big\rVert^{2}`,180          explanation: t(181            "La perte la plus simple, pour un seul exemple : celle de l'article fondateur de 1986[^rumelhart1986]. En classification, on utilise plutôt l'entropie croisée ; le mécanisme de la rétropropagation reste identique.",182            "The simplest loss, for a single example: the one in the founding 1986 paper[^rumelhart1986]. For classification, cross-entropy is used instead; the mechanics of backpropagation stay the same.",183          ),184          variables: [185            { symbol: r`\hat{y}`, meaning: t("Sortie du réseau", "Output of the network") },186            { symbol: "y", meaning: t("Sortie attendue (cible)", "Expected output (target)") },187            { symbol: r`\theta`, meaning: t("Ensemble des poids et des biais", "All the weights and biases") },188          ],189        },190        {191          id: "sim-forward", type: "simulation", kind: "neural-forward", seed: 5,192          params: { layers: 2, width: 3, inputs: 2, scale: 1.5 }, config: { activation: "tanh" },193          title: t("Suivre le signal à travers le réseau", "Follow the signal through the network"),194          caption: t("Simulation à but pédagogique sur un petit réseau aux poids tirés au hasard (graine fixe).", "Teaching simulation on a small network with randomly drawn weights (fixed seed)."),195          alt: t(196            "Simulation interactive d'un petit réseau de neurones : on fait avancer le calcul couche après couche et l'on voit l'activation de chaque neurone, puis la valeur de la sortie ; la taille du réseau et l'échelle des poids sont réglables.",197            "Interactive simulation of a small neural network: the computation advances layer by layer, showing the activation of every neuron and then the output value; the size of the network and the scale of the weights can be adjusted.",198          ),199        },200201        { id: "h-backward", type: "heading", level: 2, text: t("Passe arrière : la règle de la chaîne", "Backward pass: the chain rule") },202        {203          id: "co-chain", type: "callout", span: 6, tone: "definition", title: t("La règle de la chaîne", "The chain rule"),204          text: t(205            "Si $\\mathcal{L}$ dépend de $a$, qui dépend de $z$, qui dépend de $w$, alors\n\n$\\dfrac{\\partial \\mathcal{L}}{\\partial w} = \\dfrac{\\partial \\mathcal{L}}{\\partial a} \\cdot \\dfrac{\\partial a}{\\partial z} \\cdot \\dfrac{\\partial z}{\\partial w}$.\n\nLa rétropropagation n'est rien d'autre que l'application systématique de cette règle, de la sortie vers l'entrée[^lecun2015].",206            "If $\\mathcal{L}$ depends on $a$, which depends on $z$, which depends on $w$, then\n\n$\\dfrac{\\partial \\mathcal{L}}{\\partial w} = \\dfrac{\\partial \\mathcal{L}}{\\partial a} \\cdot \\dfrac{\\partial a}{\\partial z} \\cdot \\dfrac{\\partial z}{\\partial w}$.\n\nBackpropagation is nothing more than the systematic application of this rule, from the output back to the input[^lecun2015].",207          ),208        },209        {210          id: "p-reuse", type: "paragraph", span: 6,211          text: t(212            "L'astuce est de **ne rien recalculer**. On définit, pour chaque couche, un signal d'erreur $\\delta^{(l)}$ : la dérivée de la perte par rapport aux pré-activations $z^{(l)}$. Celui d'une couche s'obtient à partir de celui de la couche suivante. En partant de la sortie, une seule passe arrière suffit pour obtenir le gradient de **tous** les poids, pour un coût du même ordre que celui de la passe avant.",213            "The trick is to **recompute nothing**. For each layer we define an error signal $\\delta^{(l)}$: the derivative of the loss with respect to the pre-activations $z^{(l)}$. The signal of one layer is obtained from that of the next. Starting from the output, a single backward pass yields the gradient of **all** the weights, at a cost of the same order as the forward pass.",214          ),215        },216        {217          id: "eq-backprop", type: "equation", span: 8, label: t("Les quatre équations de la rétropropagation", "The four equations of backpropagation"), derivation: "standard", sourceIds: ["rumelhart1986"],218          latex: r`\begin{aligned} \delta^{(L)} &= \nabla_{a^{(L)}} \mathcal{L} \,\odot\, \sigma'\big(z^{(L)}\big) \\ \delta^{(l)} &= \Big( \big(W^{(l+1)}\big)^{\top} \delta^{(l+1)} \Big) \odot\, \sigma'\big(z^{(l)}\big) \\ \frac{\partial \mathcal{L}}{\partial W^{(l)}} &= \delta^{(l)} \big(a^{(l-1)}\big)^{\top} \\ \frac{\partial \mathcal{L}}{\partial b^{(l)}} &= \delta^{(l)} \end{aligned}`,219          explanation: t(220            "La première équation amorce le calcul à la sortie ; la deuxième le fait remonter d'une couche ; les deux dernières convertissent le signal d'erreur en gradients des paramètres[^rumelhart1986]. Avec la perte quadratique, $\\nabla_{a^{(L)}} \\mathcal{L} = \\hat{y} - y$.",221            "The first equation starts the computation at the output; the second carries it back one layer; the last two turn the error signal into parameter gradients[^rumelhart1986]. With the squared-error loss, $\\nabla_{a^{(L)}} \\mathcal{L} = \\hat{y} - y$.",222          ),223          variables: [224            { symbol: r`\delta^{(l)}`, meaning: t("Signal d'erreur de la couche $l$ : $\\partial \\mathcal{L} / \\partial z^{(l)}$", "Error signal of layer $l$: $\\partial \\mathcal{L} / \\partial z^{(l)}$") },225            { symbol: r`\sigma'`, meaning: t("Dérivée de la fonction d'activation", "Derivative of the activation function") },226            { symbol: r`\odot`, meaning: t("Produit composante par composante", "Component-wise product") },227            { symbol: r`\big(W^{(l+1)}\big)^{\top}`, meaning: t("Transposée des poids de la couche suivante : elle redistribue l'erreur vers l'arrière", "Transpose of the next layer's weights: it redistributes the error backwards") },228          ],229        },230        {231          id: "tb-activations", type: "table", span: 4, headerColumn: true,232          caption: t("Activations usuelles et leur dérivée.", "Common activations and their derivatives."),233          columns: [{ label: t("Fonction", "Function") }, { label: "$\\sigma(z)$" }, { label: "$\\sigma'(z)$" }],234          rows: [235            [t("Sigmoïde", "Sigmoid"), "$\\dfrac{1}{1 + e^{-z}}$", "$\\sigma(z)\\,(1 - \\sigma(z))$"],236            ["tanh", "$\\tanh(z)$", "$1 - \\tanh^2(z)$"],237            ["ReLU", "$\\max(0, z)$", t("$1$ si $z > 0$, sinon $0$", "$1$ if $z > 0$, else $0$")],238          ],239        },240241        { id: "h-update", type: "heading", level: 2, text: t("Mettre à jour les poids", "Updating the weights") },242        {243          id: "eq-update", type: "equation", span: 4, label: t("Descente de gradient", "Gradient descent"), derivation: "standard",244          latex: r`\theta \leftarrow \theta - \eta \, \nabla_{\theta} \mathcal{L}(\theta)`,245          explanation: t(246            "Le gradient pointe vers la plus forte hausse de la perte ; on avance donc dans le sens opposé. En pratique, le gradient est estimé sur un petit lot d'exemples tiré au hasard : c'est la descente de gradient stochastique[^lecun1998][^lecun2015].",247            "The gradient points towards the steepest increase of the loss, so we move the opposite way. In practice the gradient is estimated on a small, randomly drawn batch of examples: this is stochastic gradient descent[^lecun1998][^lecun2015].",248          ),249          variables: [250            { symbol: r`\eta`, meaning: t("Taux d'apprentissage : la longueur du pas", "Learning rate: the length of the step") },251            { symbol: r`\nabla_{\theta} \mathcal{L}`, meaning: t("Gradient de la perte par rapport aux paramètres", "Gradient of the loss with respect to the parameters") },252          ],253        },254        {255          id: "ch-lr", type: "chart", span: 8, kind: "line", dataKind: "synthetic",256          title: t("Effet du taux d'apprentissage", "Effect of the learning rate"),257          caption: t(258            "Valeurs exactes de la descente de gradient sur la fonction jouet $\\mathcal{L}(w) = w^2$ à partir de $w_0 = 1$, soit $\\mathcal{L}_t = (1 - 2\\eta)^{2t}$. Ce n'est pas la courbe d'entraînement d'un réseau.",259            "Exact values of gradient descent on the toy function $\\mathcal{L}(w) = w^2$ from $w_0 = 1$, that is $\\mathcal{L}_t = (1 - 2\\eta)^{2t}$. This is not the training curve of a network.",260          ),261          alt: t(262            "Graphique en lignes de la perte en fonction du nombre d'itérations, de 0 à 10, pour trois taux d'apprentissage. Avec un taux de 0,05, la perte baisse lentement. Avec 0,3, elle tombe à presque zéro en quelques itérations. Avec 1,05, elle augmente à chaque itération : la descente diverge.",263            "Line chart of the loss against the number of iterations, from 0 to 10, for three learning rates. With a rate of 0.05 the loss decreases slowly. With 0.3 it drops to almost zero within a few iterations. With 1.05 it increases at every iteration: the descent diverges.",264          ),265          x: { label: t("Itération", "Iteration"), type: "number", min: 0, max: 10 },266          y: { label: t("Perte", "Loss"), min: 0 },267          series: [268            { name: t("η = 0,05 (trop petit : lent)", "η = 0.05 (too small: slow)"), tone: "blue", points: lossCurve(0.05) },269            { name: t("η = 0,3 (adapté)", "η = 0.3 (well chosen)"), tone: "green", points: lossCurve(0.3) },270            { name: t("η = 1,05 (trop grand : diverge)", "η = 1.05 (too large: diverges)"), tone: "red", points: lossCurve(1.05) },271          ],272        },273        {274          id: "co-vanishing", type: "callout", span: 6, tone: "warning", title: t("Le gradient qui s'évanouit", "The vanishing gradient"),275          text: t(276            "La deuxième équation multiplie le signal d'erreur par $\\sigma'(z)$ à chaque couche traversée. Or la dérivée de la sigmoïde ne dépasse jamais $1/4$ : dans un réseau profond, ces facteurs répétés peuvent réduire le gradient des premières couches à presque rien. C'est l'une des raisons du succès de la ReLU, dont la dérivée vaut 1 sur toute la partie active[^lecun2015].",277            "The second equation multiplies the error signal by $\\sigma'(z)$ at every layer crossed. Yet the derivative of the sigmoid never exceeds $1/4$: in a deep network these repeated factors can shrink the gradient of the first layers to almost nothing. This is one reason for the success of the ReLU, whose derivative is 1 over its whole active part[^lecun2015].",278          ),279        },280        {281          id: "co-optimisers", type: "callout", span: 6, tone: "note", title: t("Au-delà du pas fixe", "Beyond the fixed step"),282          text: t(283            "La rétropropagation fournit le gradient ; ce qu'on en fait relève de l'**optimiseur**. Des méthodes comme Adam adaptent le pas de chaque paramètre à partir d'estimations des premier et second moments du gradient[^kingma2014]. Le calcul du gradient, lui, reste exactement celui décrit ici.",284            "Backpropagation supplies the gradient; what is done with it is the business of the **optimiser**. Methods such as Adam adapt the step of each parameter from estimates of the first and second moments of the gradient[^kingma2014]. The computation of the gradient itself stays exactly as described here.",285          ),286        },287        {288          id: "code-numpy", type: "code", language: "python", code: CODE,289          caption: t(290            "Le réseau du schéma en NumPy : passe avant, passe arrière et mise à jour tiennent en une dizaine de lignes. Exemple minimal : avec cette graine, le réseau apprend le « ou exclusif » ; une autre initialisation peut demander plus d'itérations.",291            "The network of the diagram in NumPy: forward pass, backward pass and update fit in about ten lines. A minimal example: with this seed the network learns exclusive-or; another initialisation may need more iterations.",292          ),293        },294295        { id: "h-check", type: "heading", level: 2, text: t("Vérifier sa compréhension", "Check your understanding") },296        {297          id: "quiz-zero", type: "quiz", span: 6,298          question: t(299            "On initialise **tous** les poids et les biais d'un réseau à zéro, avec une activation tanh. Que se passe-t-il pendant l'entraînement ?",300            "**All** the weights and biases of a network are initialised to zero, with a tanh activation. What happens during training?",301          ),302          choices: [303            { text: t("Les neurones d'une même couche restent identiques entre eux : le réseau ne peut pas apprendre des caractéristiques différentes.", "Neurons in the same layer stay identical to one another: the network cannot learn different features."), correct: true, explanation: t("Exact : des neurones partis du même point reçoivent le même gradient à chaque étape. Une initialisation aléatoire sert justement à briser cette symétrie.", "Correct: neurons starting from the same point receive the same gradient at every step. Random initialisation is there precisely to break this symmetry.") },304            { text: t("Le réseau apprend normalement, seulement un peu plus lentement.", "The network learns normally, only a little more slowly."), correct: false, explanation: t("Le problème n'est pas la vitesse : la symétrie entre neurones n'est jamais rompue.", "Speed is not the issue: the symmetry between neurons is never broken.") },305            { text: t("La perte diverge dès la première itération.", "The loss diverges from the first iteration."), correct: false, explanation: t("Rien ne diverge ; les gradients sont au contraire nuls ou identiques.", "Nothing diverges; on the contrary, gradients are zero or identical.") },306          ],307        },308        {309          id: "acc-faq", type: "accordion", span: 6,310          items: [311            {312              title: t("Rétropropagation et descente de gradient, est-ce la même chose ?", "Are backpropagation and gradient descent the same thing?"),313              text: t(314                "Non. La rétropropagation **calcule** le gradient ; la descente de gradient **l'utilise** pour modifier les poids. On peut changer d'optimiseur sans toucher à la rétropropagation, et inversement.",315                "No. Backpropagation **computes** the gradient; gradient descent **uses** it to change the weights. The optimiser can be swapped without touching backpropagation, and vice versa.",316              ),317            },318            {319              title: t("Pourquoi partir de la sortie plutôt que de l'entrée ?", "Why start from the output rather than from the input?"),320              text: t(321                "Parce que la perte est un seul nombre et que les poids sont très nombreux. En remontant depuis la sortie, chaque dérivée intermédiaire est calculée une fois et réutilisée par toutes les couches situées en amont. Partir de l'entrée obligerait à refaire un calcul par poids.",322                "Because the loss is a single number and the weights are very many. Going back from the output, each intermediate derivative is computed once and reused by all the layers upstream. Starting from the input would require one computation per weight.",323              ),324            },325            {326              title: t("Erreur fréquente : oublier le facteur $\\sigma'(z)$", "Common mistake: forgetting the factor $\\sigma'(z)$"),327              text: t(328                "Le signal d'erreur se définit par rapport à la pré-activation $z$, pas par rapport à l'activation $a$. Passer de l'une à l'autre exige de multiplier par la dérivée de l'activation, à **chaque** couche. C'est l'oubli le plus courant quand on programme la rétropropagation à la main.",329                "The error signal is defined with respect to the pre-activation $z$, not the activation $a$. Going from one to the other requires multiplying by the derivative of the activation, at **every** layer. It is the most common omission when coding backpropagation by hand.",330              ),331            },332            {333              title: t("Faut-il encore l'écrire à la main ?", "Does it still have to be written by hand?"),334              text: t(335                "Non : les bibliothèques d'apprentissage profond dérivent automatiquement le calcul de la passe arrière à partir de celui de la passe avant. Comprendre le mécanisme reste utile pour diagnostiquer un entraînement qui stagne, des gradients qui s'évanouissent ou qui explosent.",336                "No: deep learning libraries automatically derive the backward computation from the forward one. Understanding the mechanism remains useful to diagnose a training run that stalls, or gradients that vanish or explode.",337              ),338            },339          ],340        },341        { id: "refs", type: "references", title: t("Références", "References") },342      ],343      sources: pickSources("rumelhart1986", "lecun1998", "lecun2015", "kingma2014"),344      claims: [345        { id: "cl-procedure", status: "sourced", sourceIds: ["rumelhart1986"], blockId: "intro-lead", text: t("La rétropropagation ajuste de façon répétée les poids du réseau pour minimiser l'écart entre la sortie obtenue et la sortie désirée.", "Backpropagation repeatedly adjusts the weights of the network to minimise the difference between the actual output and the desired output.") },346        { id: "cl-chain", status: "sourced", sourceIds: ["lecun2015", "rumelhart1986"], blockId: "co-chain", text: t("La rétropropagation est une application de la règle de la chaîne, de la sortie vers l'entrée.", "Backpropagation is an application of the chain rule, from the output back to the input.") },347        { id: "cl-equations", status: "sourced", sourceIds: ["rumelhart1986"], blockId: "eq-backprop", text: t("Le signal d'erreur d'une couche s'obtient à partir de celui de la couche suivante, multiplié par la transposée des poids et par la dérivée de l'activation.", "The error signal of a layer is obtained from that of the next layer, multiplied by the transposed weights and by the derivative of the activation.") },348        { id: "cl-cost", status: "derived", blockId: "p-reuse", text: t("Une passe arrière donne le gradient de tous les poids pour un coût du même ordre qu'une passe avant, car chaque dérivée intermédiaire n'est calculée qu'une fois.", "One backward pass gives the gradient of all weights at a cost of the same order as a forward pass, because each intermediate derivative is computed only once.") },349        { id: "cl-sgd", status: "sourced", sourceIds: ["lecun2015", "lecun1998"], blockId: "eq-update", text: t("Les réseaux sont entraînés par descente de gradient stochastique, le gradient étant estimé sur de petits lots d'exemples.", "Networks are trained by stochastic gradient descent, with the gradient estimated on small batches of examples.") },350        { id: "cl-sigmoid", status: "derived", blockId: "co-vanishing", text: t("La dérivée de la sigmoïde σ(z)(1 − σ(z)) atteint son maximum 1/4 en z = 0.", "The derivative of the sigmoid σ(z)(1 − σ(z)) reaches its maximum 1/4 at z = 0.") },351        { id: "cl-adam", status: "sourced", sourceIds: ["kingma2014"], blockId: "co-optimisers", text: t("Adam adapte le pas à partir d'estimations des premier et second moments du gradient.", "Adam adapts the step from estimates of the first and second moments of the gradient.") },352      ],353    };354  },355};356
Files main
Menu

Theme