SPB Git

Repository Public

regression.tsx 4.7 KB 82 lines tsx

1import type { Locale } from "@/schema";2import { createRng, linspace, ols, studentTQuantile, type OlsFit } from "../core";3import { param, type SimDef } from "../types";4import { fmt, fmtInt } from "../ui/format";5import { Plot } from "../ui/Plot";6import { Readouts } from "../ui/Readouts";78export const REGRESSION_X: [number, number] = [0, 10];910export interface RegressionModel {11  trueSlope: number; trueIntercept: number; sigma: number;12  points: { x: number; y: number }[];13  fit: OlsFit;14  /** t_{0.975, n−2}. */15  critical: number;16  /** Fitted line with the 95 % confidence band of the mean response. */17  band: { x: number; y: number; lo: number; hi: number }[];18}1920export function computeRegression(p: Readonly<Record<string, number>>, seed: number): RegressionModel {21  const n = Math.round(p.n);22  const xr = createRng(seed, "reg-x"), er = createRng(seed, "reg-noise");23  const x = Array.from({ length: n }, () => xr.uniform(REGRESSION_X[0], REGRESSION_X[1]));24  const y = x.map((v) => p.intercept + p.slope * v + p.sigma * er.normal());25  const fit = ols(x, y);26  const critical = studentTQuantile(0.975, n - 2);27  const band = linspace(REGRESSION_X[0], REGRESSION_X[1], 41).map((g) => {28    const yh = fit.intercept + fit.slope * g;29    const half = critical * fit.s * Math.sqrt(1 / n + ((g - fit.xBar) * (g - fit.xBar)) / fit.sxx);30    return { x: g, y: yh, lo: yh - half, hi: yh + half };31  });32  return { trueSlope: p.slope, trueIntercept: p.intercept, sigma: p.sigma, points: x.map((v, i) => ({ x: v, y: y[i] })), fit, critical, band };33}3435const TXT = {36  fr: { title: "Régression linéaire simple par moindres carrés", data: "observations", fitted: "droite estimée", band: "bande de confiance à 95 %", truth: "vraie droite", slope: "Pente estimée (vraie)", inter: "Ordonnée estimée (vraie)", r2: "R²", s: "Écart-type résiduel s", n: "Observations" },37  en: { title: "Simple least-squares linear regression", data: "observations", fitted: "fitted line", band: "95% confidence band", truth: "true line", slope: "Estimated slope (true)", inter: "Estimated intercept (true)", r2: "R²", s: "Residual standard error s", n: "Observations" },38} as const;3940function RegressionView({ model: m, locale, idPrefix }: { model: RegressionModel; locale: Locale; idPrefix: string }) {41  const L = TXT[locale];42  const se = (v: number) => `± ${fmt(locale, v, 3)}`;43  return (44    <>45      <Plot locale={locale} idPrefix={idPrefix} spec={{46        title: L.title, xLabel: "x", yLabel: "y", xDomain: REGRESSION_X,47        layers: [48          { type: "band", points: m.band, tone: "blue", name: L.band },49          { type: "points", points: m.points, tone: "neutral", name: L.data, opacity: 0.6 },50          { type: "line", points: REGRESSION_X.map((x) => ({ x, y: m.trueIntercept + m.trueSlope * x })), tone: "amber", name: L.truth, dashed: true, width: 1.5 },51          { type: "line", points: m.band, tone: "blue", name: L.fitted },52        ],53      }} />54      <Readouts items={[55        { label: L.slope, value: `${fmt(locale, m.fit.slope, 3)} ${se(m.fit.seSlope)} (${fmt(locale, m.trueSlope, 2)})`, tone: "blue" },56        { label: L.inter, value: `${fmt(locale, m.fit.intercept, 3)} ${se(m.fit.seIntercept)} (${fmt(locale, m.trueIntercept, 2)})` },57        { label: L.r2, value: fmt(locale, m.fit.r2, 3) },58        { label: L.s, value: fmt(locale, m.fit.s, 3) },59        { label: L.n, value: fmtInt(locale, m.fit.n) },60      ]} />61    </>62  );63}6465export const regression: SimDef<RegressionModel> = {66  kind: "regression",67  title: { fr: "Régression linéaire simple (MCO)", en: "Simple linear regression (OLS)" },68  description: {69    fr: "Données $y = \\alpha + \\beta x + \\varepsilon$, avec $x$ uniforme sur $[0, 10]$ et $\\varepsilon \\sim \\mathcal{N}(0, \\sigma^2)$. La droite est estimée par moindres carrés ordinaires ; la bande est l'intervalle de confiance à 95 % de la réponse moyenne, $\\hat{y} \\pm t\\, s\\sqrt{1/n + (x - \\bar{x})^2/S_{xx}}$. Les valeurs après ± sont les erreurs types.",70    en: "Data $y = \\alpha + \\beta x + \\varepsilon$, with $x$ uniform on $[0, 10]$ and $\\varepsilon \\sim \\mathcal{N}(0, \\sigma^2)$. The line is fitted by ordinary least squares; the band is the 95% confidence interval of the mean response, $\\hat{y} \\pm t\\, s\\sqrt{1/n + (x - \\bar{x})^2/S_{xx}}$. Values after ± are standard errors.",71  },72  params: [73    param("slope", "Pente vraie β", "True slope β", -3, 3, 0.1, 1.5),74    param("intercept", "Ordonnée vraie α", "True intercept α", -5, 5, 0.5, 1),75    param("sigma", "Bruit σ", "Noise σ", 0, 6, 0.1, 2),76    param("n", "Observations n", "Observations n", 5, 200, 1, 40),77  ],78  stochastic: true,79  compute: (p, seed) => computeRegression(p, seed),80  View: RegressionView,81};82
Files main
Menu

Theme