首页 > 解决方案 > 我的 Bleu 分数与 nltk bleu 分数不同

问题描述

我试图从头开始计算 bleu 分数。

import numpy as np
reference = 'hello how are you i am good here'
output = 'hello baby are you i am fine here'

# calculate Brevity penalty
BP = 0
if len(reference) < len(output):
    BP = 1
else:
    BP = np.exp(1-(len(reference)/len(output)))

def Bleu(ref, pred):
    count = []
    clip_count = []

    for i in range(1, len(pred)):
        clp = 0
        cp = 0
        start = set()
        for j in range(len(pred)):
            if j+i >len(pred):
                continue

            goal = pred[j:i+j]

            sum = ''
            for k in goal:
                sum += k+' '

            final = sum[:-1]

            cp += 1
            if final in ref:
                if final in start:
                    continue
                else:
                    clp += 1
                    start.add(final)


        clip_count.append(clp)
        count.append(cp)

    return clip_count, count

clip, count = Bleu(reference, output.split())

pn = sum(np.divide(clip, count))

bleu = np.exp((1/len(clip)) * pn) * BP

print(bleu)

nltk python Bleu分数的输出

import nltk

t = 'hello how are you i am good here'
m = 'hello baby are you i am fine here'
hypothesis = m.split()
reference = t.split()
#there may be several references
BLEUscore = nltk.translate.bleu_score.sentence_bleu([reference], hypothesis)
print(BLEUscore)

我的问题是:

Q1。两个 bleu 分数不匹配,是什么错误?有人请帮帮我

Q2。如果我们尝试计算 Bleu 分数,则 bleu 分数的值将始终大于 1,因为 bleu 分数的公式为

Bleu score-> exp( 1/n * sum(precision n-gram) ) * Brevity_Penalty

如果 x 为 +ve,则指数函数 (e^x) 始终大于 1,并且精度 n-gram 的值始终为正。

那为什么一般文件都说 bleu score value 应该在 0 到 1 之间???

标签: pythonnumpymachine-learningnlpmachine-translation

解决方案


公式中有错误。对平均n- gram 精度取幂不会有任何合理的解释。应该是几何平均数。介于 0 和 1 之间的数字的几何平均值将始终介于 0 和 1 之间。通常计算它的方式是取对数精度的平均值,否则,您将乘以可能导致浮点下溢错误的小数字。

这是原始论文中的公式:

在此处输入图像描述


推荐阅读