/
Dirichlet.java
1687 lines (1320 loc) · 44.4 KB
/
Dirichlet.java
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
/* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package cc.mallet.types;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import com.carrotsearch.hppc.IntHashSet;
import com.carrotsearch.hppc.IntIntHashMap;
import com.carrotsearch.hppc.cursors.IntCursor;
import com.google.errorprone.annotations.Var;
import cc.mallet.util.Randoms;
/**
* Various useful functions related to Dirichlet distributions.
*
* @author Andrew McCallum and David Mimno
*/
public class Dirichlet {
Alphabet dict;
double magnitude = 1;
double[] partition;
Randoms random = null;
/** Actually the negative Euler-Mascheroni constant */
public static final double EULER_MASCHERONI = -0.5772156649015328606065121;
public static final double PI_SQUARED_OVER_SIX = Math.PI * Math.PI / 6;
public static final double HALF_LOG_TWO_PI = Math.log(2 * Math.PI) / 2;
public static final double DIGAMMA_COEF_1 = 1/12;
public static final double DIGAMMA_COEF_2 = 1/120;
public static final double DIGAMMA_COEF_3 = 1/252;
public static final double DIGAMMA_COEF_4 = 1/240;
public static final double DIGAMMA_COEF_5 = 1/132;
public static final double DIGAMMA_COEF_6 = 691/32760;
public static final double DIGAMMA_COEF_7 = 1/12;
public static final double DIGAMMA_COEF_8 = 3617/8160;
public static final double DIGAMMA_COEF_9 = 43867/14364;
public static final double DIGAMMA_COEF_10 = 174611/6600;
public static final double DIGAMMA_LARGE = 9.5;
public static final double DIGAMMA_SMALL = .000001;
/** A dirichlet parameterized by a distribution and a magnitude
*
* @param m The magnitude of the Dirichlet: sum_i alpha_i
* @param p A probability distribution: p_i = alpha_i / m
*/
public Dirichlet (double m, double[] p) {
magnitude = m;
partition = p;
}
/** A symmetric dirichlet: E(X_i) = E(X_j) for all i, j
*
* @param m The magnitude of the Dirichlet: sum_i alpha_i
* @param n The number of dimensions
*/
/*
public Dirichlet (double m, int n) {
magnitude = m;
partition = new double[n];
partition[0] = 1.0 / n;
for (int i=1; i<n; i++) {
partition[i] = partition[0];
}
}
*/
/** A dirichlet parameterized with a single vector of positive reals */
public Dirichlet(double[] p) {
magnitude = 0;
partition = new double[p.length];
// Add up the total
for (int i=0; i<p.length; i++) {
magnitude += p[i];
}
for (int i=0; i<p.length; i++) {
partition[i] = p[i] / magnitude;
}
}
/** Constructor that takes an alphabet representing the
* meaning of each dimension
*/
public Dirichlet (double[] alphas, Alphabet dict)
{
this(alphas);
if (dict != null && alphas.length != dict.size())
throw new IllegalArgumentException ("alphas and dict sizes do not match.");
this.dict = dict;
if (dict != null)
dict.stopGrowth();
}
/**
* A symmetric Dirichlet with alpha_i = 1.0 and the
* number of dimensions of the given alphabet.
*/
public Dirichlet (Alphabet dict)
{
this (dict, 1.0);
}
/**
* A symmetric Dirichlet with alpha_i = <code>alpha</code> and the
* number of dimensions of the given alphabet.
*/
public Dirichlet (Alphabet dict, double alpha)
{
this(dict.size(), alpha);
this.dict = dict;
dict.stopGrowth();
}
/** A symmetric Dirichlet with alpha_i = 1.0 and <code>size</code>
dimensions */
public Dirichlet (int size)
{
this (size, 1.0);
}
/** A symmetric dirichlet: E(X_i) = E(X_j) for all i, j
*
* @param n The number of dimensions
* @param alpha The parameter for each dimension
*/
public Dirichlet (int size, double alpha)
{
magnitude = size * alpha;
partition = new double[size];
partition[0] = 1.0 / size;
for (int i=1; i<size; i++) {
partition[i] = partition[0];
}
}
private void initRandom() {
if (random == null) {
random = new Randoms();
}
}
public double[] nextDistribution() {
double distribution[] = new double[partition.length];
initRandom();
// For each dimension, draw a sample from Gamma(mp_i, 1)
@Var
double sum = 0;
for (int i=0; i<distribution.length; i++) {
distribution[i] = random.nextGamma(partition[i] * magnitude, 1);
if (distribution[i] <= 0) {
distribution[i] = 0.0001;
}
sum += distribution[i];
}
// Normalize
for (int i=0; i<distribution.length; i++) {
distribution[i] /= sum;
}
return distribution;
}
/**
* Create a printable list of alpha_i parameters
*/
public static String distributionToString(double magnitude, double[] distribution) {
StringBuffer output = new StringBuffer();
NumberFormat formatter = NumberFormat.getInstance();
formatter.setMaximumFractionDigits(5);
output.append(formatter.format(magnitude) + ":\t");
for (int i=0; i<distribution.length; i++) {
output.append(formatter.format(distribution[i]) + "\t");
}
return output.toString();
}
/** Write the parameters alpha_i to the specified file, one
* per line
*/
public void toFile(String filename) throws IOException {
PrintWriter out =
new PrintWriter(new BufferedWriter(new FileWriter(filename)));
for (int i=0; i<partition.length; i++) {
out.println(magnitude * partition[i]);
}
out.flush();
out.close();
}
/** Dirichlet-multinomial: draw a distribution from the
dirichlet, then draw n samples from that multinomial. */
public int[] drawObservation(int n) {
initRandom();
double[] distribution = nextDistribution();
return drawObservation(n, distribution);
}
/**
* Draw a count vector from the probability distribution provided.
*
* @param n The <i>expected</i> total number of counts in the returned vector. The actual number is ~ Poisson(<code>n</code>)
*/
public int[] drawObservation(int n, double[] distribution) {
initRandom();
int[] histogram = new int[partition.length];
Arrays.fill(histogram, 0);
int count;
// I was using a poisson, but the poisson variate generator
// goes berzerk for lambda above ~500.
if (n < 100) {
count = random.nextPoisson();
}
else {
// p(N(100, 10) <= 0) = 7.619853e-24
count = (int) Math.round(random.nextGaussian(n, n));
}
for (int i=0; i<count; i++) {
histogram[random.nextDiscrete(distribution)]++;
}
return histogram;
}
/** Create a set of d draws from a dirichlet-multinomial, each
* with an average of n observations. */
public Object[] drawObservations(int d, int n) {
Object[] observations = new Object[d];
for (int i=0; i<d; i++) {
observations[i] = drawObservation(n);
}
return observations;
}
/** This calculates a log gamma function exactly.
* It's extremely inefficient -- use this for comparison only.
*/
public static double logGammaDefinition(double z) {
@Var
double result = EULER_MASCHERONI * z - Math.log(z);
for (int k=1; k < 10000000; k++) {
result += (z/k) - Math.log(1 + (z/k));
}
return result;
}
/** This directly calculates the difference between two
* log gamma functions using a recursive formula.
* The break-even with the Stirling approximation is about
* n=2, so it's not necessarily worth using this.
*/
public static double logGammaDifference(double z, int n) {
@Var
double result = 0.0;
for (int i=0; i < n; i++) {
result += Math.log(z + i);
}
return result;
}
/** Currently aliased to <code>logGammaStirling</code> */
public static double logGamma(double z) {
return logGammaStirling(z);
}
/** Use a fifth order Stirling's approximation.
*
* @param z Note that Stirling's approximation is increasingly unstable as <code>z</code> approaches 0. If <code>z</code> is less than 2, we shift it up, calculate the approximation, and then shift the answer back down.
*/
public static double logGammaStirling(@Var double z) {
@Var
int shift = 0;
while (z < 2) {
z++;
shift++;
}
@Var
double result = HALF_LOG_TWO_PI + (z - 0.5) * Math.log(z) - z +
1/(12 * z) - 1 / (360 * z * z * z) + 1 / (1260 * z * z * z * z * z);
while (shift > 0) {
shift--;
z--;
result -= Math.log(z);
}
return result;
}
/** Gergo Nemes' approximation */
public static double logGammaNemes(double z) {
double result = HALF_LOG_TWO_PI - (Math.log(z) / 2) +
z * (Math.log(z + (1/(12 * z - (1/(10*z))))) - 1);
return result;
}
/** Calculate digamma using an asymptotic expansion involving
Bernoulli numbers. */
public static double digamma(@Var double z) {
// This is based on matlab code by Tom Minka
// if (z < 0) { System.out.println(" less than zero"); }
@Var
double psi = 0;
if (z < DIGAMMA_SMALL) {
psi = EULER_MASCHERONI - (1 / z); // + (PI_SQUARED_OVER_SIX * z);
/*for (int n=1; n<100000; n++) {
psi += z / (n * (n + z));
}*/
return psi;
}
while (z < DIGAMMA_LARGE) {
psi -= 1 / z;
z++;
}
double invZ = 1/z;
double invZSquared = invZ * invZ;
psi += Math.log(z) - .5 * invZ
- invZSquared * (DIGAMMA_COEF_1 - invZSquared *
(DIGAMMA_COEF_2 - invZSquared *
(DIGAMMA_COEF_3 - invZSquared *
(DIGAMMA_COEF_4 - invZSquared *
(DIGAMMA_COEF_5 - invZSquared *
(DIGAMMA_COEF_6 - invZSquared *
DIGAMMA_COEF_7))))));
return psi;
}
public static double digammaDifference(double x, int n) {
@Var
double sum = 0;
for (int i=0; i<n; i++) {
sum += 1 / (x + i);
}
return sum;
}
public static double trigamma(@Var double z) {
@Var
int shift = 0;
while (z < 2) {
z++;
shift++;
}
double oneOverZ = 1.0 / z;
double oneOverZSquared = oneOverZ * oneOverZ;
@Var
double result =
oneOverZ +
0.5 * oneOverZSquared +
0.1666667 * oneOverZSquared * oneOverZ -
0.03333333 * oneOverZSquared * oneOverZSquared * oneOverZ +
0.02380952 * oneOverZSquared * oneOverZSquared * oneOverZSquared * oneOverZ -
0.03333333 * oneOverZSquared * oneOverZSquared * oneOverZSquared * oneOverZSquared * oneOverZ;
while (shift > 0) {
shift--;
z--;
result += 1.0 / (z * z);
}
return result;
}
/**
* Learn the concentration parameter of a symmetric Dirichlet using frequency histograms.
* Since all parameters are the same, we only need to keep track of
* the number of observation/dimension pairs with count N
*
* @param countHistogram An array of frequencies. If the matrix X represents observations such that x<sub>dt</sub> is how many times word t occurs in document d, <code>countHistogram[3]</code> is the total number of cells <i>in any column</i> that equal 3.
* @param observationLengths A histogram of sample lengths, for example <code>observationLengths[20]</code> could be the number of documents that are exactly 20 tokens long.
* @param numDimensions The total number of dimensions.
* @param currentValue An initial starting value.
*/
public static double learnSymmetricConcentration(int[] countHistogram,
int[] observationLengths,
int numDimensions,
@Var double currentValue) {
@Var
double currentDigamma;
// The histogram arrays are presumably allocated before
// we knew what went in them. It is therefore likely that
// the largest non-zero value may be much closer to the
// beginning than the end. We don't want to iterate over
// a whole bunch of zeros, so keep track of the last value.
@Var
int largestNonZeroCount = 0;
int[] nonZeroLengthIndex = new int[ observationLengths.length ];
for (int index = 0; index < countHistogram.length; index++) {
if (countHistogram[index] > 0) { largestNonZeroCount = index; }
}
@Var
int denseIndex = 0;
for (int index = 0; index < observationLengths.length; index++) {
if (observationLengths[index] > 0) {
nonZeroLengthIndex[denseIndex] = index;
denseIndex++;
}
}
int denseIndexSize = denseIndex;
for (int iteration = 1; iteration <= 200; iteration++) {
double currentParameter = currentValue / numDimensions;
// Calculate the numerator
currentDigamma = 0;
@Var
double numerator = 0;
// Counts of 0 don't matter, so start with 1
for (int index = 1; index <= largestNonZeroCount; index++) {
currentDigamma += 1.0 / (currentParameter + index - 1);
numerator += countHistogram[index] * currentDigamma;
}
// Now calculate the denominator, a sum over all observation lengths
currentDigamma = 0;
@Var
double denominator = 0;
@Var
int previousLength = 0;
double cachedDigamma = digamma(currentValue);
for (denseIndex = 0; denseIndex < denseIndexSize; denseIndex++) {
int length = nonZeroLengthIndex[denseIndex];
if (length - previousLength > 20) {
// If the next length is sufficiently far from the previous,
// it's faster to recalculate from scratch.
currentDigamma = digamma(currentValue + length) - cachedDigamma;
}
else {
// Otherwise iterate up. This looks slightly different
// from the previous version (no -1) because we're indexing differently.
for (int index = previousLength; index < length; index++) {
currentDigamma += 1.0 / (currentValue + index);
}
}
denominator += currentDigamma * observationLengths[length];
}
currentValue = currentParameter * numerator / denominator;
///System.out.println(currentValue + " = " + currentParameter + " * " + numerator + " / " + denominator);
}
return currentValue;
}
public static void testSymmetricConcentration(int numDimensions, int numObservations,
int observationMeanLength) {
double logD = Math.log(numDimensions);
for (int exponent = -5; exponent < 4; exponent++) {
double alpha = numDimensions * 1.0;
Dirichlet prior = new Dirichlet(numDimensions, alpha / numDimensions);
int[] countHistogram = new int[ 1000000 ];
int[] observationLengths = new int[ 1000000 ];
Object[] observations = prior.drawObservations(numObservations, observationMeanLength);
Dirichlet optimizedDirichlet = new Dirichlet(numDimensions, 1.0);
optimizedDirichlet.learnParametersWithHistogram(observations);
System.out.println(optimizedDirichlet.magnitude);
for (int i=0; i < numObservations; i++) {
int[] observation = (int[]) observations[i];
@Var
int total = 0;
for (int k=0; k < numDimensions; k++) {
if (observation[k] > 0) {
total += observation[k];
countHistogram[ observation[k] ]++;
}
}
observationLengths[ total ]++;
}
double estimatedAlpha = learnSymmetricConcentration(countHistogram, observationLengths,
numDimensions, 1.0);
System.out.println(alpha + "\t" + estimatedAlpha + "\t" +
Math.abs(alpha - estimatedAlpha));
}
}
/**
* Learn Dirichlet parameters using frequency histograms
* described by Hanna Wallach in "Structured Topic Models for Language" (2008), section 2.4
* Method 1: Using the Digamma Recurrence Relation (pp. 27-28)
*
* @param parameters A reference to the current values of the parameters, which will be updated in place
* @param observations An array of count histograms. <code>observations[10][3]</code> could be the number of documents that contain exactly 3 tokens of word type 10.
* @param observationLengths A histogram of sample lengths, for example <code>observationLengths[20]</code> could be the number of documents that are exactly 20 tokens long.
* @returns The sum of the learned parameters.
*/
public static double learnParameters(double[] parameters,
int[][] observations,
int[] observationLengths) {
return learnParameters(parameters, observations, observationLengths,
1.00001, 1.0, 200);
}
/**
* Learn Dirichlet parameters using frequency histograms
* described by Hanna Wallach in "Structured Topic Models for Language", section 2.4
* Method 1: Using the Digamma Recurrence Relation (pp. 27-28) and gamma hyperpriors (section 2.5, pp. 37-39)
*
* @param parameters A reference to the current values of the parameters, which will be updated in place
* @param observations An array of count histograms. <code>observations[10][3]</code> could be the number of documents that contain exactly 3 tokens of word type 10.
* @param observationLengths A histogram of sample lengths, for example <code>observationLengths[20]</code> could be the number of documents that are exactly 20 tokens long.
* @param shape Gamma prior E(X) = shape * scale, var(X) = shape * scale<sup>2</sup>
* @param scale
* @param numIterations 200 to 1000 generally insures convergence, but 1-5 is often enough to step in the right direction
* @returns The sum of the learned parameters.
*/
public static double learnParameters(double[] parameters,
int[][] observations,
int[] observationLengths,
double shape, double scale,
int numIterations) {
@Var
int i;
@Var
int k;
@Var
double parametersSum = 0;
// Initialize the parameter sum
for (k=0; k < parameters.length; k++) {
parametersSum += parameters[k];
}
@Var
double oldParametersK;
@Var
double currentDigamma;
@Var
double denominator;
@Var
int nonZeroLimit;
int[] nonZeroLimits = new int[observations.length];
Arrays.fill(nonZeroLimits, -1);
// The histogram arrays go up to the size of the largest document,
// but the non-zero values will almost always cluster in the low end.
// We avoid looping over empty arrays by saving the index of the largest
// non-zero value.
@Var
int[] histogram;
for (i=0; i<observations.length; i++) {
histogram = observations[i];
//StringBuffer out = new StringBuffer();
for (k = 0; k < histogram.length; k++) {
if (histogram[k] > 0) {
nonZeroLimits[i] = k;
//out.append(k + ":" + histogram[k] + " ");
}
}
//System.out.println(out);
}
for (int iteration=0; iteration<numIterations; iteration++) {
// Calculate the denominator
denominator = 0;
currentDigamma = 0;
// Iterate over the histogram:
for (i=1; i<observationLengths.length; i++) {
currentDigamma += 1 / (parametersSum + i - 1);
denominator += observationLengths[i] * currentDigamma;
}
// Bayesian estimation Part I
denominator -= 1/scale;
// Calculate the individual parameters
parametersSum = 0;
for (k=0; k<parameters.length; k++) {
// What's the largest non-zero element in the histogram?
nonZeroLimit = nonZeroLimits[k];
oldParametersK = parameters[k];
parameters[k] = 0;
currentDigamma = 0;
histogram = observations[k];
for (i=1; i <= nonZeroLimit; i++) {
currentDigamma += 1 / (oldParametersK + i - 1);
parameters[k] += histogram[i] * currentDigamma;
}
// Bayesian estimation part II
parameters[k] = oldParametersK * (parameters[k] + shape) / denominator;
parametersSum += parameters[k];
}
}
if (parametersSum < 0.0) { throw new RuntimeException("sum: " + parametersSum); }
return parametersSum;
}
/** Use the fixed point iteration described by Tom Minka. */
public long learnParametersWithHistogram(Object[] observations) {
@Var
int maxLength = 0;
int[] maxBinCounts = new int[partition.length];
Arrays.fill(maxBinCounts, 0);
for (int i=0; i < observations.length; i++) {
@Var
int length = 0;
int[] observation = (int[]) observations[i];
for (int bin=0; bin < observation.length; bin++) {
if (observation[bin] > maxBinCounts[bin]) {
maxBinCounts[bin] = observation[bin];
}
length += observation[bin];
}
if (length > maxLength) {
maxLength = length;
}
}
// Arrays start at zero, so I'm sacrificing one int for greater clarity
// later on...
int[][] binCountHistograms = new int[partition.length][];
for (int bin=0; bin < partition.length; bin++) {
binCountHistograms[bin] = new int[ maxBinCounts[bin] + 1 ];
Arrays.fill(binCountHistograms[bin], 0);
}
// System.out.println("got mem: " + (System.currentTimeMillis() - start));
int[] lengthHistogram = new int[maxLength + 1];
Arrays.fill(lengthHistogram, 0);
// System.out.println("got lengths: " + (System.currentTimeMillis() - start));
for (int i=0; i < observations.length; i++) {
@Var
int length = 0;
int[] observation = (int[]) observations[i];
for (int bin=0; bin < observation.length; bin++) {
binCountHistograms[bin][ observation[bin] ]++;
length += observation[bin];
}
lengthHistogram[length]++;
}
return learnParametersWithHistogram(binCountHistograms, lengthHistogram);
}
public long learnParametersWithHistogram(int[][] binCountHistograms, int[] lengthHistogram) {
long start = System.currentTimeMillis();
double[] newParameters = new double[partition.length];
@Var
double alphaK;
@Var
double currentDigamma;
@Var
double denominator;
@Var
double parametersSum = 0.0;
@Var
int i;
@Var
int k;
for (k = 0; k < partition.length; k++) {
newParameters[k] = magnitude * partition[k];
parametersSum += newParameters[k];
}
for (int iteration=0; iteration<1000; iteration++) {
// Calculate the denominator
denominator = 0;
currentDigamma = 0;
for (i=1; i < lengthHistogram.length; i++) {
currentDigamma += 1 / (parametersSum + i - 1);
denominator += lengthHistogram[i] * currentDigamma;
}
assert(denominator > 0.0);
assert(! Double.isNaN(denominator));
parametersSum = 0.0;
// Calculate the individual parameters
for (k=0; k<partition.length; k++) {
alphaK = newParameters[k];
newParameters[k] = 0.0;
currentDigamma = 0;
int[] histogram = binCountHistograms[k];
if (histogram.length <= 1) { // Since histogram[0] is for 0...
newParameters[k] = 0.000001;
}
else {
for (i=1; i<histogram.length; i++) {
currentDigamma += 1 / (alphaK + i - 1);
newParameters[k] += histogram[i] * currentDigamma;
}
}
if (! (newParameters[k] > 0.0)) {
System.out.println("length of empty array: " + (new int[0]).length);
for (i=0; i<histogram.length; i++) {
System.out.print(histogram[i] + " ");
}
System.out.println();
}
assert(newParameters[k] > 0.0);
assert(! Double.isNaN(newParameters[k]));
newParameters[k] *= alphaK / denominator;
parametersSum += newParameters[k];
}
/*
try {
if (iteration % 25 == 0) {
//System.out.println(distributionToString(parametersSum, newParameters));
//toFile("../newsgroups/direct/iteration" + iteration);
//System.out.println(iteration + ": " + (System.currentTimeMillis() - start));
}
} catch (Exception e) {
System.out.println(e);
}
*/
}
for (k = 0; k < partition.length; k++) {
partition[k] = newParameters[k] / parametersSum;
magnitude = parametersSum;
}
// System.out.println(distributionToString(magnitude, partition));
return System.currentTimeMillis() - start;
}
/** Use the fixed point iteration described by Tom Minka. */
public long learnParametersWithDigamma(Object[] observations) {
int[][] binCounts = new int[partition.length][observations.length];
// System.out.println("got mem: " + (System.currentTimeMillis() - start));
int[] observationLengths = new int[observations.length];
// System.out.println("got lengths: " + (System.currentTimeMillis() - start));
for (int i=0; i < observations.length; i++) {
int[] observation = (int[]) observations[i];
for (int bin=0; bin < partition.length; bin++) {
binCounts[bin][i] = observation[bin];
observationLengths[i] += observation[bin];
}
}
// System.out.println("init: " + (System.currentTimeMillis() - start));
return learnParametersWithDigamma(binCounts, observationLengths);
}
public long learnParametersWithDigamma(int[][] binCounts,
int[] observationLengths) {
long start = System.currentTimeMillis();
double[] newParameters = new double[partition.length];
@Var
double alphaK;
@Var
double denominator;
@Var
double newMagnitude;
@Var
int i;
@Var
int k;
for (int iteration=0; iteration<1000; iteration++) {
newMagnitude = 0;
// Calculate the denominator
denominator = 0;
for (i=0; i<observationLengths.length; i++) {
denominator += digamma(magnitude + observationLengths[i]);
}
denominator -= observationLengths.length * digamma(magnitude);
// Calculate the individual parameters
for (k=0; k<partition.length; k++) {
newParameters[k] = 0;
int[] counts = binCounts[k];
alphaK = magnitude * partition[k];
double digammaAlphaK = digamma(alphaK);
for (i=0; i<counts.length; i++) {
if (counts[i] == 0) {
newParameters[k] += digammaAlphaK;
}
else {
newParameters[k] += digamma(alphaK + counts[i]);
}
}
newParameters[k] -= counts.length * digammaAlphaK;
if (newParameters[k] <= 0) {
newParameters[k] = 0.000001;
}
else {
newParameters[k] *= alphaK / denominator;
}
if (newParameters[k] <= 0) {
System.out.println(newParameters[k] + "\t" + alphaK + "\t" + denominator);
}
assert(newParameters[k] > 0);
assert(! Double.isNaN(newParameters[k]));
newMagnitude += newParameters[k];
// System.out.println("finished dimension " + k);
}
magnitude = newMagnitude;
for (k=0; k<partition.length; k++) {
partition[k] = newParameters[k] / magnitude;
/*
if (k < 20) {
System.out.println(partition[k]+" = "+newParameters[k]+" / "+magnitude);
}
*/
}
/*
try {
if (iteration % 25 == 0) {
toFile("../newsgroups/digamma/iteration" + iteration);
//System.out.println(iteration + ": " + (System.currentTimeMillis() - start));
}
} catch (Exception e) {
System.out.println(e);
}
*/
}
// System.out.println(distributionToString(magnitude, partition));
return System.currentTimeMillis() - start;
}
/** Estimate a dirichlet with the moment matching method
* described by Ronning.
*/
public long learnParametersWithMoments(Object[] observations) {
@Var
long start = System.currentTimeMillis();
@Var
int i;
@Var
int bin;
int[] observationLengths = new int[observations.length];
double[] variances = new double[partition.length];
Arrays.fill(partition, 0.0);
Arrays.fill(observationLengths, 0);
Arrays.fill(variances, 0.0);
// Find E[p_k]'s
for (i=0; i < observations.length; i++) {
int[] observation = (int[]) observations[i];
// Find the sum of counts in each bin
for (bin=0; bin < partition.length; bin++) {
observationLengths[i] += observation[bin];
}
for (bin=0; bin < partition.length; bin++) {
partition[bin] += (double) observation[bin] / observationLengths[i];
}
}
for (bin=0; bin < partition.length; bin++) {
partition[bin] /= observations.length;
}
// Find var[p_k]'s
@Var
double difference;
for (i=0; i < observations.length; i++) {
int[] observation = (int[]) observations[i];
for (bin=0; bin < partition.length; bin++) {