543cc674dcbb21279062c8005d88bbaa72ce6e96
[libdai.git] / include / dai / emalg.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * Copyright (c) 2006-2011, The libDAI authors. All rights reserved.
4 *
5 * Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
6 */
7
8
9 #ifndef __defined_libdai_emalg_h
10 #define __defined_libdai_emalg_h
11
12
13 #include <vector>
14 #include <map>
15
16 #include <dai/factor.h>
17 #include <dai/daialg.h>
18 #include <dai/evidence.h>
19 #include <dai/index.h>
20 #include <dai/properties.h>
21
22
23 /// \file
24 /// \brief Defines classes related to Expectation Maximization (EMAlg, ParameterEstimation, CondProbEstimation and SharedParameters)
25 /// \todo Implement parameter estimation for undirected models / factor graphs.
26
27
28 namespace dai {
29
30
31 /// Base class for parameter estimation methods.
32 /** This class defines the general interface of parameter estimation methods.
33 *
34 * Implementations of this interface (see e.g. CondProbEstimation) should
35 * register a factory function (virtual constructor) via the static
36 * registerMethod() function.
37 * This factory function should return a pointer to a newly constructed
38 * object, whose type is a subclass of ParameterEstimation, and gets as
39 * input a PropertySet of parameters. After a subclass has been registered,
40 * instances of it can be constructed using the construct() method.
41 *
42 * Implementations are responsible for collecting data from a probability
43 * vector passed to it from a SharedParameters container object.
44 *
45 * The default registry only contains CondProbEstimation, named
46 * "CondProbEstimation".
47 *
48 * \author Charles Vaske
49 */
50 class ParameterEstimation {
51 public:
52 /// Type of pointer to factory function.
53 typedef ParameterEstimation* (*ParamEstFactory)( const PropertySet& );
54
55 /// Virtual destructor for deleting pointers to derived classes.
56 virtual ~ParameterEstimation() {}
57
58 /// Virtual copy constructor.
59 virtual ParameterEstimation* clone() const = 0;
60
61 /// General factory method that constructs the desired ParameterEstimation subclass
62 /** \param method Name of the subclass that should be constructed;
63 * \param p Parameters passed to constructor of subclass.
64 * \note \a method should either be in the default registry or should be registered first using registerMethod().
65 * \throw UNKNOWN_PARAMETER_ESTIMATION_METHOD if the requested \a method is not registered.
66 */
67 static ParameterEstimation* construct( const std::string &method, const PropertySet &p );
68
69 /// Register a subclass so that it can be used with construct().
70 static void registerMethod( const std::string &method, const ParamEstFactory &f ) {
71 if( _registry == NULL )
72 loadDefaultRegistry();
73 (*_registry)[method] = f;
74 }
75
76 /// Estimate the factor using the accumulated sufficient statistics and reset.
77 virtual Prob estimate() = 0;
78
79 /// Accumulate the sufficient statistics for \a p.
80 virtual void addSufficientStatistics( const Prob &p ) = 0;
81
82 /// Returns the size of the Prob that should be passed to addSufficientStatistics.
83 virtual size_t probSize() const = 0;
84
85 private:
86 /// A static registry containing all methods registered so far.
87 static std::map<std::string, ParamEstFactory> *_registry;
88
89 /// Registers default ParameterEstimation subclasses (currently, only CondProbEstimation).
90 static void loadDefaultRegistry();
91 };
92
93
94 /// Estimates the parameters of a conditional probability table, using pseudocounts.
95 /** \author Charles Vaske
96 */
97 class CondProbEstimation : private ParameterEstimation {
98 private:
99 /// Number of states of the variable of interest
100 size_t _target_dim;
101 /// Current pseudocounts
102 Prob _stats;
103 /// Initial pseudocounts
104 Prob _initial_stats;
105
106 public:
107 /// Constructor
108 /** For a conditional probability \f$ P( X | Y ) \f$,
109 * \param target_dimension should equal \f$ | X | \f$
110 * \param pseudocounts are the initial pseudocounts, of length \f$ |X| \cdot |Y| \f$
111 */
112 CondProbEstimation( size_t target_dimension, const Prob &pseudocounts );
113
114 /// Virtual constructor, using a PropertySet.
115 /** Some keys in the PropertySet are required.
116 * For a conditional probability \f$ P( X | Y ) \f$,
117 * - \a target_dimension should be equal to \f$ | X | \f$
118 * - \a total_dimension should be equal to \f$ |X| \cdot |Y| \f$
119 *
120 * An optional key is:
121 * - \a pseudo_count which specifies the initial counts (defaults to 1)
122 */
123 static ParameterEstimation* factory( const PropertySet &p );
124
125 /// Virtual copy constructor
126 virtual ParameterEstimation* clone() const { return new CondProbEstimation( _target_dim, _initial_stats ); }
127
128 /// Virtual destructor
129 virtual ~CondProbEstimation() {}
130
131 /// Returns an estimate of the conditional probability distribution.
132 /** The format of the resulting Prob keeps all the values for
133 * \f$ P(X | Y=y) \f$ in sequential order in the array.
134 */
135 virtual Prob estimate();
136
137 /// Accumulate sufficient statistics from the expectations in \a p
138 virtual void addSufficientStatistics( const Prob &p );
139
140 /// Returns the required size for arguments to addSufficientStatistics().
141 virtual size_t probSize() const { return _stats.size(); }
142 };
143
144
145 /// Represents a single factor or set of factors whose parameters should be estimated.
146 /** To ensure that parameters can be shared between different factors during
147 * EM learning, each factor's values are reordered to match a desired variable
148 * ordering. The ordering of the variables in a factor may therefore differ
149 * from the canonical ordering used in libDAI. The SharedParameters
150 * class combines one or more factors (together with the specified orderings
151 * of the variables) with a ParameterEstimation object, taking care of the
152 * necessary permutations of the factor entries / parameters.
153 *
154 * \author Charles Vaske
155 */
156 class SharedParameters {
157 public:
158 /// Convenience label for an index of a factor in a FactorGraph.
159 typedef size_t FactorIndex;
160 /// Convenience label for a grouping of factor orientations.
161 typedef std::map<FactorIndex, std::vector<Var> > FactorOrientations;
162
163 private:
164 /// Maps factor indices to the corresponding VarSets
165 std::map<FactorIndex, VarSet> _varsets;
166 /// Maps factor indices to the corresponding Permute objects that permute the canonical ordering into the desired ordering
167 std::map<FactorIndex, Permute> _perms;
168 /// Maps factor indices to the corresponding desired variable orderings
169 FactorOrientations _varorders;
170 /// Parameter estimation method to be used
171 ParameterEstimation *_estimation;
172 /// Indicates whether \c *this gets ownership of _estimation
173 bool _ownEstimation;
174
175 /// Calculates the permutation that permutes the canonical ordering into the desired ordering
176 /** \param varOrder Desired ordering of variables
177 * \param outVS Contains variables in \a varOrder represented as a VarSet
178 * \return Permute object for permuting variables in varOrder from the canonical libDAI ordering into the desired ordering
179 */
180 static Permute calculatePermutation( const std::vector<Var> &varOrder, VarSet &outVS );
181
182 /// Initializes _varsets and _perms from _varorders and checks whether their state spaces correspond with _estimation.probSize()
183 void setPermsAndVarSetsFromVarOrders();
184
185 public:
186 /// Constructor
187 /** \param varorders all the factor orientations for this parameter
188 * \param estimation a pointer to the parameter estimation method
189 * \param ownPE whether the constructed object gets ownership of \a estimation
190 */
191 SharedParameters( const FactorOrientations &varorders, ParameterEstimation *estimation, bool ownPE=false );
192
193 /// Construct a SharedParameters object from an input stream \a is and a factor graph \a fg
194 /** \see \ref fileformats-emalg-sharedparameters
195 * \throw INVALID_EMALG_FILE if the input stream is not valid
196 */
197 SharedParameters( std::istream &is, const FactorGraph &fg );
198
199 /// Copy constructor
200 SharedParameters( const SharedParameters &sp ) : _varsets(sp._varsets), _perms(sp._perms), _varorders(sp._varorders), _estimation(sp._estimation), _ownEstimation(sp._ownEstimation) {
201 // If sp owns its _estimation object, we should clone it instead of copying the pointer
202 if( _ownEstimation )
203 _estimation = _estimation->clone();
204 }
205
206 /// Destructor
207 ~SharedParameters() {
208 // If we own the _estimation object, we should delete it now
209 if( _ownEstimation )
210 delete _estimation;
211 }
212
213 /// Collect the sufficient statistics from expected values (beliefs) according to \a alg
214 /** For each of the relevant factors (that shares the parameters we are interested in),
215 * the corresponding belief according to \a alg is obtained and its entries are permuted
216 * such that their ordering corresponds with the shared parameters that we are estimating.
217 * Then, the parameter estimation subclass method addSufficientStatistics() is called with
218 * this vector of expected values of the parameters as input.
219 */
220 void collectSufficientStatistics( InfAlg &alg );
221
222 /// Estimate and set the shared parameters
223 /** Based on the sufficient statistics collected so far, the shared parameters are estimated
224 * using the parameter estimation subclass method estimate(). Then, each of the relevant
225 * factors in \a fg (that shares the parameters we are interested in) is set according
226 * to those parameters (permuting the parameters accordingly).
227 */
228 void setParameters( FactorGraph &fg );
229 };
230
231
232 /// A MaximizationStep groups together several parameter estimation tasks (SharedParameters objects) into a single unit.
233 /** \author Charles Vaske
234 */
235 class MaximizationStep {
236 private:
237 /// Vector of parameter estimation tasks of which this maximization step consists
238 std::vector<SharedParameters> _params;
239
240 public:
241 /// Default constructor
242 MaximizationStep() : _params() {}
243
244 /// Construct MaximizationStep from a vector of parameter estimation tasks
245 MaximizationStep( std::vector<SharedParameters> &maximizations ) : _params(maximizations) {}
246
247 /// Constructor from an input stream and a corresponding factor graph
248 /** \see \ref fileformats-emalg-maximizationstep
249 */
250 MaximizationStep( std::istream &is, const FactorGraph &fg_varlookup );
251
252 /// Collect the beliefs from this InfAlg as expectations for the next Maximization step
253 void addExpectations( InfAlg &alg );
254
255 /// Using all of the currently added expectations, make new factors with maximized parameters and set them in the FactorGraph.
256 void maximize( FactorGraph &fg );
257
258 /// \name Iterator interface
259 //@{
260 /// Iterator over the parameter estimation tasks
261 typedef std::vector<SharedParameters>::iterator iterator;
262 /// Constant iterator over the parameter estimation tasks
263 typedef std::vector<SharedParameters>::const_iterator const_iterator;
264
265 /// Returns iterator that points to the first parameter estimation task
266 iterator begin() { return _params.begin(); }
267 /// Returns constant iterator that points to the first parameter estimation task
268 const_iterator begin() const { return _params.begin(); }
269 /// Returns iterator that points beyond the last parameter estimation task
270 iterator end() { return _params.end(); }
271 /// Returns constant iterator that points beyond the last parameter estimation task
272 const_iterator end() const { return _params.end(); }
273 //@}
274 };
275
276
277 /// EMAlg performs Expectation Maximization to learn factor parameters.
278 /** This requires specifying:
279 * - Evidence (instances of observations from the graphical model),
280 * - InfAlg for performing the E-step (which includes the factor graph),
281 * - a vector of MaximizationStep 's steps to be performed.
282 *
283 * This implementation can perform incremental EM by using multiple
284 * MaximizationSteps. An expectation step is performed between execution
285 * of each MaximizationStep. A call to iterate() will cycle through all
286 * MaximizationStep 's. A call to run() will call iterate() until the
287 * termination criteria have been met.
288 *
289 * Having multiple and separate maximization steps allows for maximizing some
290 * parameters, performing another E-step, and then maximizing separate
291 * parameters, which may result in faster convergence in some cases.
292 *
293 * \author Charles Vaske
294 */
295 class EMAlg {
296 private:
297 /// All the data samples used during learning
298 const Evidence &_evidence;
299
300 /// How to do the expectation step
301 InfAlg &_estep;
302
303 /// The maximization steps to take
304 std::vector<MaximizationStep> _msteps;
305
306 /// Number of iterations done
307 size_t _iters;
308
309 /// History of likelihoods
310 std::vector<Real> _lastLogZ;
311
312 /// Maximum number of iterations
313 size_t _max_iters;
314
315 /// Convergence tolerance
316 Real _log_z_tol;
317
318 public:
319 /// Key for setting maximum iterations
320 static const std::string MAX_ITERS_KEY;
321 /// Default maximum iterations
322 static const size_t MAX_ITERS_DEFAULT;
323 /// Key for setting likelihood termination condition
324 static const std::string LOG_Z_TOL_KEY;
325 /// Default likelihood tolerance
326 static const Real LOG_Z_TOL_DEFAULT;
327
328 /// Construct an EMAlg from several objects
329 /** \param evidence Specifies the observed evidence
330 * \param estep Inference algorithm to be used for the E-step
331 * \param msteps Vector of maximization steps, each of which is a group of parameter estimation tasks
332 * \param termconditions Termination conditions @see setTermConditions()
333 */
334 EMAlg( const Evidence &evidence, InfAlg &estep, std::vector<MaximizationStep> &msteps, const PropertySet &termconditions )
335 : _evidence(evidence), _estep(estep), _msteps(msteps), _iters(0), _lastLogZ(), _max_iters(MAX_ITERS_DEFAULT), _log_z_tol(LOG_Z_TOL_DEFAULT)
336 {
337 setTermConditions( termconditions );
338 }
339
340 /// Construct an EMAlg from Evidence \a evidence, an InfAlg \a estep, and an input stream \a mstep_file
341 /** \see \ref fileformats-emalg
342 */
343 EMAlg( const Evidence &evidence, InfAlg &estep, std::istream &mstep_file );
344
345 /// Change the conditions for termination
346 /** There are two possible parameters in the PropertySet \a p:
347 * - \a max_iters maximum number of iterations
348 * - \a log_z_tol critical proportion of increase in logZ
349 *
350 * \see hasSatisifiedTermConditions()
351 */
352 void setTermConditions( const PropertySet &p );
353
354 /// Determine if the termination conditions have been met.
355 /** There are two sufficient termination conditions:
356 * -# the maximum number of iterations has been performed
357 * -# the ratio of logZ increase over previous logZ is less than the
358 * tolerance, i.e.,
359 * \f$ \frac{\log(Z_t) - \log(Z_{t-1})}{| \log(Z_{t-1}) | } < \mathrm{tol} \f$.
360 */
361 bool hasSatisfiedTermConditions() const;
362
363 /// Return the last calculated log likelihood
364 Real logZ() const { return _lastLogZ.back(); }
365
366 /// Returns number of iterations done so far
367 size_t Iterations() const { return _iters; }
368
369 /// Get the E-step method used
370 const InfAlg& eStep() const { return _estep; }
371
372 /// Iterate once over all maximization steps
373 /** \return Log-likelihood after iteration
374 */
375 Real iterate();
376
377 /// Iterate over a single MaximizationStep
378 Real iterate( MaximizationStep &mstep );
379
380 /// Iterate until termination conditions are satisfied
381 void run();
382
383 /// \name Iterator interface
384 //@{
385 /// Iterator over the maximization steps
386 typedef std::vector<MaximizationStep>::iterator s_iterator;
387 /// Constant iterator over the maximization steps
388 typedef std::vector<MaximizationStep>::const_iterator const_s_iterator;
389
390 /// Returns iterator that points to the first maximization step
391 s_iterator s_begin() { return _msteps.begin(); }
392 /// Returns constant iterator that points to the first maximization step
393 const_s_iterator s_begin() const { return _msteps.begin(); }
394 /// Returns iterator that points beyond the last maximization step
395 s_iterator s_end() { return _msteps.end(); }
396 /// Returns constant iterator that points beyond the last maximization step
397 const_s_iterator s_end() const { return _msteps.end(); }
398 //@}
399 };
400
401
402 } // end of namespace dai
403
404
405 /** \example example_sprinkler_em.cpp
406 * This example shows how to use the EMAlg class.
407 */
408
409
410 #endif