summaryrefslogtreecommitdiff
path: root/dtrain/score.h
blob: 3e5d82a9fd793a251386b15f40fbea21d84a7176 (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
#ifndef _DTRAIN_SCORE_H_
#define _DTRAIN_SCORE_H_

#include <iostream>
#include <vector>
#include <map>
#include <cassert>
#include <cmath>

#include "wordid.h" // cdec

using namespace std;

namespace dtrain
{


typedef double score_t; // float

struct NgramCounts
{
  unsigned N_;
  map<unsigned, unsigned> clipped;
  map<unsigned, unsigned> sum;

  NgramCounts(const unsigned N) : N_(N) { reset(); } 

  void
  operator+=(const NgramCounts& rhs)
  {
    assert(N_ == rhs.N_);
    for (unsigned i = 0; i < N_; i++) {
      this->clipped[i] += rhs.clipped.find(i)->second;
      this->sum[i] += rhs.sum.find(i)->second;
    }
  }

  const NgramCounts
  operator+(const NgramCounts &other) const
  {
    NgramCounts result = *this;
    result += other;
    return result;
  }

  void
  add(unsigned count, unsigned ref_count, unsigned i)
  {
    assert(i < N_);
    if (count > ref_count) {
      clipped[i] += ref_count;
      sum[i] += count;
    } else {
      clipped[i] += count;
      sum[i] += count;
    }
  }

  void
  reset()
  {
    unsigned i;
    for (i = 0; i < N_; i++) {
      clipped[i] = 0;
      sum[i] = 0;
    }
  }

  void
  print()
  {
    for (unsigned i = 0; i < N_; i++) {
      cout << i+1 << "grams (clipped):\t" << clipped[i] << endl;
      cout << i+1 << "grams:\t\t\t" << sum[i] << endl;
    }
  }
};

typedef map<vector<WordID>, unsigned> Ngrams;

Ngrams make_ngrams(vector<WordID>& s, unsigned N);
NgramCounts make_ngram_counts(vector<WordID> hyp, vector<WordID> ref, unsigned N);

score_t brevity_penaly(const unsigned hyp_len, const unsigned ref_len);
score_t bleu(NgramCounts& counts, const unsigned hyp_len, const unsigned ref_len, const unsigned N,
             vector<score_t> weights = vector<score_t>());
score_t stupid_bleu(NgramCounts& counts, const unsigned hyp_len, const unsigned ref_len, unsigned N,
                    vector<score_t> weights = vector<score_t>());
score_t smooth_bleu(NgramCounts& counts, const unsigned hyp_len, const unsigned ref_len, const unsigned N,
                    vector<score_t> weights = vector<score_t>());
score_t approx_bleu(NgramCounts& counts, const unsigned hyp_len, const unsigned ref_len, const unsigned N,
                    vector<score_t> weights = vector<score_t>());


} // namespace

#endif