Spelling Correction using probability#

This tutorial is available as an IPython notebook at Malaya/example/spelling-correction-probability.

This spelling correction extends the functionality of the Peter Norvig’s spell-corrector in http://norvig.com/spell-correct.html

And improve it using some algorithms from Normalization of noisy texts in Malaysian online reviews, https://www.researchgate.net/publication/287050449_Normalization_of_noisy_texts_in_Malaysian_online_reviews

Also added custom vowels augmentation.

[1]:
import os

os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['TF_FORCE_GPU_ALLOW_GROWTH'] = 'true'
[2]:
import malaya
/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/cextension.py:34: UserWarning: The installed version of bitsandbytes was compiled without GPU support. 8-bit optimizers, 8-bit multiplication, and GPU quantization are unavailable.
  warn("The installed version of bitsandbytes was compiled without GPU support. "
/home/husein/.local/lib/python3.8/site-packages/bitsandbytes/libbitsandbytes_cpu.so: undefined symbol: cadam32bit_grad_fp32
/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3397
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
/home/husein/dev/malaya/malaya/tokenizer.py:214: FutureWarning: Possible nested set at position 3927
  self.tok = re.compile(r'({})'.format('|'.join(pipeline)))
[3]:
# some text examples copied from Twitter

string1 = 'krajaan patut bagi pencen awal skt kpd warga emas supaya emosi'
string2 = 'Husein ska mkn aym dkat kampng Jawa'
string3 = 'Melayu malas ni narration dia sama je macam men are trash. True to some, false to some.'
string4 = 'Tapi tak pikir ke bahaya perpetuate myths camtu. Nanti kalau ada hiring discrimination despite your good qualifications because of your race tau pulak marah. Your kids will be victims of that too.'
string5 = 'DrM cerita Melayu malas semenjak saya kat University (early 1980s) and now as i am edging towards retirement in 4-5 years time after a career of being an Engineer, Project Manager, General Manager'
string6 = 'blh bntg dlm kls nlp sy, nnti intch'
string7 = 'mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik'

Load probability model#

def load(
    language_model=None,
    sentence_piece: bool = False,
    stemmer=None,
    additional_words: Dict[str, int] = {'ni': 100000, 'pun': 100000, 'la': 100000},
    **kwargs,
):
    """
    Load a Probability Spell Corrector.

    Parameters
    ----------
    language_model: Callable, optional (default=None)
        If not None, must an object with `score` method.
    sentence_piece: bool, optional (default=False)
        if True, reduce possible augmentation states using sentence piece.
    stemmer: Callable, optional (default=None)
        a Callable object, must have `stem_word` method.
    additional_words: Dict[str, int], (default={'ni': 100000, 'pun': 100000, 'la': 100000})
        additional bias vocab.

    Returns
    -------
    result: model
        List of model classes:

        * if passed `language_model` will return `malaya.spelling_correction.probability.ProbabilityLM`.
        * else will return `malaya.spelling_correction.probability.Probability`.
    """
[4]:
model = malaya.spelling_correction.probability.load()

List possible generated pool of words#

def edit_candidates(self, word):
    """
    Generate candidates given a word.

    Parameters
    ----------
    word: str

    Returns
    -------
    result: List[str]
    """
[5]:
model.edit_candidates('mhthir')
[5]:
['mahathir']
[6]:
model.edit_candidates('smbng')
[6]:
['sembing',
 'sambang',
 'sumbang',
 'sembung',
 'sumbing',
 'sombong',
 'sambung',
 'sembong',
 'sembang',
 'sambong',
 'simbang']

Now you can see, edit_candidates suggested quite a lot candidates and some of candidates not an actual word like sambang, to reduce that, we can use sentencepiece to check a candidate a legit word for malaysia context or not.

[8]:
model_sp = malaya.spelling_correction.probability.load(sentence_piece = True)
model_sp.edit_candidates('smbng')
[8]:
['sembing',
 'sumbang',
 'sembung',
 'sumbing',
 'sombong',
 'sambung',
 'sembong',
 'sembang',
 'sambong']

So how does the model knows which words need to pick? highest counts from the corpus!

To correct a word#

def correct(self, word: str, **kwargs):
    """
    Most probable spelling correction for word.

    Parameters
    ----------
    word: str

    Returns
    -------
    result: str
    """
[9]:
model.correct('suke')
[9]:
'suka'
[10]:
model.correct('kpd')
[10]:
'kpd'
[11]:
model.correct('krajaan')
[11]:
'kerajaan'

To correct a sentence#

def correct_text(self, text: str):
    """
    Correct all the words within a text, returning the corrected text.

    Parameters
    ----------
    text: str

    Returns
    -------
    result: str
    """
[12]:
model.correct_text(string1)
[12]:
'kerajaan patut bagi pencen awal sakit kpd warga emas supaya emosi'
[13]:
tokenizer = malaya.tokenizer.Tokenizer()
[14]:
string2
[14]:
'Husein ska mkn aym dkat kampng Jawa'
[15]:
tokenized = tokenizer.tokenize(string2)
model.correct_text(' '.join(tokenized))
[15]:
'Hussein ska makan ayam dekat kampung Jawa'
[16]:
tokenized = tokenizer.tokenize(string3)
model.correct_text(' '.join(tokenized))
[16]:
'Melayu malas ni narration dia sama je macam men are trash . True to some , false to some .'
[17]:
tokenized = tokenizer.tokenize(string5)
model.correct_text(' '.join(tokenized))
[17]:
'DrM cerita Melayu malas semenjak saya kat University ( early 1980s ) and now isu i am edging towards retirement ini 4 - 5 years time after a career of being ini Engineer , Project Manager , General Manager'
[18]:
tokenized = tokenizer.tokenize(string6)
model.correct_text(' '.join(tokenized))
[18]:
'blh bintang dlm kelas nlp saya , nnti intch'
[19]:
tokenized = tokenizer.tokenize(string7)
model.correct_text(' '.join(tokenized))
[19]:
'mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik'
[20]:
model.edit_candidates('slhkn')
[20]:
['slhkan',
 'salahkan',
 'silahkn',
 'suluhkan',
 'salahakan',
 'slahkan',
 'silahkan']

Load stemmer for probability model#

By default kata imbuhan captured using naive regex pattern without understand the word structure, and problem with that, there are so many rules need to hardcode, so we can use better stemmer model like malaya.stem.huggingface().

[21]:
stemmer = malaya.stem.huggingface()
Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.
[22]:
model_stemmer = malaya.spelling_correction.probability.load(stemmer = stemmer)
[23]:
model_stemmer.edit_candidates('slhkn')
[23]:
['slhkan',
 'salahkan',
 'silahkn',
 'suluhkan',
 'salahakan',
 'slahkan',
 'silahkan']
[24]:
tokenized = tokenizer.tokenize(string7)
model_stemmer.correct_text(' '.join(tokenized))
spaces_between_special_tokens is deprecated and will be removed in transformers v5. It was adding spaces between `added_tokens`, not special tokens, and does not exist in our fast implementation. Future tokenizers will handle the decoding process on a per-model rule.
[24]:
'mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik'
[26]:
s = 'mulakn slh org boleh ,bila geng tuh kena slhkn jgk xboleh trima .. pelik , dia slhkn org bole hri2 crta sakau then bila kna bls balik xdpt jwb ,kata mcm biasa slh (parti sampah) 🤣🤣🤣 jgn mulakn dlu slhkn org kalau xboleh trima bila kna bls balik 🤣🤣🤣'
[27]:
tokenized = tokenizer.tokenize(s)
model_stemmer.correct_text(' '.join(tokenized))
[27]:
'mulakan slh org boleh , bila geng tuh kena salahkan jgk xboleh trima . . pelik , dia salahkan org bole hri2 cerita sakau then bila kena bilis balik xdpt jwb , kata mcm biasa slh ( parti sampah ) 🤣 🤣 🤣 jgn mulakan dlu salahkan org kalau xboleh trima bila kena bilis balik 🤣 🤣 🤣'