aGrUM 3.1.1
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
64
68 GUM_OP_CPY(ParamEstimatorML);
69 return *this;
70 }
71
74 ParamEstimator::operator=(std::move(from));
75 GUM_OP_MOV(ParamEstimatorML);
76 return *this;
77 }
78
80 std::pair< std::vector< double >, double > ParamEstimatorML::_parametersAndLogLikelihood_(
81 const NodeId target_node,
82 const std::vector< NodeId >& conditioning_nodes,
83 const bool compute_log_likelihood) {
84 // create an idset that contains all the nodes in the following order:
85 // first, the target node, then all the conditioning nodes
86 IdCondSet idset(target_node, conditioning_nodes, true);
87
88 // get the counts for all the nodes in the idset and add the external and
89 // score internal priors
90 this->counter_.clear(); // for EM estimations, we need to disable caches
91 const std::vector< double >& original_N_ijk = this->counter_.counts(idset, true);
92 std::vector< double > N_ijk = original_N_ijk;
93 const bool informative_external_prior = this->external_prior_->isInformative();
94 const bool informative_score_internal_prior = this->score_internal_prior_->isInformative();
95
96 // add the priors pseudocounts
97 if (informative_external_prior) this->external_prior_->addJointPseudoCount(idset, N_ijk);
98 if (informative_score_internal_prior)
99 this->score_internal_prior_->addJointPseudoCount(idset, N_ijk);
100 double log_likelihood = 0.0;
101
102 // now, normalize N_ijk
103
104 // here, we distinguish nodesets with conditioning nodes from those
105 // without conditioning nodes
106 if (!conditioning_nodes.empty()) {
107 // get the counts for all the conditioning nodes, and add them the
108 // external and score internal priors
109 std::vector< double > N_ij(this->counter_.counts(idset.conditionalIdCondSet(), false));
110 if (informative_external_prior)
111 this->external_prior_->addConditioningPseudoCount(idset, N_ij);
112 if (informative_score_internal_prior)
113 this->score_internal_prior_->addConditioningPseudoCount(idset, N_ij);
114
115 const std::size_t conditioning_domsize = N_ij.size();
116 const std::size_t target_domsize = N_ijk.size() / conditioning_domsize;
117
118 // check that all conditioning nodes have strictly positive counts
119 for (std::size_t j = std::size_t(0); j < conditioning_domsize; ++j) {
120 if (N_ij[j] == 0) {
121 // get the domain sizes of the conditioning nodes
122 const std::size_t cond_nb = conditioning_nodes.size();
123 std::vector< Idx > cond_domsize(cond_nb);
124
125 const auto& node2cols = this->counter_.nodeId2Columns();
126 const auto& database = this->counter_.database();
127 if (node2cols.empty()) {
128 for (std::size_t i = std::size_t(0); i < cond_nb; ++i) {
129 cond_domsize[i] = database.domainSize(conditioning_nodes[i]);
130 }
131 } else {
132 for (std::size_t i = std::size_t(0); i < cond_nb; ++i) {
133 cond_domsize[i] = database.domainSize(node2cols.second(conditioning_nodes[i]));
134 }
135 }
136
137 // determine the value of each conditioning variable in N_ij[j]
138 std::vector< Idx > offsets(cond_nb);
139 Idx offset = 1;
140 std::size_t i;
141 for (i = std::size_t(0); i < cond_nb; ++i) {
142 offsets[i] = offset;
143 offset *= cond_domsize[i];
144 }
145 std::vector< Idx > values(cond_nb);
146 i = 0;
147 offset = j;
148 for (Idx jj = cond_nb - 1; i < cond_nb; ++i, --jj) {
149 values[jj] = offset / offsets[jj];
150 offset %= offsets[jj];
151 }
152
153 // create the error message
154 std::string str = "The conditioning set <";
155 bool deja = false;
156 for (i = std::size_t(0); i < cond_nb; ++i) {
157 if (deja) str += ", ";
158 else deja = true;
159 std::size_t col = node2cols.empty() ? conditioning_nodes[i]
160 : node2cols.second(conditioning_nodes[i]);
161 const DiscreteVariable& var
162 = dynamic_cast< const DiscreteVariable& >(database.variable(col));
163 str += std::format("{}={}", var.name(), var.labels()[values[i]]);
164 }
165 auto target_col = node2cols.empty() ? target_node : node2cols.second(target_node);
166 const Variable& var = database.variable(target_col);
167 str += std::format("> for target node {} never appears in the database. "
168 "Please consider using priors such as smoothing.",
169 var.name());
170
171 GUM_ERROR(DatabaseError, str)
172 }
173 }
174
175 // normalize the counts and compute, if needed, the log_likelihood
176 if (compute_log_likelihood) {
177 for (std::size_t j = std::size_t(0), k = std::size_t(0); j < conditioning_domsize; ++j) {
178 for (std::size_t i = std::size_t(0); i < target_domsize; ++i, ++k) {
179 N_ijk[k] /= N_ij[j];
180 if (original_N_ijk[k]) { log_likelihood += original_N_ijk[k] * std::log(N_ijk[k]); }
181 }
182 }
183 } else {
184 for (std::size_t j = std::size_t(0), k = std::size_t(0); j < conditioning_domsize; ++j) {
185 for (std::size_t i = std::size_t(0); i < target_domsize; ++i, ++k) {
186 N_ijk[k] /= N_ij[j];
187 }
188 }
189 }
190 } else {
191 // here, there are no conditioning nodes. Hence N_ijk is the marginal
192 // probability distribution over the target node. To normalize it, it
193 // is sufficient to divide each cell by the sum over all the cells
194 double sum = 0;
195 for (const double n_ijk: N_ijk)
196 sum += n_ijk;
197
198 if (sum != 0) {
199 if (compute_log_likelihood) {
200 for (std::size_t k = std::size_t(0), end = N_ijk.size(); k < end; ++k) {
201 N_ijk[k] /= sum;
202 if (original_N_ijk[k]) { log_likelihood += original_N_ijk[k] * std::log(N_ijk[k]); }
203 }
204 } else {
205 for (double& n_ijk: N_ijk)
206 n_ijk /= sum;
207 }
208 } else {
209 const auto& node2cols = this->counter_.nodeId2Columns();
210 const auto& database = this->counter_.database();
211 auto target_col = node2cols.empty() ? target_node : node2cols.second(target_node);
212 const Variable& var = database.variable(target_col);
213 GUM_ERROR(DatabaseError,
214 std::format("No data for target node {}. It is impossible to estimate "
215 "the parameters by maximum likelihood",
216 var.name()))
217 }
218 }
219
220 return {std::move(N_ijk), log_likelihood};
221 }
222
223 } /* namespace learning */
224
225} /* namespace gum */
226
227#endif /* DOXYGEN_SHOULD_SKIP_THIS */
The class for estimating parameters of CPTs using Maximum Likelihood.
ParamEstimatorML & operator=(const ParamEstimatorML &from)
copy operator
std::pair< std::vector< double >, double > _parametersAndLogLikelihood_(const NodeId target_node, const std::vector< NodeId > &conditioning_nodes, const bool compute_log_likelihood)
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
~ParamEstimatorML() override
destructor
RecordCounter counter_
the record counter used to parse the database
ParamEstimator & operator=(const ParamEstimator &from)
copy operator
Prior * score_internal_prior_
if a score was used for learning the structure of the PGM, this is the priori internal to the score
const DatabaseTable & database() const
returns the database on which we perform the counts
Prior * external_prior_
an external a priori
#define GUM_ERROR(type, msg)
Definition exceptions.h:76
Size Idx
Type for indexes.
Definition types.h:79
Size NodeId
Type for node ids.
include the inlined functions if necessary
Definition CSVParser.h:55
gum is the global namespace for all aGrUM entities
Definition agrum.h:46
the class for estimating parameters of CPTs using Maximum Likelihood
the class for estimating parameters of CPTs using Maximum Likelihood