forked from lamdongnd/Entity.Extraction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGisTrainer.cs
936 lines (822 loc) · 29.6 KB
/
GisTrainer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
//Copyright (C) 2005 Richard J. Northedge
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the GISTrainer.java source file found in the
//original java implementation of MaxEnt. That source file contains the following header:
// Copyright (C) 2001 Jason Baldridge and Gann Bierner
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections;
using System.Collections.Generic;
namespace SharpEntropy
{
/// <summary>
/// An implementation of Generalized Iterative Scaling. The reference paper
/// for this implementation was Adwait Ratnaparkhi's tech report at the
/// University of Pennsylvania's Institute for Research in Cognitive Science,
/// and is available at <a href ="ftp://ftp.cis.upenn.edu/pub/ircs/tr/97-08.ps.Z"><code>ftp://ftp.cis.upenn.edu/pub/ircs/tr/97-08.ps.Z</code></a>.
/// </summary>
/// <author>
/// Jason Baldridge
/// </author>
/// <author>
/// Richard J, Northedge
/// </author>
/// <version>
/// based on GISTrainer.java, $Revision: 1.15 $, $Date: 2004/06/14 20:52:41 $
/// </version>
public class GisTrainer : IO.IGisModelReader
{
private int mTokenCount; // # of event tokens
private int mPredicateCount; // # of predicates
private int mOutcomeCount; // # of mOutcomes
private int mTokenID; // global index variable for Tokens
private int mPredicateId; // global index variable for Predicates
private int mOutcomeId; // global index variable for Outcomes
// records the array of predicates seen in each event
private int[][] mContexts;
// records the array of outcomes seen in each event
private int[] mOutcomes;
// records the num of times an event has been seen, paired to
// int[][] mContexts
private int[] mNumTimesEventsSeen;
// stores the string names of the outcomes. The GIS only tracks outcomes
// as ints, and so this array is needed to save the model to disk and
// thereby allow users to know what the outcome was in human
// understandable terms.
private string[] mOutcomeLabels;
// stores the string names of the predicates. The GIS only tracks
// predicates as ints, and so this array is needed to save the model to
// disk and thereby allow users to know what the outcome was in human
// understandable terms.
private string[] mPredicateLabels;
// stores the observed expections of each of the events
private double[][] mObservedExpections;
// stores the estimated parameter value of each predicate during iteration
private double[][] mParameters;
// Stores the expected values of the features based on the current models
private double[][] mModelExpections;
//The maximum number of features fired in an event. Usually referred to as C.
private int mMaximumFeatureCount;
// stores inverse of constant, 1/C.
private double mMaximumFeatureCountInverse;
// the correction parameter of the model
private double mCorrectionParameter;
// observed expectation of correction feature
private double mCorrectionFeatureObservedExpectation;
// a global variable to help compute the amount to modify the correction
// parameter
private double mCorrectionFeatureModifier;
private const double mNearZero = 0.01;
private const double mLLThreshold = 0.0001;
// Stores the output of the current model on a single event durring
// training. This will be reset for every event for every iteration.
private double[] mModelDistribution;
// Stores the number of features that get fired per event
private int[] mFeatureCounts;
// initial probability for all outcomes.
private double mInitialProbability;
private Dictionary<string, PatternedPredicate> mPredicates;
private int[][] mOutcomePatterns;
#region smoothing algorithm (unused)
// internal class UpdateParametersWithSmoothingProcedure : Trove.IIntDoubleProcedure
// {
// private double mdSigma = 2.0;
// public UpdateParametersWithSmoothingProcedure(GisTrainer enclosingInstance)
// {
// moEnclosingInstance = enclosingInstance;
// }
//
// private GisTrainer moEnclosingInstance;
//
// public virtual bool Execute(int outcomeID, double input)
// {
// double x = 0.0;
// double x0 = 0.0;
// double tmp;
// double f;
// double fp;
// for (int i = 0; i < 50; i++)
// {
// // check what domain these parameters are in
// tmp = moEnclosingInstance.maoModelExpections[moEnclosingInstance.miPredicateID][outcomeID] * System.Math.Exp(moEnclosingInstance.miConstant * x0);
// f = tmp + (input + x0) / moEnclosingInstance.mdSigma - moEnclosingInstance.maoObservedExpections[moEnclosingInstance.miPredicateID][outcomeID];
// fp = tmp * moEnclosingInstance.miConstant + 1 / moEnclosingInstance.mdSigma;
// if (fp == 0)
// {
// break;
// }
// x = x0 - f / fp;
// if (System.Math.Abs(x - x0) < 0.000001)
// {
// x0 = x;
// break;
// }
// x0 = x;
// }
// moEnclosingInstance.maoParameters[moEnclosingInstance.miPredicateID].Put(outcomeID, input + x0);
// return true;
// }
// }
#endregion
#region training progress event
/// <summary>
/// Used to provide informational messages regarding the
/// progress of the training algorithm.
/// </summary>
public event TrainingProgressEventHandler TrainingProgress;
/// <summary>
/// Used to raise events providing messages with information
/// about training progress.
/// </summary>
/// <param name="e">
/// Contains the message with information about the progress of
/// the training algorithm.
/// </param>
protected virtual void OnTrainingProgress(TrainingProgressEventArgs e)
{
if (TrainingProgress != null)
{
TrainingProgress(this, e);
}
}
private void NotifyProgress(string message)
{
OnTrainingProgress(new TrainingProgressEventArgs(message));
}
#endregion
#region training options
private bool mSimpleSmoothing = false;
private bool mUseSlackParameter = false;
private double mSmoothingObservation = 0.1;
/// <summary>
/// Sets whether this trainer will use smoothing while training the model.
/// This can improve model accuracy, though training will potentially take
/// longer and use more memory. Model size will also be larger.
/// </summary>
/// <remarks>
/// Initial testing indicates improvements for models built on small data sets and
/// few outcomes, but performance degradation for those with large data
/// sets and lots of outcomes.
/// </remarks>
public virtual bool Smoothing
{
get
{
return mSimpleSmoothing;
}
set
{
mSimpleSmoothing = value;
}
}
/// <summary>
/// Sets whether this trainer will use slack parameters while training the model.
/// </summary>
public virtual bool UseSlackParameter
{
get
{
return mUseSlackParameter;
}
set
{
mUseSlackParameter = value;
}
}
/// <summary>
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </summary>
virtual public double SmoothingObservation
{
get
{
return mSmoothingObservation;
}
set
{
mSmoothingObservation = value;
}
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
public GisTrainer()
{
mSimpleSmoothing = false;
mUseSlackParameter = false;
mSmoothingObservation = 0.1;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="useSlackParameter">
/// Sets whether this trainer will use slack parameters while training the model.
/// </param>
public GisTrainer(bool useSlackParameter)
{
mSimpleSmoothing = false;
mUseSlackParameter = useSlackParameter;
mSmoothingObservation = 0.1;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="smoothingObservation">
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </param>
public GisTrainer(double smoothingObservation)
{
mSimpleSmoothing = true;
mUseSlackParameter = false;
mSmoothingObservation = smoothingObservation;
}
/// <summary>
/// Creates a new <code>GisTrainer</code> instance.
/// </summary>
/// <param name="useSlackParameter">
/// Sets whether this trainer will use slack parameters while training the model.
/// </param>
/// <param name="smoothingObservation">
/// If smoothing is in use, this value indicates the "number" of
/// times we want the trainer to imagine that it saw a feature that it
/// actually didn't see. Defaulted to 0.1.
/// </param>
public GisTrainer(bool useSlackParameter, double smoothingObservation)
{
mSimpleSmoothing = true;
mUseSlackParameter = useSlackParameter;
mSmoothingObservation = smoothingObservation;
}
#endregion
#region alternative TrainModel signatures
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="eventReader">
/// The ITrainingEventReader holding the data on which this model
/// will be trained.
/// </param>
public virtual void TrainModel(ITrainingEventReader eventReader)
{
TrainModel(eventReader, 100, 0);
}
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="eventReader">
/// The ITrainingEventReader holding the data on which this model
/// will be trained.
/// </param>
/// <param name="iterations">
/// The number of GIS iterations to perform.
/// </param>
/// <param name="cutoff">
/// The number of times a predicate must be seen in order
/// to be relevant for training.
/// </param>
public virtual void TrainModel(ITrainingEventReader eventReader, int iterations, int cutoff)
{
TrainModel(iterations, new OnePassDataIndexer(eventReader, cutoff));
}
#endregion
#region training algorithm
/// <summary>
/// Train a model using the GIS algorithm.
/// </summary>
/// <param name="iterations">
/// The number of GIS iterations to perform.
/// </param>
/// <param name="dataIndexer">
/// The data indexer used to compress events in memory.
/// </param>
public virtual void TrainModel(int iterations, ITrainingDataIndexer dataIndexer)
{
int[] outcomeList;
//incorporate all of the needed info
NotifyProgress("Incorporating indexed data for training...");
mContexts = dataIndexer.GetContexts();
mOutcomes = dataIndexer.GetOutcomeList();
mNumTimesEventsSeen = dataIndexer.GetNumTimesEventsSeen();
mTokenCount = mContexts.Length;
// determine the correction constant and its inverse
mMaximumFeatureCount = mContexts[0].Length;
for (mTokenID = 1; mTokenID < mContexts.Length; mTokenID++)
{
if (mContexts[mTokenID].Length > mMaximumFeatureCount)
{
mMaximumFeatureCount = mContexts[mTokenID].Length;
}
}
mMaximumFeatureCountInverse = 1.0 / mMaximumFeatureCount;
NotifyProgress("done.");
mOutcomeLabels = dataIndexer.GetOutcomeLabels();
outcomeList = dataIndexer.GetOutcomeList();
mOutcomeCount = mOutcomeLabels.Length;
mInitialProbability = System.Math.Log(1.0 / mOutcomeCount);
mPredicateLabels = dataIndexer.GetPredicateLabels();
mPredicateCount = mPredicateLabels.Length;
NotifyProgress("\tNumber of Event Tokens: " + mTokenCount);
NotifyProgress("\t Number of Outcomes: " + mOutcomeCount);
NotifyProgress("\t Number of Predicates: " + mPredicateCount);
// set up feature arrays
int[][] predicateCounts = new int[mPredicateCount][];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
predicateCounts[mPredicateId] = new int[mOutcomeCount];
}
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
predicateCounts[mContexts[mTokenID][currentContext]][outcomeList[mTokenID]] += mNumTimesEventsSeen[mTokenID];
}
}
dataIndexer = null; // don't need it anymore
// A fake "observation" to cover features which are not detected in
// the data. The default is to assume that we observed "1/10th" of a
// feature during training.
double smoothingObservation = mSmoothingObservation;
// Get the observed expectations of the features. Strictly speaking,
// we should divide the counts by the number of Tokens, but because of
// the way the model's expectations are approximated in the
// implementation, this is cancelled out when we compute the next
// iteration of a parameter, making the extra divisions wasteful.
mOutcomePatterns = new int[mPredicateCount][];
mParameters = new double[mPredicateCount][];
mModelExpections = new double[mPredicateCount][];
mObservedExpections = new double[mPredicateCount][];
int activeOutcomeCount;
int currentOutcome;
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
if (mSimpleSmoothing)
{
activeOutcomeCount = mOutcomeCount;
}
else
{
activeOutcomeCount = 0;
for (mOutcomeId = 0; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (predicateCounts[mPredicateId][mOutcomeId] > 0)
{
activeOutcomeCount++;
}
}
}
mOutcomePatterns[mPredicateId] = new int[activeOutcomeCount];
mParameters[mPredicateId] = new double[activeOutcomeCount];
mModelExpections[mPredicateId] = new double[activeOutcomeCount];
mObservedExpections[mPredicateId] = new double[activeOutcomeCount];
currentOutcome = 0;
for (mOutcomeId = 0; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (predicateCounts[mPredicateId][mOutcomeId] > 0)
{
mOutcomePatterns[mPredicateId][currentOutcome] = mOutcomeId;
mObservedExpections[mPredicateId][currentOutcome] = System.Math.Log(predicateCounts[mPredicateId][mOutcomeId]);
currentOutcome++;
}
else if (mSimpleSmoothing)
{
mOutcomePatterns[mPredicateId][currentOutcome] = mOutcomeId;
mObservedExpections[mPredicateId][currentOutcome] = System.Math.Log(smoothingObservation);
currentOutcome++;
}
}
}
// compute the expected value of correction
if (mUseSlackParameter)
{
int correctionFeatureValueSum = 0;
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
mPredicateId = mContexts[mTokenID][currentContext];
if ((!mSimpleSmoothing) && predicateCounts[mPredicateId][mOutcomes[mTokenID]] == 0)
{
correctionFeatureValueSum += mNumTimesEventsSeen[mTokenID];
}
}
correctionFeatureValueSum += (mMaximumFeatureCount - mContexts[mTokenID].Length) * mNumTimesEventsSeen[mTokenID];
}
if (correctionFeatureValueSum == 0)
{
mCorrectionFeatureObservedExpectation = System.Math.Log(mNearZero); //nearly zero so log is defined
}
else
{
mCorrectionFeatureObservedExpectation = System.Math.Log(correctionFeatureValueSum);
}
mCorrectionParameter = 0.0;
}
predicateCounts = null; // don't need it anymore
NotifyProgress("...done.");
mModelDistribution = new double[mOutcomeCount];
mFeatureCounts = new int[mOutcomeCount];
//Find the parameters
NotifyProgress("Computing model parameters...");
FindParameters(iterations);
NotifyProgress("Converting to new predicate format...");
ConvertPredicates();
}
/// <summary>
/// Estimate and return the model parameters.
/// </summary>
/// <param name="iterations">
/// Number of iterations to run through.
/// </param>
private void FindParameters(int iterations)
{
double previousLogLikelihood = 0.0;
double currentLogLikelihood = 0.0;
NotifyProgress("Performing " + iterations + " iterations.");
for (int currentIteration = 1; currentIteration <= iterations; currentIteration++)
{
if (currentIteration < 10)
{
NotifyProgress(" " + currentIteration + ": ");
}
else if (currentIteration < 100)
{
NotifyProgress(" " + currentIteration + ": ");
}
else
{
NotifyProgress(currentIteration + ": ");
}
currentLogLikelihood = NextIteration();
if (currentIteration > 1)
{
if (previousLogLikelihood > currentLogLikelihood)
{
throw new SystemException("Model Diverging: loglikelihood decreased");
}
if (currentLogLikelihood - previousLogLikelihood < mLLThreshold)
{
break;
}
}
previousLogLikelihood = currentLogLikelihood;
}
// kill a bunch of these big objects now that we don't need them
mObservedExpections = null;
mModelExpections = null;
mNumTimesEventsSeen = null;
mContexts = null;
}
/// <summary>
/// Use this model to evaluate a context and return an array of the
/// likelihood of each outcome given that context.
/// </summary>
/// <param name="context">
/// The integers of the predicates which have been
/// observed at the present decision point.
/// </param>
/// <param name="outcomeSums">
/// The normalized probabilities for the outcomes given the
/// context. The indexes of the double[] are the outcome
/// ids.
/// </param>
protected virtual void Evaluate(int[] context, double[] outcomeSums)
{
for (int outcomeIndex = 0; outcomeIndex < mOutcomeCount; outcomeIndex++)
{
outcomeSums[outcomeIndex] = mInitialProbability;
mFeatureCounts[outcomeIndex] = 0;
}
int[] activeOutcomes;
int outcomeId;
int predicateId;
int currentActiveOutcome;
for (int currentContext = 0; currentContext < context.Length; currentContext++)
{
predicateId = context[currentContext];
activeOutcomes = mOutcomePatterns[predicateId];
for (currentActiveOutcome = 0; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
{
outcomeId = activeOutcomes[currentActiveOutcome];
mFeatureCounts[outcomeId]++;
outcomeSums[outcomeId] += mMaximumFeatureCountInverse * mParameters[predicateId][currentActiveOutcome];
}
}
double sum = 0.0;
for (int currentOutcomeId = 0; currentOutcomeId < mOutcomeCount; currentOutcomeId++)
{
outcomeSums[currentOutcomeId] = System.Math.Exp(outcomeSums[currentOutcomeId]);
if (mUseSlackParameter)
{
outcomeSums[currentOutcomeId] += ((1.0 - ((double) mFeatureCounts[currentOutcomeId] / mMaximumFeatureCount)) * mCorrectionParameter);
}
sum += outcomeSums[currentOutcomeId];
}
for (int currentOutcomeId = 0; currentOutcomeId < mOutcomeCount; currentOutcomeId++)
{
outcomeSums[currentOutcomeId] /= sum;
}
}
/// <summary>
/// Compute one iteration of GIS and retutn log-likelihood.
/// </summary>
/// <returns>The log-likelihood.</returns>
private double NextIteration()
{
// compute contribution of p(a|b_i) for each feature and the new
// correction parameter
double logLikelihood = 0.0;
mCorrectionFeatureModifier = 0.0;
int eventCount = 0;
int numCorrect = 0;
int outcomeId;
for (mTokenID = 0; mTokenID < mTokenCount; mTokenID++)
{
Evaluate(mContexts[mTokenID], mModelDistribution);
for (int currentContext = 0; currentContext < mContexts[mTokenID].Length; currentContext++)
{
mPredicateId = mContexts[mTokenID][currentContext];
for (int currentActiveOutcome = 0; currentActiveOutcome < mOutcomePatterns[mPredicateId].Length; currentActiveOutcome++)
{
outcomeId = mOutcomePatterns[mPredicateId][currentActiveOutcome];
mModelExpections[mPredicateId][currentActiveOutcome] += (mModelDistribution[outcomeId] * mNumTimesEventsSeen[mTokenID]);
if (mUseSlackParameter)
{
mCorrectionFeatureModifier += mModelDistribution[mOutcomeId] * mNumTimesEventsSeen[mTokenID];
}
}
}
if (mUseSlackParameter)
{
mCorrectionFeatureModifier += (mMaximumFeatureCount - mContexts[mTokenID].Length) * mNumTimesEventsSeen[mTokenID];
}
logLikelihood += System.Math.Log(mModelDistribution[mOutcomes[mTokenID]]) * mNumTimesEventsSeen[mTokenID];
eventCount += mNumTimesEventsSeen[mTokenID];
//calculation solely for the information messages
int max = 0;
for (mOutcomeId = 1; mOutcomeId < mOutcomeCount; mOutcomeId++)
{
if (mModelDistribution[mOutcomeId] > mModelDistribution[max])
{
max = mOutcomeId;
}
}
if (max == mOutcomes[mTokenID])
{
numCorrect += mNumTimesEventsSeen[mTokenID];
}
}
NotifyProgress(".");
// compute the new parameter values
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
for (int currentActiveOutcome = 0; currentActiveOutcome < mOutcomePatterns[mPredicateId].Length; currentActiveOutcome++)
{
outcomeId = mOutcomePatterns[mPredicateId][currentActiveOutcome];
mParameters[mPredicateId][currentActiveOutcome] += (mObservedExpections[mPredicateId][currentActiveOutcome] - System.Math.Log(mModelExpections[mPredicateId][currentActiveOutcome]));
mModelExpections[mPredicateId][currentActiveOutcome] = 0.0;// re-initialize to 0.0's
}
}
if (mCorrectionFeatureModifier > 0.0 && mUseSlackParameter)
{
mCorrectionParameter += (mCorrectionFeatureObservedExpectation - System.Math.Log(mCorrectionFeatureModifier));
}
NotifyProgress(". logLikelihood=" + logLikelihood + "\t" + ((double) numCorrect / eventCount));
return (logLikelihood);
}
/// <summary>
/// Convert the predicate data into the outcome pattern / patterned predicate format used by the GIS models.
/// </summary>
private void ConvertPredicates()
{
PatternedPredicate[] predicates = new PatternedPredicate[mParameters.Length];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
double[] parameters = mParameters[mPredicateId];
predicates[mPredicateId] = new PatternedPredicate(mPredicateLabels[mPredicateId], parameters);
}
OutcomePatternComparer comparer = new OutcomePatternComparer();
Array.Sort(mOutcomePatterns, predicates, comparer);
List<int[]> outcomePatterns = new List<int[]>();
int currentPatternId = 0;
int predicatesInPattern = 0;
int[] currentPattern = mOutcomePatterns[0];
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
if (comparer.Compare(currentPattern, mOutcomePatterns[mPredicateId]) == 0)
{
predicates[mPredicateId].OutcomePattern = currentPatternId;
predicatesInPattern++;
}
else
{
int[] pattern = new int[currentPattern.Length + 1];
pattern[0] = predicatesInPattern;
currentPattern.CopyTo(pattern, 1);
outcomePatterns.Add(pattern);
currentPattern = mOutcomePatterns[mPredicateId];
currentPatternId++;
predicates[mPredicateId].OutcomePattern = currentPatternId;
predicatesInPattern = 1;
}
}
int[] finalPattern = new int[currentPattern.Length + 1];
finalPattern[0] = predicatesInPattern;
currentPattern.CopyTo(finalPattern, 1);
outcomePatterns.Add(finalPattern);
mOutcomePatterns = outcomePatterns.ToArray();
mPredicates = new Dictionary<string, PatternedPredicate>(predicates.Length);
for (mPredicateId = 0; mPredicateId < mPredicateCount; mPredicateId++)
{
mPredicates.Add(predicates[mPredicateId].Name, predicates[mPredicateId]);
}
}
#endregion
#region IGisModelReader implementation
/// <summary>
/// The correction constant for the model produced as a result of training.
/// </summary>
public int CorrectionConstant
{
get
{
return mMaximumFeatureCount;
}
}
/// <summary>
/// The correction parameter for the model produced as a result of training.
/// </summary>
public double CorrectionParameter
{
get
{
return mCorrectionParameter;
}
}
/// <summary>
/// Obtains the outcome labels for the model produced as a result of training.
/// </summary>
/// <returns>
/// Array of outcome labels.
/// </returns>
public string[] GetOutcomeLabels()
{
return mOutcomeLabels;
}
/// <summary>
/// Obtains the outcome patterns for the model produced as a result of training.
/// </summary>
/// <returns>
/// Array of outcome patterns.
/// </returns>
public int[][] GetOutcomePatterns()
{
return mOutcomePatterns;
}
/// <summary>
/// Obtains the predicate data for the model produced as a result of training.
/// </summary>
/// <returns>
/// Dictionary containing PatternedPredicate objects.
/// </returns>
public Dictionary<string, PatternedPredicate> GetPredicates()
{
return mPredicates;
}
/// <summary>
/// Returns trained model information for a predicate, given the predicate label.
/// </summary>
/// <param name="predicateLabel">
/// The predicate label to fetch information for.
/// </param>
/// <param name="featureCounts">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method increments the count of each outcome that is active in the specified
/// predicate.
/// </param>
/// <param name="outcomeSums">
/// Array to be passed in to the method; it should have a length equal to the number of outcomes
/// in the model. The method adds the parameter values for each of the active outcomes in the
/// predicate.
/// </param>
public void GetPredicateData(string predicateLabel, int[] featureCounts, double[] outcomeSums)
{
if (mPredicates.ContainsKey(predicateLabel))
{
PatternedPredicate predicate = (PatternedPredicate)mPredicates[predicateLabel];
if (predicate != null)
{
int[] activeOutcomes = mOutcomePatterns[predicate.OutcomePattern];
for (int currentActiveOutcome = 1; currentActiveOutcome < activeOutcomes.Length; currentActiveOutcome++)
{
int outcomeIndex = activeOutcomes[currentActiveOutcome];
featureCounts[outcomeIndex]++;
outcomeSums[outcomeIndex] += predicate.GetParameter(currentActiveOutcome - 1);
}
}
}
}
#endregion
private class OutcomePatternComparer : IComparer<int[]>
{
internal OutcomePatternComparer()
{
}
/// <summary>
/// Compare two outcome patterns and determines which comes first,
/// based on the outcome ids (lower outcome ids first)
/// </summary>
/// <param name="firstPattern">
/// First outcome pattern to compare.
/// </param>
/// <param name="secondPattern">
/// Second outcome pattern to compare.
/// </param>
/// <returns></returns>
public virtual int Compare(int[] firstPattern, int[] secondPattern)
{
int smallerLength = (firstPattern.Length > secondPattern.Length ? secondPattern.Length : firstPattern.Length);
for (int currentOutcome = 0; currentOutcome < smallerLength; currentOutcome++)
{
if (firstPattern[currentOutcome] < secondPattern[currentOutcome])
{
return - 1;
}
else if (firstPattern[currentOutcome] > secondPattern[currentOutcome])
{
return 1;
}
}
if (firstPattern.Length < secondPattern.Length)
{
return - 1;
}
else if (firstPattern.Length > secondPattern.Length)
{
return 1;
}
return 0;
}
}
}
/// <summary>
/// Event arguments class for training progress events.
/// </summary>
public class TrainingProgressEventArgs : EventArgs
{
private string mMessage;
/// <summary>
/// Constructor for the training progress event arguments.
/// </summary>
/// <param name="message">
/// Information message about the progress of training.
/// </param>
public TrainingProgressEventArgs(string message)
{
mMessage = message;
}
/// <summary>
/// Information message about the progress of training.
/// </summary>
public string Message
{
get
{
return mMessage;
}
}
}
/// <summary>
/// Event handler delegate for the training progress event.
/// </summary>
public delegate void TrainingProgressEventHandler(object sender, TrainingProgressEventArgs e);
}