Repository Public MIT Research preview
1"""Laboratoire S01 — CORRIGÉ (réservé à l'enseignant). Ne pas distribuer avec le matériel de départ."""2from __future__ import annotations34import random5from collections import Counter678def compter_suites(corpus: list[str]) -> dict[str, Counter]:9 suites: dict[str, Counter] = {}10 for phrase in corpus:11 mots = phrase.split()12 for mot, suivant in zip(mots, mots[1:]):13 suites.setdefault(mot, Counter())[suivant] += 114 return suites151617def distribution_suivant(suites: dict[str, Counter], mot: str) -> dict[str, float]:18 comptes = suites.get(mot)19 if not comptes:20 return {}21 total = sum(comptes.values())22 return {suivant: n / total for suivant, n in sorted(comptes.items(), key=lambda mc: (-mc[1], mc[0]))}232425def generer(suites: dict[str, Counter], amorce: str, graine: int, longueur_max: int = 12) -> list[str]:26 hasard = random.Random(graine)27 texte = [amorce]28 while len(texte) < longueur_max and texte[-1] != ".":29 distribution = distribution_suivant(suites, texte[-1])30 if not distribution:31 break32 mots = list(distribution)33 texte.append(hasard.choices(mots, weights=[distribution[m] for m in mots], k=1)[0])34 return texte353637def appliquer_temperature(distribution: dict[str, float], temperature: float) -> dict[str, float]:38 """Défi : température < 1 = distribution plus pointue ; > 1 = plus étalée ; 1 = inchangée."""39 if temperature <= 0:40 raise ValueError("la température doit être strictement positive")41 ajustees = {mot: p ** (1 / temperature) for mot, p in distribution.items()}42 total = sum(ajustees.values())43 return {mot: v / total for mot, v in ajustees.items()}444546def generer_avec_temperature(suites, amorce: str, graine: int, temperature: float,47 longueur_max: int = 12) -> list[str]:48 hasard = random.Random(graine)49 texte = [amorce]50 while len(texte) < longueur_max and texte[-1] != ".":51 distribution = distribution_suivant(suites, texte[-1])52 if not distribution:53 break54 distribution = appliquer_temperature(distribution, temperature)55 mots = list(distribution)56 texte.append(hasard.choices(mots, weights=[distribution[m] for m in mots], k=1)[0])57 return texte585960def mesurer_diversite(suites, temperature: float, essais: int = 200) -> int:61 """Nombre de phrases différentes obtenues en `essais` générations (graines 0 à essais-1)."""62 return len({" ".join(generer_avec_temperature(suites, "le", g, temperature)) for g in range(essais)})636465if __name__ == "__main__":66 from corpus import CORPUS6768 s = compter_suites(CORPUS)69 print("Effet de la température sur le mot qui suit « le » (calcul exact, sans tirage) :")70 for t in (0.5, 1.0, 2.0):71 d = appliquer_temperature(distribution_suivant(s, "le"), t)72 print(f" température {t:>3} : P(chat) = {d['chat']:.3f} ; P(grenier) = {d['grenier']:.3f}")73 print("Nombre de phrases différentes sur 200 générations (graines 0 à 199) :")74 for t in (0.5, 1.0, 2.0):75 print(f" température {t:>3} : {mesurer_diversite(s, t)}")76