Improved documentation of include/dai/exactinf.h
[libdai.git] / include / dai / emalg.h
1 /* This file is part of libDAI - http://www.libdai.org/
2 *
3 * libDAI is licensed under the terms of the GNU General Public License version
4 * 2, or (at your option) any later version. libDAI is distributed without any
5 * warranty. See the file COPYING for more details.
6 *
7 * Copyright (C) 2009 Charles Vaske [cvaske at soe dot ucsc dot edu]
8 * Copyright (C) 2009 University of California, Santa Cruz
9 */
10
11
12 #ifndef __defined_libdai_emalg_h
13 #define __defined_libdai_emalg_h
14
15
16 #include <vector>
17 #include <map>
18
19 #include <dai/factor.h>
20 #include <dai/daialg.h>
21 #include <dai/evidence.h>
22 #include <dai/index.h>
23 #include <dai/properties.h>
24
25
26 /// \file
27 /// \brief Defines classes related to Expectation Maximization: EMAlg, ParameterEstimation, CondProbEstimation and SharedParameters
28 /// \todo Describe EM file format
29 /// \todo Improve documentation
30
31
32 namespace dai {
33
34
35 /// Interface for a parameter estimation method.
36 /** This parameter estimation interface is based on sufficient statistics.
37 * Implementations are responsible for collecting data from a probability
38 * vector passed to it from a SharedParameters container object.
39 *
40 * Implementations of this interface should register a factory function
41 * via the static ParameterEstimation::registerMethod function.
42 * The default registry only contains CondProbEstimation, named
43 * "ConditionalProbEstimation".
44 */
45 class ParameterEstimation {
46 public:
47 /// A pointer to a factory function.
48 typedef ParameterEstimation* (*ParamEstFactory)( const PropertySet& );
49
50 /// Virtual destructor for deleting pointers to derived classes.
51 virtual ~ParameterEstimation() {}
52 /// Virtual copy constructor.
53 virtual ParameterEstimation* clone() const = 0;
54
55 /// General factory method for construction of ParameterEstimation subclasses.
56 static ParameterEstimation* construct( const std::string &method, const PropertySet &p );
57
58 /// Register a subclass so that it can be used with ParameterEstimation::construct.
59 static void registerMethod( const std::string &method, const ParamEstFactory &f ) {
60 if( _registry == NULL )
61 loadDefaultRegistry();
62 (*_registry)[method] = f;
63 }
64
65 /// Estimate the factor using the accumulated sufficient statistics and reset.
66 virtual Prob estimate() = 0;
67
68 /// Accumulate the sufficient statistics for p.
69 virtual void addSufficientStatistics( const Prob &p ) = 0;
70
71 /// Returns the size of the Prob that should be passed to addSufficientStatistics.
72 virtual size_t probSize() const = 0;
73
74 private:
75 /// A static registry containing all methods registered so far.
76 static std::map<std::string, ParamEstFactory> *_registry;
77
78 /// Registers default ParameterEstimation subclasses (currently, only CondProbEstimation).
79 static void loadDefaultRegistry();
80 };
81
82
83 /// Estimates the parameters of a conditional probability table, using pseudocounts.
84 class CondProbEstimation : private ParameterEstimation {
85 private:
86 /// Number of states of the variable of interest
87 size_t _target_dim;
88 /// Current pseudocounts
89 Prob _stats;
90 /// Initial pseudocounts
91 Prob _initial_stats;
92
93 public:
94 /// Constructor
95 /** For a conditional probability \f$ P( X | Y ) \f$,
96 * \param target_dimension should equal \f$ | X | \f$
97 * \param pseudocounts has length \f$ |X| \cdot |Y| \f$
98 */
99 CondProbEstimation( size_t target_dimension, const Prob &pseudocounts );
100
101 /// Virtual constructor, using a PropertySet.
102 /** Some keys in the PropertySet are required.
103 * For a conditional probability \f$ P( X | Y ) \f$,
104 * - target_dimension should be equal to \f$ | X | \f$
105 * - total_dimension should be equal to \f$ |X| \cdot |Y| \f$
106 *
107 * An optional key is:
108 * - pseudo_count, which specifies the initial counts (defaults to 1)
109 */
110 static ParameterEstimation* factory( const PropertySet &p );
111
112 /// Virtual copy constructor
113 virtual ParameterEstimation* clone() const { return new CondProbEstimation( _target_dim, _initial_stats ); }
114
115 /// Virtual destructor
116 virtual ~CondProbEstimation() {}
117
118 /// Returns an estimate of the conditional probability distribution.
119 /** The format of the resulting Prob keeps all the values for
120 * \f$ P(X | Y=y) \f$ in sequential order in the array.
121 */
122 virtual Prob estimate();
123
124 /// Accumulate sufficient statistics from the expectations in p.
125 virtual void addSufficientStatistics( const Prob &p );
126
127 /// Returns the required size for arguments to addSufficientStatistics.
128 virtual size_t probSize() const { return _stats.size(); }
129 };
130
131
132 /// A single factor or set of factors whose parameters should be estimated.
133 /** To ensure that parameters can be shared between different factors during
134 * EM learning, each factor's values are reordered to match a desired variable
135 * ordering. The ordering of the variables in a factor may therefore differ
136 * from the canonical ordering used in libDAI. The SharedParameters
137 * class couples one or more factors (together with the specified orderings
138 * of the variables) with a ParameterEstimation object, taking care of the
139 * necessary permutations of the factor entries / parameters.
140 */
141 class SharedParameters {
142 public:
143 /// Convenience label for an index into a factor in a FactorGraph.
144 typedef size_t FactorIndex;
145 /// Convenience label for a grouping of factor orientations.
146 typedef std::map<FactorIndex, std::vector<Var> > FactorOrientations;
147
148 private:
149 /// Maps factor indices to the corresponding VarSets
150 std::map<FactorIndex, VarSet> _varsets;
151 /// Maps factor indices to the corresponding Permute objects that permute the desired ordering into the canonical ordering
152 std::map<FactorIndex, Permute> _perms;
153 /// Maps factor indices to the corresponding desired variable orderings
154 FactorOrientations _varorders;
155 /// Parameter estimation method to be used
156 ParameterEstimation *_estimation;
157 /// Indicates whether the object pointed to by _estimation should be deleted upon destruction
158 bool _deleteEstimation;
159
160 /// Calculates the permutation that permutes the variables in varorder into the canonical ordering
161 static Permute calculatePermutation( const std::vector<Var> &varorder, VarSet &outVS );
162
163 /// Initializes _varsets and _perms from _varorders
164 void setPermsAndVarSetsFromVarOrders();
165
166 public:
167 /// Copy constructor
168 SharedParameters( const SharedParameters &sp );
169
170 /// Constructor
171 /** \param varorders all the factor orientations for this parameter
172 * \param estimation a pointer to the parameter estimation method
173 * \param deletePE whether the parameter estimation object should be deleted in the destructor
174 */
175 SharedParameters( const FactorOrientations &varorders, ParameterEstimation *estimation, bool deletePE=false );
176
177 /// Constructor for making an object from a stream and a factor graph
178 SharedParameters( std::istream &is, const FactorGraph &fg_varlookup );
179
180 /// Destructor
181 ~SharedParameters() {
182 if( _deleteEstimation )
183 delete _estimation;
184 }
185
186 /// Collect the necessary statistics from expected values
187 void collectSufficientStatistics( InfAlg &alg );
188
189 /// Estimate and set the shared parameters
190 void setParameters( FactorGraph &fg );
191
192 /// Returns the parameters
193 void collectParameters( const FactorGraph &fg, std::vector<Real> &outVals, std::vector<Var> &outVarOrder );
194 };
195
196
197 /// A MaximizationStep groups together several parameter estimation tasks into a single unit.
198 class MaximizationStep {
199 private:
200 std::vector<SharedParameters> _params;
201
202 public:
203 /// Default constructor
204 MaximizationStep() : _params() {}
205
206 /// Constructor from a vector of SharedParameters objects
207 MaximizationStep( std::vector<SharedParameters> &maximizations ) : _params(maximizations) {}
208
209 /// Constructor from an input stream and a corresponding factor graph
210 MaximizationStep( std::istream &is, const FactorGraph &fg_varlookup );
211
212 /// Collect the beliefs from this InfAlg as expectations for the next Maximization step.
213 void addExpectations( InfAlg &alg );
214
215 /// Using all of the currently added expectations, make new factors with maximized parameters and set them in the FactorGraph.
216 void maximize( FactorGraph &fg );
217
218 /// \name Iterator interface
219 //@{
220 typedef std::vector<SharedParameters>::iterator iterator;
221 typedef std::vector<SharedParameters>::const_iterator const_iterator;
222 iterator begin() { return _params.begin(); }
223 const_iterator begin() const { return _params.begin(); }
224 iterator end() { return _params.end(); }
225 const_iterator end() const { return _params.end(); }
226 //@}
227 };
228
229
230 /// EMAlg performs Expectation Maximization to learn factor parameters.
231 /** This requires specifying:
232 * - Evidence (instances of observations from the graphical model),
233 * - InfAlg for performing the E-step, which includes the factor graph,
234 * - a vector of MaximizationSteps steps to be performed.
235 *
236 * This implementation can perform incremental EM by using multiple
237 * MaximizationSteps. An expectation step is performed between execution
238 * of each MaximizationStep. A call to iterate() will cycle through all
239 * MaximizationSteps.
240 *
241 * Having multiple and separate maximization steps allows for maximizing some
242 * parameters, performing another E step, and then maximizing separate
243 * parameters, which may result in faster convergence in some cases.
244 */
245 class EMAlg {
246 private:
247 /// All the data samples used during learning
248 const Evidence &_evidence;
249
250 /// How to do the expectation step
251 InfAlg &_estep;
252
253 /// The maximization steps to take
254 std::vector<MaximizationStep> _msteps;
255
256 /// Number of iterations done
257 size_t _iters;
258
259 /// History of likelihoods
260 std::vector<Real> _lastLogZ;
261
262 /// Maximum number of iterations
263 size_t _max_iters;
264
265 /// Convergence tolerance
266 Real _log_z_tol;
267
268 public:
269 /// Key for setting maximum iterations @see setTermConditions
270 static const std::string MAX_ITERS_KEY;
271 /// Default maximum iterations @see setTermConditions
272 static const size_t MAX_ITERS_DEFAULT;
273 /// Key for setting likelihood termination condition @see setTermConditions
274 static const std::string LOG_Z_TOL_KEY;
275 /// Default likelihood tolerance @see setTermConditions
276 static const Real LOG_Z_TOL_DEFAULT;
277
278 /// Construct an EMAlg from all these objects
279 EMAlg( const Evidence &evidence, InfAlg &estep, std::vector<MaximizationStep> &msteps, const PropertySet &termconditions )
280 : _evidence(evidence), _estep(estep), _msteps(msteps), _iters(0), _lastLogZ(), _max_iters(MAX_ITERS_DEFAULT), _log_z_tol(LOG_Z_TOL_DEFAULT)
281 {
282 setTermConditions( termconditions );
283 }
284
285 /// Construct an EMAlg from an Evidence object, an InfAlg object, and an input stream
286 EMAlg( const Evidence &evidence, InfAlg &estep, std::istream &mstep_file );
287
288 /// Change the conditions for termination
289 /** There are two possible parameters in the PropertySet
290 * - max_iters maximum number of iterations
291 * - log_z_tol proportion of increase in logZ
292 *
293 * \see hasSatisifiedTermConditions()
294 */
295 void setTermConditions( const PropertySet &p );
296
297 /// Determine if the termination conditions have been met.
298 /** There are two sufficient termination conditions:
299 * -# the maximum number of iterations has been performed
300 * -# the ratio of logZ increase over previous logZ is less than the
301 * tolerance, i.e.,
302 * \f$ \frac{\log(Z_t) - \log(Z_{t-1})}{| \log(Z_{t-1}) | } < \mathrm{tol} \f$.
303 */
304 bool hasSatisfiedTermConditions() const;
305
306 /// Return the last calculated log likelihood
307 Real getLogZ() const { return _lastLogZ.back(); }
308
309 /// Returns number of iterations done so far
310 size_t getCurrentIters() const { return _iters; }
311
312 /// Get the iteration method used
313 const InfAlg& eStep() const { return _estep; }
314
315 /// Perform an iteration over all maximization steps
316 Real iterate();
317
318 /// Perform an iteration over a single MaximizationStep
319 Real iterate( MaximizationStep &mstep );
320
321 /// Iterate until termination conditions are satisfied
322 void run();
323
324 /// \name Iterator interface
325 //@{
326 typedef std::vector<MaximizationStep>::iterator s_iterator;
327 typedef std::vector<MaximizationStep>::const_iterator const_s_iterator;
328 s_iterator s_begin() { return _msteps.begin(); }
329 const_s_iterator s_begin() const { return _msteps.begin(); }
330 s_iterator s_end() { return _msteps.end(); }
331 const_s_iterator s_end() const { return _msteps.end(); }
332 //@}
333 };
334
335
336 } // end of namespace dai
337
338
339 #endif