1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
|
#!/usr/bin/env ruby
require 'nlp_ruby'
require 'trollop'
# reference-length hack as in (Nakov et al., 2012)
def brevity_penalty hypothesis, reference, hack=0
a = tokenize hypothesis; b = tokenize reference
return 1.0 if a.size>=b.size
return Math.exp(1.0 - ((b.size.to_f+hack)/a.size));
end
def per_sentence_bleu hypothesis, reference, n=4, hack=0
h_ng = {}; r_ng = {}
(1).upto(n) {|i| h_ng[i] = []; r_ng[i] = []}
ngrams(hypothesis, n) {|i| h_ng[i.size] << i}
ngrams(reference, n) {|i| r_ng[i.size] << i}
m = [n, reference.split.size].min
weight = 1.0/m
add = 0.0
sum = 0
(1).upto(m) { |i|
counts_clipped = 0
counts_sum = h_ng[i].size
h_ng[i].uniq.each {|j| counts_clipped += r_ng[i].count(j)}
add = 1.0 if i >= 2
sum += weight * Math.log((counts_clipped + add)/(counts_sum + add));
}
return brevity_penalty(hypothesis, reference, hack) * Math.exp(sum)
end
def main
cfg = Trollop::options do
opt :input, "input", :type => :string, :default => '-'
opt :references, "references", :type => :string, :required => true
opt :len_hack, "hack of Nakov et al", :type => :int, :default => 0
opt :n, "N", :default => 4
end
refs = ReadFile.new(cfg[:references]).readlines_strip
i = -1
input = ReadFile.new cfg[:input]
while line = input.gets
i += 1
if line.strip == ''
puts 0.0
next
end
puts per_sentence_bleu line.strip, refs[i], cfg[:n], cfg[:len_hack]
end
input.close
end
main
|