ZGen  0.2.0
a linearization system for natural language.
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
score_map.h
Go to the documentation of this file.
1 #ifndef __ZGEN_BESTFIRST_MODEL_SCORE_MAP_H__
2 #define __ZGEN_BESTFIRST_MODEL_SCORE_MAP_H__
3 
4 #include <vector>
5 #include <boost/unordered_map.hpp>
9 #include "ml/perceptron/param.h"
10 
11 namespace ZGen {
12 
13 namespace BestFirst {
14 
15 template<class ScoreType>
16 class ScoreMap {
17 private:
19  typedef boost::unordered_map<ScoreType, param_t> map_t;
20  typedef std::function<void(const ScoreContext&, std::vector<ScoreType>&)> extractor_t;
21 
22 public:
23  ScoreMap(extractor_t _extractor): extractor(_extractor) {}
24 
25  floatval_t score(const ScoreContext& ctx, bool avg,
26  floatval_t default_return_value = 0.) const {
27  std::vector<ScoreType> features;
28  extractor(ctx, features);
29  floatval_t retval = 0.;
30 
31  for (int i = 0; i < features.size(); ++ i) {
32  const ScoreType& entry = features[i];
33  typename map_t::const_iterator itx = payload.find(entry);
34 
35  if (itx == payload.end()) {
36  retval += default_return_value;
37  } else {
38  if (avg) {
39  retval += itx->second.w_sum;
40  } else {
41  retval += itx->second.w;
42  }
43  }
44  }
45 
46  return retval;
47  }
48 
49  void update(const ScoreContext& ctx, int now, floatval_t scale = 1.) {
50  std::vector<ScoreType> features;
51  extractor(ctx, features);
52 
53  for (int i = 0; i < features.size(); ++ i) {
54  const ScoreType& entry = features[i];
55  param_t& param = payload[entry];
56  param.add(now, scale);
57  }
58  }
59 
60  void flush(int now) {
61  for (typename map_t::iterator itx = payload.begin();
62  itx != payload.end(); ++ itx) {
63  itx->second.flush(now);
64  }
65  }
66 
67  void save(boost::archive::text_oarchive& oa) {
68  oa << payload;
69  }
70 
71  void load(boost::archive::text_iarchive& ia) {
72  ia >> payload;
73  }
74 
75 private:
76  map_t payload;
77  extractor_t extractor;
78 };
79 
80 } // end for namespace BestFirst
81 } // end for namespace ZGen
82 
83 
84 #endif // end for __ZGEN_BESTFIRST_MODEL_SCORE_MAP_H__
void update(const ScoreContext &ctx, int now, floatval_t scale=1.)
Definition: score_map.h:49
void add(int now, floatval_t scale)
Definition: param.h:39
ScoreMap(extractor_t _extractor)
Definition: score_map.h:23
void save(boost::archive::text_oarchive &oa)
Definition: score_map.h:67
void flush(int now)
Definition: score_map.h:60
floatval_t score(const ScoreContext &ctx, bool avg, floatval_t default_return_value=0.) const
Definition: score_map.h:25
double floatval_t
Definition: settings.h:24
Definition: score_map.h:16
void load(boost::archive::text_iarchive &ia)
Definition: score_map.h:71
Definition: score_context.h:13