Python 评估神经机器翻译的BLEU评分

Python 评估神经机器翻译的BLEU评分

在NLP中使用NMT或神经机器翻译,我们可以将给定语言的文本翻译为目标语言。为了评估翻译的质量,我们使用Python中的BLEU或双语评估学习分数。

BLEU评分通过比较机器翻译的句子和人工翻译的句子的n-gram来进行。此外,随着句子长度的增加,BLEU分数会减少。一般来说,BLEU分数的范围在0到1之间,较高的值表示质量较好。然而,达到完美的分数非常罕见。请注意,评估是基于子字符串匹配进行的,它不考虑语言的连贯性、时态和语法等其他方面。

公式

BLEU = BP * exp(1/n * sum_{i=1}^{n} log(p_i))

在这里,各种术语具有以下含义 –

  • BP 是缩略惩罚。它基于两个文本的长度调整BLEU分数。它的公式如下 –
BP = min(1, exp(1 - (r / c)))
  • n是n-gram匹配的最大顺序

  • p_i是精确度分数

步骤

  • 步骤1 - 导入数据集库。

  • 步骤2 - 使用load_metric函数,并将参数设置为bleu。

  • 步骤3 - 将翻译后的字符串的单词制作成列表。

  • 步骤4 - 使用期望输出字符串的单词重复步骤3。

  • 步骤5 - 使用bleu.compute找到BLEU值。

示例1

在这个示例中,我们将使用Python的NLTK库计算将德语句子机器翻译为英语的BLEU分数。

  • 源文本(德语) – es regnet heute

  • 机器翻译文本 – it rain today

  • 期望文本 – it is raining today, it was raining today

虽然我们可以看到翻译并没有做得很正确,但通过找到BLUE分数,我们可以更好地评估翻译质量。

示例

#import the libraries
from datasets import load_metric

#use the load_metric function
bleu = load_metric("bleu")

#setup the predicted string
predictions = [["it", "rain", "today"]]

#setup the desired string
references = [
   [["it", "is", "raining", "today"], 
   ["it", "was", "raining", "today"]]
]

#print the values
print(bleu.compute(predictions=predictions, references=references))

输出

{'bleu': 0.0, 'precisions': [0.6666666666666666, 0.0, 0.0, 0.0], 'brevity_penalty': 0.7165313105737893, 'length_ratio': 0.75, 'translation_length': 3, 'reference_length': 4}

你可以看到翻译质量不好,因此 BLEU 得分为 0。

示例 2

在这个例子中,我们将再次计算 BLEU 分数。但是这一次,我们将使用一个被机器翻译成英文的法语句子。

  • 原始文本(德语)− nous partons en voyage

  • 机器翻译文本− we going on a trip

  • 期望文本− we are going on a trip, we were going on a trip

你可以看到这次翻译的文本更接近期望文本。让我们为它检查 BLEU 分数。

示例

#import the libraries
from datasets import load_metric

#use the load_metric function
bleu = load_metric("bleu")

#steup the predicted string
predictions = [["we", "going", "on", "a", "trip"]]

#steup the desired string
references = [
   [["we", "are", "going", "on", "a", "trip"], 
   ["we", "were", "going", "on", "a", "trip"]]
]

#print the values
print(bleu.compute(predictions=predictions, references=references))

输出

{'bleu': 0.5789300674674098, 'precisions': [1.0, 0.75, 0.6666666666666666, 0.5], 'brevity_penalty': 0.8187307530779819, 'length_ratio': 0.8333333333333334, 'translation_length': 5, 'reference_length': 6}

你可以看到这一次翻译的结果与期望的输出非常接近,因此蓝分数也高于0.5。

结论

BLEU分数是检测翻译模型效率的一种很好的工具,可以进一步改进模型以获得更好的结果。尽管BLEU分数可以用来对模型进行大致评估,但它受到特定词汇的限制,经常忽略语言的细微差异。这就是为什么BLEU分数与人类判断之间的协调度很低。但是,还有一些替代方法,比如ROUGE分数、METEOR度量和CIDEr度量,你可以试一试。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程