Welcome to mirror list, hosted at ThFree Co, Russian Federation.

BleuScorer.cpp « mert - github.com/moses-smt/mosesdecoder.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 4779205acaf889dec47b61e021696d2e7758a747 (plain)
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#include "BleuScorer.h"

#include <algorithm>
#include <cmath>
#include <climits>
#include <fstream>
#include <iterator>
#include <stdexcept>
#include "Util.h"
#include "ScoreDataIterator.h"
#include "FeatureDataIterator.h"

BleuScorer::BleuScorer(const string& config)
    : StatisticsBasedScorer("BLEU",config),
      kLENGTH(4),
      _refLengthStrategy(BLEU_CLOSEST) {
  //configure regularisation
  static string KEY_REFLEN = "reflen";
  static string REFLEN_AVERAGE = "average";
  static string REFLEN_SHORTEST = "shortest";
  static string REFLEN_CLOSEST = "closest";

  string reflen = getConfig(KEY_REFLEN,REFLEN_CLOSEST);
  if (reflen == REFLEN_AVERAGE) {
    _refLengthStrategy = BLEU_AVERAGE;
  } else if (reflen == REFLEN_SHORTEST) {
    _refLengthStrategy = BLEU_SHORTEST;
  } else if (reflen == REFLEN_CLOSEST) {
    _refLengthStrategy = BLEU_CLOSEST;
  } else {
    throw runtime_error("Unknown reference length strategy: " + reflen);
  }
  //    cerr << "Using reference length strategy: " << reflen << endl;
}

BleuScorer::~BleuScorer() {}

size_t BleuScorer::countNgrams(const string& line, counts_t& counts, unsigned int n)
{
  vector<int> encoded_tokens;
  //cerr << line << endl;
  encode(line,encoded_tokens);
  //copy(encoded_tokens.begin(), encoded_tokens.end(), ostream_iterator<int>(cerr," "));
  //cerr << endl;
  for (size_t k = 1; k <= n; ++k) {
    //ngram order longer than sentence - no point
    if (k > encoded_tokens.size()) {
      continue;
    }
    for (size_t i = 0; i < encoded_tokens.size()-k+1; ++i) {
      vector<int> ngram;
      for (size_t j = i; j < i+k && j < encoded_tokens.size(); ++j) {
        ngram.push_back(encoded_tokens[j]);
      }
      int count = 1;
      counts_iterator oldcount = counts.find(ngram);
      if (oldcount != counts.end()) {
        count = (oldcount->second) + 1;
      }
      //cerr << count << endl;
      counts[ngram] = count;
      //cerr << endl;
    }
  }
  //cerr << "counted ngrams" << endl;
  //dump_counts(counts);
  return encoded_tokens.size();
}

void BleuScorer::setReferenceFiles(const vector<string>& referenceFiles)
{
  //make sure reference data is clear
  _refcounts.reset();
  _reflengths.clear();
  _encodings.clear();

  //load reference data
  for (size_t i = 0; i < referenceFiles.size(); ++i) {
    //TRACE_ERR("Loading reference from " << referenceFiles[i] << endl);
    ifstream refin(referenceFiles[i].c_str());
    if (!refin) {
      throw runtime_error("Unable to open: " + referenceFiles[i]);
    }
    string line;
    size_t sid = 0; //sentence counter
    while (getline(refin,line)) {
      //cerr << line << endl;
      if (i == 0) {
        counts_t *counts = new counts_t; //these get leaked
        _refcounts.push_back(counts);
        vector<size_t> lengths;
        _reflengths.push_back(lengths);
      }
      if (_refcounts.size() <= sid) {
        throw runtime_error("File " + referenceFiles[i] + " has too many sentences");
      }
      counts_t counts;
      size_t length = countNgrams(line,counts,kLENGTH);
      //for any counts larger than those already there, merge them in
      for (counts_iterator ci = counts.begin(); ci != counts.end(); ++ci) {
        counts_iterator oldcount_it = _refcounts[sid]->find(ci->first);
        int oldcount = 0;
        if (oldcount_it != _refcounts[sid]->end()) {
          oldcount = oldcount_it->second;
        }
        int newcount = ci->second;
        if (newcount > oldcount) {
          _refcounts[sid]->operator[](ci->first) = newcount;
        }
      }
      //add in the length
      _reflengths[sid].push_back(length);
      if (sid > 0 && sid % 100 == 0) {
        TRACE_ERR(".");
      }
      ++sid;
    }
    TRACE_ERR(endl);
  }
}


