aGrUM 3.2.0
a C++ library for (probabilistic) graphical models
paramEstimatorML.cpp
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
48
50
51#ifndef DOXYGEN_SHOULD_SKIP_THIS
52
54# ifdef GUM_NO_INLINE
56# endif /* GUM_NO_INLINE */
57
58namespace gum {
59
60 namespace learning {
61
62 // Constructors are defined out-of-line (not INLINE) on purpose: see
63 // the comment in score.cpp for the MSVC LNK2005 rationale.
64
67 const DBRowGeneratorParser& parser,
68 const Prior& external_prior,
69 const Prior& score_internal_prior,
70 const std::vector< std::pair< std::size_t, std::size_t > >& ranges,
71 const Bijection< NodeId, std::size_t >& nodeId2columns) :
72 ParamEstimator(parser, external_prior, score_internal_prior, ranges, nodeId2columns) {
73 GUM_CONSTRUCTOR(ParamEstimatorML);
74 }
75
77 ParamEstimatorML::ParamEstimatorML(const DBRowGeneratorParser& parser,
78 const Prior& external_prior,
79 const Prior& score_internal_prior,
80 const Bijection< NodeId, std::size_t >& nodeId2columns) :
81 ParamEstimator(parser, external_prior, score_internal_prior, nodeId2columns) {
82 GUM_CONSTRUCTOR(ParamEstimatorML);
83 }
84
86 ParamEstimatorML::ParamEstimatorML(const ParamEstimatorML& from) : ParamEstimator(from) {
87 GUM_CONS_CPY(ParamEstimatorML);
88 }
89
91 ParamEstimatorML::ParamEstimatorML(ParamEstimatorML&& from) : ParamEstimator(std::move(from)) {
92 GUM_CONS_MOV(ParamEstimatorML);
93 }
94
96 ParamEstimatorML::~ParamEstimatorML() { GUM_DESTRUCTOR(ParamEstimatorML); }
97
99 ParamEstimatorML& ParamEstimatorML::operator=(const ParamEstimatorML& from) {
100 ParamEstimator::operator=(from);
101 GUM_OP_CPY(ParamEstimatorML);
102 return *this;
103 }
104
106 ParamEstimatorML& ParamEstimatorML::operator=(ParamEstimatorML&& from) {
107 ParamEstimator::operator=(std::move(from));
108 GUM_OP_MOV(ParamEstimatorML);
109 return *this;
110 }
111
113 std::pair< std::vector< double >, double > ParamEstimatorML::_parametersAndLogLikelihood_(
114 const NodeId target_node,
115 const std::vector< NodeId >& conditioning_nodes,
116 const bool compute_log_likelihood) {
117 // create an idset that contains all the nodes in the following order:
118 // first, the target node, then all the conditioning nodes
119 IdCondSet idset(target_node, conditioning_nodes, true);
120
121 // get the counts for all the nodes in the idset and add the external and
122 // score internal priors
123 this->counter_.clear(); // for EM estimations, we need to disable caches
124 const std::vector< double >& original_N_ijk = this->counter_.counts(idset, true);
125 std::vector< double > N_ijk = original_N_ijk;
126 const bool informative_external_prior = this->external_prior_->isInformative();
127 const bool informative_score_internal_prior = this->score_internal_prior_->isInformative();
128
129 // add the priors pseudocounts
130 if (informative_external_prior) this->external_prior_->addJointPseudoCount(idset, N_ijk);
131 if (informative_score_internal_prior)
132 this->score_internal_prior_->addJointPseudoCount(idset, N_ijk);
133 double log_likelihood = 0.0;
134
135 // now, normalize N_ijk
136
137 // here, we distinguish nodesets with conditioning nodes from those
138 // without conditioning nodes
139 if (!conditioning_nodes.empty()) {
140 // get the counts for all the conditioning nodes, and add them the
141 // external and score internal priors
142 std::vector< double > N_ij(this->counter_.counts(idset.conditionalIdCondSet(), false));
143 if (informative_external_prior)
144 this->external_prior_->addConditioningPseudoCount(idset, N_ij);
145 if (informative_score_internal_prior)
146 this->score_internal_prior_->addConditioningPseudoCount(idset, N_ij);
147
148 const std::size_t conditioning_domsize = N_ij.size();
149 const std::size_t target_domsize = N_ijk.size() / conditioning_domsize;
150
151 // check that all conditioning nodes have strictly positive counts
152 for (std::size_t j = std::size_t(0); j < conditioning_domsize; ++j) {
153 if (N_ij[j] == 0) {
154 // get the domain sizes of the conditioning nodes
155 const std::size_t cond_nb = conditioning_nodes.size();
156 std::vector< Idx > cond_domsize(cond_nb);
157
158 const auto& node2cols = this->counter_.nodeId2Columns();
159 const auto& database = this->counter_.database();
160 if (node2cols.empty()) {
161 for (std::size_t i = std::size_t(0); i < cond_nb; ++i) {
162 cond_domsize[i] = database.domainSize(conditioning_nodes[i]);
163 }
164 } else {
165 for (std::size_t i = std::size_t(0); i < cond_nb; ++i) {
166 cond_domsize[i] = database.domainSize(node2cols.second(conditioning_nodes[i]));
167 }
168 }
169
170 // determine the value of each conditioning variable in N_ij[j]
171 std::vector< Idx > offsets(cond_nb);
172 Idx offset = 1;
173 std::size_t i;
174 for (i = std::size_t(0); i < cond_nb; ++i) {
175 offsets[i] = offset;
176 offset *= cond_domsize[i];
177 }
178 std::vector< Idx > values(cond_nb);
179 i = 0;
180 offset = j;
181 for (Idx jj = cond_nb - 1; i < cond_nb; ++i, --jj) {
182 values[jj] = offset / offsets[jj];
183 offset %= offsets[jj];
184 }
185
186 // create the error message
187 std::string str = "The conditioning set <";
188 bool deja = false;
189 for (i = std::size_t(0); i < cond_nb; ++i) {
190 if (deja) str += ", ";
191 else deja = true;
192 std::size_t col = node2cols.empty() ? conditioning_nodes[i]
193 : node2cols.second(conditioning_nodes[i]);
194 const DiscreteVariable& var
195 = dynamic_cast< const DiscreteVariable& >(database.variable(col));
196 str += std::format("{}={}", var.name(), var.labels()[values[i]]);
197 }
198 auto target_col = node2cols.empty() ? target_node : node2cols.second(target_node);
199 const Variable& var = database.variable(target_col);
200 str += std::format("> for target node {} never appears in the database. "
201 "Please consider using priors such as smoothing.",
202 var.name());
203
205 }
206 }
207
208 // normalize the counts and compute, if needed, the log_likelihood
209 if (compute_log_likelihood) {
210 for (std::size_t j = std::size_t(0), k = std::size_t(0); j < conditioning_domsize; ++j) {
211 for (std::size_t i = std::size_t(0); i < target_domsize; ++i, ++k) {
212 N_ijk[k] /= N_ij[j];
213 if (original_N_ijk[k]) { log_likelihood += original_N_ijk[k] * std::log(N_ijk[k]); }
214 }
215 }
216 } else {
217 for (std::size_t j = std::size_t(0), k = std::size_t(0); j < conditioning_domsize; ++j) {
218 for (std::size_t i = std::size_t(0); i < target_domsize; ++i, ++k) {
219 N_ijk[k] /= N_ij[j];
220 }
221 }
222 }
223 } else {
224 // here, there are no conditioning nodes. Hence N_ijk is the marginal
225 // probability distribution over the target node. To normalize it, it
226 // is sufficient to divide each cell by the sum over all the cells
227 double sum = 0;
228 for (const double n_ijk: N_ijk)
229 sum += n_ijk;
230
231 if (sum != 0) {
232 if (compute_log_likelihood) {
233 for (std::size_t k = std::size_t(0), end = N_ijk.size(); k < end; ++k) {
234 N_ijk[k] /= sum;
235 if (original_N_ijk[k]) { log_likelihood += original_N_ijk[k] * std::log(N_ijk[k]); }
236 }
237 } else {
238 for (double& n_ijk: N_ijk)
239 n_ijk /= sum;
240 }
241 } else {
242 const auto& node2cols = this->counter_.nodeId2Columns();
243 const auto& database = this->counter_.database();
244 auto target_col = node2cols.empty() ? target_node : node2cols.second(target_node);
245 const Variable& var = database.variable(target_col);
247 std::format("No data for target node {}. It is impossible to estimate "
248 "the parameters by maximum likelihood",
249 var.name()))
250 }
251 }
252
253 return {std::move(N_ijk), log_likelihood};
254 }
255
256 } /* namespace learning */
257
258} /* namespace gum */
259
260#endif /* DOXYGEN_SHOULD_SKIP_THIS */
Error: An unknown error occurred while accessing a database.
the class used to read a row in the database and to transform it into a set of DBRow instances that c...
ParamEstimatorML(const DBRowGeneratorParser &parser, const Prior &external_prior, const Prior &_score_internal_prior, const std::vector< std::pair< std::size_t, std::size_t > > &ranges, const Bijection< NodeId, std::size_t > &nodeId2columns=Bijection< NodeId, std::size_t >())
default constructor
The base class for estimating parameters of CPTs.
the base class for all a priori
Definition prior.h:84
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
include the inlined functions if necessary
Definition CSVParser.h:55
class GUM_SHARED_PUBLIC IdCondSet
Definition idCondSet.h:68
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
STL namespace.
the class for estimating parameters of CPTs using Maximum Likelihood
the class for estimating parameters of CPTs using Maximum Likelihood