lm_scorer.py 2.3 KB
Newer Older
Y
Yibing Liu 已提交
1 2 3 4 5 6 7 8 9 10
"""External Scorer for Beam Search Decoder."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import kenlm
import numpy as np


Y
Yibing Liu 已提交
11 12 13 14
class LmScorer(object):
    """External scorer to evaluate a prefix or whole sentence in
       beam search decoding, including the score from n-gram language
       model and word count.
Y
Yibing Liu 已提交
15

Y
Yibing Liu 已提交
16 17
    :param alpha: Parameter associated with language model. Don't use
                  language model when alpha = 0.
Y
Yibing Liu 已提交
18
    :type alpha: float
Y
Yibing Liu 已提交
19 20
    :param beta: Parameter associated with word count. Don't use word
                count when beta = 0.
Y
Yibing Liu 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33
    :type beta: float
    :model_path: Path to load language model.
    :type model_path: basestring
    """

    def __init__(self, alpha, beta, model_path):
        self._alpha = alpha
        self._beta = beta
        if not os.path.isfile(model_path):
            raise IOError("Invaid language model path: %s" % model_path)
        self._language_model = kenlm.LanguageModel(model_path)

    # n-gram language model scoring
Y
Yibing Liu 已提交
34
    def _language_model_score(self, sentence):
Y
Yibing Liu 已提交
35 36 37 38 39 40
        #log10 prob of last word
        log_cond_prob = list(
            self._language_model.full_scores(sentence, eos=False))[-1][0]
        return np.power(10, log_cond_prob)

    # word insertion term
Y
Yibing Liu 已提交
41
    def _word_count(self, sentence):
Y
Yibing Liu 已提交
42 43 44
        words = sentence.strip().split(' ')
        return len(words)

Y
Yibing Liu 已提交
45 46 47 48 49
    # reset alpha and beta
    def reset_params(self, alpha, beta):
        self._alpha = alpha
        self._beta = beta

Y
Yibing Liu 已提交
50 51 52 53 54 55 56 57 58 59 60 61
    # execute evaluation
    def __call__(self, sentence, log=False):
        """Evaluation function, gathering all the different scores
        and return the final one.

        :param sentence: The input sentence for evalutation
        :type sentence: basestring
        :param log: Whether return the score in log representation.
        :type log: bool
        :return: Evaluation score, in the decimal or log.
        :rtype: float
        """
Y
Yibing Liu 已提交
62 63
        lm = self._language_model_score(sentence)
        word_cnt = self._word_count(sentence)
Y
Yibing Liu 已提交
64
        if log == False:
Y
Yibing Liu 已提交
65
            score = np.power(lm, self._alpha) * np.power(word_cnt, self._beta)
Y
Yibing Liu 已提交
66
        else:
Y
Yibing Liu 已提交
67
            score = self._alpha * np.log(lm) + self._beta * np.log(word_cnt)
Y
Yibing Liu 已提交
68
        return score