void BleuScorer::prepareStats(size_t sid, const string& text, ScoreStats& entry)
{
//      cerr << text << endl;
//      cerr << sid << endl;
  //dump_counts(*_refcounts[sid]);
  if (sid >= _refcounts.size()) {
    stringstream msg;
    msg << "Sentence id (" << sid << ") not found in reference set";
    throw runtime_error(msg.str());
  }
  counts_t testcounts;
  //stats for this line
  vector<float> stats(kLENGTH*2);;
  size_t length = countNgrams(text,testcounts,kLENGTH);
  //dump_counts(testcounts);
  if (_refLengthStrategy == BLEU_SHORTEST) {
    //cerr << reflengths.size() << " " << sid << endl;
    int shortest = *min_element(_reflengths[sid].begin(),_reflengths[sid].end());
    stats.push_back(shortest);
  } else if (_refLengthStrategy == BLEU_AVERAGE) {
    int total = 0;
    for (size_t i = 0; i < _reflengths[sid].size(); ++i) {
      total += _reflengths[sid][i];
    }
    float mean = (float)total/_reflengths[sid].size();
    stats.push_back(mean);
  } else if (_refLengthStrategy == BLEU_CLOSEST)  {
    int min_diff = INT_MAX;
    int min_idx = 0;
    for (size_t i = 0; i < _reflengths[sid].size(); ++i) {
      int reflength = _reflengths[sid][i];
      if (abs(reflength-(int)length) < abs(min_diff)) { //look for the closest reference
        min_diff = reflength-length;
        min_idx = i;
      } else if (abs(reflength-(int)length) == abs(min_diff)) { // if two references has the same closest length, take the shortest
        if (reflength < (int)_reflengths[sid][min_idx]) {
          min_idx = i;
        }
      }
    }
    stats.push_back(_reflengths[sid][min_idx]);
  } else {
    throw runtime_error("Unsupported reflength strategy");
  }
  //cerr << "computed length" << endl;
  //precision on each ngram type
  for (counts_iterator testcounts_it = testcounts.begin();
       testcounts_it != testcounts.end(); ++testcounts_it) {
    counts_iterator refcounts_it = _refcounts[sid]->find(testcounts_it->first);
    int correct = 0;
    int guess = testcounts_it->second;
    if (refcounts_it != _refcounts[sid]->end()) {
      correct = min(refcounts_it->second,guess);
    }
    size_t len = testcounts_it->first.size();
    stats[len*2-2] += correct;
    stats[len*2-1] += guess;
  }
  stringstream sout;
  copy(stats.begin(),stats.end(),ostream_iterator<float>(sout," "));
  //TRACE_ERR(sout.str() << endl);
  string stats_str = sout.str();
  entry.set(stats_str);
}

float BleuScorer::calculateScore(const vector<int>& comps) const
{
  //cerr << "BLEU: ";
  //copy(comps.begin(),comps.end(), ostream_iterator<int>(cerr," "));
  float logbleu = 0.0;
  for (int i = 0; i < kLENGTH; ++i) {
    if (comps[2*i] == 0) {
      return 0.0;
    }
    logbleu += log(comps[2*i]) - log(comps[2*i+1]);

  }
  logbleu /= kLENGTH;
  float brevity = 1.0 - (float)comps[kLENGTH*2]/comps[1];//reflength divided by test length
  if (brevity < 0.0) {
    logbleu += brevity;
  }
  //cerr << " " << exp(logbleu) << endl;
  return exp(logbleu);
}

void BleuScorer::dump_counts(counts_t& counts) const {
  for (counts_const_iterator i = counts.begin(); i != counts.end(); ++i) {
    cerr << "(";
    copy(i->first.begin(), i->first.end(), ostream_iterator<int>(cerr," "));
    cerr << ") " << i->second << ", ";
  }
  cerr << endl;
}

vector<float> BleuScorer::ScoreNbestList(string scoreFile, string featureFile) {
	vector<string> scoreFiles;
	vector<string> featureFiles;
	scoreFiles.push_back(scoreFile);
	featureFiles.push_back(featureFile);
	
	vector<FeatureDataIterator> featureDataIters;
	vector<ScoreDataIterator> scoreDataIters;
	for (size_t i = 0; i < featureFiles.size(); ++i) {
		featureDataIters.push_back(FeatureDataIterator(featureFiles[i]));
	    scoreDataIters.push_back(ScoreDataIterator(scoreFiles[i]));
	}
	  
	vector<pair<size_t,size_t> > hypotheses;
	if (featureDataIters[0] == FeatureDataIterator::end()) {
		cerr << "Error: at the end of feature data iterator" << endl;
		exit(1);
	}
	for (size_t i = 0; i < featureFiles.size(); ++i) {
		if (featureDataIters[i] == FeatureDataIterator::end()) {
			cerr << "Error: Feature file " << i << " ended prematurely" << endl;
	        exit(1);
		}
		if (scoreDataIters[i] == ScoreDataIterator::end()) {
			cerr << "Error: Score file " << i << " ended prematurely" << endl;
	        exit(1);
	    }
		if (featureDataIters[i]->size() != scoreDataIters[i]->size()) {
			cerr << "Error: features and scores have different size" << endl;
	        exit(1);
		}
		for (size_t j = 0; j < featureDataIters[i]->size(); ++j) {
			hypotheses.push_back(pair<size_t,size_t>(i,j));
	    }
	}
	    
	// score the nbest list
	vector<float> bleuScores;
	for (size_t i=0; i < hypotheses.size(); ++i) {
		pair<size_t,size_t> translation = hypotheses[i];
		float bleu = sentenceLevelBleuPlusOne(scoreDataIters[translation.first]->operator[](translation.second));
		bleuScores.push_back(bleu);
	}	
	return bleuScores;
}	

float BleuScorer::sentenceLevelBleuPlusOne(const vector<float>& stats) {
	float logbleu = 0.0;
	const unsigned int bleu_order = 4;
	for (unsigned int j=0; j<bleu_order; j++) {
		//cerr << (stats.get(2*j)+1) << "/" << (stats.get(2*j+1)+1) << " ";
		logbleu += log(stats[2*j]+1) - log(stats[2*j+1]+1);
	}
	logbleu /= bleu_order;
	float brevity = 1.0 - (float)stats[(bleu_order*2)]/stats[1];
	if (brevity < 0.0) {
		logbleu += brevity;
	}
	//cerr << brevity << " -> " << exp(logbleu) << endl;
	return exp(logbleu);
}