设 𝒙 为模型生成的候选序列,
为一组参考序列,𝒲 为从生成的候选序列中提取所有N元组合的集合。BLEU算法的精度(Precision)定义如下:
其中
是N元组合
在生成序列
中出现的次数,
是N元组合
在参考序列
中出现的次数。
为了处理生成序列长度短于参考序列的情况,引入长度惩罚因子
:
其中
是生成序列的长度,
是参考序列的最短长度。
BLEU算法通过计算不同长度的N元组合的精度,并进行几何加权平均,得到最终的BLEU分数:
其中
为最长N元组合的长度,
是不同N元组合的权重,一般设为
。
w w w | c w ( x ) c_w(\mathbf{x}) cw(x) | c w ( s ( 1 ) ) c_w(\mathbf{s^{(1)}}) cw(s(1)) | c w ( s ( 2 ) ) c_w(\mathbf{s^{(2)}}) cw(s(2)) | max k = 1 K c w ( s ( k ) ) ) \max_{k=1}^{K} c_w(\mathbf{s}^{(k)})) maxk=1Kcw(s(k))) | min ( c w ( x ) , max k = 1 K c w ( s ( k ) ) ) \min(c_w(\mathbf{x}), \max_{k=1}^{K} c_w(\mathbf{s}^{(k)})) min(cw(x),maxk=1Kcw(s(k))) |
---|---|---|---|---|---|
the cat | 1 | 1 | 0 | 1 | 1 |
cat sat | 1 | 0 | 0 | 0 | 0 |
sat on | 1 | 0 | 1 | 1 | 1 |
on the | 1 | 1 | 1 | 1 | 1 |
the mat | 1 | 1 | 0 | 1 | 1 |
the cat11011cat sat10000sat on10111on the11111the mat11011
为了处理生成序列长度短于参考序列的情况,引入长度惩罚因子
:
其中
是生成序列的长度,
是参考序列的最短长度。
这里
,因此
BLEU算法通过计算不同长度的N元组合的精度,并进行几何加权平均,得到最终的BLEU分数:
其中
为最长N元组合的长度,
是不同N元组合的权重,一般设为
。
main_string = 'the cat sat on the mat'
string1 = 'the cat is on the mat'
string2 = 'the bird sat on the bush'
# 计算单词
unique_words = set(main_string.split())
total_occurrences, matching_occurrences = 0, 0
for word in unique_words:
count_main_string = main_string.count(word)
total_occurrences += count_main_string
matching_occurrences += min(count_main_string, max(string1.count(word), string2.count(word)))
similarity_word = matching_occurrences / total_occurrences
print(f"N=1: {similarity_word}")
# 计算双词
word_tokens = main_string.split()
bigrams = set([f"{word_tokens[i]} {word_tokens[i + 1]}" for i in range(len(word_tokens) - 1)])
total_occurrences, matching_occurrences = 0, 0
for bigram in bigrams:
count_main_string = main_string.count(bigram)
total_occurrences += count_main_string
matching_occurrences += min(count_main_string, max(string1.count(bigram), string2.count(bigram)))
similarity_bigram = matching_occurrences / total_occurrences
print(f"N=2: {similarity_bigram}")
输出:
N=1: 1.0
N=2: 0.8