""" Exemple sur DONNÉES FICTIVES pour l'article « Catégoriser des libellés bancaires français : règles, apprentissage ou les deux ». Aucune donnée réelle. Les libellés, les enseignes (génériques, inventées), les noms de personnes (inventés) et les montants sont générés ci-dessous avec une graine fixe : relancer le script redonne les mêmes chiffres. Bibliothèque standard uniquement. Exécution : python3 -I ce_fichier.py Ce que fait le script : 1. génère 2 000 libellés au format CB / PRLV / VIR, répartis en 13 catégories (10 divisions ECOICOP et 3 catégories propres à la banque) ; 2. sépare 1 400 libellés d'apprentissage (neuf premiers mois) et 600 libellés tenus à l'écart (trois mois suivants, avec des enseignes nouvelles) ; 3. compare un jeu de règles écrit à la main, un classifieur bayésien naïf multinomial sur les mots (lissage de Laplace) et un hybride (règles d'abord, modèle au-dessus d'un seuil de confiance, sinon « à vérifier ») ; 4. imprime précision et rappel par catégorie, moyennes micro et macro, la calibration des probabilités du modèle et trois libellés ambigus. """ import math import random import re from collections import Counter, defaultdict rng = random.Random(20261113) # --------------------------------------------------------------------------- # 1. Nomenclature : 10 divisions ECOICOP (intitulés INSEE) + 3 catégories bancaires # --------------------------------------------------------------------------- CATS = { "01": "Produits alimentaires et boissons non alcoolisées", "04": "Logement, eau, gaz, électricité et autres combustibles", "06": "Santé", "07": "Transports", "08": "Information et communication", "09": "Loisirs, sport et culture", "10": "Services de l'enseignement", "11": "Services de restauration et d'hébergement", "12": "Assurance et services financiers", "13": "Soins corporels, protection sociale et biens et services divers", "B1": "Revenus (banque)", "B2": "Virements internes et épargne (banque)", "B3": "Virements entre particuliers (banque)", } WEIGHTS = {"01": 22, "04": 8, "06": 4, "07": 12, "08": 6, "09": 7, "10": 1, "11": 10, "12": 5, "13": 5, "B1": 6, "B2": 8, "B3": 7} CITIES = ["LYON", "NANTES", "LILLE", "RENNES", "DIJON", "TOURS", "METZ", "ANGERS", "BREST", "NIMES", "PAU", "ANNECY", "VANNES", "ARRAS", "COLMAR"] # Noms manifestement inventés (aucun patronyme réel), un mot chacun. MAQUETTE sert aussi # de nom à une enseigne (ETS MAQUETTE ET FILS), comme un commerce qui porte le nom de son patron. SURNAMES = ["FICTIF", "MAQUETTE", "SPECIMEN", "ANONYME", "FACTICE", "INVENTE", "EXEMPLE", "PSEUDO", "PLACEBO", "UNTEL", "IMAGINAIRE", "SUPPOSE", "PRETENDU", "FAUXNOM", "SANSNOM"] # Enseignes génériques inventées, par catégorie. Les règles (plus bas) ne connaissent # qu'une partie de ces mots : c'est voulu, comme dans une vraie base de règles. CB_MERCHANTS = { "01": ["SUPERMARCHE DU PARC", "SUPER MARCHE DES HALLES", "EPICERIE DU CENTRE", "BOULANGERIE DU MARCHE", "BOUL. LES DEUX FOURS", "PRIMEUR DE LA PLACE", "HYPER LES PORTES", "FROMAGERIE DU VIEUX PONT", "MARCHE BIO DES QUAIS", "BOUCHERIE DU LAVOIR", "CAVE ET EPICERIE FINE", "DRIVE COURSES EST"], "06": ["PHARMACIE DE LA GARE", "PHARMA DU CENTRE", "CABINET DENTAIRE DES TILLEULS", "LABO ANALYSES DU NORD", "OPTIQUE DU BEFFROI", "DR KINESITHERAPIE"], "07": ["STATION DES ALPES", "STATION SERVICE DU RELAIS", "CARBURANT EXPRESS 24", "PEAGE AUTOROUTE A7", "PARKING DE LA GARE", "BILLET TRAIN EN LIGNE", "TRANSPORTS URBAINS METROPOLE", "GARAGE DU ROND POINT", "VELO PARTAGE VILLE"], "09": ["CINEMA LE GRAND ECRAN", "LIBRAIRIE DES ARCADES", "SALLE ESCALADE BLOC", "BILLETTERIE CONCERTS", "MUSEE DES BEAUX ARTS", "JARDINERIE DU VAL", "JEUX ET JOUETS DU PORT", "ARTICLES DE SPORT DU LAC"], "11": ["BRASSERIE DU PORT", "RESTAURANT LE PETIT ZINC", "PIZZERIA DU COIN", "CAFE DE LA MAIRIE", "HOTEL DES VOYAGEURS", "SNACK DU STADE", "LIVRAISON REPAS EN LIGNE", "CREPERIE DU CHATEAU", "SUSHI DE LA RIVE"], "13": ["COIFFURE DU CENTRE", "INSTITUT BEAUTE ZEN", "PARFUMERIE DE LA PLACE", "PRESSING DU MARCHE", "BIJOUTERIE HORLOGERIE DU PONT", "PHARMACIE DE LA GARE"], } # Enseignes apparues après la période d'apprentissage (jeu tenu à l'écart seulement). NEW_CB_MERCHANTS = { "01": ["MAISON DU PAIN", "LA HALLE AUX FRUITS", "SAS KORALIE", "AU PANIER FERMIER", "MINI MARKET 7J", "ETS MAQUETTE ET FILS"], "06": ["CENTRE DE SANTE VISUELLE", "SAS ORTHOPED"], "07": ["RECHARGE ELEC BORNE", "TROTTINETTE PARTAGE", "SAS AUTOPLUS"], "09": ["ESCAPE GAME LE CODE", "DISQUAIRE DU PASSAGE", "SAS LUDIK"], "11": ["LE COMPTOIR 47", "TRAITEUR DU SOLEIL", "FOOD TRUCK TACO", "SAS GOURMANDINE"], "13": ["BARBIER DU QUAI", "ONGLERIE PERLE"], } NEW_PRLV_CREDITORS = { "04": ["REGIE DES EAUX DU VAL", "COPROPRIETE LES ERABLES"], "08": ["OPERATEUR SIGMA TELECOM"], "09": ["ABONNEMENT MUSIQUE EN LIGNE"], "12": ["SAS PROTEGYS"], "13": ["SERVICES A LA PERSONNE DU VAL"], } PRLV_CREDITORS = { "04": ["ENERGIE DU SUD", "EAU DE LA METROPOLE", "GAZ ET CHALEUR SA", "SYNDIC RESIDENCE DES PINS", "FOURNISSEUR ELEC VERTE"], "07": ["ABONNEMENT TRANSPORTS METROPOLE", "TELEPEAGE AUTOROUTES"], "08": ["BOX FIBRE OPERATEUR ZETA", "MOBILE OPERATEUR OMEGA", "STREAMING VIDEO PLUS", "FORFAIT MOBILE KAPPA"], "09": ["ASSOC SPORTIVE DU QUARTIER", "CLUB DE NATATION", "SALLE DE SPORT FORME+", "ASSOC SPORTIVE ET CULTURELLE"], "12": ["ASSURANCE HABITATION MUTUELLE DU LAC", "ASSUR AUTO PROTECTA", "PREVOYANCE FAMILLE SA", "COTISATION CARTE BANCAIRE", "FRAIS TENUE DE COMPTE", "MUTUELLE SANTE DES ARTISANS"], "13": ["CRECHE LES PETITS PAS", "ASSOC AIDE A DOMICILE", "ASSOC SPORTIVE ET CULTURELLE"], "10": ["ECOLE DE LANGUES DU CENTRE", "COURS DE SOUTIEN SCOLAIRE", "UNIVERSITE DROITS INSCRIPTION", "ECOLE DE MUSIQUE MUNICIPALE"], } EMPLOYERS = ["SOCIETE INDUSTRIELLE DE L OUEST", "SARL BATI CONSEIL", "GROUPE LOGISTIQUE NORD", "CAISSE ALLOC FAMILIALES", "ASSUR RETRAITE REGIME GENERAL", "POLE EMPLOI REGION"] def date_ddmm(): return f"{rng.randint(1, 28):02d}/{rng.randint(1, 12):02d}" def noisy(label): """Abréviations, troncature à 32 caractères, références : le bruit des libellés réels.""" if rng.random() < 0.15: label = label.replace("SUPERMARCHE", "SUPERM").replace("PHARMACIE", "PHIE") \ .replace("RESTAURANT", "REST").replace("BOULANGERIE", "BOUL") \ .replace("ASSOCIATION", "ASSOC").replace("STATION", "STA") if rng.random() < 0.20: label = label[:32] return label def make_cb(cat, new=False): pool = NEW_CB_MERCHANTS[cat] if new and cat in NEW_CB_MERCHANTS else CB_MERCHANTS[cat] m = rng.choice(pool) form = rng.random() if form < 0.5: lab = f"CB {m} {date_ddmm()} {rng.choice(CITIES)}" elif form < 0.8: lab = f"PAIEMENT CB {date_ddmm()} {rng.choice(CITIES)} {m}" else: lab = f"CARTE X{rng.randint(1000, 9999)} {date_ddmm()} {m}" return noisy(lab) def make_prlv(cat, new=False): pool = NEW_PRLV_CREDITORS[cat] if new and cat in NEW_PRLV_CREDITORS else PRLV_CREDITORS[cat] c = rng.choice(pool) ref = rng.randint(100000, 999999) if rng.random() < 0.6: lab = f"PRLV SEPA {c} ECH/{rng.randint(1, 28):02d}{rng.randint(1, 12):02d}26 MDT/{ref}" else: lab = f"PRELEVEMENT {c} REF {ref}" return noisy(lab) def make_label(cat, new=False): """Renvoie (libellé, catégorie vraie). Les catégories vraies existent car les données sont générées ; sur des données réelles, c'est l'étiquetage humain qui les fixe.""" if cat in ("01", "06", "11"): return make_cb(cat, new) if cat == "13": return make_prlv(cat, new) if rng.random() < 0.4 else make_cb(cat, new) if cat == "09": return make_prlv(cat, new) if rng.random() < 0.35 else make_cb(cat, new) if cat == "07": return make_prlv(cat, new) if rng.random() < 0.2 else make_cb(cat, new) if cat == "10": return make_prlv(cat, new) if cat in ("04", "08", "12"): if cat == "04" and rng.random() < 0.35: # loyer versé par virement à un particulier : même forme qu'un remboursement return f"VIR INST M. {rng.choice(SURNAMES)}" + (" LOYER" if rng.random() < 0.4 else "") return make_prlv(cat, new) if cat == "B1": e = rng.choice(EMPLOYERS) motif = rng.choice(["SALAIRE", "PAIE", "VERSEMENT", "PRESTATIONS"]) return noisy(f"VIR SEPA RECU /DE {e} /MOTIF {motif} {rng.randint(1, 12):02d}/26") if cat == "B2": return rng.choice([ f"VIR VERS LIVRET A {rng.randint(10000, 99999)}", f"VIR PERMANENT EPARGNE {rng.randint(10000, 99999)}", f"VIR INTERNE COMPTE JOINT", f"VIREMENT DE VOTRE COMPTE {rng.randint(10000, 99999)}", f"VIR INST VERS LDDS {rng.randint(10000, 99999)}", ]) if cat == "B3": motif = rng.choice(["", "", " REMBT", " RESTO", " CADEAU", " WEEKEND", " MERCI"]) return f"VIR INST M. {rng.choice(SURNAMES)}{motif}" raise ValueError(cat) population = [c for c, w in WEIGHTS.items() for _ in range(w)] # Apprentissage : 1 400 libellés des neuf premiers mois. Jeu tenu à l'écart : 600 libellés # des trois mois suivants, dont une part d'enseignes et de créanciers nouveaux. NEW_SHARE = 0.30 train = [(make_label(c), c) for c in (rng.choice(population) for _ in range(1400))] test = [] for _ in range(600): c = rng.choice(population) test.append((make_label(c, new=rng.random() < NEW_SHARE), c)) data = train + test # --------------------------------------------------------------------------- # 2. Règles écrites à la main, dans l'ordre : la première qui s'applique gagne. # Elles ont été écrites en regardant une partie des enseignes, pas toutes. # --------------------------------------------------------------------------- RULES = [ (r"\bLIVRET A\b|\bLDDS\b|\bEPARGNE\b|COMPTE JOINT|DE VOTRE COMPTE", "B2"), (r"\bSALAIRE\b|\bPAIE\b|ALLOC FAMILIALES|RETRAITE|POLE EMPLOI", "B1"), (r"\bLOYER\b", "04"), (r"\bVIR INST M\.", "B3"), (r"ENERGIE|\bELEC\b|\bGAZ\b|\bEAU DE\b|SYNDIC", "04"), (r"ASSURANCE|\bASSUR\b|PREVOYANCE|MUTUELLE|COTISATION CARTE|FRAIS TENUE", "12"), (r"\bBOX\b|\bMOBILE\b|\bFIBRE\b|STREAMING|FORFAIT", "08"), (r"PHARMACIE|\bPHIE\b|DENTAIRE|\bLABO\b|OPTIQUE|KINE", "06"), (r"COIFFURE|BEAUTE|PARFUMERIE|PRESSING|BIJOUTERIE|CRECHE", "13"), (r"SUPERMARCHE|\bSUPERM\b|EPICERIE|BOULANGERIE|\bBOUL\b|PRIMEUR|\bHYPER\b|BOUCHERIE", "01"), (r"STATION|\bSTA\b|CARBURANT|PEAGE|PARKING|BILLET TRAIN|TRANSPORTS|GARAGE", "07"), (r"BRASSERIE|RESTAURANT|\bREST\b|PIZZERIA|\bCAFE\b|HOTEL|SNACK|CREPERIE", "11"), (r"CINEMA|LIBRAIRIE|ESCALADE|MUSEE|BILLETTERIE|\bCLUB\b|SALLE DE SPORT|JARDINERIE", "09"), (r"ASSOC SPORTIVE", "09"), ] N_RULE_LINES = sum(r.count("|") + 1 for r, _ in RULES) COMPILED = [(re.compile(r), c) for r, c in RULES] def rules_predict(label): for rx, c in COMPILED: if rx.search(label): return c return None # --------------------------------------------------------------------------- # 3. Bayésien naïf multinomial sur les mots, lissage de Laplace (alpha = 1) # --------------------------------------------------------------------------- def tokens(label): out = [] for t in re.findall(r"[A-Z]+", label): if len(t) >= 2: out.append(t) return out class NaiveBayes: def fit(self, rows): self.count_c = Counter(c for _, c in rows) self.word_c = defaultdict(Counter) vocab = set() for lab, c in rows: for t in tokens(lab): self.word_c[c][t] += 1 vocab.add(t) self.vocab = vocab self.total_w = {c: sum(self.word_c[c].values()) for c in self.count_c} self.n = len(rows) return self def posterior(self, label): V = len(self.vocab) scores = {} for c in self.count_c: s = math.log(self.count_c[c] / self.n) for t in tokens(label): if t in self.vocab: # mot jamais vu : ignoré s += math.log((self.word_c[c][t] + 1) / (self.total_w[c] + V)) scores[c] = s m = max(scores.values()) z = sum(math.exp(v - m) for v in scores.values()) return {c: math.exp(v - m) / z for c, v in scores.items()} def predict(self, label): p = self.posterior(label) c = max(p, key=p.get) return c, p[c] nb = NaiveBayes().fit(train) # --------------------------------------------------------------------------- # 4. Mesures # --------------------------------------------------------------------------- def fr(x, d=1): return f"{x:.{d}f}".replace(".", ",") def pct(num, den): return "n.d." if den == 0 else fr(100 * num / den) + " %" def evaluate(preds): """preds : liste de (vrai, prédit ou None). Renvoie stats par catégorie et moyennes.""" tp, fp, fn = Counter(), Counter(), Counter() for y, p in preds: if p == y: tp[y] += 1 else: fn[y] += 1 if p is not None: fp[p] += 1 per = {} for c in CATS: prec = tp[c] / (tp[c] + fp[c]) if tp[c] + fp[c] else None rec = tp[c] / (tp[c] + fn[c]) if tp[c] + fn[c] else None per[c] = (prec, rec, tp[c] + fn[c]) # micro : sur toutes les paires ; macro : moyenne simple des catégories micro_p = sum(tp.values()) / max(1, sum(tp.values()) + sum(fp.values())) micro_r = sum(tp.values()) / max(1, sum(tp.values()) + sum(fn.values())) precs = [v[0] if v[0] is not None else 0.0 for v in per.values()] recs = [v[1] for v in per.values() if v[1] is not None] return per, micro_p, micro_r, sum(precs) / len(precs), sum(recs) / len(recs) THRESHOLD = 0.90 # fixé avant la mesure rule_preds, nb_preds, hyb_preds = [], [], [] hyb_source = Counter() nb_conf = [] for lab, y in test: r = rules_predict(lab) c, p = nb.predict(lab) rule_preds.append((y, r)) nb_preds.append((y, c)) nb_conf.append((p, c == y)) if r is not None: hyb_preds.append((y, r)); hyb_source["règle"] += 1 elif p >= THRESHOLD: hyb_preds.append((y, c)); hyb_source["modèle"] += 1 else: hyb_preds.append((y, None)); hyb_source["à vérifier"] += 1 print("=== Jeu de données fictif ===") print(f"Libellés : {len(data)} ; apprentissage : {len(train)} ; tenus à l'écart : {len(test)}") print(f"Lignes de règles (alternatives comprises) : {N_RULE_LINES} ; règles : {len(RULES)}") print(f"Vocabulaire du modèle : {len(nb.vocab)} mots") print("Effectif du jeu tenu à l'écart par catégorie :", ", ".join(f"{c} {sum(1 for _, y in test if y == c)}" for c in CATS)) print() print("Exemples de libellés générés :") for lab, y in data[:8]: print(f" [{y}] {lab}") print() for name, preds in (("Règles seules", rule_preds), ("Bayésien naïf seul", nb_preds), (f"Hybride (règles, puis modèle si confiance >= {fr(THRESHOLD, 2)})", hyb_preds)): per, mp, mr, Mp, Mr = evaluate(preds) unclassified = sum(1 for _, p in preds if p is None) print(f"=== {name} ===") print(f"Non classés : {unclassified} sur {len(preds)} ({pct(unclassified, len(preds))})") print(f"{'cat':4} {'eff.':>5} {'précision':>11} {'rappel':>9}") for c, (p, r, n) in per.items(): ps = "n.d." if p is None else fr(100 * p) + " %" rs = "n.d." if r is None else fr(100 * r) + " %" print(f"{c:4} {n:5d} {ps:>11} {rs:>9}") print(f"Micro : précision {fr(100 * mp)} %, rappel {fr(100 * mr)} %") print(f"Macro : précision {fr(100 * Mp)} %, rappel {fr(100 * Mr)} %") print() print("=== Hybride : origine des décisions ===") for k in ("règle", "modèle", "à vérifier"): print(f"{k} : {hyb_source[k]} ({pct(hyb_source[k], len(test))})") model_ok = sum(1 for (lab, y), (yy, p) in zip(test, hyb_preds) if rules_predict(lab) is None and p is not None and p == y) print(f"Décisions du modèle justes : {model_ok} sur {hyb_source['modèle']} " f"({pct(model_ok, hyb_source['modèle'])})") print() print("=== Hybride : effet du seuil de confiance (libellés sans règle) ===") no_rule = [(y, c, p) for (lab, y), (p, _ok), (_y, c) in zip(test, nb_conf, nb_preds) if rules_predict(lab) is None] print(f"Libellés sans règle : {len(no_rule)}") for th in (0.0, 0.60, 0.90, 0.99): kept = [(y, c) for y, c, p in no_rule if p >= th] ok = sum(1 for y, c in kept if y == c) print(f"seuil {fr(th, 2)} : modèle décide {len(kept)} ({pct(len(kept), len(no_rule))}), " f"justes {ok} ({pct(ok, len(kept))}), à vérifier {len(no_rule) - len(kept)}") print() print("=== Calibration du bayésien naïf (jeu tenu à l'écart) ===") bins = [(0.0, 0.6), (0.6, 0.9), (0.9, 0.99), (0.99, 1.0001)] for lo, hi in bins: sel = [(p, ok) for p, ok in nb_conf if lo <= p < hi] if sel: mean_p = sum(p for p, _ in sel) / len(sel) acc = sum(ok for _, ok in sel) / len(sel) print(f"confiance [{fr(lo, 2)} ; {fr(min(hi, 1.0), 2)}[ : {len(sel)} libellés, " f"confiance moyenne {fr(100 * mean_p)} %, taux de bonnes réponses {fr(100 * acc)} %") print() print("=== Trois libellés ambigus ===") for lab in ("VIR INST M. EXEMPLE", "CB PHARMACIE DE LA GARE 14/10 TOURS", "PRLV SEPA ASSOC SPORTIVE ET CULTURELLE ECH/0510 MDT/481516"): post = nb.posterior(lab) top = sorted(post.items(), key=lambda kv: -kv[1])[:3] if lab.startswith("VIR INST M."): same = lambda l: re.fullmatch(r"VIR INST M\. [A-Z]+", l) is not None # sans motif elif "PHARMACIE DE LA GARE" in lab: same = lambda l: "PHARMACIE DE LA GARE" in l else: same = lambda l: "ASSOC SPORTIVE ET CULTURELLE" in l truth = Counter(y for l, y in data if same(l)) print(f"{lab}") print(f" règle : {rules_predict(lab)} ; modèle : " + ", ".join(f"{c} {fr(100 * p)} %" for c, p in top)) print(" catégories vraies des libellés de même forme dans le jeu fictif : " + ", ".join(f"{c} {n}" for c, n in truth.most_common())) print() print("=== Erreurs des règles (catégorie vraie -> catégorie de la règle, motif) ===") errs = Counter() for lab, y in test: r = rules_predict(lab) if r is not None and r != y: key = ("RECHARGE ELEC BORNE" if "RECHARGE" in lab else "PRESTATIONS" if "PRESTATIONS" in lab else "VIR INST (loyer)" if lab.startswith("VIR INST") else "PHARMACIE" if ("PHARMACIE" in lab or "PHIE" in lab) else "ASSOC SPORTIVE ET CULTURELLE" if "ASSOC SPORTIVE ET CULTURELLE" in lab else lab) errs[(y, r, key)] += 1 for (y, r, key), n in errs.most_common(): print(f" {y} -> {r} : {key} x {n}") print() print("=== Libellés d'enseignement du jeu tenu à l'écart : réponse du modèle ===") for lab, y in test: if y == "10": c, p = nb.predict(lab) print(f" {lab} -> {c} ({fr(p, 2)})")