Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- #####
- # Clément Hamel-Doyon - 18099246
- ###
- from pdb import set_trace as dbg # Utiliser dbg() pour faire un break dans votre code.
- import numpy as np
- import math
- class Correcteur:
- def __init__(self, p_init, p_transition, p_observation, int2letters, letters2int):
- '''Correcteur de frappes dans un mot.
- Modèle de Markov caché (HMM) permettant de corriger les erreurs de frappes
- dans un mot. La correction est dictée par l'inférence de l'explication
- la plus pausible du modèle.
- Parameters
- ------------
- p_init : array-like shape (N,)
- Probabilités initiales de l'état caché à la première position.
- p_transition : array-like shape (X,Y)
- Modèle de transition.
- p_observation : array-like shape (X,Y)
- Modèle d'observation.
- int2letters : list
- Associe un entier (l'indice) à une lettre.
- letters2int : dict
- Associe une lettre (clé) à un entier (valeur).
- '''
- self.p_init = p_init
- self.p_transition = p_transition
- self.p_observation = p_observation
- self.int2letters = int2letters
- self.letters2int = letters2int
- def corrige(self, mot):
- '''Corrige les frappes dans un mot.
- Retourne la correction du mot donné et la probabilité p(mot, mot corrigé).
- Parameters
- ------------
- mot : string
- Mot à corriger.
- Returns
- -----------
- mot_corrige : string
- Le mot corrigé.
- prob : float
- Probabilité dans le HMM du mot observé et du mot corrigé.
- C'est-à-dire 'p(mot, mot_corrige)'.
- '''
- a = np.empty([26, len(mot)])
- for t in range(len(mot)):
- for i in range(26):
- if t == 0:
- a[i, t] = self.p_init[i] * self.p_observation[self.letters2int[mot[t]], i]
- else:
- a[i, t] = self.p_observation[self.letters2int[mot[t]], i] * self.sumPrecedence(a, t, i)
- #print("a[", i, ",", t, "]=", a[i, t])
- mot_corrige = ""
- total_prob = 1.0
- for t in range(len(mot)):
- current_prob = 0
- current_letter = None
- for i in range(26):
- prob = a[i, t]# / self.sumProb(a, t)
- if prob > current_prob:
- #if current_letter is not None:
- # print("#", t, ": ", self.int2letters[i], "[", prob, "] VS ", self.int2letters[current_letter], "[", current_prob,"]")
- current_prob = prob
- current_letter = i
- mot_corrige += self.int2letters[current_letter]
- total_prob *= a[current_letter, t]
- # Retourne le mot sans correction avec une probabilité de 0.0 (.~= À MODIFIER =~.)
- return mot_corrige, total_prob
- def sumProb(self, a, t_index):
- sum = 0.0
- for i in range(26):
- sum += a[i, t_index]
- return sum
- def sumPrecedence(self, a, t_index, i_index):
- sum = 0.0
- for i in range(26):
- sum += (self.p_transition[i_index, i] * a[i, (t_index - 1)])
- return sum
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement