Improved HAK (added 'maxtime' property)
[libdai.git] / src / emalg.cpp
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 #include <dai/util.h>
13 #include <dai/emalg.h>
14
15
16 namespace dai {
17
18
19 // Initialize static private member of ParameterEstimation
20 std::map<std::string, ParameterEstimation::ParamEstFactory> *ParameterEstimation::_registry = NULL;
21
22
23 void ParameterEstimation::loadDefaultRegistry() {
24 _registry = new std::map<std::string, ParamEstFactory>();
25 (*_registry)["CondProbEstimation"] = CondProbEstimation::factory;
26 }
27
28
29 ParameterEstimation* ParameterEstimation::construct( const std::string &method, const PropertySet &p ) {
30 if( _registry == NULL )
31 loadDefaultRegistry();
32 std::map<std::string, ParamEstFactory>::iterator i = _registry->find(method);
33 if( i == _registry->end() )
34 DAI_THROWE(UNKNOWN_PARAMETER_ESTIMATION_METHOD, "Unknown parameter estimation method: " + method);
35 ParamEstFactory factory = i->second;
36 return factory(p);
37 }
38
39
40 ParameterEstimation* CondProbEstimation::factory( const PropertySet &p ) {
41 size_t target_dimension = p.getStringAs<size_t>("target_dim");
42 size_t total_dimension = p.getStringAs<size_t>("total_dim");
43 Real pseudo_count = 1;
44 if( p.hasKey("pseudo_count") )
45 pseudo_count = p.getStringAs<Real>("pseudo_count");
46 return new CondProbEstimation( target_dimension, Prob( total_dimension, pseudo_count ) );
47 }
48
49
50 CondProbEstimation::CondProbEstimation( size_t target_dimension, const Prob &pseudocounts )
51 : _target_dim(target_dimension), _stats(pseudocounts), _initial_stats(pseudocounts)
52 {
53 DAI_ASSERT( !(_stats.size() % _target_dim) );
54 }
55
56
57 void CondProbEstimation::addSufficientStatistics( const Prob &p ) {
58 _stats += p;
59 }
60
61
62 Prob CondProbEstimation::estimate() {
63 // normalize pseudocounts
64 for( size_t parent = 0; parent < _stats.size(); parent += _target_dim ) {
65 // calculate norm
66 size_t top = parent + _target_dim;
67 Real norm = 0.0;
68 for( size_t i = parent; i < top; ++i )
69 norm += _stats[i];
70 if( norm != 0.0 )
71 norm = 1.0 / norm;
72 // normalize
73 for( size_t i = parent; i < top; ++i )
74 _stats.set( i, _stats[i] * norm );
75 }
76 // reset _stats to _initial_stats
77 Prob result = _stats;
78 _stats = _initial_stats;
79 return result;
80 }
81
82
83 Permute SharedParameters::calculatePermutation( const std::vector<Var> &varOrder, VarSet &outVS ) {
84 outVS = VarSet( varOrder.begin(), varOrder.end(), varOrder.size() );
85 return Permute( varOrder );
86 }
87
88
89 void SharedParameters::setPermsAndVarSetsFromVarOrders() {
90 if( _varorders.size() == 0 )
91 return;
92 DAI_ASSERT( _estimation != NULL );
93
94 // Construct the permutation objects and the varsets
95 for( FactorOrientations::const_iterator foi = _varorders.begin(); foi != _varorders.end(); ++foi ) {
96 VarSet vs;
97 _perms[foi->first] = calculatePermutation( foi->second, vs );
98 _varsets[foi->first] = vs;
99 DAI_ASSERT( _estimation->probSize() == vs.nrStates() );
100 }
101 }
102
103
104 SharedParameters::SharedParameters( const FactorOrientations &varorders, ParameterEstimation *estimation, bool ownPE )
105 : _varsets(), _perms(), _varorders(varorders), _estimation(estimation), _ownEstimation(ownPE)
106 {
107 // Calculate the necessary permutations and varsets
108 setPermsAndVarSetsFromVarOrders();
109 }
110
111
112 SharedParameters::SharedParameters( std::istream &is, const FactorGraph &fg )
113 : _varsets(), _perms(), _varorders(), _estimation(NULL), _ownEstimation(true)
114 {
115 // Read the desired parameter estimation method from the stream
116 std::string est_method;
117 PropertySet props;
118 is >> est_method;
119 is >> props;
120
121 // Construct a corresponding object
122 _estimation = ParameterEstimation::construct( est_method, props );
123
124 // Read in the factors that are to be estimated
125 size_t num_factors;
126 is >> num_factors;
127 for( size_t sp_i = 0; sp_i < num_factors; ++sp_i ) {
128 std::string line;
129 while( line.size() == 0 && getline(is, line) )
130 ;
131
132 std::vector<std::string> fields;
133 tokenizeString(line, fields, " \t");
134
135 // Lookup the factor in the factorgraph
136 if( fields.size() < 1 )
137 DAI_THROWE(INVALID_EMALG_FILE,"Empty line unexpected");
138 std::istringstream iss;
139 iss.str( fields[0] );
140 size_t factor;
141 iss >> factor;
142 const VarSet &vs = fg.factor(factor).vars();
143 if( fields.size() != vs.size() + 1 )
144 DAI_THROWE(INVALID_EMALG_FILE,"Number of fields does not match factor size");
145
146 // Construct the vector of Vars
147 std::vector<Var> var_order;
148 var_order.reserve( vs.size() );
149 for( size_t fi = 1; fi < fields.size(); ++fi ) {
150 // Lookup a single variable by label
151 size_t label;
152 std::istringstream labelparse( fields[fi] );
153 labelparse >> label;
154 VarSet::const_iterator vsi = vs.begin();
155 for( ; vsi != vs.end(); ++vsi )
156 if( vsi->label() == label )
157 break;
158 if( vsi == vs.end() )
159 DAI_THROWE(INVALID_EMALG_FILE,"Specified variables do not match the factor variables");
160 var_order.push_back( *vsi );
161 }
162 _varorders[factor] = var_order;
163 }
164
165 // Calculate the necessary permutations
166 setPermsAndVarSetsFromVarOrders();
167 }
168
169
170 void SharedParameters::collectSufficientStatistics( InfAlg &alg ) {
171 for( std::map< FactorIndex, Permute >::iterator i = _perms.begin(); i != _perms.end(); ++i ) {
172 Permute &perm = i->second;
173 VarSet &vs = _varsets[i->first];
174
175 Factor b = alg.belief(vs);
176 Prob p( b.nrStates(), 0.0 );
177 for( size_t entry = 0; entry < b.nrStates(); ++entry )
178 p.set( entry, b[perm.convertLinearIndex(entry)] ); // apply inverse permutation
179 _estimation->addSufficientStatistics( p );
180 }
181 }
182
183
184 void SharedParameters::setParameters( FactorGraph &fg ) {
185 Prob p = _estimation->estimate();
186 for( std::map<FactorIndex, Permute>::iterator i = _perms.begin(); i != _perms.end(); ++i ) {
187 Permute &perm = i->second;
188 VarSet &vs = _varsets[i->first];
189
190 Factor f( vs, 0.0 );
191 for( size_t entry = 0; entry < f.nrStates(); ++entry )
192 f.set( perm.convertLinearIndex(entry), p[entry] );
193
194 fg.setFactor( i->first, f );
195 }
196 }
197
198
199 MaximizationStep::MaximizationStep( std::istream &is, const FactorGraph &fg_varlookup ) : _params() {
200 size_t num_params = -1;
201 is >> num_params;
202 _params.reserve( num_params );
203 for( size_t i = 0; i < num_params; ++i )
204 _params.push_back( SharedParameters( is, fg_varlookup ) );
205 }
206
207
208 void MaximizationStep::addExpectations( InfAlg &alg ) {
209 for( size_t i = 0; i < _params.size(); ++i )
210 _params[i].collectSufficientStatistics( alg );
211 }
212
213
214 void MaximizationStep::maximize( FactorGraph &fg ) {
215 for( size_t i = 0; i < _params.size(); ++i )
216 _params[i].setParameters( fg );
217 }
218
219
220 const std::string EMAlg::MAX_ITERS_KEY("max_iters");
221 const std::string EMAlg::LOG_Z_TOL_KEY("log_z_tol");
222 const size_t EMAlg::MAX_ITERS_DEFAULT = 30;
223 const Real EMAlg::LOG_Z_TOL_DEFAULT = 0.01;
224
225
226 EMAlg::EMAlg( const Evidence &evidence, InfAlg &estep, std::istream &msteps_file )
227 : _evidence(evidence), _estep(estep), _msteps(), _iters(0), _lastLogZ(), _max_iters(MAX_ITERS_DEFAULT), _log_z_tol(LOG_Z_TOL_DEFAULT)
228 {
229 msteps_file.exceptions( std::istream::eofbit | std::istream::failbit | std::istream::badbit );
230 size_t num_msteps = -1;
231 msteps_file >> num_msteps;
232 _msteps.reserve(num_msteps);
233 for( size_t i = 0; i < num_msteps; ++i )
234 _msteps.push_back( MaximizationStep( msteps_file, estep.fg() ) );
235 }
236
237
238 void EMAlg::setTermConditions( const PropertySet &p ) {
239 if( p.hasKey(MAX_ITERS_KEY) )
240 _max_iters = p.getStringAs<size_t>(MAX_ITERS_KEY);
241 if( p.hasKey(LOG_Z_TOL_KEY) )
242 _log_z_tol = p.getStringAs<Real>(LOG_Z_TOL_KEY);
243 }
244
245
246 bool EMAlg::hasSatisfiedTermConditions() const {
247 if( _iters >= _max_iters )
248 return true;
249 else if( _lastLogZ.size() < 3 )
250 // need at least 2 to calculate ratio
251 // Also, throw away first iteration, as the parameters may not
252 // have been normalized according to the estimation method
253 return false;
254 else {
255 Real current = _lastLogZ[_lastLogZ.size() - 1];
256 Real previous = _lastLogZ[_lastLogZ.size() - 2];
257 if( previous == 0 )
258 return false;
259 Real diff = current - previous;
260 if( diff < 0 ) {
261 std::cerr << "Error: in EM log-likehood decreased from " << previous << " to " << current << std::endl;
262 return true;
263 }
264 return (diff / fabs(previous)) <= _log_z_tol;
265 }
266 }
267
268
269 Real EMAlg::iterate( MaximizationStep &mstep ) {
270 Real logZ = 0;
271 Real likelihood = 0;
272
273 _estep.run();
274 logZ = _estep.logZ();
275
276 // Expectation calculation
277 for( Evidence::const_iterator e = _evidence.begin(); e != _evidence.end(); ++e ) {
278 InfAlg* clamped = _estep.clone();
279 // Apply evidence
280 for( Evidence::Observation::const_iterator i = e->begin(); i != e->end(); ++i )
281 clamped->clamp( clamped->fg().findVar(i->first), i->second );
282 clamped->init();
283 clamped->run();
284
285 likelihood += clamped->logZ() - logZ;
286
287 mstep.addExpectations( *clamped );
288
289 delete clamped;
290 }
291
292 // Maximization of parameters
293 mstep.maximize( _estep.fg() );
294
295 return likelihood;
296 }
297
298
299 Real EMAlg::iterate() {
300 Real likelihood;
301 for( size_t i = 0; i < _msteps.size(); ++i )
302 likelihood = iterate( _msteps[i] );
303 _lastLogZ.push_back( likelihood );
304 ++_iters;
305 return likelihood;
306 }
307
308
309 void EMAlg::run() {
310 while( !hasSatisfiedTermConditions() )
311 iterate();
312 }
313
314
315 } // end of namespace dai