-
Notifications
You must be signed in to change notification settings - Fork 5
/
em.c
executable file
·2539 lines (2235 loc) · 75 KB
/
em.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 EM classification */
/* Copyright (C) 1997, 1998, 1999 Andrew McCallum
Written by: Kamal Nigam <[email protected]>
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>
#include <stdlib.h>
#include <bow/em.h>
#include <bow/naivebayes.h>
/* EM-specific types */
/* a specification for how to convert naive bayes scores into probabilities */
typedef enum
{
simple, /* 1 or 0 based on winning class */
nb_score /* score directly from naivebayes */
} bow_em_stat_method;
/* a specification for how to use the unlabeled data when setting the EM
starting point */
typedef enum
{
em_start_zero, /* unlabeled docs have no effect on starting point */
em_start_even, /* unlabeled docs distributed evenly */
em_start_prior, /* unlabeled docs distributed according to labeled prior */
em_start_random /* unlabeled docs distributed randomly */
} bow_em_unlabeled_start_method;
/* a specification for how to use the unlabeled data when setting the EM
starting point for multi-hump negative class */
typedef enum
{
bow_em_init_spiked, /* distribute each doc to one class */
bow_em_init_spread /* distribute each doc across classes */
} bow_em_multi_hump_init_method;
/* some forward definitions */
void bow_em_print_word_distribution (bow_barrel *vpc_barrel,
int em_runs, int num_classes);
double em_calculate_perplexity (bow_barrel *doc_barrel,
bow_barrel *class_barrel);
float em_calculate_accuracy (bow_barrel *doc_barrel, bow_barrel *class_barrel);
void bow_em_set_weights (bow_barrel *barrel);
/* Global Variables */
/* hack for binary scoring method */
static int bow_em_making_barrel = 0;
/* hack for scoring for perplexity calculation */
int bow_em_calculating_perplexity = 0;
/* ci of binary positive class */
static int binary_pos_ci = -1;
/* Command-line options specific to EM. See em_optinos for documentation*/
static char * em_binary_pos_classname = NULL;
static char * em_binary_neg_classname = NULL;
static int em_compare_to_nb = 0;
static bow_em_stat_method em_stat_method = nb_score;
int bow_em_num_em_runs = 7;
static int bow_em_print_probs = 0;
static int bow_em_print_word_vector = 0;
static int bow_em_binary_case = 0;
static float unlabeled_normalizer = 1.0;
static int bow_em_multi_hump_neg = 0;
bow_em_perturb_method bow_em_perturb_starting_point = 0;
int em_cross_entropy = 0;
static int em_anneal = 0;
static float em_temperature = 200;
static float em_temp_reduction = 0.9;
static bow_em_unlabeled_start_method em_unlabeled_start = em_start_zero;
static bow_em_multi_hump_init_method em_multi_hump_init =
bow_em_init_spread;
static int em_halt_using_perplexity = 0;
static int (* em_perplexity_docs)(bow_cdoc *) = NULL;
static int em_perplexity_loo = 0;
static int bow_em_anneal_normalizer = 0;
static int em_halt_using_accuracy = 0;
static int (* em_accuracy_docs)(bow_cdoc *) = NULL;
static int em_accuracy_loo = 0;
static int em_labeled_for_start_only = 0;
static int em_set_vocab_from_unlabeled = 0;
/* The integer or single char used to represent this command-line option.
Make sure it is unique across all libbow and rainbow. */
enum {
EM_COMPARE_TO_NB = 2222,
EM_STAT_METHOD,
EM_NUM_RUNS,
EM_PRINT_PROBS,
EM_BINARY_POS_CLASS,
EM_BINARY_NEG_CLASS,
EM_PRINT_TOP_WORDS,
EM_BINARY,
EM_UNLABELED_NORMALIZER,
EM_MULTI_HUMP,
EM_PERTURB_STARTING_POINT,
EM_NO_PERTURB,
EM_CROSSENTROPY,
EM_ANNEAL,
EM_TEMPERATURE,
EM_TEMP_REDUCE,
EM_UNLABELED_START,
EM_MULTI_HUMP_INIT,
EM_HALT_USING_PERPLEXITY,
EM_ANNEAL_NORMALIZER,
EM_PRINT_PERPLEXITY,
EM_HALT_USING_ACCURACY,
EM_PRINT_ACCURACY,
EM_LABELED_FOR_START_ONLY,
EM_SET_VOCAB_FROM_UNLABELED
};
static struct argp_option em_options[] =
{
{0,0,0,0,
"EM options:", 60},
{"em-compare-to-nb", EM_COMPARE_TO_NB, 0, 0,
"When building an EM class barrel, show doc stats for the naivebayes"
"barrel equivalent. Only use in conjunction with --test."},
{"em-stat-method", EM_STAT_METHOD, "STAT", 0,
"The method to convert scores to probabilities."
"The default is 'nb_score'."},
{"em-num-iterations", EM_NUM_RUNS, "NUM", 0,
"Number of EM iterations to run when building model."},
{"em-save-probs", EM_PRINT_PROBS, 0, 0,
"On each EM iteration, save all P(C|w) to a file."},
{"em-binary-pos-classname", EM_BINARY_POS_CLASS, "CLASS", 0,
"Specify the name of the positive class if building a binary classifier."},
{"em-binary-neg-classname", EM_BINARY_NEG_CLASS, "CLASS", 0,
"Specify the name of the negative class if building a binary classifier."},
{"em-print-top-words", EM_PRINT_TOP_WORDS, 0, 0,
"Print the top 10 words per class for each EM iteration."},
{"em-binary", EM_BINARY, 0, 0,
"Do special tricks for the binary case."},
{"em-unlabeled-normalizer", EM_UNLABELED_NORMALIZER, "NUM", 0,
"Number of unlabeled docs it takes to equal a labeled doc."
"Defaults to one."},
{"em-multi-hump-neg", EM_MULTI_HUMP, "NUM", 0,
"Use NUM center negative classes. Only use in binary case."
"Must be using scoring method nb_score."},
{"em-perturb-starting-point", EM_PERTURB_STARTING_POINT, "TYPE", 0,
"Instead of starting EM with P(w|c) from the labeled training data, "
"start from values that are randomly sampled from the multinomial "
"specified by the labeled training data. TYPE specifies what "
"distribution to use for the perturbation; choices are `gaussian' "
"`dirichlet', and `none'. Default is `none'."},
{"em-crossentropy", EM_CROSSENTROPY, 0, 0,
"Use crossentropy instead of naivebayes for scoring."},
{"em-anneal", EM_ANNEAL, 0, 0,
"Use Deterministic annealing EM."},
{"em-temperature", EM_TEMPERATURE, "NUM", 0,
"Initial temperature for deterministic annealing. Default is 200."},
{"em-temp-reduce", EM_TEMP_REDUCE, "NUM", 0,
"Temperature reduction factor for deterministic annealing. Default is 0.9."},
{"em-unlabeled-start", EM_UNLABELED_START, "TYPE", 0,
"When initializing the EM starting point, how the unlabeled docs"
" contribute. Default is `zero'. Other choices are `prior' `random' "
" and `even'."},
{"em-multi-hump-init", EM_MULTI_HUMP_INIT, "METHOD", 0,
"When initializing mixture components, how to assign component probs "
"to documents. Default is `spread'. Other choices are `spiked'."},
{"em-halt-using-perplexity", EM_HALT_USING_PERPLEXITY, "TYPE", 0,
"When running EM, halt when perplexity plataeus. TYPE is type of document "
"to measure perplexity on. Choices are `validation', `train', `test', "
"`unlabeled', `trainandunlabeled' and `trainandunlabeledloo'"},
{"em-anneal-normalizer", EM_ANNEAL_NORMALIZER, 0, 0,
"When running EM, do deterministic annealing-ish stuff with the unlabeled "
"normalizer."},
{"em-print-perplexity", EM_PRINT_PERPLEXITY, "TYPE", 0,
"When running EM, print the perplexity of documents at each round. "
"TYPE is type of document to measure perplexity on. See "
"`--em-halt-using-perplexity` for choices for TYPE"},
{"em-halt-using-accuracy", EM_HALT_USING_ACCURACY, "TYPE", 0,
"When running EM, halt when accuracy plateaus. TYPE is type of document "
"to measure perplexity on. Choices are `validation', `train', `test', "
"`unlabeled' and `trainandunlabeled' and `trainandunlabeledloo'"},
{"em-print-accuracy", EM_PRINT_ACCURACY, "TYPE", 0,
"When running EM, 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"},
{"em-labeled-for-start-only", EM_LABELED_FOR_START_ONLY, 0, 0,
"Use the labeled documents to set the starting point for EM, but"
"ignore them during the iterations"},
{"em-set-vocab-from-unlabeled", EM_SET_VOCAB_FROM_UNLABELED, 0, 0,
"Remove words from the vocabulary not used in the unlabeled data"},
{0, 0}
};
error_t
em_parse_opt (int key, char *arg, struct argp_state *state)
{
switch (key)
{
case EM_COMPARE_TO_NB:
em_compare_to_nb = 1;
break;
case EM_STAT_METHOD:
if (!strcmp(arg, "nb_score"))
em_stat_method = nb_score;
else if (!strcmp(arg, "simple"))
em_stat_method = simple;
else
bow_error("Invalid argument for --em-stat-method");
break;
case EM_NUM_RUNS:
bow_em_num_em_runs = atoi(arg);
break;
case EM_PRINT_PROBS:
bow_em_print_probs = 1;
break;
case EM_BINARY_POS_CLASS:
em_binary_pos_classname = arg;
break;
case EM_BINARY_NEG_CLASS:
em_binary_neg_classname = arg;
break;
case EM_PRINT_TOP_WORDS:
bow_em_print_word_vector = 1;
break;
case EM_BINARY:
bow_em_binary_case = 1;
break;
case EM_UNLABELED_NORMALIZER:
unlabeled_normalizer = 1.0 / atoi(arg);
break;
case EM_MULTI_HUMP:
bow_em_multi_hump_neg = atoi(arg);
break;
case EM_PERTURB_STARTING_POINT:
if (!strcmp (arg, "none"))
bow_em_perturb_starting_point = bow_em_perturb_none;
else if (!strcmp (arg, "gaussian"))
bow_em_perturb_starting_point = bow_em_perturb_with_gaussian;
else if (!strcmp (arg, "dirichlet"))
bow_em_perturb_starting_point = bow_em_perturb_with_dirichlet;
else
bow_error ("Bad arg to --perturb-starting-point");
break;
case EM_CROSSENTROPY:
em_cross_entropy = 1;
break;
case EM_ANNEAL:
em_anneal = 1;
break;
case EM_TEMPERATURE:
em_temperature = atoi (arg);
break;
case EM_TEMP_REDUCE:
em_temp_reduction = atof (arg);
break;
case EM_UNLABELED_START:
if (!strcmp (arg, "zero"))
em_unlabeled_start = em_start_zero;
else if (!strcmp (arg, "prior"))
em_unlabeled_start = em_start_prior;
else if (!strcmp (arg, "even"))
em_unlabeled_start = em_start_even;
else if (!strcmp (arg, "random"))
em_unlabeled_start = em_start_random;
else
bow_error ("Bad arg to --em-unlabled-start");
break;
case EM_MULTI_HUMP_INIT:
if (!strcmp(arg, "spread"))
em_multi_hump_init = bow_em_init_spread;
else if (!strcmp (arg, "spiked"))
em_multi_hump_init = bow_em_init_spiked;
else
bow_error ("Bad arg to --em-multi-hump-init");
break;
case EM_HALT_USING_PERPLEXITY:
em_halt_using_perplexity = 1;
/* Intentional lack of a break here */
case EM_PRINT_PERPLEXITY:
if (!strcmp (arg, "validation"))
em_perplexity_docs = bow_cdoc_is_validation;
else if (!strcmp (arg, "train"))
em_perplexity_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "unlabeled"))
em_perplexity_docs = bow_cdoc_is_unlabeled;
else if (!strcmp (arg, "test"))
em_perplexity_docs = bow_cdoc_is_test;
else if (!strcmp (arg, "trainandunlabeled"))
em_perplexity_docs = bow_cdoc_is_train_or_unlabeled;
else if (!strcmp (arg, "trainandunlabeledloo"))
{
em_perplexity_docs = bow_cdoc_is_train_or_unlabeled;
em_perplexity_loo = 1;
}
else
bow_error("Unknown document type for --em-halt-using-perplexity");
break;
case EM_HALT_USING_ACCURACY:
em_halt_using_accuracy = 1;
/* Intentional lack of break here */
case EM_PRINT_ACCURACY:
if (!strcmp (arg, "validation"))
em_accuracy_docs = bow_cdoc_is_validation;
else if (!strcmp (arg, "train"))
em_accuracy_docs = bow_cdoc_is_train;
else if (!strcmp (arg, "test"))
em_accuracy_docs = bow_cdoc_is_test;
else if (!strcmp (arg, "trainloo"))
{
em_accuracy_docs = bow_cdoc_is_train;
em_accuracy_loo = 1;
}
else
bow_error("Unknown document type for --em-halt-using-accuracy");
break;
case EM_ANNEAL_NORMALIZER:
bow_em_anneal_normalizer = 1;
unlabeled_normalizer = 0;
break;
case EM_LABELED_FOR_START_ONLY:
em_labeled_for_start_only = 1;
break;
case EM_SET_VOCAB_FROM_UNLABELED:
em_set_vocab_from_unlabeled = 1;
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
static const struct argp em_argp =
{
em_options,
em_parse_opt
};
static struct argp_child em_argp_child =
{
&em_argp, /* This child's argp structure */
0, /* flags for child */
0, /* optional header in help message */
0 /* arbitrary group number for ordering */
};
/* End of command-line options specific to EM */
/* return 1 for all docs to be tested by EM during the E-step when
doing multi-hump negative class */
int
bow_cdoc_is_multi_hump_doc (bow_cdoc *cdoc)
{
return((cdoc->type == bow_doc_unlabeled) ||
(cdoc->type == bow_doc_train && cdoc->class != binary_pos_ci));
}
/* Given a fully-specified file path name (all the way from `/'),
return just the last filename part of it. */
static inline const char *
filename_to_classname (const char *filename)
{
const char *ret;
ret = strrchr (filename, '/');
if (ret)
return ret + 1;
return filename;
}
int
bow_em_pr_struct_compare (const void *x, const void *y)
{
if (((bow_em_pr_struct *)x)->score > ((bow_em_pr_struct *)y)->score)
return -1;
else if (((bow_em_pr_struct *)x)->score == ((bow_em_pr_struct *)y)->score)
return 0;
else
return 1;
}
/* Return a random number sampled from a gaussian with MEAN and VARIANCE. */
/* From "Recipies in C", page 289. */
double
bow_em_gaussian (double mean, double variance)
{
static int iset = 0;
static double gset;
double fac, rsq, v1, v2;
double gaussian_zero_one; /* random gaussian with mean=0, variance=1 */
bow_random_set_seed ();
if (iset == 0)
{
do
{
v1 = 2.0 * bow_random_double (0.0, 1.0) - 1.0;
v2 = 2.0 * bow_random_double (0.0, 1.0) - 1.0;
rsq = v1 * v1 + v2 * v2;
}
while (rsq >= 1.0 || rsq == 0.0);
fac = sqrt (-2.0 * log (rsq)/rsq);
gset = v1 * fac;
iset = 1;
gaussian_zero_one = v2 * fac;
}
else
{
iset = 0;
gaussian_zero_one = gset;
}
return gaussian_zero_one * sqrt (variance) + mean;
}
/* From Numerical "Recipes in C", page 292 */
double
bow_gamma_distribution (int ia)
{
int j;
double am, e, s, v1, v2, x, y;
assert (ia >= 1) ;
if (ia < 6)
{
x = 1.0;
for (j = 1; j <= ia; j++)
x *= bow_random_01 ();
x = - log (x);
}
else
{
do
{
do
{
do
{
v1 = 2.0 * bow_random_01 () - 1.0;
v2 = 2.0 * bow_random_01 () - 1.0;
}
while (v1 * v1 + v2 * v2 > 1.0);
y = v2 / v1;
am = ia - 1;
s = sqrt (2.0 * am + 1.0);
x = s * y + am;
}
while (x <= 0.0);
e = (1.0 + y * y) * exp (am * log (x/am) - s * y);
}
while (bow_random_01 () > e);
}
return x;
}
/* Change the weights by sampling from the multinomial distribution
specified by the training data. Start from the current values of
the DV WEIGHTS. Typically this would be called after iteration 1
of EM, before the unlabeled documents were included in the
WEIGHTS. */
void
bow_em_perturb_weights (bow_barrel *doc_barrel, bow_barrel *vpc_barrel)
{
double variance;
double num_words_per_ci[bow_barrel_num_classes (vpc_barrel)];
int ci, wi, dvi, max_wi;
bow_dv *dv;
bow_cdoc *cdoc;
double pr_w_c;
if (bow_em_perturb_starting_point == bow_em_perturb_none)
return;
bow_random_set_seed ();
max_wi = MIN (doc_barrel->wi2dvf->size, bow_num_words ());
/* Perturb the counts (which are stored in WEIGHT) */
for (wi = 0; wi < max_wi; wi++)
{
dv = bow_wi2dvf_dv (vpc_barrel->wi2dvf, wi);
if (!dv)
continue;
for (dvi = 0; dvi < dv->length; dvi++)
{
/* WEIGHT can be zero if the prob of a class for the doc
that had this word was zero */
if (bow_em_perturb_starting_point
== bow_em_perturb_with_gaussian)
{
if (0 != dv->entry[dvi].weight)
{
cdoc = bow_array_entry_at_index (vpc_barrel->cdocs,
dv->entry[dvi].di);
pr_w_c = dv->entry[dvi].weight / cdoc->normalizer;
variance = cdoc->normalizer * pr_w_c * (1 - pr_w_c);
dv->entry[dvi].weight =
bow_em_gaussian (dv->entry[dvi].weight, variance);
if (dv->entry[dvi].weight < 0)
dv->entry[dvi].weight = 0;
}
}
else if (bow_em_perturb_starting_point
== bow_em_perturb_with_dirichlet)
{
dv->entry[dvi].weight =
bow_gamma_distribution (dv->entry[dvi].weight + 1);
/* The +1 is assuming we are using LaPlace smoothing */
/* xxx I hope that we are still multiplying weights by
200 (for a length 200 document), otherwise weight
will always get rounded down into nothing, because
bow_gamma_distribution only takes int's */
}
}
}
/* Reset the CDOC->WORD_COUNT and CDOC->NORMALIZER */
for (ci = 0; ci < bow_barrel_num_classes (vpc_barrel); ci++)
{
cdoc = bow_array_entry_at_index (vpc_barrel->cdocs, ci);
cdoc->normalizer = 0;
num_words_per_ci[ci] = 0;
}
for (wi = 0; wi < max_wi; wi++)
{
dv = bow_wi2dvf_dv (vpc_barrel->wi2dvf, wi);
if (!dv)
continue;
for (dvi = 0; dvi < dv->length; dvi++)
{
/* WEIGHT can be zero if the prob of a class for the doc
that had this word was zero */
if (0 != dv->entry[dvi].weight)
{
cdoc = bow_array_entry_at_index (vpc_barrel->cdocs,
dv->entry[dvi].di);
num_words_per_ci[dv->entry[dvi].di] +=
dv->entry[dvi].weight;
#if 0
/* Now using normalizer for non-int word_count */
cdoc->normalizer++;
#endif
}
}
}
for (ci = 0; ci < bow_barrel_num_classes (vpc_barrel); ci++)
{
bow_cdoc *cdoc =
bow_array_entry_at_index (vpc_barrel->cdocs, ci);
cdoc->normalizer = num_words_per_ci[ci];
#if 0
cdoc->word_count = (int) rint(num_words_per_ci[ci]);
assert (cdoc->word_count >= 0);
#endif
assert (cdoc->normalizer >= 0);
}
}
/* Create a class barrel with EM-style clustering on unlabeled
docs */
bow_barrel *
bow_em_new_vpc_with_weights (bow_barrel *doc_barrel)
{
bow_barrel *vpc_barrel; /* the vector-per-class barrel */
int wi; /* word index */
int max_wi; /* max word index */
int dvi; /* document vector index */
int ci; /* class index */
bow_dv *dv; /* document vector */
int di; /* document index */
int binary_neg_ci = -1;
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;
int hi; /* hit index */
bow_cdoc *doc_cdoc;
int num_tested;
int em_runs = 0;
int num_train_docs = 0;
int num_unlabeled_docs = 0;
int max_new_ci;
int max_old_ci;
int (* bow_cdoc_next_em_doc)(bow_cdoc *) = bow_cdoc_is_unlabeled;
double old_perplexity = DBL_MAX;
double new_perplexity = DBL_MAX / 2;
double old_accuracy = -2;
double new_accuracy = -1;
/*bow_wi2dvf *prev_wi2dvf = NULL;*/
/*float prev_priors[200];*/
/*int prev_word_counts[200];*/
/*float prev_normalizers[200];*/
float total_weight;
float labeled_weight_fraction;
float new_labeled_fraction;
/* some sanity checks first */
assert(200 > bow_barrel_num_classes(doc_barrel));
assert(200 > bow_em_multi_hump_neg + 1);
assert (!bow_em_multi_hump_neg ||
(bow_em_binary_case && em_stat_method == nb_score));
assert (!strcmp(doc_barrel->method->name, "em") ||
!strcmp(doc_barrel->method->name, "active"));
assert (doc_barrel->classnames);
assert (!(bow_em_perturb_starting_point && em_anneal));
assert (em_stat_method == nb_score || bow_em_multi_hump_neg == 0);
assert (bow_em_multi_hump_neg == 0 || em_labeled_for_start_only == 0);
/* this option is broken */
assert (!em_halt_using_perplexity);
/* initialize some variables */
bow_em_making_barrel = 1;
if (bow_smoothing_method == bow_smoothing_dirichlet)
bow_naivebayes_load_dirichlet_alphas ();
max_old_ci = bow_barrel_num_classes(doc_barrel);
if (bow_em_multi_hump_neg)
max_new_ci = bow_em_multi_hump_neg + 1;
else
max_new_ci = max_old_ci;
if (bow_em_multi_hump_neg > 1)
bow_cdoc_next_em_doc = bow_cdoc_is_multi_hump_doc;
max_wi = MIN (doc_barrel->wi2dvf->size, bow_num_words ());
/* assert(doc_barrel->wi2dvf->size == bow_num_words ()); */
/* remove words from vocab if using only the unlabeled vocab */
if (em_set_vocab_from_unlabeled)
{
int removed = 0;
int kept = 0;
for (wi = 0; wi < max_wi; wi++)
{
int found = 0;
bow_dv *dv = bow_wi2dvf_dv (doc_barrel->wi2dvf, wi);
if (!dv)
continue;
dvi = 0;
while (dvi < dv->length)
{
bow_cdoc *cdoc = bow_array_entry_at_index (doc_barrel->cdocs,
dv->entry[dvi].di);
if (cdoc->type == bow_doc_unlabeled)
{
found = 1;
break;
}
dvi++;
}
if (!found)
{
bow_wi2dvf_hide_wi (doc_barrel->wi2dvf, wi);
removed++;
}
else
kept++;
}
bow_verbosify (bow_progress, "Removed %d words using unlabeled data; %d remaining\n",
removed, kept);
}
/* Count the number of training and unlabeled documents */
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_train)
num_train_docs++;
else if (cdoc->type == bow_doc_unlabeled)
num_unlabeled_docs++;
}
/* Identify the binary positive and negative class */
if (bow_em_binary_case)
{
assert (em_binary_pos_classname != NULL);
assert (em_binary_neg_classname != NULL);
for (ci = 0; ci < max_old_ci; ci++)
{
if (em_binary_pos_classname != NULL &&
-1 == binary_pos_ci &&
!strcmp(em_binary_pos_classname,
filename_to_classname
(bow_barrel_classname_at_index (doc_barrel, ci))))
{
binary_pos_ci = ci;
}
if (em_binary_neg_classname != NULL &&
-1 == binary_neg_ci &&
!strcmp(em_binary_neg_classname,
filename_to_classname
(bow_barrel_classname_at_index (doc_barrel, ci))))
{
binary_neg_ci = ci;
}
}
if (binary_pos_ci == -1)
bow_error ("No such binary positive class %s.",
em_binary_pos_classname);
if (binary_neg_ci == -1)
bow_error ("No such binary negative class %s.",
em_binary_neg_classname);
}
/* should the free function be a real one? */
/* Create an empty barrel; we fill it with vector-per-class
data and return it. */
vpc_barrel = bow_barrel_new (doc_barrel->wi2dvf->size,
doc_barrel->cdocs->length-1,
doc_barrel->cdocs->entry_size,
doc_barrel->cdocs->free_func);
vpc_barrel->method = doc_barrel->method;
vpc_barrel->classnames = bow_int4str_new (0);
/* setup the cdoc structure for the class barrel, except for the
word counts and normalizer, which we'll do later. */
for (ci = 0; ci < max_old_ci; ci++)
{
bow_cdoc cdoc;
/* create the cdoc structure */
cdoc.type = bow_doc_train;
cdoc.normalizer = -0.0f; /* just a temporary measure */
cdoc.word_count = 0; /* just a temporary measure */
cdoc.filename = strdup (bow_barrel_classname_at_index (doc_barrel,
ci));
bow_barrel_add_classname(vpc_barrel, cdoc.filename);
if (!cdoc.filename)
bow_error ("Memory exhausted.");
cdoc.class_probs = NULL;
cdoc.class = ci;
bow_array_append (vpc_barrel->cdocs, &cdoc);
}
/* if multi-hump, then add a cdoc for each of the other negative
humps as well */
if (bow_em_multi_hump_neg)
{
for (ci = max_old_ci; ci < max_new_ci; ci++)
{
bow_cdoc cdoc;
char *name = bow_malloc (sizeof (char) *
(strlen(em_binary_neg_classname) + 10));
cdoc.type = bow_doc_train;
cdoc.normalizer = 0.0f; /* just a temporary measure */
cdoc.word_count = 0; /* just a temporary measure */
sprintf(name, "%s%d", em_binary_neg_classname, ci);
cdoc.filename = name;
bow_barrel_add_classname(vpc_barrel, cdoc.filename);
if (!cdoc.filename)
bow_error ("Memory exhausted.");
cdoc.class_probs = NULL;
cdoc.class = ci;
bow_array_append (vpc_barrel->cdocs, &cdoc);
}
}
/* if we're comparing to naivebayes, do that now */
if (em_compare_to_nb == 1)
bow_em_compare_to_nb(doc_barrel);
/* Set word_count for docs correctly. Do this after comparing to NB b/c
making a NB class barrel messes with the word counts. */
{
/* Create the heap from which we'll get WV's. */
query_wv = NULL;
test_heap = bow_test_new_heap (doc_barrel);
/* Loop once for each document. */
while (-1 != (di = bow_heap_next_wv (test_heap, doc_barrel, &query_wv,
bow_cdoc_yes)))
{
int word_count = 0;
int wvi;
doc_cdoc = bow_array_entry_at_index (doc_barrel->cdocs,
di);
for (wvi = 0; wvi < query_wv->num_entries; wvi++)
word_count += query_wv->entry[wvi].count;
doc_cdoc->word_count = word_count;
}
}
/* initialize the EM starting point */
{
/* cycle through the document barrel and make sure that each
document has a correctly initialized class_probs structure.
set class_probs of train docs. Note that these class_probs
indexes are indexes into the NEW class indexes not the OLD
ones!*/
for (di=0; di < doc_barrel->cdocs->length; di++)
{
bow_cdoc *cdoc = bow_array_entry_at_index (doc_barrel->cdocs, di);
if (!cdoc->class_probs)
cdoc->class_probs = bow_malloc (sizeof (float) * max_new_ci);
/* initialize the class_probs to all zeros */
for (ci=0; ci < max_new_ci; ci++)
cdoc->class_probs[ci] = 0.0;
/* if it's a known doc, set its class_probs that way */
if (cdoc->type == bow_doc_train)
cdoc->class_probs[cdoc->class] = 1.0;
}
/* redistribute class probs of negative docs if multi-hump */
if (bow_em_multi_hump_neg)
{
if (em_multi_hump_init == bow_em_init_spiked)
{
int counts[500];
int n;
int yet_to_find = 0;
assert (bow_em_multi_hump_neg < 500);
/* Count the number of negative documents */
for (di=0; di < doc_barrel->cdocs->length; di++)
{
bow_cdoc *cdoc = bow_array_entry_at_index (doc_barrel->cdocs, di);
if (cdoc->class == binary_neg_ci)
yet_to_find++;
}
/* set the number of docs per negative hump */
assert(yet_to_find >= bow_em_multi_hump_neg);
for (n=0; n < bow_em_multi_hump_neg; n++)
counts[n] = 0;
for (n=0; n < yet_to_find; n++)
counts[n % bow_em_multi_hump_neg]++;
/* reassign the negative docs */
for (di=0; di < doc_barrel->cdocs->length; di++)
{
bow_cdoc *cdoc =
bow_array_entry_at_index (doc_barrel->cdocs, di);
int new_class;
if (cdoc->type != bow_doc_train ||
cdoc->class == binary_pos_ci)
continue;
assert(yet_to_find > 0);
/* find a new class */
for (new_class = rand() % bow_em_multi_hump_neg;
counts[new_class] == 0;
new_class = rand() % bow_em_multi_hump_neg);
yet_to_find--;
counts[new_class]--;
/* assign it to the right hump */
if (new_class != 0)
{
cdoc->class_probs[new_class + 1] = 1.0;
cdoc->class_probs[binary_neg_ci] = 0.0;
}
}
assert(yet_to_find == 0);
}
else if (em_multi_hump_init == bow_em_init_spread)
{
bow_random_set_seed();
/* spread each negative doc randomly over neg components */
for (di=0; di < doc_barrel->cdocs->length; di++)
{
bow_cdoc *cdoc =
bow_array_entry_at_index (doc_barrel->cdocs, di);
float total = 0;
if (cdoc->type != bow_doc_train || cdoc->class == binary_pos_ci)
continue;
for (ci=0; ci < max_new_ci; ci++)
{
if (ci == binary_pos_ci)
cdoc->class_probs[ci] = 0.0;
else
{
cdoc->class_probs[ci] = (float) (rand() % 100) + 1;
total += cdoc->class_probs[ci];
}
}
for (ci=0; ci < max_new_ci; ci++)
{
cdoc->class_probs[ci] /= total ;
}
}
}
else
bow_error ("No initialization for this type");
}
/* set priors using just the known docs if we'll need them
for setting class_probs */
if (em_unlabeled_start == em_start_prior)
{
assert (num_train_docs > 0);
assert (!bow_uniform_class_priors);
(*doc_barrel->method->vpc_set_priors) (vpc_barrel, doc_barrel);
}
else
{
for (ci = 0; ci < max_new_ci; ci++)
{
bow_cdoc *cdoc = bow_array_entry_at_index(vpc_barrel->cdocs, ci);
cdoc->prior = 0.0;
}
}
/* set the class probs of all the unlabeled docs to determine the EM
starting point */
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)
continue;
if (em_unlabeled_start == em_start_zero)
{
/* set class_probs as all zeros (ignore them for first M step) */
for (ci=0; ci < max_new_ci; ci++)
cdoc->class_probs[ci] = 0.0;
}
else if (em_unlabeled_start == em_start_random)
{
float total = 0;
/* if there are no labeled docs, randomly assign class probs */
bow_random_set_seed();
for (ci=0; ci < max_new_ci; ci++)
{
cdoc->class_probs[ci] = (float) (rand() % 100);
total += cdoc->class_probs[ci];
}
for (ci=0; ci < max_new_ci; ci++)
{
cdoc->class_probs[ci] *= unlabeled_normalizer / total ;
}
}
else if (em_unlabeled_start == em_start_prior)
{
/* distribute class_probs according to priors on just the known */
assert (!bow_em_multi_hump_neg && !bow_uniform_class_priors);
assert (num_train_docs > 0);
for (ci=0; ci < max_new_ci; ci++)
{
bow_cdoc *class_cdoc = bow_array_entry_at_index
(vpc_barrel->cdocs, ci);
cdoc->class_probs[ci] = class_cdoc->prior *
unlabeled_normalizer;
}