目錄
- 定義
- BLEU算法詳解
- NLTK實現
一、定義
BLEU (其全稱為Bilingual Evaluation Understudy), 其意思是雙語評估替補。所謂Understudy (替補),意思是代替人進行翻譯結果的評估。盡管這項指標是為翻譯而發明的,但它可以用於評估一組自然語言處理任務生成的文本。
它是用於評估候選句子(candidate)和參考句子(reference)的差異的指標.它的取值范圍在0.0到1.0之間, 如果兩個句子完美匹配(perfect match), 那么BLEU是1.0, 反之, 如果兩個句子完美不匹配(perfect mismatch), 那么BLEU為0.0.原論文可見【1】,IBM出品。
二、BLEU算法詳解
2.1 主要公式
其中:BP(Brevity Penalty),翻譯過來就是"過短懲罰"。由BP的公式可知取值范圍是(0,1],候選句子越短,越接近0。c 表示候選句子長度,r 表示參考句子長度。
2.2 n-gram precision
candinate: the cat sat on the mat
reference: the cat is on the mat
三、NLTK實現
可以直接用工具包實現,代碼如下:
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
from nltk.translate.bleu_score import sentence_bleu, corpus_bleu
from nltk.translate.bleu_score import SmoothingFunction
reference = [['The', 'cat', 'is', 'on', 'the', 'mat']]
candidate = ['The', 'cat', 'sat', 'on', 'the', 'mat']
smooth = SmoothingFunction() # 定義平滑函數對象
score = sentence_bleu(reference, candidate, weight=(0.25,0.25, 0.25, 0.25), smoothing_function=smooth.method1)
corpus_score = corpus_bleu([reference], [candidate], smoothing_function=smooth.method1)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
代碼說明:NLTK中提供了兩種計算BLEU的方法,實際上在sentence_bleu中是調用了corpus_bleu方法
注意reference和candinate連個參數的列表嵌套不要錯了(我的理解: 比Sentence的都多加了一個維度)
weight參數是設置不同的n−gram的權重,weight中的數量決定了計算BLEU時,會用幾個n−gram,以上面為例,會用1−gram,2−gram,3−gram,4−gram(默認是4-gram,並且是均值,也就是不寫參數也會是本例一樣的效果)。SmoothingFunction是用來平滑log函數的結果的,防止fn=0時,取對數為負無窮。
參考文獻
【1】來源 BLEU: a Method for Automatic Evaluation of Machine Translation
【2】機器翻譯評價指標 — BLEU算法:https://www.cnblogs.com/jiangxinyang/p/10523585.html