-
Notifications
You must be signed in to change notification settings - Fork 35
/
yahmm.pyx
4499 lines (3621 loc) · 149 KB
/
yahmm.pyx
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
#!/usr/bin/env python2.7
# yahmm.pyx: Yet Another Hidden Markov Model library
# Contact: Jacob Schreiber ( jmschreiber91@gmail.com )
# Adam Novak ( anovak1@ucsc.edu )
"""
For detailed documentation and examples, see the README.
"""
cimport cython
from cython.view cimport array as cvarray
from libc.math cimport log as clog, sqrt as csqrt, exp as cexp
import math, random, itertools as it, sys, bisect
import networkx
import scipy.stats, scipy.sparse, scipy.special
if sys.version_info[0] > 2:
# Set up for Python 3
from functools import reduce
xrange = range
izip = zip
else:
izip = it.izip
import numpy
cimport numpy
from matplotlib import pyplot
# Define some useful constants
DEF NEGINF = float("-inf")
DEF INF = float("inf")
DEF SQRT_2_PI = 2.50662827463
# Useful speed optimized functions
cdef inline double _log ( double x ):
'''
A wrapper for the c log function, by returning negative input if the
input is 0.
'''
return clog( x ) if x > 0 else NEGINF
cdef inline int pair_int_max( int x, int y ):
'''
Calculate the maximum of a pair of two integers. This is
significantly faster than the Python function max().
'''
return x if x > y else y
cdef inline double pair_lse( double x, double y ):
'''
Perform log-sum-exp on a pair of numbers in log space.. This is calculated
as z = log( e**x + e**y ). However, this causes underflow sometimes
when x or y are too negative. A simplification of this is thus
z = x + log( e**(y-x) + 1 ), where x is the greater number. If either of
the inputs are infinity, return infinity, and if either of the inputs
are negative infinity, then simply return the other input.
'''
if x == INF or y == INF:
return INF
if x == NEGINF:
return y
if y == NEGINF:
return x
if x > y:
return x + clog( cexp( y-x ) + 1 )
return y + clog( cexp( x-y ) + 1 )
# Useful python-based array-intended operations
def log(value):
"""
Return the natural log of the given value, or - infinity if the value is 0.
Can handle both scalar floats and numpy arrays.
"""
if isinstance( value, numpy.ndarray ):
to_return = numpy.zeros(( value.shape ))
to_return[ value > 0 ] = numpy.log( value[ value > 0 ] )
to_return[ value == 0 ] = NEGINF
return to_return
return _log( value )
def exp(value):
"""
Return e^value, or 0 if the value is - infinity.
"""
return numpy.exp(value)
def log_probability( model, samples ):
'''
Return the log probability of samples given a model.
'''
return reduce( lambda x, y: pair_lse( x, y ),
map( model.log_probability, samples ) )
cdef class Distribution(object):
"""
Represents a probability distribution over whatever the HMM you're making is
supposed to emit. Ought to be subclassed and have log_probability(),
sample(), and from_sample() overridden. Distribution.name should be
overridden and replaced with a unique name for the distribution type. The
distribution should be registered by calling register() on the derived
class, so that Distribution.read() can read it. Any distribution parameters
need to be floats stored in self.parameters, so they will be properly
written by write().
"""
cdef public str name
cdef public list parameters, summaries
cdef public bint frozen
def __init__( self ):
"""
Make a new Distribution with the given parameters. All parameters must
be floats.
Storing parameters in self.parameters instead of e.g. self.mean on the
one hand makes distribution code ugly, because we don't get to call them
self.mean. On the other hand, it means we don't have to override the
serialization code for every derived class.
"""
self.name = "Distribution"
self.frozen = False
self.parameters = []
self.summaries = []
def __str__( self ):
"""
Represent this distribution in a human-readable form.
"""
parameters = [ list(p) if isinstance(p, numpy.ndarray) else p
for p in self.parameters ]
return "{}({})".format(self.name, ", ".join(map(str, parameters)))
def __repr__( self ):
"""
Represent this distribution in the same format as string.
"""
return self.__str__()
def copy( self ):
"""
Return a copy of this distribution, untied.
"""
return self.__class__( *self.parameters )
def freeze( self ):
"""
Freeze the distribution, preventing training from changing any of the
parameters of the distribution.
"""
self.frozen = True
def thaw( self ):
"""
Thaw the distribution, allowing training to change the parameters of
the distribution again.
"""
self.frozen = False
def log_probability( self, symbol ):
"""
Return the log probability of the given symbol under this distribution.
"""
raise NotImplementedError
def sample( self ):
"""
Return a random item sampled from this distribution.
"""
raise NotImplementedError
def from_sample( self, items, weights=None ):
"""
Set the parameters of this Distribution to maximize the likelihood of
the given sample. Items holds some sort of sequence. If weights is
specified, it holds a sequence of value to weight each item by.
"""
if self.frozen == True:
return
raise NotImplementedError
def summarize( self, items, weights=None ):
"""
Summarize the incoming items into a summary statistic to be used to
update the parameters upon usage of the `from_summaries` method. By
default, this will simply store the items and weights into a large
sample, and call the `from_sample` method.
"""
# If no previously stored summaries, just store the incoming data
if len( self.summaries ) == 0:
self.summaries = [ items, weights ]
# Otherwise, append the items and weights
else:
prior_items, prior_weights = self.summaries
items = numpy.concatenate( [prior_items, items] )
# If even one summary lacks weights, then weights can't be assigned
# to any of the points.
if weights is not None:
weights = numpy.concatenate( [prior_weights, weights] )
self.summaries = [ items, weights ]
def from_summaries( self ):
"""
Update the parameters of the distribution based on the summaries stored
previously.
"""
# If the distribution is frozen, don't bother with any calculation
if self.frozen == True:
return
self.from_sample( *self.summaries )
self.summaries = []
cdef class UniformDistribution( Distribution ):
"""
A uniform distribution between two values.
"""
def __init__( self, start, end, frozen=False ):
"""
Make a new Uniform distribution over floats between start and end,
inclusive. Start and end must not be equal.
"""
# Store the parameters
self.parameters = [start, end]
self.summaries = []
self.name = "UniformDistribution"
self.frozen = frozen
def log_probability( self, symbol ):
"""
What's the probability of the given float under this distribution?
"""
return self._log_probability( self.parameters[0], self.parameters[1], symbol )
cdef double _log_probability( self, double a, double b, double symbol ):
if symbol == a and symbol == b:
return 0
if symbol >= a and symbol <= b:
return _log( 1.0 / ( b - a ) )
return NEGINF
def sample( self ):
"""
Sample from this uniform distribution and return the value sampled.
"""
return random.uniform(self.parameters[0], self.parameters[1])
def from_sample (self, items, weights=None, inertia=0.0 ):
"""
Set the parameters of this Distribution to maximize the likelihood of
the given sample. Items holds some sort of sequence. If weights is
specified, it holds a sequence of value to weight each item by.
"""
# If the distribution is frozen, don't bother with any calculation
if self.frozen == True:
return
# Calculate weights. If none are provided, give uniform weights
if weights is None:
weights = numpy.ones_like( items )
else:
weights = numpy.asarray( weights )
if weights.sum() == 0:
return
if len(items) == 0:
# No sample, so just ignore it and keep our old parameters.
return
# The ML uniform distribution is just min to max. Weights don't matter
# for this.
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
prior_min, prior_max = self.parameters
self.parameters[0] = prior_min*inertia + numpy.min(items)*(1-inertia)
self.parameters[1] = prior_max*inertia + numpy.max(items)*(1-inertia)
def summarize( self, items, weights=None ):
'''
Take in a series of items and their weights and reduce it down to a
summary statistic to be used in training later.
'''
if weights is None:
weights = numpy.ones_like( items )
else:
weights = numpy.asarray( weights )
if weights.sum() == 0:
return
if len( items ) == 0:
# No sample, so just ignore it and keep our own parameters.
return
items = numpy.asarray( items )
# Record the min and max, which are the summary statistics for a
# uniform distribution.
self.summaries.append([ items.min(), items.max() ])
def from_summaries( self, inertia=0.0 ):
'''
Takes in a series of summaries, consisting of the minimum and maximum
of a sample, and determine the global minimum and maximum.
'''
# If the distribution is frozen, don't bother with any calculation
if self.frozen == True:
return
summaries = numpy.asarray( self.summaries )
# Load the prior parameters
prior_min, prior_max = self.parameters
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
self.parameters = [ prior_min*inertia + summaries[:,0].min()*(1-inertia),
prior_max*inertia + summaries[:,1].max()*(1-inertia) ]
self.summaries = []
cdef class NormalDistribution( Distribution ):
"""
A normal distribution based on a mean and standard deviation.
"""
def __init__( self, mean, std, frozen=False ):
"""
Make a new Normal distribution with the given mean mean and standard
deviation std.
"""
# Store the parameters
self.parameters = [mean, std]
self.summaries = []
self.name = "NormalDistribution"
self.frozen = frozen
def log_probability( self, symbol, epsilon=1E-4 ):
"""
What's the probability of the given float under this distribution?
For distributions with 0 std, epsilon is the distance within which to
consider things equal to the mean.
"""
return self._log_probability( symbol, epsilon )
cdef double _log_probability( self, double symbol, double epsilon ):
"""
Do the actual math here.
"""
cdef double mu = self.parameters[0], sigma = self.parameters[1]
if sigma == 0.0:
if abs( symbol - mu ) < epsilon:
return 0
else:
return NEGINF
return _log( 1.0 / ( sigma * SQRT_2_PI ) ) - ((symbol - mu) ** 2) /\
(2 * sigma ** 2)
def sample( self ):
"""
Sample from this normal distribution and return the value sampled.
"""
# This uses the same parameterization
return random.normalvariate(*self.parameters)
def from_sample( self, items, weights=None, inertia=0.0, min_std=0.01 ):
"""
Set the parameters of this Distribution to maximize the likelihood of
the given sample. Items holds some sort of sequence. If weights is
specified, it holds a sequence of value to weight each item by.
min_std specifieds a lower limit on the learned standard deviation.
"""
# If the distribution is frozen, don't bother with any calculation
if len(items) == 0 or self.frozen == True:
# No sample, so just ignore it and keep our old parameters.
return
# Make it be a numpy array
items = numpy.asarray(items)
if weights is None:
# Weight everything 1 if no weights specified
weights = numpy.ones_like(items)
else:
# Force whatever we have to be a Numpy array
weights = numpy.asarray(weights)
if weights.sum() == 0:
# Since negative weights are banned, we must have no data.
# Don't change the parameters at all.
return
# The ML uniform distribution is just sample mean and sample std.
# But we have to weight them. average does weighted mean for us, but
# weighted std requires a trick from Stack Overflow.
# http://stackoverflow.com/a/2415343/402891
# Take the mean
mean = numpy.average(items, weights=weights)
if len(weights[weights != 0]) > 1:
# We want to do the std too, but only if more than one thing has a
# nonzero weight
# First find the variance
variance = (numpy.dot(items ** 2 - mean ** 2, weights) /
weights.sum())
if variance >= 0:
std = csqrt(variance)
else:
# May have a small negative variance on accident. Ignore and set
# to 0.
std = 0
else:
# Only one data point, can't update std
std = self.parameters[1]
# Enforce min std
std = max( numpy.array([std, min_std]) )
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
prior_mean, prior_std = self.parameters
self.parameters = [ prior_mean*inertia + mean*(1-inertia),
prior_std*inertia + std*(1-inertia) ]
def summarize( self, items, weights=None ):
'''
Take in a series of items and their weights and reduce it down to a
summary statistic to be used in training later.
'''
items = numpy.asarray( items )
# Calculate weights. If none are provided, give uniform weights
if weights is None:
weights = numpy.ones_like( items )
else:
weights = numpy.asarray( weights )
if weights.sum() == 0:
return
# Save the mean and variance, the summary statistics for a normal
# distribution.
mean = numpy.average( items, weights=weights )
variance = numpy.dot( items**2 - mean**2, weights ) / weights.sum()
# Append the mean, variance, and sum of the weights to give the weights
# of these statistics.
self.summaries.append( [ mean, variance, weights.sum() ] )
def from_summaries( self, inertia=0.0, min_std=0.01 ):
'''
Takes in a series of summaries, represented as a mean, a variance, and
a weight, and updates the underlying distribution. Notes on how to do
this for a Gaussian distribution were taken from here:
http://math.stackexchange.com/questions/453113/how-to-merge-two-gaussians
'''
# If no summaries stored or the summary is frozen, don't do anything.
if len( self.summaries ) == 0 or self.frozen == True:
return
summaries = numpy.asarray( self.summaries )
# Calculate the new mean and variance.
mean = numpy.average( summaries[:,0], weights=summaries[:,2] )
variance = numpy.sum( [(v+m**2)*w for m, v, w in summaries] ) \
/ summaries[:,2].sum() - mean**2
if variance >= 0:
std = csqrt(variance)
else:
std = 0
std = max( min_std, std )
# Get the previous parameters.
prior_mean, prior_std = self.parameters
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
self.parameters = [ prior_mean*inertia + mean*(1-inertia),
prior_std*inertia + std*(1-inertia) ]
self.summaries = []
cdef class LogNormalDistribution( Distribution ):
"""
Represents a lognormal distribution over non-negative floats.
"""
def __init__( self, mu, sigma, frozen=False ):
"""
Make a new lognormal distribution. The parameters are the mu and sigma
of the normal distribution, which is the the exponential of the log
normal distribution.
"""
self.parameters = [ mu, sigma ]
self.summaries = []
self.name = "LogNormalDistribution"
self.frozen = frozen
def log_probability( self, symbol ):
"""
What's the probability of the given float under this distribution?
"""
return self._log_probability( symbol )
cdef double _log_probability( self, symbol ):
"""
Actually perform the calculations here, in the Cython-optimized
function.
"""
mu, sigma = self.parameters
return -clog( symbol * sigma * SQRT_2_PI ) \
- 0.5 * ( ( clog( symbol ) - mu ) / sigma ) ** 2
def sample( self ):
"""
Return a sample from this distribution.
"""
return numpy.random.lognormal( *self.parameters )
def from_sample( self, items, weights=None, inertia=0.0, min_std=0.01 ):
"""
Set the parameters of this distribution to maximize the likelihood of
the given samples. Items hold some sort of sequence over floats. If
weights is specified, hold a sequence of values to weight each item by.
"""
# If the distribution is frozen, don't bother with any calculation
if len(items) == 0 or self.frozen == True:
# No sample, so just ignore it and keep our old parameters.
return
# Make it be a numpy array
items = numpy.asarray(items)
if weights is None:
# Weight everything 1 if no weights specified
weights = numpy.ones_like(items)
else:
# Force whatever we have to be a Numpy array
weights = numpy.asarray(weights)
if weights.sum() == 0:
# Since negative weights are banned, we must have no data.
# Don't change the parameters at all.
return
# The ML uniform distribution is just the mean of the log of the samples
# and sample std the variance of the log of the samples.
# But we have to weight them. average does weighted mean for us, but
# weighted std requires a trick from Stack Overflow.
# http://stackoverflow.com/a/2415343/402891
# Take the mean
mean = numpy.average( numpy.log(items), weights=weights)
if len(weights[weights != 0]) > 1:
# We want to do the std too, but only if more than one thing has a
# nonzero weight
# First find the variance
variance = ( numpy.dot( numpy.log(items) ** 2 - mean ** 2, weights) /
weights.sum() )
if variance >= 0:
std = csqrt(variance)
else:
# May have a small negative variance on accident. Ignore and set
# to 0.
std = 0
else:
# Only one data point, can't update std
std = self.parameters[1]
# Enforce min std
std = max( numpy.array([std, min_std]) )
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
prior_mean, prior_std = self.parameters
self.parameters = [ prior_mean*inertia + mean*(1-inertia),
prior_std*inertia + std*(1-inertia) ]
def summarize( self, items, weights=None ):
'''
Take in a series of items and their weights and reduce it down to a
summary statistic to be used in training later.
'''
items = numpy.asarray( items )
# If no weights are specified, use uniform weights.
if weights is None:
weights = numpy.ones_like( items )
else:
weights = numpy.asarray( weights )
if weights.sum() == 0:
return
# Calculate the mean and variance, which are the summary statistics
# for a log-normal distribution.
mean = numpy.average( numpy.log(items), weights=weights )
variance = numpy.dot( numpy.log(items)**2 - mean**2, weights ) / weights.sum()
# Save the summary statistics and the weights.
self.summaries.append( [ mean, variance, weights.sum() ] )
def from_summaries( self, inertia=0.0, min_std=0.01 ):
'''
Takes in a series of summaries, represented as a mean, a variance, and
a weight, and updates the underlying distribution. Notes on how to do
this for a Gaussian distribution were taken from here:
http://math.stackexchange.com/questions/453113/how-to-merge-two-gaussians
'''
# If no summaries are provided or the distribution is frozen,
# don't do anything.
if len( self.summaries ) == 0 or self.frozen == True:
return
summaries = numpy.asarray( self.summaries )
# Calculate the mean and variance from the summary statistics.
mean = numpy.average( summaries[:,0], weights=summaries[:,2] )
variance = numpy.sum( [(v+m**2)*w for m, v, w in summaries] ) \
/ summaries[:,2].sum() - mean**2
if variance >= 0:
std = csqrt(variance)
else:
std = 0
std = max( min_std, std )
# Load the previous parameters
prior_mean, prior_std = self.parameters
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
self.parameters = [ prior_mean*inertia + mean*(1-inertia),
prior_std*inertia + std*(1-inertia) ]
self.summaries = []
cdef class ExtremeValueDistribution( Distribution ):
"""
Represent a generalized extreme value distribution over floats.
"""
def __init__( self, mu, sigma, epsilon, frozen=True ):
"""
Make a new extreme value distribution, where mu is the location
parameter, sigma is the scale parameter, and epsilon is the shape
parameter.
"""
self.parameters = [ float(mu), float(sigma), float(epsilon) ]
self.name = "ExtremeValueDistribution"
self.frozen = frozen
def log_probability( self, symbol ):
"""
What's the probability of the given float under this distribution?
"""
return self._log_probability( symbol )
cdef double _log_probability( self, symbol ):
"""
Actually perform the calculations here, in the Cython-optimized
function.
"""
mu, sigma, epsilon = self.parameters
t = ( symbol - mu ) / sigma
if epsilon == 0:
return -clog( sigma ) - t - cexp( -t )
return -clog( sigma ) + clog( 1 + epsilon * t ) * (-1. / epsilon - 1) \
- ( 1 + epsilon * t ) ** ( -1. / epsilon )
cdef class ExponentialDistribution( Distribution ):
"""
Represents an exponential distribution on non-negative floats.
"""
def __init__( self, rate, frozen=False ):
"""
Make a new inverse gamma distribution. The parameter is called "rate"
because lambda is taken.
"""
self.parameters = [rate]
self.summaries = []
self.name = "ExponentialDistribution"
self.frozen = frozen
def log_probability( self, symbol ):
"""
What's the probability of the given float under this distribution?
"""
return _log(self.parameters[0]) - self.parameters[0] * symbol
def sample( self ):
"""
Sample from this exponential distribution and return the value
sampled.
"""
return random.expovariate(*self.parameters)
def from_sample( self, items, weights=None, inertia=0.0 ):
"""
Set the parameters of this Distribution to maximize the likelihood of
the given sample. Items holds some sort of sequence. If weights is
specified, it holds a sequence of value to weight each item by.
"""
# If the distribution is frozen, don't bother with any calculation
if len(items) == 0 or self.frozen == True:
# No sample, so just ignore it and keep our old parameters.
return
# Make it be a numpy array
items = numpy.asarray(items)
if weights is None:
# Weight everything 1 if no weights specified
weights = numpy.ones_like(items)
else:
# Force whatever we have to be a Numpy array
weights = numpy.asarray(weights)
if weights.sum() == 0:
# Since negative weights are banned, we must have no data.
# Don't change the parameters at all.
return
# Parameter MLE = 1/sample mean, easy to weight
# Compute the weighted mean
weighted_mean = numpy.average(items, weights=weights)
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
prior_rate = self.parameters[0]
rate = 1.0 / weighted_mean
self.parameters[0] = prior_rate*inertia + rate*(1-inertia)
def summarize( self, items, weights=None ):
'''
Take in a series of items and their weights and reduce it down to a
summary statistic to be used in training later.
'''
items = numpy.asarray( items )
# Either store the weights, or assign uniform weights to each item
if weights is None:
weights = numpy.ones_like( items )
else:
weights = numpy.asarray( weights )
if weights.sum() == 0:
return
# Calculate the summary statistic, which in this case is the mean.
mean = numpy.average( items, weights=weights )
self.summaries.append( [ mean, weights.sum() ] )
def from_summaries( self, inertia=0.0 ):
'''
Takes in a series of summaries, represented as a mean, a variance, and
a weight, and updates the underlying distribution. Notes on how to do
this for a Gaussian distribution were taken from here:
http://math.stackexchange.com/questions/453113/how-to-merge-two-gaussians
'''
# If no summaries or the distribution is frozen, do nothing.
if len( self.summaries ) == 0 or self.frozen == True:
return
summaries = numpy.asarray( self.summaries )
# Calculate the new parameter from the summary statistics.
mean = numpy.average( summaries[:,0], weights=summaries[:,1] )
# Get the parameters
prior_rate = self.parameters[0]
rate = 1.0 / mean
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
self.parameters[0] = prior_rate*inertia + rate*(1-inertia)
self.summaries = []
cdef class GammaDistribution( Distribution ):
"""
This distribution represents a gamma distribution, parameterized in the
alpha/beta (shape/rate) parameterization. ML estimation for a gamma
distribution, taking into account weights on the data, is nontrivial, and I
was unable to find a good theoretical source for how to do it, so I have
cobbled together a solution here from less-reputable sources.
"""
def __init__( self, alpha, beta, frozen=False ):
"""
Make a new gamma distribution. Alpha is the shape parameter and beta is
the rate parameter.
"""
self.parameters = [alpha, beta]
self.summaries = []
self.name = "GammaDistribution"
self.frozen = frozen
def log_probability( self, symbol ):
"""
What's the probability of the given float under this distribution?
"""
# Gamma pdf from Wikipedia (and stats class)
return (_log(self.parameters[1]) * self.parameters[0] -
math.lgamma(self.parameters[0]) +
_log(symbol) * (self.parameters[0] - 1) -
self.parameters[1] * symbol)
def sample( self ):
"""
Sample from this gamma distribution and return the value sampled.
"""
# We have a handy sample from gamma function. Unfortunately, while we
# use the alpha, beta parameterization, and this function uses the
# alpha, beta parameterization, our alpha/beta are shape/rate, while its
# alpha/beta are shape/scale. So we have to mess with the parameters.
return random.gammavariate(self.parameters[0], 1.0 / self.parameters[1])
def from_sample( self, items, weights=None, inertia=0.0, epsilon=1E-9,
iteration_limit=1000 ):
"""
Set the parameters of this Distribution to maximize the likelihood of
the given sample. Items holds some sort of sequence. If weights is
specified, it holds a sequence of value to weight each item by.
In the Gamma case, likelihood maximization is necesarily numerical, and
the extension to weighted values is not trivially obvious. The algorithm
used here includes a Newton-Raphson step for shape parameter estimation,
and analytical calculation of the rate parameter. The extension to
weights is constructed using vital information found way down at the
bottom of an Experts Exchange page.
Newton-Raphson continues until the change in the parameter is less than
epsilon, or until iteration_limit is reached
See:
http://en.wikipedia.org/wiki/Gamma_distribution
http://www.experts-exchange.com/Other/Math_Science/Q_23943764.html
"""
# If the distribution is frozen, don't bother with any calculation
if len(items) == 0 or self.frozen == True:
# No sample, so just ignore it and keep our old parameters.
return
# Make it be a numpy array
items = numpy.asarray(items)
if weights is None:
# Weight everything 1 if no weights specified
weights = numpy.ones_like(items)
else:
# Force whatever we have to be a Numpy array
weights = numpy.asarray(weights)
if weights.sum() == 0:
# Since negative weights are banned, we must have no data.
# Don't change the parameters at all.
return
# First, do Newton-Raphson for shape parameter.
# Calculate the sufficient statistic s, which is the log of the average
# minus the average log. When computing the average log, we weight
# outside the log function. (In retrospect, this is actually pretty
# obvious.)
statistic = (log(numpy.average(items, weights=weights)) -
numpy.average(log(items), weights=weights))
# Start our Newton-Raphson at what Wikipedia claims a 1969 paper claims
# is a good approximation.
# Really, start with new_shape set, and shape set to be far away from it
shape = float("inf")
if statistic != 0:
# Not going to have a divide by 0 problem here, so use the good
# estimate
new_shape = (3 - statistic + math.sqrt((statistic - 3) ** 2 + 24 *
statistic)) / (12 * statistic)
if statistic == 0 or new_shape <= 0:
# Try the current shape parameter
new_shape = self.parameters[0]
# Count the iterations we take
iteration = 0
# Now do the update loop.
# We need the digamma (gamma derivative over gamma) and trigamma
# (digamma derivative) functions. Luckily, scipy.special.polygamma(0, x)
# is the digamma function (0th derivative of the digamma), and
# scipy.special.polygamma(1, x) is the trigamma function.
while abs(shape - new_shape) > epsilon and iteration < iteration_limit:
shape = new_shape
new_shape = shape - (log(shape) -
scipy.special.polygamma(0, shape) -
statistic) / (1.0 / shape - scipy.special.polygamma(1, shape))
# Don't let shape escape from valid values
if abs(new_shape) == float("inf") or new_shape == 0:
# Hack the shape parameter so we don't stop the loop if we land
# near it.
shape = new_shape
# Re-start at some random place.
new_shape = random.random()
iteration += 1
# Might as well grab the new value
shape = new_shape
# Now our iterative estimation of the shape parameter has converged.
# Calculate the rate parameter
rate = 1.0 / (1.0 / (shape * weights.sum()) * items.dot(weights) )
# Get the previous parameters
prior_shape, prior_rate = self.parameters
# Calculate the new parameters, respecting inertia, with an inertia
# of 0 being completely replacing the parameters, and an inertia of
# 1 being to ignore new training data.
self.parameters = [ prior_shape*inertia + shape*(1-inertia),
prior_rate*inertia + rate*(1-inertia) ]
def summarize( self, items, weights=None ):
"""
Take in a series of items and their weights and reduce it down to a
summary statistic to be used in training later.
"""
if len(items) == 0:
# No sample, so just ignore it and keep our old parameters.