summaryrefslogtreecommitdiff
path: root/training/entropy.cc
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2012-07-03 15:43:20 +0200
committerPatrick Simianer <p@simianer.de>2012-07-03 15:43:20 +0200
commit4ec3625b3a1aa9cb417f8a551ad6723626a4c656 (patch)
treeb26acbcb8e1d434f144b5396acdd8095c94d3328 /training/entropy.cc
parentefe18d73d96958dfb6581f6f8a60362f7ad0a0c9 (diff)
parent7937972d2478a3b377930a30b77b07d2e6e902ba (diff)
Merge remote-tracking branch 'upstream/master'
Diffstat (limited to 'training/entropy.cc')
-rw-r--r--training/entropy.cc41
1 files changed, 41 insertions, 0 deletions
diff --git a/training/entropy.cc b/training/entropy.cc
new file mode 100644
index 00000000..4fdbe2be
--- /dev/null
+++ b/training/entropy.cc
@@ -0,0 +1,41 @@
+#include "entropy.h"
+
+#include "prob.h"
+#include "candidate_set.h"
+
+using namespace std;
+
+namespace training {
+
+// see Mann and McCallum "Efficient Computation of Entropy Gradient ..." for
+// a mostly clear derivation of:
+// g = E[ F(x,y) * log p(y|x) ] + H(y | x) * E[ F(x,y) ]
+double CandidateSetEntropy::operator()(const vector<double>& params,
+ SparseVector<double>* g) const {
+ prob_t z;
+ vector<double> dps(cands_.size());
+ for (unsigned i = 0; i < cands_.size(); ++i) {
+ dps[i] = cands_[i].fmap.dot(params);
+ const prob_t u(dps[i], init_lnx());
+ z += u;
+ }
+ const double log_z = log(z);
+
+ SparseVector<double> exp_feats;
+ double entropy = 0;
+ for (unsigned i = 0; i < cands_.size(); ++i) {
+ const double log_prob = cands_[i].fmap.dot(params) - log_z;
+ const double prob = exp(log_prob);
+ const double e_logprob = prob * log_prob;
+ entropy -= e_logprob;
+ if (g) {
+ (*g) += cands_[i].fmap * e_logprob;
+ exp_feats += cands_[i].fmap * prob;
+ }
+ }
+ if (g) (*g) += exp_feats * entropy;
+ return entropy;
+}
+
+}
+