aGrUM 3.3.2
a C++ library for (probabilistic) graphical models
estimator_tpl.h
Go to the documentation of this file.
1/****************************************************************************
2 * This file is part of the aGrUM/pyAgrum library. *
3 * *
4 * Copyright (c) 2005-2026 by *
5 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
6 * - Christophe GONZALES(_at_AMU) *
7 * *
8 * The aGrUM/pyAgrum library is free software; you can redistribute it *
9 * and/or modify it under the terms of either : *
10 * *
11 * - the GNU Lesser General Public License as published by *
12 * the Free Software Foundation, either version 3 of the License, *
13 * or (at your option) any later version, *
14 * - the MIT license (MIT), *
15 * - or both in dual license, as here. *
16 * *
17 * (see https://agrum.gitlab.io/articles/dual-licenses-lgplv3mit.html) *
18 * *
19 * This aGrUM/pyAgrum library is distributed in the hope that it will be *
20 * useful, but WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *
21 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES MERCHANTABILITY or FITNESS *
22 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
23 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
24 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
25 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR *
26 * OTHER DEALINGS IN THE SOFTWARE. *
27 * *
28 * See LICENCES for more details. *
29 * *
30 * SPDX-FileCopyrightText: Copyright 2005-2026 *
31 * - Pierre-Henri WUILLEMIN(_at_LIP6) *
32 * - Christophe GONZALES(_at_AMU) *
33 * SPDX-License-Identifier: LGPL-3.0-or-later OR MIT *
34 * *
35 * Contact : info_at_agrum_dot_org *
36 * homepage : http://agrum.gitlab.io *
37 * gitlab : https://gitlab.com/agrumery/agrum *
38 * *
39 ****************************************************************************/
40
41#pragma once
42
50
51#include <agrum/BN/inference/tools/estimator.h> // to ease IDE parser
52
53namespace gum {
54
55 template < GUM_Numeric GUM_SCALAR >
57 GUM_CONSTRUCTOR(Estimator);
58 wtotal_ = (GUM_SCALAR)0.;
59 ntotal_ = (Size)0;
60 nvirtual_ = (GUM_SCALAR)0.;
61 bn_ = nullptr;
62 }
63
64 template < GUM_Numeric GUM_SCALAR >
66 bn_ = bn;
67
68 for (gum::NodeGraphPartIterator iter = bn->nodes().begin(); iter != bn->nodes().end(); ++iter)
69 estimator_.insert(bn->variable(*iter).name(),
70 std::vector< GUM_SCALAR >(bn->variable(*iter).domainSize(), 0.0));
71
72 GUM_CONSTRUCTOR(Estimator);
73 }
74
75 template < GUM_Numeric GUM_SCALAR >
77 GUM_DESTRUCTOR(Estimator);
78 // remove all the posteriors computed
79 clear();
80 }
81
82 /* adds all tensor target variables from a given BN to the Estimator */
83
84 template < GUM_Numeric GUM_SCALAR >
86 const NodeSet& hardEvidence) {
87 prior_.clear();
88 nvirtual_ = (GUM_SCALAR)0;
89 for (gum::NodeGraphPartIterator iter = bn->nodes().begin(); iter != bn->nodes().end(); ++iter) {
90 auto v = bn->variable(*iter).name();
91
92 if (!hardEvidence.contains(*iter)) {
93 if (estimator_.exists(v))
94 estimator_[v]
95 = std::vector< GUM_SCALAR >(bn->variable(*iter).domainSize(), (GUM_SCALAR)0.0);
96 else
97 estimator_.insert(
98 v,
99 std::vector< GUM_SCALAR >(bn->variable(*iter).domainSize(), (GUM_SCALAR)0.0));
100 }
101 }
102 }
103
104 // the posteriors obtained by LoopyBeliefPropagation are used as a prior worth virtualLBPSize
105 // samples (see EV)
106 template < GUM_Numeric GUM_SCALAR >
108 const NodeSet& hardEvidence,
109 GUM_SCALAR virtualLBPSize) {
110 for (const auto& node: lbp->BN().nodes()) {
111 if (!hardEvidence.contains(node)) {
112 std::vector< GUM_SCALAR > v;
113 auto p = lbp->posterior(node);
114 gum::Instantiation inst(p);
115
116 for (inst.setFirst(); !inst.end(); ++inst) {
117 v.push_back(p[inst]);
118 }
119
120 const auto& name = lbp->BN().variable(node).name();
121 estimator_.insert(name, std::vector< GUM_SCALAR >(v.size(), (GUM_SCALAR)0.0));
122 prior_.insert(name, std::move(v));
123 }
124 }
125 ntotal_ = (Size)0;
126 nvirtual_ = virtualLBPSize;
127 wtotal_ = (GUM_SCALAR)0.;
128 }
129
130 template < GUM_Numeric GUM_SCALAR >
132 return (GUM_SCALAR)ntotal_ >= nvirtual_;
133 }
134
135 /*update the Estimator given an instantiation I with weight bias w*/
136
137 template < GUM_Numeric GUM_SCALAR >
139 wtotal_ += w;
140 ntotal_ += (Size)1;
141
142 for (Idx i = 0; i < I.nbrDim(); i++) {
143 if (estimator_.exists(I.variable(i).name())) estimator_[I.variable(i).name()][I.val(i)] += w;
144 }
145 }
146
147 /* returns the approximation CPT of a variable */
148
149 template < GUM_Numeric GUM_SCALAR >
150 const Tensor< GUM_SCALAR >& Estimator< GUM_SCALAR >::posterior(const DiscreteVariable& var) {
151 Tensor< GUM_SCALAR >* p = nullptr;
152
153 if (!estimator_.exists(var.name())) GUM_ERROR(NotFound, "Target variable not found")
154
155 // check if we have already computed the posterior
156 if (_target_posteriors_.exists(var.name())) {
157 p = _target_posteriors_[var.name()];
158 } else {
159 p = new Tensor< GUM_SCALAR >();
160 *p << var;
161 _target_posteriors_.insert(var.name(), p);
162 }
163
164 if (nvirtual_ > (GUM_SCALAR)0 && prior_.exists(var.name())) {
165 std::vector< GUM_SCALAR > v(var.domainSize());
166 for (Idx i = 0; i < v.size(); ++i)
167 v[i] = EV(var.name(), i);
168 p->fillWith(v);
169 } else {
170 p->fillWith(estimator_[var.name()]);
171 }
172 p->normalize();
173 return *p;
174 }
175
176 /* expected value considering a Bernouilli variable with parameter val */
177
178 template < GUM_Numeric GUM_SCALAR >
179 GUM_SCALAR Estimator< GUM_SCALAR >::EV(std::string_view name, Idx val) {
180 if (nvirtual_ > (GUM_SCALAR)0) {
181 if (const auto prior = prior_.tryGet(name)) {
182 // The prior is worth nvirtual_ samples of the mean weight of the generated samples: the
183 // weights of the generated samples (e.g. likelihood or importance weights) may be far from
184 // 1, the prior must be expressed in the same unit to be balanced against them.
185 const auto n = (GUM_SCALAR)ntotal_;
186 const auto sampled
187 = (wtotal_ > (GUM_SCALAR)0) ? estimator_[name][val] / wtotal_ : (GUM_SCALAR)0;
188 return (nvirtual_ * (*prior)[val] + n * sampled) / (nvirtual_ + n);
189 }
190 }
191 return estimator_[name][val] / wtotal_;
192 }
193
194 /* variance considering a Bernouilli variable with parameter val */
195
196 template < GUM_Numeric GUM_SCALAR >
197 GUM_SCALAR Estimator< GUM_SCALAR >::variance(std::string_view name, Idx val) {
198 GUM_SCALAR p = EV(name, val);
199 return p * (1 - p);
200 }
201
202 /* returns maximum length of confidence intervals for each variable, each
203 * parameter */
204
205 template < GUM_Numeric GUM_SCALAR >
207 GUM_SCALAR ic_max = 0;
208
209 for (auto iter = estimator_.begin(); iter != estimator_.end(); ++iter) {
210 for (Idx i = 0; i < iter.val().size(); i++) {
211 // the virtual samples of the prior (if any) count in the size of the sample
212 GUM_SCALAR ic = GUM_SCALAR(
213 2 * 1.96 * std::sqrt(variance(iter.key(), i) / (nvirtual_ + (GUM_SCALAR)ntotal_ - 1)));
214 if (ic > ic_max) ic_max = ic;
215 }
216 }
217
218 return ic_max;
219 }
220
221 template < GUM_Numeric GUM_SCALAR >
223 estimator_.clear();
224 prior_.clear();
225 wtotal_ = (GUM_SCALAR)0;
226 ntotal_ = Size(0);
227 nvirtual_ = (GUM_SCALAR)0;
228 for (const auto& pot: _target_posteriors_)
229 delete pot.second;
230 _target_posteriors_.clear();
231 }
232} // namespace gum
virtual const IBayesNet< GUM_SCALAR > & BN() const final
Returns a constant reference over the IBayesNet referenced by this class.
const NodeGraphPart & nodes() const final
Returns a named copy of the internal DAG: each node id is assigned the name of the corresponding vari...
const DiscreteVariable & variable(NodeId id) const override
Returns a constant reference over a variable given its node id.
Base class for discrete random variable.
virtual Size domainSize() const =0
GUM_SCALAR wtotal_
cumulated weights of the generated samples
Definition estimator.h:154
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:148
void setFromLBP(LoopyBeliefPropagation< GUM_SCALAR > *lbp, const NodeSet &hardEvidence, GUM_SCALAR virtualLBPSize)
sets the estimatoor object with posteriors obtained by LoopyBeliefPropagation
void setFromBN(const IBayesNet< GUM_SCALAR > *bn, const NodeSet &hardEvidence)
estimator initializing
const IBayesNet< GUM_SCALAR > * bn_
Bayesian network on which approximation is done.
Definition estimator.h:163
bool isPriorOutweighed() const
returns true if the generated samples outnumber the virtual ones of the prior (if any)
GUM_SCALAR nvirtual_
size of the prior as a number of virtual samples (0 if no prior)
Definition estimator.h:160
const Tensor< GUM_SCALAR > & posterior(const DiscreteVariable &var)
returns the posterior of a node
HashTable< std::string, std::vector< GUM_SCALAR > > prior_
prior distribution of each variable (e.g. LBP posteriors), if any
Definition estimator.h:151
Estimator()
Default constructor.
void clear()
refresh the estimator state as empty
Size ntotal_
number of generated samples
Definition estimator.h:157
GUM_SCALAR variance(std::string_view name, Idx val)
returns variance of Bernouilli variable (called by it's name) of given parameter
GUM_SCALAR EV(std::string_view name, Idx val)
returns expected value of Bernouilli variable (called by it's name) of given parameter
void update(Instantiation I, GUM_SCALAR w)
updates the estimator with a given sample
HashTable< std::string, Tensor< GUM_SCALAR > * > _target_posteriors_
the set of single posteriors computed during the last inference
Definition estimator.h:193
GUM_SCALAR confidence()
computes the maximum length of confidence interval for each possible value of each variable
value_type & insert(const Key &key, const Val &val)
Adds a new element (actually a copy of this element) into the hash table.
Class representing the minimal interface for Bayesian network with no numerical data.
Definition IBayesNet.h:79
Class for assigning/browsing values to tuples of discrete variables.
bool end() const
Returns true if the Instantiation reached the end.
Idx val(Idx i) const
Returns the current value of the variable at position i.
void setFirst()
Assign the first values to the tuple of the Instantiation.
const DiscreteVariable & variable(Idx i) const final
Returns the variable at position i in the tuple.
Idx nbrDim() const final
Returns the number of variables in the Instantiation.
<agrum/BN/inference/loopyBeliefPropagation.h>
virtual const Tensor< GUM_SCALAR > & posterior(NodeId node)
Computes and returns the posterior of a node.
Unsafe iterator on the node set of a graph.
node_iterator begin() const noexcept
a begin iterator to parse the set of nodes contained in the NodeGraphPart
const node_iterator & end() const noexcept
the end iterator to parse the set of nodes contained in the NodeGraphPart
Exception : the element we looked for cannot be found.
bool contains(const Key &k) const
Indicates whether a given elements belong to the set.
Definition set_tpl.h:468
const std::string & name() const
returns the name of the variable
This file contains estimating tools for approximate inference.
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
std::size_t Size
In aGrUM, hashed values are unsigned long int.
Definition types.h:74
Size Idx
Type for indexes.
Definition types.h:79
Set< NodeId > NodeSet
Some typdefs and define for shortcuts ...
gum is the global namespace for all aGrUM entities
Definition agrum.h:46