-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathmaxent.c
1781 lines (1489 loc) · 52 KB
/
maxent.c
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
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* Weight-setting and scoring implementation for Maximum Entropy classification */
/* Copyright (C) 1997, 1998, 1999 Andrew McCallum
Written by: Kamal Nigam (knigam@cs.cmu.edu>
This file is part of the Bag-Of-Words Library, `libbow'.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public License
as published by the Free Software Foundation, version 2.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA */
#include <bow/libbow.h>
#include <math.h>
#include <argp/argp.h>
typedef struct _maxent_coefficient {
int power;
double coeff;
} maxent_coefficient;
typedef struct _maxent_polynomial {
int length;
int size;
maxent_coefficient entry[0];
} maxent_polynomial;
/* whether to add a gaussian prior for each lambda value */
static int maxent_gaussian_prior = 0;
/* the variance of each gaussian prior */
static float maxent_prior_variance = 0.01;
/* whether to enforce zero constraints when using a gaussian prior */
static int maxent_gaussian_prior_zero_constraints = 1;
/* if == 0, then constant variance. if ==1 then K*log(1+N(w,c)). If ==2 then K*N(w,c) */
static int maxent_prior_vary_by_count = 0;
static int maxent_scoring_hack = 0;
/* option to add one to each empirical count when calculating constraint */
static int maxent_smooth_counts = 0;
static int maxent_logprob_constraints = 0;
/* internal variable for scoring */
static int bow_maxent_model_building = 0;
/* the function to use to identify documents for checking accuracy */
static int (*maxent_accuracy_docs)(bow_cdoc *) = NULL;
static int (*maxent_logprob_docs)(bow_cdoc *) = NULL;
static int (*maxent_halt_accuracy_docs)(bow_cdoc *) = NULL;
/* which documents to use for maxent iterations */
static int (*maxent_iteration_docs)(bow_cdoc *) = bow_cdoc_is_train;
/* the number of iterations of iterative scaling to perform */
static int maxent_num_iterations = 40;
/* the number of top words by mutual info per class to use as features. 0 means all */
static int maxent_words_per_class = 0;
/* the minimum count for a word/class feature */
static int maxent_prune_features_by_count = 0;
/* whether or not to use unlabeled docs in setting the constraints */
static int maxent_constraint_use_unlabeled = 0;
#if 0
static int maxent_print_constraints = 1;
static int maxent_print_lambdas = 1;
#endif
enum {
MAXENT_PRINT_ACCURACY = 6000,
MAXENT_ITERATIONS,
MAXENT_WORDS_PER_CLASS,
MAXENT_HALT_BY_LOGPROB,
MAXENT_HALT_BY_ACCURACY,
MAXENT_LOGPROB_CONSTRAINTS,
MAXENT_SMOOTH_COUNTS,
MAXENT_SCORING_HACK,
MAXENT_GAUSSIAN_PRIOR,
MAXENT_PRIOR_VARIANCE,
MAXENT_PRUNE_FEATURES_BY_COUNT,
MAXENT_GAUSSIAN_PRIOR_ZERO_CONSTRAINTS,
MAXENT_PRIOR_VARY_BY_COUNT,
MAXENT_PRIOR_VARY_BY_COUNT_LINEAR,
MAXENT_ITERATION_DOCS,
MAXENT_CONSTRAINT_DOCS,
};
static struct argp_option maxent_options[] =
{
{0,0,0,0,
"Maximum Entropy options, --method=maxent:", 55},
{"maxent-print-accuracy", MAXENT_PRINT_ACCURACY, "TYPE", 0,
"When running maximum entropy, print the accuracy of documents at each round. "
"TYPE is type of document to measure perplexity on. See "
"`--em-halt-using-perplexity` for choices for TYPE"},
{"maxent-halt-by-logprob", MAXENT_HALT_BY_LOGPROB, "TYPE", 0,
"When running maxent, halt iterations using the logprob of documents. TYPE is type of documents"
"to test. See `--em-halt-using-perplexity` for choices for TYPE"},
{"maxent-halt-by-accuracy", MAXENT_HALT_BY_ACCURACY, "TYPE", 0,
"When running maxent, halt iterations using the accuracy of documents. TYPE is type of documents"
"to test. See `--em-halt-using-perplexity` for choices for TYPE"},
{"maxent-iterations", MAXENT_ITERATIONS, "NUM", 0,
"The number of iterative scaling iterations to perform. The default is 40."},
{"maxent-keep-features-by-mi", MAXENT_WORDS_PER_CLASS, "NUM", 0,
"The number of top words by mutual information per class to use as features. Zero"
"implies no pruning and is the default."},
{"maxent-logprob-constraints", MAXENT_LOGPROB_CONSTRAINTS, 0, 0,
"Set constraints to be the log prob of the word."},
{"maxent-smooth-counts", MAXENT_SMOOTH_COUNTS, 0, 0,
"Add 1 to the count of each word/class pair when calculating the constraint values."},
{"maxent-scoring-hack", MAXENT_SCORING_HACK, 0, 0,
"Use smoothed naive Bayes probability for zero occuring word/class pairs during scoring"},
{"maxent-gaussian-prior", MAXENT_GAUSSIAN_PRIOR, 0, 0,
"Add a Gaussian prior to each word/class feature constraint."},
{"maxent-prior-variance", MAXENT_PRIOR_VARIANCE, "NUM", 0,
"The variance to use for the Gaussian prior. The default is 0.01."},
{"maxent-vary-prior-by-count", MAXENT_PRIOR_VARY_BY_COUNT, 0, 0,
"Multiply log (1 + N(w,c)) times variance when using a gaussian prior."},
{"maxent-gaussian-prior-no-zero-constraints", MAXENT_GAUSSIAN_PRIOR_ZERO_CONSTRAINTS, 0, 0,
"When using a gaussian prior, do not enforce constraints that have no"
"training data."},
{"maxent-prune-features-by-count", MAXENT_PRUNE_FEATURES_BY_COUNT, "NUM", 0,
"Prune the word/class feature set, keeping only those features that have"
"at least NUM occurrences in the training set."},
{"maxent-vary-prior-by-count-linearly", MAXENT_PRIOR_VARY_BY_COUNT_LINEAR, 0, 0,
"Mulitple N(w,c) times variance when using a Gaussian prior."},
{"maxent-iteration-docs", MAXENT_ITERATION_DOCS, "TYPE", 0,
"The types of documents to use for maxent iterations. The default is train. "
"TYPE is type of documents to test. See `--em-halt-using-perplexity` "
"for choices for TYPE"},
{"maxent-constraint-docs", MAXENT_CONSTRAINT_DOCS, "TYPE", 0,
"The documents to use for setting the constraints. The default is train. "
"The other choice is trainandunlabeled."},
{0, 0}
};
error_t
maxent_parse_opt (int key, char *arg, struct argp_state *state)
{
switch (key)
{
case MAXENT_ITERATION_DOCS:
if (!strcmp (arg, "train"))
maxent_iteration_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "unlabeled"))
maxent_iteration_docs = bow_cdoc_is_unlabeled;
else if (!strcmp (arg, "trainandunlabeled"))
maxent_iteration_docs = bow_cdoc_is_train_or_unlabeled;
else
bow_error("Unknown document type for --maxent-iteration-docs");
break;
case MAXENT_CONSTRAINT_DOCS:
if (!strcmp (arg, "train"))
maxent_constraint_use_unlabeled = 0;
else if (!strcmp (arg, "trainandunlabeled"))
maxent_constraint_use_unlabeled = 1;
else
bow_error("Unknown document type for --maxent-constraint-docs");
break;
case MAXENT_PRINT_ACCURACY:
if (!strcmp (arg, "validation"))
maxent_accuracy_docs = bow_cdoc_is_validation;
else if (!strcmp (arg, "train"))
maxent_accuracy_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "unlabeled"))
maxent_accuracy_docs = bow_cdoc_is_unlabeled;
else if (!strcmp (arg, "test"))
maxent_accuracy_docs = bow_cdoc_is_test;
else
bow_error("Unknown document type for --maxent-print-accuracy");
break;
case MAXENT_HALT_BY_LOGPROB:
if (!strcmp (arg, "validation"))
maxent_logprob_docs = bow_cdoc_is_validation;
else if (!strcmp (arg, "train"))
maxent_logprob_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "unlabeled"))
maxent_logprob_docs = bow_cdoc_is_unlabeled;
else if (!strcmp (arg, "test"))
maxent_logprob_docs = bow_cdoc_is_test;
else
bow_error("Unknown document type for --maxent-halt-by-logprob");
break;
case MAXENT_HALT_BY_ACCURACY:
if (!strcmp (arg, "validation"))
maxent_halt_accuracy_docs = bow_cdoc_is_validation;
else if (!strcmp (arg, "train"))
maxent_halt_accuracy_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "unlabeled"))
maxent_halt_accuracy_docs = bow_cdoc_is_unlabeled;
else if (!strcmp (arg, "test"))
maxent_halt_accuracy_docs = bow_cdoc_is_test;
else
bow_error("Unknown document type for --maxent-halt-by-accuracy");
break;
case MAXENT_ITERATIONS:
maxent_num_iterations = atoi (arg);
break;
case MAXENT_WORDS_PER_CLASS:
maxent_words_per_class = atoi (arg);
break;
case MAXENT_LOGPROB_CONSTRAINTS:
maxent_logprob_constraints = 1;
break;
case MAXENT_SMOOTH_COUNTS:
maxent_smooth_counts = 1;
break;
case MAXENT_SCORING_HACK:
maxent_scoring_hack = 1;
break;
case MAXENT_GAUSSIAN_PRIOR:
maxent_gaussian_prior = 1;
break;
case MAXENT_PRIOR_VARIANCE:
maxent_prior_variance = atof(arg);
assert (maxent_prior_variance > 0);
break;
case MAXENT_PRUNE_FEATURES_BY_COUNT:
maxent_prune_features_by_count = atoi (arg);
break;
case MAXENT_GAUSSIAN_PRIOR_ZERO_CONSTRAINTS:
maxent_gaussian_prior_zero_constraints = 0;
break;
case MAXENT_PRIOR_VARY_BY_COUNT:
maxent_prior_vary_by_count = 1;
break;
case MAXENT_PRIOR_VARY_BY_COUNT_LINEAR:
maxent_prior_vary_by_count = 2;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static const struct argp maxent_argp =
{
maxent_options,
maxent_parse_opt
};
static struct argp_child maxent_argp_child =
{
&maxent_argp, /* This child's argp structure */
0, /* flags for child */
0, /* optional header in help message */
0 /* arbitrary group number for ordering */
};
/* alter the class barrel and excise dv entries that have count less
than min_count */
void
maxent_prune_features_by_occurrence_count (bow_barrel *barrel, int min_count)
{
int wi;
int max_wi = MIN (barrel->wi2dvf->size, bow_num_words());
/* delete dv entries and dvs (if necessary) for word/class pairs
with less than min_count occurrences */
for (wi = 0; wi < max_wi; wi++)
{
bow_dv *dv = bow_wi2dvf_dv(barrel->wi2dvf, wi);
int new_dvi = 0;
int old_dvi = 0;
if (!dv)
continue;
for (old_dvi = 0; old_dvi < dv->length; old_dvi++)
if (dv->entry[old_dvi].count >= min_count)
{
dv->entry[new_dvi].count = dv->entry[old_dvi].count;
dv->entry[new_dvi].weight = dv->entry[old_dvi].weight;
new_dvi++;
}
/* adjust the length of the dv, or remove it if empty */
if (new_dvi == 0)
bow_wi2dvf_hide_wi (barrel->wi2dvf, wi);
else
dv->length = new_dvi;
}
}
/* alter the class barrel and excise dv's and dv entries that are not
in the top num_per_class words per class */
void
maxent_prune_vocab_by_mutual_information (bow_barrel *barrel, int num_per_class)
{
int ci;
int wi;
long total_words = 0;
int max_wi = MIN (barrel->wi2dvf->size, bow_num_words());
int max_ci = bow_barrel_num_classes (barrel);
struct wiig { int wi; float ig; } **mis;
int wpi;
int wiig_compare (const void *wiig1, const void *wiig2)
{
if (((struct wiig*)wiig1)->ig > ((struct wiig*)wiig2)->ig)
return -1;
else if (((struct wiig*)wiig1)->ig == ((struct wiig*)wiig2)->ig)
return 0;
else
return 1;
}
/* do this on a class barrel */
/* malloc and initialize the double array of mutual infos */
mis = bow_malloc (sizeof(struct wiig *) * max_ci);
for (ci = 0; ci < max_ci ; ci ++)
mis[ci] = bow_malloc (sizeof (struct wiig) * max_wi);
for (ci = 0; ci < max_ci ; ci++)
for (wi = 0 ; wi < max_wi; wi++)
{
mis[ci][wi].wi = wi;
mis[ci][wi].ig = 0;
}
/* first calculate total_words */
for (ci = 0 ; ci < max_ci ; ci++)
{
bow_cdoc *cdoc = bow_array_entry_at_index (barrel->cdocs, ci);
total_words += cdoc->word_count;
}
/* calculate the mutual informations */
for (wi = 0; wi < max_wi; wi++)
{
bow_dv *dv;
int dvi;
int local_total = 0;
dv = bow_wi2dvf_dv (barrel->wi2dvf, wi);
if (!dv)
continue;
dvi = 0;
for (dvi = 0; dvi < dv->length; dvi++)
local_total += dv->entry[dvi].count;
for (dvi = 0; dvi < dv->length; dvi++)
{
bow_cdoc *cdoc = bow_array_entry_at_index (barrel->cdocs,
dv->entry[dvi].di);
mis[dv->entry[dvi].di][wi].ig = fabs((double) dv->entry[dvi].count *
log ((double) dv->entry[dvi].count * (double) total_words /
(double) cdoc->word_count / (double) local_total));
}
}
/* ok, now sort each class to bring the best infogains to the top*/
for (ci = 0; ci < max_ci; ci++)
qsort(mis[ci], max_wi, sizeof (struct wiig), wiig_compare);
/* Check that we're not saving bogus words */
for (ci = 0; ci < max_ci; ci++)
assert (mis[ci][num_per_class - 1].ig > 0);
for (ci = 0; ci < max_ci; ci++)
{
bow_verbosify (bow_progress, "\n%s\n", bow_barrel_classname_at_index (barrel, ci));
for (wi = 0; wi < 10; wi++)
bow_verbosify (bow_progress, "%20.10f %s\n", mis[ci][wi].ig,
bow_int2word (mis[ci][wi].wi));
}
/* now edit the class barrel, knocking out word/class pairs where appropriate */
/* first set all word counts to be 1 */
for (wi = 0; wi < max_wi; wi++)
{
bow_dv *dv = bow_wi2dvf_dv (barrel->wi2dvf, wi);
int dvi;
if (!dv)
continue;
for (dvi = 0; dvi < dv->length; dvi++)
dv->entry[dvi].count = 1;
}
/* now set counts to be 2 where we're keeping the word/class pair */
for (ci = 0; ci < max_ci; ci++)
for (wpi = 0; wpi < num_per_class; wpi++)
{
bow_dv *dv = bow_wi2dvf_dv(barrel->wi2dvf, mis[ci][wpi].wi);
int dvi;
assert (dv);
/* find the class pair for this word */
for (dvi = 0; dvi < dv->length && ci > dv->entry[dvi].di ; dvi++);
assert (dvi < dv->length && ci == dv->entry[dvi].di);
dv->entry[dvi].count = 2;
}
/* now delete dv entries and dvs (if necessary) for word/class pairs with 1 */
for (wi = 0; wi < max_wi; wi++)
{
bow_dv *dv = bow_wi2dvf_dv(barrel->wi2dvf, wi);
int new_dvi = 0;
int old_dvi = 0;
if (!dv)
continue;
for (old_dvi = 0; old_dvi < dv->length; old_dvi++)
if (dv->entry[old_dvi].count == 2)
{
dv->entry[new_dvi].count = 2;
dv->entry[new_dvi].weight = dv->entry[old_dvi].weight;
new_dvi++;
}
/* adjust the length of the dv, or remove it if empty */
if (new_dvi == 0)
bow_wi2dvf_hide_wi (barrel->wi2dvf, wi);
else
dv->length = new_dvi;
}
for (ci = 0; ci < max_ci; ci++)
bow_free (mis[ci]);
bow_free (mis);
return;
}
/* Newton's method. max_fi is one more than the index of the largest
coefficient given */
double
maxent_newton (maxent_polynomial *poly)
{
double root;
double fun_val = 100;
double deriv_val;
double low = 0;
double high = 1000000;
double dxold = 1000000;
double dx = 1000000;
static double epsilon=1.0E-8;
int fi;
int rounds = 0;
/* initial guess of root */
root = 1.0001;
while (fabs(fun_val) > epsilon)
{
/* calculate function at new root */
fun_val = 0.0;
for (fi = 0; fi < poly->length; fi++)
fun_val += poly->entry[fi].coeff * pow (root, poly->entry[fi].power);
if (maxent_gaussian_prior)
fun_val += poly->entry[poly->length].coeff * log (root);
/* calculate derivative at root */
deriv_val = 0.0;
for (fi = 1; fi < poly->length; fi++)
deriv_val += poly->entry[fi].power * poly->entry[fi].coeff *
pow (root, poly->entry[fi].power - 1);
if (maxent_gaussian_prior)
deriv_val += poly->entry[poly->length].coeff / root;
assert (fun_val == fun_val &&
deriv_val == deriv_val);
if (fun_val < 0)
low = root;
else
high = root;
dxold = dx;
/* if fun_val is infinity, bisect the region.
otherwise, use newton. */
if (fun_val == HUGE_VAL ||
2 * fabs(fun_val) > fabs(dxold * deriv_val))
{
dx = (high - low) / 2.0;
root = low + dx;
}
else
{
dx = fun_val / deriv_val;
root -= dx;
/* if newton thinks to go outside the region, bisect the
region */
if (root < low || root > high)
{
dx = (high - low) / 2.0;
root = low + dx;
}
}
rounds++;
if (rounds > 100)
bow_error ("Newton's method did not converge.\n");
}
return (root);
}
/* Calculate the accuracy or the model prob of the barrel on a set of
docs. accuracy_or_logprob 1 for accuracy, else for logprob */
float
maxent_calculate_accuracy (bow_barrel *doc_barrel, bow_barrel *class_barrel,
int (*test_docs)(bow_cdoc *), int accuracy_or_logprob)
{
bow_dv_heap *test_heap; /* we'll extract test WV's from here */
bow_wv *query_wv;
int di; /* a document index */
bow_score *hits;
int num_hits_to_retrieve = bow_barrel_num_classes (class_barrel);
int actual_num_hits;
bow_cdoc *doc_cdoc;
int num_tested = 0;
int num_correct = 0;
int old_model_building = 0;
double log_prob = 0;
if (accuracy_or_logprob == 1)
{
old_model_building = bow_maxent_model_building;
bow_maxent_model_building = 0;
}
/* Create the heap from which we'll get WV's. Initialize QUERY_WV so
BOW_TEST_NEXT_WV() knows not to try to free. */
hits = alloca (sizeof (bow_score) * num_hits_to_retrieve);
test_heap = bow_test_new_heap (doc_barrel);
query_wv = NULL;
/* Loop once for each test document. */
while ((di = bow_heap_next_wv (test_heap, doc_barrel, &query_wv,
test_docs))
!= -1)
{
doc_cdoc = bow_array_entry_at_index (doc_barrel->cdocs,
di);
bow_wv_set_weights (query_wv, class_barrel);
bow_wv_normalize_weights (query_wv, class_barrel);
actual_num_hits =
bow_barrel_score (class_barrel,
query_wv, hits,
num_hits_to_retrieve, -1);
assert (actual_num_hits == num_hits_to_retrieve);
if (doc_cdoc->class == hits[0].di)
num_correct++;
log_prob += log(hits[doc_cdoc->class].weight);
num_tested++;
}
if (accuracy_or_logprob == 1)
{
bow_maxent_model_building = old_model_building;
return (((float) num_correct) / ((float) num_tested));
}
else
return (log_prob);
}
bow_barrel *
bow_maxent_new_vpc_with_weights_doc_then_word (bow_barrel *doc_barrel)
{
bow_barrel *vpc_barrel; /* the vector-per-class barrel */
int wi; /* word index */
int wvi;
int max_wi; /* max word index */
int dvi; /* document vector index */
int ci; /* class index */
bow_dv *dv; /* document vector */
int di; /* document index */
bow_dv_heap *test_heap=NULL; /* we'll extract test WV's from here */
bow_wv *query_wv;
bow_score *hits;
int actual_num_hits;
bow_cdoc *doc_cdoc;
bow_wi2dvf *constraint_wi2dvf;
int max_ci;
int rounds = 0;
double total_count_per_ci[200];
int total_num_docs = 0;
float old_log_prob = -FLT_MAX;
float new_log_prob = -FLT_MAX / 2;
float old_accuracy = -1;
float new_accuracy = 0;
maxent_polynomial *newton_poly;
int num_unlabeled = 0;
int *unlabeled_dis = NULL;
bow_maxent_model_building = 1;
/* some sanity checks first */
assert (200 > bow_barrel_num_classes(doc_barrel));
assert (doc_barrel->classnames);
assert (bow_event_model == bow_event_document_then_word);
assert (!maxent_scoring_hack);
assert (!maxent_logprob_constraints);
assert (!maxent_words_per_class);
assert (!maxent_prune_features_by_count);
max_wi = MIN (doc_barrel->wi2dvf->size, bow_num_words ());
max_ci = bow_barrel_num_classes (doc_barrel);
newton_poly = bow_malloc (sizeof (maxent_polynomial) +
sizeof (maxent_coefficient) * 3);
newton_poly->size = 3;
newton_poly->length = 2;
newton_poly->entry[0].power = 0;
newton_poly->entry[1].power = bow_event_document_then_word_document_length;
newton_poly->entry[2].power = -1;
/* if we're using unlabeled data to set the constraints, then we
need to temporarily convert these into training documents. */
if (maxent_constraint_use_unlabeled)
{
unlabeled_dis = bow_malloc (sizeof (int) * doc_barrel->cdocs->length);
for (di = 0; di < doc_barrel->cdocs->length; di++)
{
bow_cdoc *cdoc = bow_array_entry_at_index(doc_barrel->cdocs, di);
if (cdoc->type == bow_doc_unlabeled)
{
unlabeled_dis[num_unlabeled] = di;
num_unlabeled++;
cdoc->type = bow_doc_train;
}
}
}
/* get a barrel where the weights and counts are set to word counts
based on the labeled data only */
vpc_barrel = bow_barrel_new_vpc (doc_barrel);
/* switch back the unlabeled documents to have their original tag */
if (maxent_constraint_use_unlabeled)
{
int ui;
for (ui = 0; ui < num_unlabeled; ui++)
{
bow_cdoc *cdoc = bow_array_entry_at_index(doc_barrel->cdocs,
unlabeled_dis[ui]);
cdoc->type = bow_doc_unlabeled;
}
bow_free (unlabeled_dis);
}
/* re-initialize the weights to 0.
Set the constraint wi2dvf to the counts.
*/
for (ci = 0; ci < max_ci; ci++)
{
bow_cdoc *cdoc = bow_array_entry_at_index (vpc_barrel->cdocs, ci);
total_num_docs += cdoc->word_count;
}
/* Count how many training documents there are. Exclude documents
that have no features, as we need to ignore them for
doc_then_word */
query_wv = NULL;
test_heap = bow_test_new_heap (doc_barrel);
/* Iterate over each document. */
while (-1 != (di = bow_heap_next_wv (test_heap, doc_barrel, &query_wv,
bow_cdoc_is_train)))
{
if (query_wv->num_entries == 0)
total_num_docs--;
}
constraint_wi2dvf = bow_wi2dvf_new (doc_barrel->wi2dvf->size);
for (wi = 0; wi < max_wi; wi++)
{
dv = bow_wi2dvf_dv (vpc_barrel->wi2dvf, wi);
if (!dv)
continue;
if (maxent_smooth_counts)
{
dvi = 0;
for (ci = 0; ci < max_ci; ci++)
{
while (dv->entry[dvi].di < ci &&
dvi < dv->length)
dvi++;
/* set contraint to smoothed empirical average */
if (dvi < dv->length && dv->entry[dvi].di == ci)
bow_wi2dvf_set_wi_di_count_weight(&constraint_wi2dvf, wi, ci,
dv->entry[dvi].count + 1,
(dv->entry[dvi].weight + 1.0) /
(double) total_num_docs);
else
bow_wi2dvf_set_wi_di_count_weight(&constraint_wi2dvf, wi, ci,
1,
1.0 / (double) total_num_docs);
/* initialize the lambda to 0 */
bow_wi2dvf_set_wi_di_count_weight (&(vpc_barrel->wi2dvf),
wi, ci,
1,
0);
}
}
else if (maxent_gaussian_prior)
{
dvi = 0;
for (ci = 0; ci < max_ci; ci++)
{
while (dv->entry[dvi].di < ci &&
dvi < dv->length)
dvi++;
/* set contraint to smoothed empirical average */
if (dvi < dv->length && dv->entry[dvi].di == ci)
{
bow_wi2dvf_set_wi_di_count_weight(&constraint_wi2dvf, wi, ci,
dv->entry[dvi].count,
dv->entry[dvi].weight /
(double) total_num_docs);
/* initialize the lambda to 0 */
bow_wi2dvf_set_wi_di_count_weight (&(vpc_barrel->wi2dvf),
wi, ci,
1,
0);
}
else if (maxent_gaussian_prior_zero_constraints)
{
bow_wi2dvf_set_wi_di_count_weight(&constraint_wi2dvf, wi, ci,
1,
0);
/* initialize the lambda to 0 */
bow_wi2dvf_set_wi_di_count_weight (&(vpc_barrel->wi2dvf),
wi, ci,
1,
0);
}
}
}
else
{
for (dvi = 0; dvi < dv->length; dvi++)
{
bow_cdoc *cdoc;
ci = dv->entry[dvi].di;
cdoc = bow_array_entry_at_index (vpc_barrel->cdocs, ci);
assert (dv->entry[dvi].weight > 0);
/* */
bow_wi2dvf_set_wi_di_count_weight(&constraint_wi2dvf, wi, ci,
dv->entry[dvi].count,
dv->entry[dvi].weight /
(double) total_num_docs);
bow_wi2dvf_set_wi_di_count_weight (&(vpc_barrel->wi2dvf),
wi, ci,
dv->entry[dvi].count,
0);
}
}
}
#if 0
if (maxent_print_constraints)
{
bow_verbosify (bow_progress, "foo");
for (ci = 0; ci < max_ci; ci++)
bow_verbosify (bow_progress, " %s", bow_barrel_classname_at_index (doc_barrel, ci));
bow_verbosify (bow_progress, "\n");
for (wi = 0; wi < max_wi; wi++)
{
bow_verbosify (bow_progress, "%s", bow_int2word (wi));
dv = bow_wi2dvf_dv (constraint_wi2dvf, wi);
dvi = 0;
for (ci = 0; ci < max_ci; ci++)
{
while ((ci > dv->entry[dvi].di) && (dvi < dv->length))
dvi++;
if ((ci == dv->entry[dvi].di) && (dvi < dv->length))
bow_verbosify (bow_progress, " %f", dv->entry[dvi].weight);
else
bow_verbosify (bow_progress, " 0");
}
bow_verbosify (bow_progress, "\n");
}
}
#endif
/* Lets start some maximum entropy iteration */
while (maxent_logprob_docs ?
new_log_prob > old_log_prob :
(maxent_halt_accuracy_docs ?
new_accuracy > old_accuracy :
rounds < maxent_num_iterations))
{
bow_wi2dvf *exp_wi2dvf = bow_wi2dvf_new (doc_barrel->wi2dvf->size);
int num_tested = 0;
for (ci = 0; ci < max_ci; ci++)
total_count_per_ci[ci] = 0.0;
rounds++;
/* classify all the documents, and put their contribution into the
different lambdas */
query_wv = NULL;
hits = alloca (sizeof (bow_score) * max_ci);
num_tested = 0;
test_heap = bow_test_new_heap (doc_barrel);
/* Calculate accuracy of the validation set for halting check */
if (maxent_accuracy_docs)
bow_verbosify (bow_progress, "%4d Correct: %f\n", rounds,
maxent_calculate_accuracy(doc_barrel, vpc_barrel, maxent_accuracy_docs, 1));
/* Loop once for each training document, scoring it and recording its
contribution to all the E[f_{w,c}] */
while ((di = bow_heap_next_wv (test_heap, doc_barrel, &query_wv,
maxent_iteration_docs))
!= -1)
{
doc_cdoc = bow_array_entry_at_index (doc_barrel->cdocs,
di);
bow_wv_set_weights (query_wv, vpc_barrel);
bow_wv_normalize_weights (query_wv, vpc_barrel);
// skip documents with no words
if (query_wv->num_entries == 0)
continue;
num_tested++;
actual_num_hits =
bow_barrel_score (vpc_barrel,
query_wv, hits,
max_ci, -1);
assert (actual_num_hits == max_ci);
for (ci = 0; ci < max_ci; ci++)
total_count_per_ci[ci] += hits[ci].weight;
/* now loop over the words in the document and all the classes,
adding the contribution to E[f_{w,c}] */
for (wvi=0; wvi < query_wv->num_entries; wvi++)
{
wi = query_wv->entry[wvi].wi;
for (ci=0; ci < bow_barrel_num_classes (vpc_barrel); ci++)
bow_wi2dvf_add_wi_di_count_weight
(&exp_wi2dvf, wi, ci, 1,
hits[ci].weight * query_wv->entry[wvi].weight);
}
}
/* now update the lambdas. Ignore zero constraints? */
for (wi = 0; wi < max_wi; wi++)
{
bow_dv *vpc_dv;
bow_dv *constraint_dv;
bow_dv *exp_dv;
int exp_dvi = 0;
vpc_dv = bow_wi2dvf_dv (vpc_barrel->wi2dvf, wi);
constraint_dv = bow_wi2dvf_dv (constraint_wi2dvf, wi);
exp_dv = bow_wi2dvf_dv (exp_wi2dvf, wi);
/* the exp_dv can be null if we're using only some of the
documents for the iteration step. If there are no
iteration docs that have this word, then we don't need to
worry about its weight... leave it at zero */
if (!constraint_dv || !exp_dv)
continue;
/* the dvi goes over the constraint and the vpc; the
constraint and vpc wi2dvf should have exactly
corresponding entries. The exp wi2dvf can have
a superset of the entries; */
for (dvi = 0; dvi < vpc_dv->length; dvi++)
{
ci = vpc_dv->entry[dvi].di;
/* get the corresponding exp_dvi */
while (exp_dvi < exp_dv->length &&
ci > exp_dv->entry[exp_dvi].di)
exp_dvi++;
assert (exp_dvi < exp_dv->length);
assert (ci == constraint_dv->entry[dvi].di &&
ci == exp_dv->entry[exp_dvi].di);
/* need to normalize this delta with M? */
#if 1
if (exp_dv->entry[exp_dvi].weight == 0)
assert (constraint_dv->entry[dvi].weight == 0);
else
#endif
{
double delta = 0;
if (maxent_gaussian_prior)
{
double variance = maxent_prior_variance;
if (maxent_prior_vary_by_count == 1)
variance = maxent_prior_variance *
log (1 + constraint_dv->entry[dvi].count);
else if (maxent_prior_vary_by_count == 2)
variance = maxent_prior_variance * constraint_dv->entry[dvi].count;
newton_poly->entry[0].coeff = -constraint_dv->entry[dvi].weight +
vpc_dv->entry[dvi].weight / variance;
newton_poly->entry[1].coeff = exp_dv->entry[exp_dvi].weight /
(double) num_tested;
newton_poly->entry[2].coeff = 1.0 / variance;
delta = maxent_newton (newton_poly);
delta = log (delta);
}
else
{
if (exp_dv->entry[exp_dvi].weight != 0)
delta = log (((double) num_tested) * constraint_dv->entry[dvi].weight /
(exp_dv->entry[exp_dvi].weight)) /
(double) bow_event_document_then_word_document_length;
else
delta = 0;
/* check that delta is not NaN */
assert (delta == delta);
assert (constraint_dv->entry[dvi].weight);
}
bow_wi2dvf_set_wi_di_count_weight
(&(vpc_barrel->wi2dvf), wi, ci,
vpc_dv->entry[dvi].count,
(vpc_dv->entry[dvi].weight + delta));
}
}
}