Repository Public
1import type { Locale, SheetInput } from "@/schema";2import type { TemplateDef } from "../types";3import { T, doiSource, r, round } from "./shared";45/** Exact coefficient maps under an orthonormal design, for lambda = 1. */6const GRID = Array.from({ length: 25 }, (_, i) => -3 + i * 0.25);7const soft = (b: number, lam: number) => Math.sign(b) * Math.max(Math.abs(b) - lam, 0);89function build(locale: Locale): SheetInput {10 const t = T(locale);11 return {12 schemaVersion: 1,13 metadata: {14 title: t("Trois méthodes comparées : MCO, Ridge et Lasso", "Three methods compared: OLS, Ridge and Lasso"),15 locale,16 summary: t(17 "Une grille de comparaison réutilisable, appliquée à trois estimateurs de régression linéaire : même problème, trois fonctions objectif, mêmes critères de jugement.",18 "A reusable comparison grid, applied to three linear regression estimators: same problem, three objective functions, same criteria.",19 ),20 topics: [t("Statistique", "Statistics"), t("Économétrie", "Econometrics"), t("Apprentissage statistique", "Statistical learning")],21 tags: [t("MCO", "OLS"), "Ridge", "Lasso", t("régularisation", "regularisation"), t("biais-variance", "bias–variance"), t("parcimonie", "sparsity"), t("comparaison de méthodes", "method comparison")],22 level: "intermediate",23 kind: "comparison",24 objectives: [25 t("Écrire la fonction objectif des MCO, de Ridge et du Lasso et dire ce que chaque pénalité fait aux coefficients.", "Write the objective function of OLS, Ridge and Lasso and say what each penalty does to the coefficients."),26 t("Expliquer par la géométrie pourquoi le Lasso annule des coefficients et pas Ridge.", "Explain through geometry why Lasso sets coefficients to zero and Ridge does not."),27 t("Raisonner en termes de compromis biais-variance et choisir $\\lambda$ par validation croisée.", "Reason in terms of the bias–variance trade-off and choose $\\lambda$ by cross-validation."),28 t("Choisir entre les trois méthodes selon le but poursuivi : inférence, prévision ou sélection.", "Choose among the three methods according to the goal: inference, prediction or selection."),29 ],30 example: true,31 },32 theme: { preset: "editorial", accent: "violet" },33 blocks: [34 { id: "title", type: "heading", level: 1, eyebrow: t("Comparaison de méthodes", "Method comparison"), text: t("MCO, Ridge et Lasso : trois réponses à un même problème", "OLS, Ridge and Lasso: three answers to one problem") },35 {36 id: "lead", type: "paragraph", lead: true,37 text: t(38 "Les trois méthodes ajustent le même modèle linéaire ; elles ne diffèrent que par ce qu'elles **pénalisent**. Les moindres carrés ordinaires (MCO) ne pénalisent rien, Ridge pénalise la somme des carrés des coefficients[^hoerl-kennard-1970], le Lasso la somme de leurs valeurs absolues[^tibshirani-1996]. De cette seule différence découlent le biais, la variance et la parcimonie de chaque estimateur.",39 "All three methods fit the same linear model; they differ only in what they **penalise**. Ordinary least squares (OLS) penalises nothing, Ridge penalises the sum of squared coefficients[^hoerl-kennard-1970], Lasso the sum of their absolute values[^tibshirani-1996]. From that single difference follow the bias, the variance and the sparsity of each estimator.",40 ),41 },42 {43 id: "callout-template", type: "callout", tone: "tip", title: t("Réutiliser cette grille", "Reusing this grid"),44 text: t(45 "La structure vaut pour toute comparaison de trois méthodes : **(1)** le problème commun et ses hypothèses, **(2)** ce que chaque méthode optimise, **(3)** un schéma qui les place côte à côte, **(4)** l'intuition qui les sépare, **(5)** un tableau critère par critère, **(6)** une règle de choix, **(7)** les erreurs fréquentes. Remplacez le contenu, gardez les sections.",46 "The structure works for any comparison of three methods: **(1)** the shared problem and its assumptions, **(2)** what each method optimises, **(3)** a diagram placing them side by side, **(4)** the intuition that separates them, **(5)** a criterion-by-criterion table, **(6)** a decision rule, **(7)** common mistakes. Replace the content, keep the sections.",47 ),48 },4950 { id: "sec-problem", type: "heading", level: 2, eyebrow: t("1 · Le problème commun", "1 · The shared problem"), text: t("Un modèle linéaire, des coefficients à estimer", "A linear model, coefficients to estimate") },51 {52 id: "eq-model", type: "equation", span: 8, label: t("Modèle de régression linéaire", "Linear regression model"),53 latex: r`y = X\beta + \varepsilon, \qquad \mathbb{E}[\varepsilon \mid X] = 0, \qquad \operatorname{Var}(\varepsilon \mid X) = \sigma^2 I_n`,54 explanation: t(55 "Sous ces hypothèses (linéarité, exogénéité, erreurs homoscédastiques et non corrélées) et si $X$ est de plein rang colonne, le théorème de Gauss-Markov établit que l'estimateur des MCO a la plus petite variance parmi les estimateurs linéaires **sans biais**[^hastie-2009]. Ridge et Lasso acceptent un biais pour sortir de cette classe.",56 "Under these assumptions (linearity, exogeneity, homoskedastic uncorrelated errors) and if $X$ has full column rank, the Gauss–Markov theorem states that the OLS estimator has the smallest variance among linear **unbiased** estimators[^hastie-2009]. Ridge and Lasso accept some bias to step outside that class.",57 ),58 variables: [59 { symbol: r`y`, meaning: t("vecteur $n\\times 1$ de la variable expliquée", "$n\\times 1$ vector of the response") },60 { symbol: r`X`, meaning: t("matrice $n\\times p$ des variables explicatives", "$n\\times p$ matrix of predictors") },61 { symbol: r`\beta`, meaning: t("vecteur $p\\times 1$ des coefficients à estimer", "$p\\times 1$ vector of coefficients to estimate") },62 { symbol: r`\varepsilon`, meaning: t("vecteur des erreurs", "vector of errors") },63 { symbol: r`\sigma^2`, meaning: t("variance des erreurs", "error variance") },64 { symbol: r`n,\ p`, meaning: t("nombre d'observations et nombre de variables", "number of observations and number of predictors") },65 ],66 },67 {68 id: "callout-standardise", type: "callout", span: 4, tone: "assumption", title: t("Convention pour les méthodes pénalisées", "Convention for penalised methods"),69 text: t(70 "Les pénalités dépendent de l'échelle des variables : on **centre** $y$, on **centre et réduit** chaque colonne de $X$, et l'on ne pénalise pas la constante[^hastie-2009]. Sans cela, changer l'unité d'une variable changerait la solution.",71 "Penalties depend on the scale of the predictors: **centre** $y$, **centre and scale** every column of $X$, and leave the intercept unpenalised[^hastie-2009]. Otherwise changing the unit of a predictor would change the solution.",72 ),73 },7475 { id: "sec-objectives", type: "heading", level: 2, eyebrow: t("2 · Ce que chaque méthode optimise", "2 · What each method optimises"), text: t("Trois fonctions objectif", "Three objective functions") },76 {77 id: "eq-ols", type: "equation", span: 4, label: t("MCO", "OLS"), sourceIds: ["hastie-2009"],78 latex: r`\begin{aligned} \hat\beta^{\text{mco}} &= \arg\min_{\beta}\ \lVert y - X\beta \rVert_2^2 \\ &= (X^\top X)^{-1} X^\top y \end{aligned}`.replace("mco", locale === "fr" ? "mco" : "ols"),79 explanation: t("Aucune pénalité. Solution unique si $X^\\top X$ est inversible, ce qui exige $p\\le n$ et aucune colinéarité parfaite.", "No penalty. Unique solution if $X^\\top X$ is invertible, which requires $p\\le n$ and no perfect collinearity."),80 variables: [81 { symbol: r`\lVert v \rVert_2^2`, meaning: t("somme des carrés des composantes de $v$", "sum of squared components of $v$") },82 ],83 },84 {85 id: "eq-ridge", type: "equation", span: 4, label: "Ridge", sourceIds: ["hoerl-kennard-1970"],86 latex: r`\begin{aligned} \hat\beta^{\text{ridge}} &= \arg\min_{\beta}\ \lVert y - X\beta \rVert_2^2 + \lambda \lVert \beta \rVert_2^2 \\ &= (X^\top X + \lambda I_p)^{-1} X^\top y \end{aligned}`,87 explanation: t("Pénalité $\\ell_2$. Pour $\\lambda>0$, la matrice $X^\\top X+\\lambda I_p$ est toujours inversible : la solution existe et est unique même si $p>n$.", "$\\ell_2$ penalty. For $\\lambda>0$ the matrix $X^\\top X+\\lambda I_p$ is always invertible: the solution exists and is unique even when $p>n$."),88 variables: [89 { symbol: r`\lambda`, meaning: t("intensité de la pénalité, $\\lambda\\ge 0$ ; $\\lambda=0$ redonne les MCO", "penalty strength, $\\lambda\\ge 0$; $\\lambda=0$ gives back OLS") },90 { symbol: r`I_p`, meaning: t("matrice identité d'ordre $p$", "identity matrix of order $p$") },91 ],92 },93 {94 id: "eq-lasso", type: "equation", span: 4, label: "Lasso", sourceIds: ["tibshirani-1996"],95 latex: r`\begin{aligned} \hat\beta^{\text{lasso}} &= \arg\min_{\beta}\ \tfrac{1}{2}\lVert y - X\beta \rVert_2^2 + \lambda \lVert \beta \rVert_1 \\ \lVert \beta \rVert_1 &= \textstyle\sum_{j=1}^{p} \lvert \beta_j \rvert \end{aligned}`,96 explanation: t("Pénalité $\\ell_1$. Pas de forme fermée en général : le problème est convexe et se résout numériquement, par exemple par descente par coordonnées[^friedman-2010]. Le facteur $\\tfrac12$ est une convention qui ne fait que changer l'échelle de $\\lambda$.", "$\\ell_1$ penalty. No closed form in general: the problem is convex and solved numerically, for example by coordinate descent[^friedman-2010]. The factor $\\tfrac12$ is a convention that merely rescales $\\lambda$."),97 variables: [98 { symbol: r`\lVert \beta \rVert_1`, meaning: t("somme des valeurs absolues des coefficients", "sum of absolute values of the coefficients") },99 ],100 },101102 { id: "sec-map", type: "heading", level: 2, eyebrow: t("3 · Côte à côte", "3 · Side by side"), text: t("Le même chemin, trois embranchements", "The same path, three branches") },103 {104 id: "diagram-methods", type: "diagram", span: 8, kind: "flow", direction: "TB", routing: "orthogonal",105 title: t("Des données à l'estimateur, selon la pénalité choisie", "From data to estimator, depending on the penalty chosen"),106 caption: t(107 "Les trois méthodes partagent l'entrée et l'évaluation ; elles ne divergent qu'entre la pénalité et la propriété du résultat.",108 "The three methods share the input and the evaluation; they diverge only between the penalty and the property of the result.",109 ),110 alt: t(111 "Diagramme de flux descendant. Les données X et y sont centrées et réduites, puis le chemin se divise en trois colonnes. MCO : aucune pénalité, forme fermée, coefficients sans biais mais de variance parfois élevée. Ridge : pénalité sur la somme des carrés, forme fermée, tous les coefficients rétrécis, aucun nul. Lasso : pénalité sur la somme des valeurs absolues, descente par coordonnées, certains coefficients exactement nuls. Ridge et Lasso reçoivent lambda de la validation croisée. Les trois colonnes se rejoignent dans l'évaluation de l'erreur hors échantillon.",112 "Top-down flow diagram. The data X and y are first centred and scaled, then the path splits into three columns. OLS: no penalty, closed-form solution, unbiased coefficients but high variance when predictors are correlated. Ridge: penalty on the sum of squares, closed form, every coefficient shrunk but none zero. Lasso: penalty on the sum of absolute values, coordinate descent, some coefficients exactly zero. Ridge and Lasso go through the choice of lambda by cross-validation. The three columns meet again in the out-of-sample error evaluation.",113 ),114 groups: [115 { id: "g-common", label: t("Commun", "Shared"), tone: "neutral" },116 { id: "g-ols", label: t("MCO", "OLS"), tone: "blue" },117 { id: "g-ridge", label: "Ridge", tone: "teal" },118 { id: "g-lasso", label: "Lasso", tone: "violet" },119 ],120 nodes: [121 { id: "n-data", label: t("Données (X, y)", "Data (X, y)"), shape: "cylinder", tone: "neutral", icon: "database", group: "g-common" },122 { id: "n-std", label: t("Centrer et réduire", "Centre and scale"), shape: "round", tone: "neutral", icon: "scale", group: "g-common" },123 { id: "n-ols-pen", label: t("Aucune pénalité", "No penalty"), shape: "pill", tone: "blue", group: "g-ols" },124 { id: "n-ols-solve", label: t("Forme fermée", "Closed form"), sublabel: "(XᵀX)⁻¹Xᵀy", shape: "round", tone: "blue", icon: "calculator", group: "g-ols" },125 { id: "n-ols-prop", label: t("Sans biais", "Unbiased"), sublabel: t("variance parfois élevée", "variance sometimes high"), shape: "rect", tone: "blue", group: "g-ols" },126 { id: "n-ridge-pen", label: t("Pénalité λ‖β‖₂²", "Penalty λ‖β‖₂²"), shape: "pill", tone: "teal", group: "g-ridge" },127 { id: "n-ridge-solve", label: t("Forme fermée", "Closed form"), sublabel: "(XᵀX + λI)⁻¹Xᵀy", shape: "round", tone: "teal", icon: "calculator", group: "g-ridge" },128 { id: "n-ridge-prop", label: t("Rétrécit tout", "Shrinks everything"), sublabel: t("aucun coefficient nul", "no coefficient at zero"), shape: "rect", tone: "teal", group: "g-ridge" },129 { id: "n-lasso-pen", label: t("Pénalité λ‖β‖₁", "Penalty λ‖β‖₁"), shape: "pill", tone: "violet", group: "g-lasso" },130 { id: "n-lasso-solve", label: t("Descente par coordonnées", "Coordinate descent"), sublabel: t("solution numérique", "numerical solution"), shape: "round", tone: "violet", icon: "gear", group: "g-lasso" },131 { id: "n-lasso-prop", label: t("Rétrécit et sélectionne", "Shrinks and selects"), sublabel: t("coefficients exactement nuls", "coefficients exactly zero"), shape: "rect", tone: "violet", group: "g-lasso" },132 { id: "n-cv", label: t("Choix de λ", "Choice of λ"), sublabel: t("validation croisée", "cross-validation"), shape: "diamond", tone: "amber", icon: "split", group: "g-common" },133 { id: "n-eval", label: t("Erreur hors échantillon", "Out-of-sample error"), shape: "hexagon", tone: "green", icon: "target", group: "g-common" },134 ],135 edges: [136 { id: "e-data-std", from: "n-data", to: "n-std", tone: "neutral" },137 { id: "e-std-ols", from: "n-std", to: "n-ols-pen", tone: "blue" },138 { id: "e-std-ridge", from: "n-std", to: "n-ridge-pen", tone: "teal" },139 { id: "e-std-lasso", from: "n-std", to: "n-lasso-pen", tone: "violet" },140 { id: "e-ols-1", from: "n-ols-pen", to: "n-ols-solve", tone: "blue" },141 { id: "e-ols-2", from: "n-ols-solve", to: "n-ols-prop", tone: "blue" },142 { id: "e-ridge-1", from: "n-ridge-pen", to: "n-ridge-solve", tone: "teal" },143 { id: "e-ridge-2", from: "n-ridge-solve", to: "n-ridge-prop", tone: "teal" },144 { id: "e-lasso-1", from: "n-lasso-pen", to: "n-lasso-solve", tone: "violet" },145 { id: "e-lasso-2", from: "n-lasso-solve", to: "n-lasso-prop", tone: "violet" },146 { id: "e-cv-ridge", from: "n-cv", to: "n-ridge-pen", label: "λ", style: "dashed", tone: "amber" },147 { id: "e-cv-lasso", from: "n-cv", to: "n-lasso-pen", label: "λ", style: "dashed", tone: "amber" },148 { id: "e-ols-eval", from: "n-ols-prop", to: "n-eval", tone: "green" },149 { id: "e-ridge-eval", from: "n-ridge-prop", to: "n-eval", tone: "green" },150 { id: "e-lasso-eval", from: "n-lasso-prop", to: "n-eval", tone: "green" },151 { id: "e-eval-cv", from: "n-eval", to: "n-cv", label: t("guide le choix", "guides the choice"), style: "dashed", tone: "amber" },152 ],153 legend: [154 { label: t("Bleu : MCO", "Blue: OLS"), tone: "blue", shape: "square" },155 { label: t("Sarcelle : Ridge", "Teal: Ridge"), tone: "teal", shape: "square" },156 { label: t("Violet : Lasso", "Violet: Lasso"), tone: "violet", shape: "square" },157 { label: t("Flèche tiretée ambre : réglage de λ par validation croisée", "Amber dashed arrow: tuning λ by cross-validation"), tone: "amber", shape: "dashed" },158 { label: t("Vert : évaluation commune", "Green: shared evaluation"), tone: "green", shape: "arrow" },159 ],160 },161 {162 id: "cards-methods", type: "cards", span: 4, columns: 2,163 items: [164 { icon: "target", title: t("MCO", "OLS"), tone: "blue", badge: t("référence", "baseline"), text: t("Colle aux données autant qu'un modèle linéaire le permet. Meilleur estimateur linéaire sans biais, mais instable quand les variables sont nombreuses ou corrélées.", "Fits the data as closely as a linear model can. Best linear unbiased estimator, but unstable when predictors are many or correlated.") },165 { icon: "scale", title: "Ridge", tone: "teal", badge: "ℓ₂", text: t("Tire tous les coefficients vers zéro, d'autant plus fort dans les directions où les données informent peu. Garde toutes les variables.", "Pulls every coefficient towards zero, more strongly in directions where the data is least informative. Keeps every predictor.") },166 { icon: "filter", title: "Lasso", tone: "violet", badge: "ℓ₁", text: t("Rétrécit et, au-delà d'un seuil, annule. Produit un modèle parcimonieux : estimation et sélection en une seule étape.", "Shrinks and, beyond a threshold, zeroes out. Produces a sparse model: estimation and selection in a single step.") },167 ],168 },169170 { id: "sec-geometry", type: "heading", level: 2, eyebrow: t("4 · L'intuition qui les sépare", "4 · The intuition that separates them"), text: t("Géométrie de la pénalité et compromis biais-variance", "Penalty geometry and the bias–variance trade-off") },171 {172 id: "para-geometry", type: "paragraph", span: 6,173 text: t(174 "Chaque problème pénalisé équivaut à minimiser la somme des carrés des résidus **sous contrainte** : $\\lVert\\beta\\rVert_2^2\\le s$ pour Ridge, $\\lVert\\beta\\rVert_1\\le s$ pour le Lasso. La solution est le premier point où les ellipses de niveau de la somme des carrés touchent la région permise. Pour Ridge, cette région est un disque, sans point particulier : le contact se fait presque sûrement hors des axes. Pour le Lasso, c'est un losange dont les **coins sont sur les axes** : le contact s'y produit souvent, et un coin signifie qu'un coefficient vaut exactement zéro[^hastie-2009].",175 "Each penalised problem is equivalent to minimising the residual sum of squares **under a constraint**: $\\lVert\\beta\\rVert_2^2\\le s$ for Ridge, $\\lVert\\beta\\rVert_1\\le s$ for Lasso. The solution is the first point where the elliptical contours of the sum of squares touch the feasible region. For Ridge that region is a disc with no special point: contact almost surely happens off the axes. For Lasso it is a diamond whose **corners lie on the axes**: contact often happens there, and a corner means a coefficient is exactly zero[^hastie-2009].",176 ),177 },178 {179 id: "eq-orthonormal", type: "equation", span: 6, label: t("Cas orthonormé : $X^\\top X = I_p$", "Orthonormal case: $X^\\top X = I_p$"), sourceIds: ["hastie-2009"],180 latex: r`\hat\beta_j^{\text{ridge}} = \frac{\hat\beta_j}{1+\lambda}, \qquad \hat\beta_j^{\text{lasso}} = \operatorname{sign}(\hat\beta_j)\,\bigl(\lvert\hat\beta_j\rvert - \lambda\bigr)_{+}`,181 explanation: t(182 "Lorsque les colonnes de $X$ sont orthonormées, chaque coefficient se traite séparément. Ridge **multiplie** par un facteur inférieur à 1 (rétrécissement proportionnel) ; le Lasso **soustrait** $\\lambda$ et tronque à zéro (seuillage doux)[^hastie-2009].",183 "When the columns of $X$ are orthonormal, each coefficient is handled separately. Ridge **multiplies** by a factor below 1 (proportional shrinkage); Lasso **subtracts** $\\lambda$ and truncates at zero (soft thresholding)[^hastie-2009].",184 ),185 variables: [186 { symbol: r`\hat\beta_j`, meaning: t("coefficient $j$ estimé par les MCO", "OLS estimate of coefficient $j$") },187 { symbol: r`(u)_{+}`, meaning: t("partie positive : $\\max(u,0)$", "positive part: $\\max(u,0)$") },188 ],189 },190 {191 id: "chart-shrinkage", type: "chart", span: 6, kind: "line", dataKind: "illustrative",192 title: t("Ce que chaque méthode fait à un coefficient", "What each method does to a coefficient"),193 caption: t(194 "Fonctions exactes du cas orthonormé, tracées pour $\\lambda=1$ (valeur choisie pour la lisibilité). Aucune donnée n'est estimée.",195 "Exact functions of the orthonormal case, drawn for $\\lambda=1$ (a value chosen for readability). No data is estimated.",196 ),197 alt: t(198 "Trois courbes du coefficient estimé en fonction du coefficient MCO, de −3 à 3. Les MCO suivent la diagonale. Ridge est une droite de pente un demi passant par l'origine. Le Lasso est plat à zéro entre −1 et 1, puis parallèle à la diagonale, décalé de 1 vers zéro.",199 "Three curves of the estimated coefficient against the OLS coefficient, from −3 to 3. OLS follows the diagonal. Ridge is a straight line of slope one half through the origin. Lasso is flat at zero between −1 and 1, then parallel to the diagonal, shifted by 1 towards zero.",200 ),201 x: { label: t("Coefficient MCO", "OLS coefficient"), min: -3, max: 3 },202 y: { label: t("Coefficient estimé", "Estimated coefficient"), min: -3, max: 3 },203 series: [204 { name: t("MCO", "OLS"), tone: "blue", points: GRID.map((x) => ({ x, y: x })) },205 { name: "Ridge (λ = 1)", tone: "teal", points: GRID.map((x) => ({ x, y: round(x / 2, 4) })) },206 { name: "Lasso (λ = 1)", tone: "violet", points: GRID.map((x) => ({ x, y: round(soft(x, 1), 4) })) },207 ],208 },209 {210 id: "eq-bias-variance", type: "equation", span: 6, label: t("Biais et variance de Ridge", "Bias and variance of Ridge"), derivation: "derived",211 latex: r`\begin{aligned} \mathbb{E}\bigl[\hat\beta^{\text{ridge}} \mid X\bigr] - \beta &= -\lambda\,(X^\top X + \lambda I_p)^{-1}\beta \\ \operatorname{Var}\bigl(\hat\beta^{\text{ridge}} \mid X\bigr) &= \sigma^2\,(X^\top X + \lambda I_p)^{-1} X^\top X\,(X^\top X + \lambda I_p)^{-1} \end{aligned}`,212 explanation: t(213 "Obtenu en remplaçant $y$ par $X\\beta+\\varepsilon$ dans la forme fermée. Quand $\\lambda$ augmente, le biais croît et la variance décroît. Hoerl et Kennard ont montré qu'il existe toujours un $\\lambda>0$ pour lequel l'erreur quadratique moyenne de Ridge est inférieure à celle des MCO[^hoerl-kennard-1970] ; ce $\\lambda$ dépend toutefois de $\\beta$ et de $\\sigma^2$, inconnus.",214 "Obtained by substituting $X\\beta+\\varepsilon$ for $y$ in the closed form. As $\\lambda$ grows, bias increases and variance decreases. Hoerl and Kennard showed that there always exists a $\\lambda>0$ for which the mean squared error of Ridge is below that of OLS[^hoerl-kennard-1970]; that $\\lambda$, however, depends on the unknown $\\beta$ and $\\sigma^2$.",215 ),216 variables: [217 { symbol: r`\mathbb{E}[\hat\beta \mid X] - \beta`, meaning: t("biais de l'estimateur", "bias of the estimator") },218 { symbol: r`\operatorname{Var}(\hat\beta \mid X)`, meaning: t("matrice de covariance de l'estimateur", "covariance matrix of the estimator") },219 ],220 },221 {222 id: "sim-regression", type: "simulation", kind: "regression", params: { slope: 1.5, intercept: 1, sigma: 3, n: 20 }, config: {}, seed: 5,223 title: t("Voir la variance d'un ajustement", "See the variance of a fit"),224 caption: t(225 "Données synthétiques tirées d'un modèle linéaire avec bruit gaussien et une graine fixe. Réduisez la taille de l'échantillon ou augmentez le bruit : la droite ajustée devient instable, ce que la régularisation cherche à corriger.",226 "Synthetic data drawn from a linear model with Gaussian noise and a fixed seed. Shrink the sample or raise the noise: the fitted line becomes unstable, which is what regularisation aims to correct.",227 ),228 alt: t(229 "Simulation interactive : un nuage de points simulés, la droite de régression ajustée avec sa bande de confiance et la vraie droite ; des curseurs règlent la pente et l'ordonnée vraies, l'écart-type du bruit et la taille de l'échantillon, et la droite ajustée s'écarte plus ou moins de la vraie.",230 "Interactive simulation: a cloud of simulated points, the fitted regression line with its confidence band and the true line; sliders set the true slope and intercept, the noise standard deviation and the sample size, and the fitted line strays more or less from the true one.",231 ),232 },233234 { id: "sec-table", type: "heading", level: 2, eyebrow: t("5 · Critère par critère", "5 · Criterion by criterion"), text: t("Le tableau de comparaison", "The comparison table") },235 {236 id: "comparison-main", type: "comparison",237 caption: t("Les mêmes critères appliqués aux trois méthodes.", "The same criteria applied to all three methods."),238 columns: [239 { title: t("MCO", "OLS"), tone: "blue", badge: t("sans pénalité", "no penalty") },240 { title: "Ridge", tone: "teal", badge: "ℓ₂" },241 { title: "Lasso", tone: "violet", badge: "ℓ₁" },242 ],243 rows: [244 { label: t("Solution", "Solution"), cells: [t("Forme fermée.", "Closed form."), t("Forme fermée.", "Closed form."), t("Numérique (problème convexe) ; descente par coordonnées[^friedman-2010].", "Numerical (convex problem); coordinate descent[^friedman-2010].")] },245 { label: t("Biais", "Bias"), cells: [t("Nul sous les hypothèses du modèle.", "None under the model assumptions."), t("Oui, vers zéro, croissant avec $\\lambda$.", "Yes, towards zero, increasing with $\\lambda$."), t("Oui, vers zéro, y compris pour les grands coefficients.", "Yes, towards zero, including for large coefficients.")] },246 { label: t("Variance", "Variance"), cells: [t("Élevée si les variables sont corrélées ou si $p$ est proche de $n$.", "High when predictors are correlated or $p$ is close to $n$."), t("Réduite, surtout dans les directions de faible variance de $X$.", "Reduced, especially in the low-variance directions of $X$."), t("Réduite ; la sélection ajoute sa propre instabilité.", "Reduced; selection adds its own instability.")] },247 { label: t("Parcimonie", "Sparsity"), cells: [t("Non.", "No."), t("Non : coefficients petits, jamais exactement nuls.", "No: small coefficients, never exactly zero."), t("Oui : coefficients exactement nuls[^tibshirani-1996].", "Yes: coefficients exactly zero[^tibshirani-1996].")] },248 { label: t("Cas $p>n$", "Case $p>n$"), cells: [t("Solution non unique.", "Solution not unique."), t("Solution unique pour tout $\\lambda>0$.", "Unique solution for any $\\lambda>0$."), t("Possible, mais retient au plus $n$ variables[^zou-hastie-2005].", "Feasible, but selects at most $n$ predictors[^zou-hastie-2005].")] },249 { label: t("Variables très corrélées", "Highly correlated predictors"), cells: [t("Coefficients instables, de signes parfois contraires.", "Unstable coefficients, sometimes of opposite signs."), t("Répartit le poids entre les variables du groupe.", "Spreads the weight across the group."), t("Tend à n'en retenir qu'une, sans raison particulière[^zou-hastie-2005].", "Tends to keep only one, somewhat arbitrarily[^zou-hastie-2005].")] },250 { label: t("Inférence classique", "Classical inference"), cells: [t("Écarts-types, tests $t$ et $F$ disponibles.", "Standard errors, $t$ and $F$ tests available."), t("Estimateur biaisé : les intervalles usuels ne s'appliquent pas tels quels.", "Biased estimator: the usual intervals do not apply as is."), t("Les tests usuels après sélection ne sont pas valides.", "The usual tests after selection are not valid.")] },251 { label: t("Paramètre à régler", "Tuning parameter"), cells: [t("Aucun.", "None."), t("$\\lambda$, par validation croisée.", "$\\lambda$, by cross-validation."), t("$\\lambda$, par validation croisée.", "$\\lambda$, by cross-validation.")] },252 ],253 verdict: t(254 "Aucune méthode ne domine : les MCO pour interpréter et tester quand $p\\ll n$ ; Ridge pour prévoir quand de nombreuses variables ont chacune un petit effet ou sont corrélées ; le Lasso quand on croit que peu de variables comptent et que l'on veut savoir lesquelles. Entre les deux, le filet élastique combine les pénalités $\\ell_1$ et $\\ell_2$[^zou-hastie-2005].",255 "No method dominates: OLS to interpret and test when $p\\ll n$; Ridge to predict when many predictors each have a small effect or are correlated; Lasso when you believe few predictors matter and want to know which. In between, the elastic net combines the $\\ell_1$ and $\\ell_2$ penalties[^zou-hastie-2005].",256 ),257 },258259 { id: "sec-choice", type: "heading", level: 2, eyebrow: t("6 · Règle de choix", "6 · Decision rule"), text: t("Laquelle utiliser, et comment régler λ", "Which one to use, and how to tune λ") },260 {261 id: "steps-choice", type: "steps", span: 6,262 items: [263 { icon: "target", title: t("Préciser le but", "State the goal"), text: t("Tester une hypothèse sur un coefficient, prévoir au mieux, ou repérer les variables utiles : ce sont trois problèmes différents.", "Testing a hypothesis about a coefficient, predicting as well as possible, or finding the useful predictors: these are three different problems.") },264 { icon: "table", title: t("Regarder $n$, $p$ et les corrélations", "Look at $n$, $p$ and the correlations"), text: t("$p$ petit devant $n$ et variables peu corrélées : les MCO suffisent. Sinon, régulariser.", "$p$ small relative to $n$ and weakly correlated predictors: OLS is enough. Otherwise, regularise.") },265 { icon: "scale", title: t("Centrer, réduire", "Centre, scale"), text: t("Avant toute pénalité, et en calculant moyennes et écarts-types sur l'échantillon d'apprentissage seulement.", "Before any penalty, computing means and standard deviations on the training sample only.") },266 { icon: "split", title: t("Choisir $\\lambda$ par validation croisée", "Choose $\\lambda$ by cross-validation"), text: t("Calculer la solution sur une grille de $\\lambda$, retenir celle qui minimise l'erreur de prévision estimée sur les blocs laissés de côté[^hastie-2009].", "Compute the solution over a grid of $\\lambda$, keep the one minimising the prediction error estimated on held-out folds[^hastie-2009].") },267 { icon: "check", title: t("Évaluer sur des données jamais vues", "Evaluate on unseen data"), text: t("L'erreur de validation croisée a servi à choisir $\\lambda$ : elle est optimiste. Garder un échantillon de test à part.", "The cross-validation error was used to choose $\\lambda$: it is optimistic. Keep a separate test sample.") },268 ],269 },270 {271 id: "table-when", type: "table", span: 6, headerColumn: true,272 caption: t("Repères pratiques ; à confirmer par validation croisée dans chaque application.", "Practical pointers; to be confirmed by cross-validation in each application."),273 columns: [{ label: t("Situation", "Situation") }, { label: t("Premier choix", "First choice") }, { label: t("Pourquoi", "Why") }],274 rows: [275 [t("Peu de variables, effet causal ou test à rapporter", "Few predictors, a causal effect or a test to report"), t("MCO", "OLS"), t("Sans biais, inférence classique disponible.", "Unbiased, classical inference available.")],276 [t("Nombreuses variables corrélées, objectif de prévision", "Many correlated predictors, prediction goal"), "Ridge", t("Stabilise les coefficients ; souvent meilleur que le Lasso en prévision dans ce cas[^zou-hastie-2005].", "Stabilises coefficients; often predicts better than Lasso in this case[^zou-hastie-2005].")],277 [t("Beaucoup de candidates, peu de variables réellement utiles", "Many candidates, few truly useful predictors"), "Lasso", t("Sélectionne en estimant.", "Selects while estimating.")],278 [t("$p>n$ avec groupes de variables corrélées", "$p>n$ with groups of correlated predictors"), t("Filet élastique", "Elastic net"), t("Parcimonieux tout en gardant les groupes[^zou-hastie-2005].", "Sparse while keeping groups together[^zou-hastie-2005].")],279 ],280 },281282 { id: "sec-check", type: "heading", level: 2, eyebrow: t("7 · Erreurs fréquentes", "7 · Common mistakes"), text: t("Vérifier sa compréhension", "Check your understanding") },283 {284 id: "quiz-sparsity", type: "quiz", span: 6,285 question: t(286 "Dans le cas orthonormé avec $\\lambda=1$, un coefficient MCO vaut $0{,}6$. Que valent ses estimations Ridge et Lasso (avec les fonctions objectif de cette fiche) ?",287 "In the orthonormal case with $\\lambda=1$, an OLS coefficient equals $0.6$. What are its Ridge and Lasso estimates (with the objective functions of this sheet)?",288 ),289 choices: [290 { text: t("Ridge : 0,3 ; Lasso : 0", "Ridge: 0.3; Lasso: 0"), correct: true, explanation: t("Ridge divise par $1+\\lambda=2$ ; le Lasso soustrait $\\lambda=1$ à la valeur absolue et tronque à zéro.", "Ridge divides by $1+\\lambda=2$; Lasso subtracts $\\lambda=1$ from the absolute value and truncates at zero.") },291 { text: t("Ridge : 0 ; Lasso : 0,3", "Ridge: 0; Lasso: 0.3"), correct: false, explanation: t("C'est l'inverse : Ridge n'annule jamais un coefficient non nul.", "It is the other way round: Ridge never zeroes a non-zero coefficient.") },292 { text: t("Ridge : 0,3 ; Lasso : −0,4", "Ridge: 0.3; Lasso: −0.4"), correct: false, explanation: t("Le seuillage doux tronque à zéro : il ne change jamais le signe.", "Soft thresholding truncates at zero: it never flips the sign.") },293 { text: t("Ridge : 0,6 ; Lasso : 0,6", "Ridge: 0.6; Lasso: 0.6"), correct: false, explanation: t("Ce serait le cas pour $\\lambda=0$, où les trois méthodes coïncident.", "That would be the case for $\\lambda=0$, where all three methods coincide.") },294 ],295 },296 {297 id: "accordion-mistakes", type: "accordion", span: 6,298 items: [299 { title: t("Pénaliser sans centrer ni réduire", "Penalising without centring and scaling"), text: t("Une variable exprimée en milliers plutôt qu'en unités a un coefficient mille fois plus grand, donc mille fois plus pénalisé. La solution dépendrait de l'unité de mesure.", "A predictor expressed in thousands rather than units has a coefficient a thousand times larger, hence penalised a thousand times more. The solution would depend on the unit of measurement.") },300 { title: t("Lire les coefficients du Lasso comme des effets causaux", "Reading Lasso coefficients as causal effects"), text: t("Le Lasso retient ce qui aide à prévoir. Entre deux variables corrélées, il peut garder la mauvaise ; et les coefficients retenus sont biaisés vers zéro.", "Lasso keeps what helps prediction. Between two correlated predictors it may keep the wrong one; and the retained coefficients are biased towards zero.") },301 { title: t("Rapporter des tests $t$ après sélection", "Reporting $t$ tests after selection"), text: t("Réestimer par MCO sur les variables choisies par le Lasso, puis lire les tests comme si le modèle avait été fixé d'avance, ignore l'étape de sélection : les seuils usuels ne tiennent plus.", "Refitting OLS on the predictors chosen by Lasso, then reading the tests as if the model had been fixed in advance, ignores the selection step: the usual significance levels no longer hold.") },302 { title: t("Choisir λ sur l'échantillon de test", "Choosing λ on the test sample"), text: t("L'erreur de test devient alors optimiste. $\\lambda$ se choisit par validation croisée à l'intérieur de l'échantillon d'apprentissage.", "The test error then becomes optimistic. $\\lambda$ is chosen by cross-validation inside the training sample.") },303 { title: t("Croire que « plus de biais » veut dire « moins bon »", "Believing that \"more bias\" means \"worse\""), text: t("L'erreur quadratique moyenne additionne le carré du biais et la variance. Un peu de biais peut acheter une forte baisse de variance[^hoerl-kennard-1970].", "Mean squared error adds squared bias and variance. A little bias can buy a large drop in variance[^hoerl-kennard-1970].") },304 { title: t("Comparer des λ entre logiciels", "Comparing λ values across software"), text: t("Les conventions diffèrent (facteur $\\tfrac12$, division par $n$) : un même $\\lambda$ ne désigne pas la même pénalité d'un outil à l'autre.", "Conventions differ (factor $\\tfrac12$, division by $n$): the same $\\lambda$ does not denote the same penalty from one tool to the next.") },305 ],306 },307 { id: "refs", type: "references", title: t("Références", "References") },308 ],309 sources: [310 doiSource("hoerl-kennard-1970", "article", "Ridge Regression: Biased Estimation for Nonorthogonal Problems", ["Arthur E. Hoerl", "Robert W. Kennard"], 1970, "Technometrics, 12(1), 55–67", "10.1080/00401706.1970.10488634"),311 doiSource("tibshirani-1996", "article", "Regression Shrinkage and Selection Via the Lasso", ["Robert Tibshirani"], 1996, "Journal of the Royal Statistical Society Series B: Statistical Methodology, 58(1), 267–288", "10.1111/j.2517-6161.1996.tb02080.x"),312 doiSource("hastie-2009", "book", "The Elements of Statistical Learning", ["Trevor Hastie", "Robert Tibshirani", "Jerome Friedman"], 2009, "Springer Series in Statistics, Springer New York", "10.1007/978-0-387-84858-7"),313 doiSource("zou-hastie-2005", "article", "Regularization and Variable Selection Via the Elastic Net", ["Hui Zou", "Trevor Hastie"], 2005, "Journal of the Royal Statistical Society Series B: Statistical Methodology, 67(2), 301–320", "10.1111/j.1467-9868.2005.00503.x"),314 doiSource("friedman-2010", "article", "Regularization Paths for Generalized Linear Models via Coordinate Descent", ["Jerome Friedman", "Trevor Hastie", "Robert Tibshirani"], 2010, "Journal of Statistical Software, 33(1)", "10.18637/jss.v033.i01"),315 ],316 claims: [317 { id: "c-gauss-markov", text: t("Sous les hypothèses du modèle linéaire classique, l'estimateur des MCO a la plus petite variance parmi les estimateurs linéaires sans biais.", "Under the classical linear model assumptions, the OLS estimator has the smallest variance among linear unbiased estimators."), status: "sourced", sourceIds: ["hastie-2009"], blockId: "eq-model" },318 { id: "c-ridge-form", text: t("L'estimateur Ridge a la forme fermée (XᵀX + λI)⁻¹Xᵀy, définie pour tout λ > 0.", "The Ridge estimator has the closed form (XᵀX + λI)⁻¹Xᵀy, defined for any λ > 0."), status: "sourced", sourceIds: ["hoerl-kennard-1970", "hastie-2009"], blockId: "eq-ridge" },319 { id: "c-existence", text: t("Il existe toujours un λ > 0 pour lequel l'erreur quadratique moyenne de Ridge est inférieure à celle des MCO.", "There always exists a λ > 0 for which the mean squared error of Ridge is below that of OLS."), status: "sourced", sourceIds: ["hoerl-kennard-1970"], blockId: "eq-bias-variance" },320 { id: "c-lasso-zero", text: t("La pénalité ℓ₁ du Lasso produit des coefficients exactement nuls.", "The ℓ₁ penalty of Lasso produces coefficients that are exactly zero."), status: "sourced", sourceIds: ["tibshirani-1996"], blockId: "eq-lasso" },321 { id: "c-orthonormal", text: t("Dans le cas orthonormé, Ridge rétrécit proportionnellement et le Lasso applique un seuillage doux.", "In the orthonormal case Ridge shrinks proportionally and Lasso applies soft thresholding."), status: "sourced", sourceIds: ["hastie-2009"], blockId: "eq-orthonormal" },322 { id: "c-bias-var", text: t("Le biais de Ridge vaut −λ(XᵀX + λI)⁻¹β et sa variance σ²(XᵀX + λI)⁻¹XᵀX(XᵀX + λI)⁻¹.", "The bias of Ridge is −λ(XᵀX + λI)⁻¹β and its variance σ²(XᵀX + λI)⁻¹XᵀX(XᵀX + λI)⁻¹."), status: "derived", sourceIds: ["hoerl-kennard-1970"], blockId: "eq-bias-variance" },323 { id: "c-lasso-limits", text: t("Quand p > n, le Lasso retient au plus n variables ; face à un groupe de variables très corrélées, il tend à n'en retenir qu'une.", "When p > n, Lasso selects at most n predictors; faced with a group of highly correlated predictors, it tends to keep only one."), status: "sourced", sourceIds: ["zou-hastie-2005"], blockId: "comparison-main" },324 { id: "c-coordinate", text: t("Le chemin de régularisation du Lasso se calcule efficacement par descente par coordonnées.", "The Lasso regularisation path is computed efficiently by coordinate descent."), status: "sourced", sourceIds: ["friedman-2010"], blockId: "eq-lasso" },325 ],326 };327}328329export const threeMethodsComparison: TemplateDef = {330 id: "three-methods-comparison",331 title: { fr: "Comparaison de trois méthodes : MCO, Ridge, Lasso", en: "Three-method comparison: OLS, Ridge, Lasso" },332 description: {333 fr: "Grille réutilisable de comparaison de trois méthodes scientifiques, illustrée par les MCO, Ridge et le Lasso : objectifs, géométrie des pénalités, biais-variance, parcimonie, règle de choix.",334 en: "Reusable grid for comparing three scientific methods, instantiated with OLS, Ridge and Lasso: objectives, penalty geometry, bias–variance, sparsity, decision rule.",335 },336 category: "method",337 build,338};339