aGrUM  0.14.2
estimator_tpl.h
Go to the documentation of this file.
1 /***************************************************************************
2  * Copyright (C) 2005 by Christophe GONZALES et Pierre-Henri WUILLEMIN *
3  * {prenom.nom}_at_lip6.fr *
4  * *
5  * This program is free software; you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation; either version 2 of the License, or *
8  * (at your option) any later version. *
9  * *
10  * This program is distributed in the hope that it will be useful, *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
13  * GNU General Public License for more details. *
14  * *
15  * You should have received a copy of the GNU General Public License *
16  * along with this program; if not, write to the *
17  * Free Software Foundation, Inc., *
18  * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
19  ***************************************************************************/
28 namespace gum {
29 
30  template < typename GUM_SCALAR >
32  GUM_CONSTRUCTOR(Estimator);
33  _wtotal = (GUM_SCALAR)0.;
34  _ntotal = (Size)0;
35  _bn = nullptr;
36  }
37 
38 
39  template < typename GUM_SCALAR >
41  Estimator() {
42  _bn = bn;
43 
44  for (gum::NodeGraphPartIterator iter = bn->nodes().begin();
45  iter != bn->nodes().end();
46  ++iter)
48  bn->variable(*iter).name(),
49  std::vector< GUM_SCALAR >(bn->variable(*iter).domainSize(), 0.0));
50 
51  GUM_CONSTRUCTOR(Estimator);
52  }
53 
54 
55  template < typename GUM_SCALAR >
57  GUM_DESTRUCTOR(Estimator);
58  // remove all the posteriors computed
59  clear();
60  }
61 
62 
63  /* adds all potential target variables from a given BN to the Estimator */
64 
65  template < typename GUM_SCALAR >
67  const NodeSet& hardEvidence) {
68  for (gum::NodeGraphPartIterator iter = bn->nodes().begin();
69  iter != bn->nodes().end();
70  ++iter) {
71  auto v = bn->variable(*iter).name();
72 
73  if (!hardEvidence.contains(*iter)) {
74  if (_estimator.exists(v))
75  _estimator[v] = std::vector< GUM_SCALAR >(
76  bn->variable(*iter).domainSize(), (GUM_SCALAR)0.0);
77  else
79  std::vector< GUM_SCALAR >(
80  bn->variable(*iter).domainSize(), (GUM_SCALAR)0.0));
81  }
82  }
83  }
84 
85  // we multiply the posteriors obtained by LoopyBeliefPropagation by the it's
86  // number of iterations
87  template < typename GUM_SCALAR >
88  void
90  const NodeSet& hardEvidence,
91  GUM_SCALAR virtualLBPSize) {
92  for (const auto& node : lbp->BN().nodes()) {
93  if (!hardEvidence.contains(node)) {
94  std::vector< GUM_SCALAR > v;
95  auto p = lbp->posterior(node);
96  gum::Instantiation inst(p);
97 
98  for (inst.setFirst(); !inst.end(); ++inst) {
99  v.push_back(p[inst] * virtualLBPSize);
100  }
101 
102  _estimator.insert(lbp->BN().variable(node).name(), v);
103  }
104  }
105  _ntotal = (Size)virtualLBPSize;
106  _wtotal = virtualLBPSize;
107  }
108 
109  /*update the Estimator given an instantiation I with weight bias w*/
110 
111  template < typename GUM_SCALAR >
113  _wtotal += w;
114  _ntotal += (Size)1;
115 
116  for (Idx i = 0; i < I.nbrDim(); i++) {
117  if (_estimator.exists(I.variable(i).name()))
118  _estimator[I.variable(i).name()][I.val(i)] += w;
119  }
120  }
121 
122  /* returns the approximation CPT of a variable */
123 
124  template < typename GUM_SCALAR >
127  Potential< GUM_SCALAR >* p = nullptr;
128 
129  if (!_estimator.exists(var.name()))
130  GUM_ERROR(NotFound, "Target variable not found");
131 
132  // check if we have already computed the posterior
133  if (__target_posteriors.exists(var.name())) {
134  p = __target_posteriors[var.name()];
135  } else {
136  p = new Potential< GUM_SCALAR >();
137  *p << var;
138  __target_posteriors.insert(var.name(), p);
139  }
140 
141  p->fillWith(_estimator[var.name()]);
142  p->normalize();
143  return *p;
144  }
145 
146 
147  /* expected value considering a Bernouilli variable with parameter val */
148 
149  template < typename GUM_SCALAR >
150  GUM_SCALAR Estimator< GUM_SCALAR >::EV(std::string name, Idx val) {
151  return _estimator[name][val] / _wtotal;
152  }
153 
154 
155  /* variance considering a Bernouilli variable with parameter val */
156 
157  template < typename GUM_SCALAR >
158  GUM_SCALAR Estimator< GUM_SCALAR >::variance(std::string name, Idx val) {
159  GUM_SCALAR p = EV(name, val);
160  return p * (1 - p);
161  }
162 
163 
164  /* returns maximum length of confidence intervals for each variable, each
165  * parameter */
166 
167  template < typename GUM_SCALAR >
169  GUM_SCALAR ic_max = 0;
170 
171  for (auto iter = _estimator.begin(); iter != _estimator.end(); ++iter) {
172  for (Idx i = 0; i < iter.val().size(); i++) {
173  GUM_SCALAR ic = GUM_SCALAR(
174  2 * 1.96 * std::sqrt(variance(iter.key(), i) / (_ntotal - 1)));
175  if (ic > ic_max) ic_max = ic;
176  }
177  }
178 
179  return ic_max;
180  }
181 
182  template < typename GUM_SCALAR >
184  _estimator.clear();
185  _wtotal = (GUM_SCALAR)0;
186  _ntotal = Size(0);
187  for (const auto& pot : __target_posteriors)
188  delete pot.second;
189  __target_posteriors.clear();
190  }
191 } // namespace gum
iterator begin()
Returns an unsafe iterator pointing to the beginning of the hashtable.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition: set_tpl.h:578
aGrUM&#39;s Potential is a multi-dimensional array with tensor operators.
Definition: potential.h:57
void setFromBN(const IBayesNet< GUM_SCALAR > *bn, const NodeSet &hardEvidence)
estimator initializing
Definition: estimator_tpl.h:66
void clear()
refresh the estimator state as empty
const iterator & end() noexcept
Returns the unsafe iterator pointing to the end of the hashtable.
Idx nbrDim() const final
Returns the number of variables in the Instantiation.
const Potential< GUM_SCALAR > & posterior(const DiscreteVariable &var)
returns the posterior of a node
const Potential< GUM_SCALAR > & normalize() const
normalisation of this do nothing if sum is 0
HashTable< std::string, std::vector< GUM_SCALAR > > _estimator
estimator represented by hashtable between each variable name and a vector of cumulative sample weigh...
Definition: estimator.h:116
GUM_SCALAR _wtotal
cumulated weights of all samples
Definition: estimator.h:119
Size _ntotal
number of generated samples
Definition: estimator.h:122
bool exists(const Key &key) const
Checks whether there exists an element with a given key in the hashtable.
void update(Instantiation I, GUM_SCALAR w)
updates the estimator with a given sample
Base class for discrete random variable.
Class representing the minimal interface for Bayesian Network.
Definition: IBayesNet.h:59
gum is the global namespace for all aGrUM entities
Definition: agrum.h:25
GUM_SCALAR EV(std::string name, Idx val)
returns expected value of Bernouilli variable (called by it&#39;s name) of given parameter ...
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFromLBP(LoopyBeliefPropagation< GUM_SCALAR > *lbp, const NodeSet &hardEvidence, GUM_SCALAR virtualLBPSize)
sets the estimatoor object with posteriors obtained by LoopyBeliefPropagation
Definition: estimator_tpl.h:89
Unsafe iterator on the node set of a graph.
Definition: nodeGraphPart.h:55
virtual const DiscreteVariable & variable(NodeId id) const =0
Returns a constant reference over a variable given it&#39;s node id.
const NodeGraphPart & nodes() const
Returns a constant reference to the dag of this Bayes Net.
Definition: DAGmodel_inl.h:112
const Potential< GUM_SCALAR > & fillWith(const Potential< GUM_SCALAR > &src) const
copy a Potential data using name of variables and labels (not necessarily the same variables in the s...
const IBayesNet< GUM_SCALAR > * _bn
bayesian network on which approximation is done
Definition: estimator.h:125
<agrum/BN/inference/loopyBeliefPropagation.h>
virtual const Potential< GUM_SCALAR > & posterior(NodeId node)
Computes and returns the posterior of a node.
Class for assigning/browsing values to tuples of discrete variables.
Definition: instantiation.h:80
GUM_SCALAR variance(std::string name, Idx val)
returns variance of Bernouilli variable (called by it&#39;s name) of given parameter
void clear()
Removes all the elements in the hash table.
void setFirst()
Assign the first values to the tuple of the Instantiation.
Size Idx
Type for indexes.
Definition: types.h:50
Estimator()
Default constructor.
Definition: estimator_tpl.h:31
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition: types.h:45
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
const std::string & name() const
returns the name of the variable
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
virtual const IBayesNet< GUM_SCALAR > & BN() const final
Returns a constant reference over the IBayesNet referenced by this class.
HashTable< std::string, Potential< GUM_SCALAR > *> __target_posteriors
the set of single posteriors computed during the last inference
Definition: estimator.h:155
#define GUM_ERROR(type, msg)
Definition: exceptions.h:52
bool end() const
Returns true if the Instantiation reached the end.
GUM_SCALAR confidence()
computes the maximum length of confidence interval for each possible value of each variable ...