-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
1883 lines (1499 loc) · 63.8 KB
/
models.py
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
"""
Top level classes for the Hawkes process model.
"""
import abc
import copy
import numpy as np
from scipy.special import gammaln
from scipy.optimize import minimize
from pybasicbayes.abstractions import ModelGibbsSampling, ModelMeanField
from pybasicbayes.util.text import progprint_xrange
from pyhawkes.internals.bias import GammaBias
from pyhawkes.internals.weights import SpikeAndSlabGammaWeights, GammaMixtureWeights
from pyhawkes.internals.impulses import DirichletImpulseResponses
from pyhawkes.internals.parents import DiscreteTimeParents
from pyhawkes.internals.network import StochasticBlockModel, StochasticBlockModelFixedSparsity, ErdosRenyiFixedSparsity
from pyhawkes.utils.basis import CosineBasis
# TODO: Add a simple HomogeneousPoissonProcessModel
class DiscreteTimeStandardHawkesModel(object):
"""
Discrete time standard Hawkes process model with support for
regularized (stochastic) gradient descent.
"""
def __init__(self, K, dt=1.0, dt_max=10.0,
B=5, basis=None,
alpha=1.0, beta=1.0,
allow_instantaneous=False,
W_max=None,
allow_self_connections=True):
"""
Initialize a discrete time network Hawkes model with K processes.
:param K: Number of processes
:param dt: Time bin size
:param dt_max:
"""
self.K = K
self.dt = dt
self.dt_max = dt_max
self.allow_self_connections = allow_self_connections
self.W_max = W_max
# Initialize the basis
if basis is None:
self.B = B
self.allow_instantaneous = allow_instantaneous
self.basis = CosineBasis(self.B, self.dt, self.dt_max, norm=True,
allow_instantaneous=allow_instantaneous)
else:
self.basis = basis
self.allow_instantaneous = basis.allow_instantaneous
self.B = basis.B
assert not (self.allow_instantaneous and self.allow_self_connections), \
"Cannot allow instantaneous self connections"
# Save the gamma prior
assert alpha >= 1.0, "Alpha must be greater than 1.0 to ensure log concavity"
self.alpha = alpha
self.beta = beta
# Initialize with sample from Gamma(alpha, beta)
# self.weights = np.random.gamma(self.alpha, 1.0/self.beta, size=(self.K, 1 + self.K*self.B))
# self.weights = self.alpha/self.beta * np.ones((self.K, 1 + self.K*self.B))
self.weights = 1e-3 * np.ones((self.K, 1 + self.K*self.B))
if not self.allow_self_connections:
self._remove_self_weights()
# Initialize the data list to empty
self.data_list = []
def _remove_self_weights(self):
for k in range(self.K):
self.weights[k,1+(k*self.B):1+(k+1)*self.B] = 1e-32
def initialize_with_gibbs_model(self, gibbs_model):
"""
Initialize with a sample from the network Hawkes model
:param W:
:param g:
:return:
"""
assert isinstance(gibbs_model, _DiscreteTimeNetworkHawkesModelBase)
assert gibbs_model.K == self.K
assert gibbs_model.B == self.B
lambda0 = gibbs_model.bias_model.lambda0,
Weff = gibbs_model.weight_model.W_effective
g = gibbs_model.impulse_model.g
for k in range(self.K):
self.weights[k,0] = lambda0[k]
self.weights[k,1:] = (Weff[:,k][:,None] * g[:,k,:]).ravel()
if not self.allow_self_connections:
self._remove_self_weights()
def initialize_to_background_rate(self):
if len(self.data_list) > 0:
N = 0
T = 0
for S,_ in self.data_list:
N += S.sum(axis=0)
T += S.shape[0] * self.dt
lambda0 = N / float(T)
self.weights[:,0] = lambda0
@property
def W(self):
WB = self.weights[:,1:].reshape((self.K,self.K, self.B))
# DEBUG
assert WB[0,0,self.B-1] == self.weights[0,1+self.B-1]
assert WB[0,self.K-1,0] == self.weights[0,1+(self.K-1)*self.B]
if self.B > 2:
assert WB[self.K-1,self.K-1,self.B-2] == self.weights[self.K-1,-2]
# Weight matrix is summed over impulse response functions
WT = WB.sum(axis=2)
# Then we transpose so that the weight matrix is (outgoing x incoming)
W = WT.T
return W
@property
def bias(self):
return self.weights[:,0]
@property
def G(self):
G = self.weights[:,1:].reshape((self.K,self.K, self.B))
# Weight matrix is summed over impulse response functions
W = G.sum(axis=2, keepdims=True)
# Then we transpose so that the weight matrix is (outgoing x incoming)
G /= W
G = np.transpose(G, [1,0,2])
return G
def add_data(self, S, F=None, minibatchsize=None):
"""
Add a data set to the list of observations.
First, filter the data with the impulse response basis,
then instantiate a set of parents for this data set.
:param S: a TxK matrix of of event counts for each time bin
and each process.
"""
assert isinstance(S, np.ndarray) and S.ndim == 2 and S.shape[1] == self.K \
and np.amin(S) >= 0 and S.dtype == np.int, \
"Data must be a TxK array of event counts"
T = S.shape[0]
if F is None:
# Filter the data into a TxKxB array
Ftens = self.basis.convolve_with_basis(S)
# Flatten this into a T x (KxB) matrix
# [F00, F01, F02, F10, F11, ... F(K-1)0, F(K-1)(B-1)]
F = Ftens.reshape((T, self.K * self.B))
assert np.allclose(F[:,0], Ftens[:,0,0])
if self.B > 1:
assert np.allclose(F[:,1], Ftens[:,0,1])
if self.K > 1:
assert np.allclose(F[:,self.B], Ftens[:,1,0])
# Prepend a column of ones
F = np.concatenate((np.ones((T,1)), F), axis=1)
# If minibatchsize is not None, add minibatches of data
if minibatchsize is not None:
for offset in np.arange(T, step=minibatchsize):
end = min(offset+minibatchsize, T)
S_mb = S[offset:end,:]
F_mb = F[offset:end,:]
# Add minibatch to the data list
self.data_list.append((S_mb, F_mb))
else:
self.data_list.append((S,F))
def check_stability(self):
"""
Check that the weight matrix is stable
:return:
"""
# Compute the effective weight matrix
W_eff = self.weights.sum(axis=2)
eigs = np.linalg.eigvals(W_eff)
maxeig = np.amax(np.real(eigs))
# print "Max eigenvalue: ", maxeig
if maxeig < 1.0:
return True
else:
return False
def copy_sample(self):
"""
Return a copy of the parameters of the model
:return: The parameters of the model (A,W,\lambda_0, \beta)
"""
# return copy.deepcopy(self.get_parameters())
# Shallow copy the data
data_list = copy.copy(self.data_list)
self.data_list = []
# Make a deep copy without the data
model_copy = copy.deepcopy(self)
# Reset the data and return the data-less copy
self.data_list = data_list
return model_copy
def compute_rate(self, index=None, ks=None):
"""
Compute the rate of the k-th process.
:param index: Which dataset to comput the rate of
:param k: Which process to compute the rate of
:return:
"""
if index is None:
index = 0
_,F = self.data_list[index]
if ks is None:
ks = np.arange(self.K)
if isinstance(ks, int):
R = F.dot(self.weights[ks,:])
return R
elif isinstance(ks, np.ndarray):
Rs = []
for k in ks:
Rs.append(F.dot(self.weights[k,:])[:,None])
return np.concatenate(Rs, axis=1)
else:
raise Exception("ks must be int or array of indices in 0..K-1")
def log_prior(self, ks=None):
"""
Compute the log prior probability of log W
:param ks:
:return:
"""
lp = 0
for k in ks:
# lp += (self.alpha * np.log(self.weights[k,1:])).sum()
# lp += (-self.beta * self.weights[k,1:]).sum()
if self.alpha > 1:
lp += (self.alpha -1) * np.log(self.weights[k,1:]).sum()
lp += (-self.beta * self.weights[k,1:]).sum()
return lp
def log_likelihood(self, indices=None, ks=None):
"""
Compute the log likelihood
:return:
"""
ll = 0
if indices is None:
indices = np.arange(len(self.data_list))
if isinstance(indices, int):
indices = [indices]
for index in indices:
S,F = self.data_list[index]
R = self.compute_rate(index, ks=ks)
if ks is not None:
ll += (S[:,ks] * np.log(R) -R*self.dt).sum()
else:
ll += (S * np.log(R) -R*self.dt).sum()
return ll
def log_posterior(self, indices=None, ks=None):
if ks is None:
ks = np.arange(self.K)
lp = self.log_likelihood(indices, ks)
lp += self.log_prior(ks)
return lp
def heldout_log_likelihood(self, S):
self.add_data(S)
hll = self.log_likelihood(indices=-1)
self.data_list.pop()
return hll
def compute_gradient(self, k, indices=None):
"""
Compute the gradient of the log likelihood with respect
to the log biases and log weights
:param k: Which process to compute gradients for.
If none, return a list of gradients for each process.
"""
grad = np.zeros(1 + self.K * self.B)
if indices is None:
indices = np.arange(len(self.data_list))
# d_W_d_log_W = self._d_W_d_logW(k)
for index in indices:
d_rate_d_W = self._d_rate_d_W(index, k)
# d_rate_d_log_W = d_rate_d_W.dot(d_W_d_log_W)
d_ll_d_rate = self._d_ll_d_rate(index, k)
# d_ll_d_log_W = d_ll_d_rate.dot(d_rate_d_log_W)
d_ll_d_W = d_ll_d_rate.dot(d_rate_d_W)
# grad += d_ll_d_log_W
grad += d_ll_d_W
# Add the prior
# d_log_prior_d_log_W = self._d_log_prior_d_log_W(k)
# grad += d_log_prior_d_log_W
d_log_prior_d_W = self._d_log_prior_d_W(k)
assert np.allclose(d_log_prior_d_W[0], 0.0)
# grad += d_log_prior_d_W.dot(d_W_d_log_W)
grad += d_log_prior_d_W
# Zero out the gradient if
if not self.allow_self_connections:
assert np.allclose(self.weights[k,1+k*self.B:1+(k+1)*self.B], 0.0)
grad[1+k*self.B:1+(k+1)*self.B] = 0
return grad
def _d_ll_d_rate(self, index, k):
S,_ = self.data_list[index]
T = S.shape[0]
rate = self.compute_rate(index, k)
# d/dR S*ln(R) -R*dt
grad = S[:,k] / rate - self.dt * np.ones(T)
return grad
def _d_rate_d_W(self, index, k):
_,F = self.data_list[index]
grad = F
return grad
def _d_W_d_logW(self, k):
"""
Let u = logW
d{e^u}/du = e^u
= W
"""
return np.diag(self.weights[k,:])
def _d_log_prior_d_log_W(self, k):
"""
Use a gamma prior on W (it is log concave for alpha >= 1)
By change of variables this implies that
LN p(LN W) = const + \alpha LN W - \beta W
and
d/d (LN W) (LN p(LN W)) = \alpha - \beta W
TODO: Is this still concave? It is a concave function of W,
but what about of LN W? As a function of u=LN(W) it is
linear plus a -\beta e^u which is concave for beta > 0,
so yes, it is still concave.
So why does BFGS not converge monotonically?
"""
d_log_prior_d_log_W = np.zeros_like(self.weights[k,:])
d_log_prior_d_log_W[1:] = self.alpha - self.beta * self.weights[k,1:]
return d_log_prior_d_log_W
def _d_log_prior_d_W(self, k):
"""
Use a gamma prior on W (it is log concave for alpha >= 1)
and
LN p(W) = (\alpha-1)LN W - \beta W
d/dW LN p(W)) = (\alpha -1)/W - \beta
"""
d_log_prior_d_W = np.zeros_like(self.weights[k,:])
if self.alpha > 1.0:
d_log_prior_d_W[1:] += (self.alpha-1) / self.weights[k,1:]
d_log_prior_d_W[1:] += -self.beta
return d_log_prior_d_W
def fit_with_bfgs_logspace(self):
"""
Fit the model with BFGS
"""
# If W_max is specified, set this as a bound
if self.W_max is not None:
bnds = [(None, None)] + [(None, np.log(self.W_max))] * (self.K * self.B)
else:
bnds = None
def objective(x, k):
self.weights[k,:] = np.exp(x)
self.weights[k,:] = np.nan_to_num(self.weights[k,:])
return np.nan_to_num(-self.log_posterior(ks=np.array([k])))
def gradient(x, k):
self.weights[k,:] = np.exp(x)
self.weights[k,:] = np.nan_to_num(self.weights[k,:])
dll_dW = -self.compute_gradient(k)
d_W_d_log_W = self._d_W_d_logW(k)
return np.nan_to_num(dll_dW.dot(d_W_d_log_W))
itr = [0]
def callback(x):
if itr[0] % 10 == 0:
print("Iteration: %03d\t LP: %.1f" % (itr[0], self.log_posterior()))
itr[0] = itr[0] + 1
for k in range(self.K):
print("Optimizing process ", k)
itr[0] = 0
x0 = np.log(self.weights[k,:])
res = minimize(objective, # Objective function
x0, # Initial value
jac=gradient, # Gradient of the objective
args=(k,), # Arguments to the objective and gradient fns
bounds=bnds, # Bounds on x
callback=callback)
self.weights[k,:] = np.exp(res.x)
def fit_with_bfgs(self):
"""
Fit the model with BFGS
"""
# If W_max is specified, set this as a bound
if self.W_max is not None:
bnds = [(1e-16, None)] + [(1e-16, self.W_max)] * (self.K * self.B)
else:
bnds = [(1e-16, None)] * (1 + self.K * self.B)
def objective(x, k):
self.weights[k,:] = x
return np.nan_to_num(-self.log_posterior(ks=np.array([k])))
def gradient(x, k):
self.weights[k,:] = x
return np.nan_to_num(-self.compute_gradient(k))
itr = [0]
def callback(x):
if itr[0] % 10 == 0:
print("Iteration: %03d\t LP: %.1f" % (itr[0], self.log_posterior()))
itr[0] = itr[0] + 1
for k in range(self.K):
print("Optimizing process ", k)
itr[0] = 0
x0 = self.weights[k,:]
res = minimize(objective, # Objective function
x0, # Initial value
jac=gradient, # Gradient of the objective
args=(k,), # Arguments to the objective and gradient fns
bounds=bnds, # Bounds on x
callback=callback)
self.weights[k,:] = res.x
def gradient_descent_step(self, stepsz=0.01):
grad = np.zeros((self.K, 1+self.K*self.B))
# Compute gradient and take a step for each process
for k in range(self.K):
d_W_d_log_W = self._d_W_d_logW(k)
grad[k,:] = self.compute_gradient(k).dot(d_W_d_log_W)
self.weights[k,:] = np.exp(np.log(self.weights[k,:]) + stepsz * grad[k,:])
# Compute the current objective
ll = self.log_likelihood()
return self.weights, ll, grad
def sgd_step(self, prev_velocity, learning_rate, momentum):
"""
Take a step of the stochastic gradient descent algorithm
"""
if prev_velocity is None:
prev_velocity = np.zeros((self.K, 1+self.K*self.B))
# Compute this gradient row by row
grad = np.zeros((self.K, 1+self.K*self.B))
velocity = np.zeros((self.K, 1+self.K*self.B))
# Get a minibatch
mb = np.random.choice(len(self.data_list))
T = self.data_list[mb][0].shape[0]
# Compute gradient and take a step for each process
for k in range(self.K):
d_W_d_log_W = self._d_W_d_logW(k)
grad[k,:] = self.compute_gradient(k, indices=[mb]).dot(d_W_d_log_W) / T
velocity[k,:] = momentum * prev_velocity[k,:] + learning_rate * grad[k,:]
# Gradient steps are taken in log weight space
log_weightsk = np.log(self.weights[k,:]) + velocity[k,:]
# The true weights are stored
self.weights[k,:] = np.exp(log_weightsk)
# Compute the current objective
ll = self.log_likelihood()
return self.weights, ll, velocity
class _DiscreteTimeNetworkHawkesModelBase(object):
"""
Discrete time network Hawkes process model with support for
Gibbs sampling inference, variational inference (TODO), and
stochastic variational inference (TODO).
"""
__metaclass__ = abc.ABCMeta
# Define the model components and their default hyperparameters
_basis_class = CosineBasis
_default_basis_hypers = {'norm': True, 'allow_instantaneous': False}
_bkgd_class = GammaBias
_default_bkgd_hypers = {'alpha': 1.0, 'beta': 10.0}
_impulse_class = DirichletImpulseResponses
_default_impulse_hypers = {'gamma' : 1.0}
# Weight, parent, and network class must be specified by subclasses
_weight_class = None
_default_weight_hypers = {}
_parent_class = DiscreteTimeParents
_network_class = None
_default_network_hypers = {}
def __init__(self, K, dt=1.0, dt_max=10.0, B=5,
basis=None, basis_hypers={},
bkgd=None, bkgd_hypers={},
impulse=None, impulse_hypers={},
weights=None, weight_hypers={},
network=None, network_hypers={}):
"""
Initialize a discrete time network Hawkes model with K processes.
:param K: Number of processes
"""
self.K = K
self.dt = dt
self.dt_max = dt_max
self.B = B
# Initialize the data list to empty
self.data_list = []
# Initialize the basis
if basis is not None:
# assert basis.B == B
self.basis = basis
self.B = basis.B
else:
# Use the given basis hyperparameters
self.basis_hypers = copy.deepcopy(self._default_basis_hypers)
self.basis_hypers.update(basis_hypers)
self.basis = self._basis_class(self.B, self.dt, self.dt_max,
**self.basis_hypers)
# Initialize the bias
if bkgd is not None:
self.bias_model = bkgd
else:
# Use the given basis hyperparameters
self.bkgd_hypers = copy.deepcopy(self._default_bkgd_hypers)
self.bkgd_hypers.update(bkgd_hypers)
self.bias_model = self._bkgd_class(self, **self.bkgd_hypers)
# Initialize the impulse response model
if impulse is not None:
assert impulse.B == self.B
assert impulse.K == self.K
self.impulse_model = impulse
else:
# Use the given basis hyperparameters
self.impulse_hypers = copy.deepcopy(self._default_impulse_hypers)
self.impulse_hypers.update(impulse_hypers)
self.impulse_model = self._impulse_class(self, **self.impulse_hypers)
# Initialize the network model
if network is not None:
assert network.K == self.K
self.network = network
else:
# Use the given network hyperparameters
self.network_hypers = copy.deepcopy(self._default_network_hypers)
self.network_hypers.update(network_hypers)
self.network = self._network_class(K=self.K,
**self.network_hypers)
# Check that the model doesn't allow instantaneous self connections
assert not (self.basis.allow_instantaneous and
self.network.allow_self_connections), \
"Cannot allow instantaneous self connections"
# Initialize the weight model
if weights is not None:
assert weights.K == self.K
self.weight_model = weights
else:
self.weight_hypers = copy.deepcopy(self._default_weight_hypers)
self.weight_hypers.update(weight_hypers)
self.weight_model = self._weight_class(self, **self.weight_hypers)
# Expose basic variables
@property
def A(self):
return self.weight_model.A
@property
def W(self):
return self.weight_model.W
@property
def W_effective(self):
return self.weight_model.W_effective
@property
def lambda0(self):
return self.bias_model.lambda0
@property
def impulses(self):
return self.impulse_model.impulses
def initialize_with_standard_model(self, standard_model=None):
"""
Initialize with a standard Hawkes model. Typically this will have
been fit by gradient descent or BFGS, and we just want to copy
over the parameters to get a good starting point for MCMC or VB.
:param W:
:param g:
:return:
"""
if standard_model is None:
standard_model = DiscreteTimeStandardHawkesModel(
K=self.K, dt=self.dt, dt_max=self.dt_max, B=self.B)
for data in self.data_list:
standard_model.add_data(data.S)
standard_model.initialize_to_background_rate()
standard_model.fit_with_bfgs()
else:
assert isinstance(standard_model, DiscreteTimeStandardHawkesModel)
assert standard_model.K == self.K
assert standard_model.B == self.B
lambda0 = standard_model.bias
# Get the connection weights
# Wg = standard_model.weights[:,1:].reshape((self.K, self.K, self.B))
# # Permute to out x in x basis
# Wg = np.transpose(Wg, [1,0,2])
# # Sum to get the total weight
# W = Wg.sum(axis=2) + 1e-6
W = standard_model.W + 1e-6
# The impulse responses are normalized weights
# Clip g to make sure it is stable for MF updates
g = standard_model.G
g = np.clip(g, 1e-2, np.inf)
g = g / g.sum(axis=2)[:,:,None]
# We need to decide how to set A.
# The simplest is to initialize it to all ones, but
# A = np.ones((self.K, self.K))
# Alternatively, we can start with a sparse matrix
# of only strong connections. What sparsity? How about the
# mean under the network model
# sparsity = self.network.tau1 / (self.network.tau0 + self.network.tau1)
sparsity = np.mean(self.network.p)
A = W > np.percentile(W, (1.0 - sparsity) * 100)
# Set the model parameters
self.bias_model.lambda0 = lambda0.copy('C')
self.weight_model.A = A.copy('C')
self.weight_model.W = W.copy('C')
self.impulse_model.g = g.copy('C')
def add_data(self, S, F=None, minibatchsize=None):
"""
Add a data set to the list of observations.
First, filter the data with the impulse response basis,
then instantiate a set of parents for this data set.
:param S: a TxK matrix of of event counts for each time bin
and each process.
"""
assert isinstance(S, np.ndarray) and S.ndim == 2 and S.shape[1] == self.K \
and np.amin(S) >= 0 and S.dtype == np.int, \
"Data must be a TxK array of event counts"
T = S.shape[0]
# Filter the data into a TxKxB array
if F is not None:
assert isinstance(F, np.ndarray) and F.shape == (T, self.K, self.B), \
"F must be a filtered event count matrix"
else:
F = self.basis.convolve_with_basis(S)
# If minibatchsize is not None, add minibatches of data
if minibatchsize is not None:
for offset in np.arange(T, step=minibatchsize):
end = min(offset+minibatchsize, T)
T_mb = end - offset
S_mb = S[offset:end,:]
F_mb = F[offset:end,:]
# Instantiate parent object for this minibatch
parents = self._parent_class(self, T_mb, S_mb, F_mb)
# Add minibatch to the data list
self.data_list.append(parents)
else:
# Instantiate corresponding parent object
parents = self._parent_class(self, T, S, F)
# Add to the data list
self.data_list.append(parents)
def check_stability(self, verbose=False):
"""
Check that the weight matrix is stable
:return:
"""
if self.K < 100:
eigs = np.linalg.eigvals(self.weight_model.W_effective)
maxeig = np.amax(np.real(eigs))
else:
from scipy.sparse.linalg import eigs
maxeig = eigs(self.weight_model.W_effective, k=1)[0]
if verbose:
print("Max eigenvalue: ", maxeig)
return maxeig < 1.0
def copy_sample(self):
"""
Return a copy of the parameters of the model
:return: The parameters of the model (A,W,\lambda_0, \beta)
"""
# return copy.deepcopy(self.get_parameters())
# Shallow copy the data
data_list = copy.copy(self.data_list)
self.data_list = []
# Make a deep copy without the data
model_copy = copy.deepcopy(self)
# Reset the data and return the data-less copy
self.data_list = data_list
return model_copy
def generate(self, keep=True, T=100, print_interval=25, verbose=False):
"""
Generate a new data set with the sampled parameters
:param keep: If True, add the generated data to the data list.
:param T: Number of time bins to simulate.
:return: A TxK
"""
assert isinstance(T, int), "T must be an integer number of time bins"
# Test stability
self.check_stability()
# Initialize the output
S = np.zeros((T, self.K))
# Precompute the impulse responses (LxKxK array)
G = np.tensordot(self.basis.basis, self.impulse_model.g, axes=([1], [2]))
L = self.basis.L
assert G.shape == (L,self.K, self.K)
H = self.weight_model.W_effective[None,:,:] * G
# Transpose H so that it is faster for tensor mult
H = np.transpose(H, axes=[0,2,1])
# Compute the rate matrix R
R = np.zeros((T+L, self.K))
# Add the background rate
R += self.bias_model.lambda0[None,:]
iterator = progprint_xrange(T, perline=print_interval) if verbose else range(T)
# Iterate over time bins
for t in iterator:
# Sample a Poisson number of events for each process
S[t,:] = np.random.poisson(R[t,:] * self.dt)
# Compute change in rate via tensor product
dR = np.tensordot( H, S[t,:], axes=([2, 0]))
R[t:t+L,:] += dR
# For each sampled event, add a weighted impulse response to the rate
# for k in xrange(self.K):
# if S[t,k] > 0:
# R[t+1:t+L+1,:] += S[t,k] * H[:,k,:]
# Check Spike limit
if np.any(S[t,:] >= 1000):
print("More than 1000 events in one time bin!")
import pdb; pdb.set_trace()
# Only keep the first T time bins
S = S[:T,:].astype(np.int)
R = R[:T,:]
if keep:
# Xs = [X[:T,:] for X in Xs]
# data = np.hstack(Xs + [S])
self.add_data(S)
return S, R
def get_parameters(self):
"""
Get a copy of the parameters of the model
:return:
"""
return self.weight_model.A, \
self.weight_model.W, \
self.impulse_model.g, \
self.bias_model.lambda0, \
self.network.p, \
self.network.v
def set_parameters(self, params):
"""
Set the parameters of the model
:param params:
:return:
"""
A, W, beta, lambda0, c, p, v, m = params
K, B, = self.K, self.basis.B
assert isinstance(A, np.ndarray) and A.shape == (K,K), \
"A must be a KxK adjacency matrix"
assert isinstance(W, np.ndarray) and W.shape == (K,K) \
and np.amin(W) >= 0, \
"W must be a KxK weight matrix"
assert isinstance(beta, np.ndarray) and beta.shape == (K,K,B) and \
np.allclose(beta.sum(axis=2), 1.0), \
"beta must be a KxKxB impulse response array"
assert isinstance(lambda0, np.ndarray) and lambda0.shape == (K,) \
and np.amin(lambda0) >=0, \
"lambda0 must be a K-vector of background rates"
self.weight_model.A = A
self.weight_model.W = W
self.impulse_model.g = beta
self.bias_model.lambda0 = lambda0
self.network.c = c
self.network.p = p
self.network.v = v
self.network.m = m
def compute_rate(self, index=0, proc=None, S=None, F=None):
"""
Compute the rate function for a given data set
:param index: An integer specifying which dataset (if S is None)
:param S: TxK array of event counts for which we would like to
compute the model's rate
:return: TxK array of rates
"""
# TODO: Write a Cython function to evaluate this
if S is not None:
assert isinstance(S, np.ndarray) and S.ndim == 2, "S must be a TxK array."
T,K = S.shape
# Filter the data into a TxKxB array
if F is not None:
assert F.shape == (T,K, self.B)
else:
F = self.basis.convolve_with_basis(S)
else:
assert len(self.data_list) > index, "Dataset %d does not exist!" % index
data = self.data_list[index]
T,K,S,F = data.T, data.K, data.S, data.F
if proc is None:
# Compute the rate
R = np.zeros((T,K))
# Background rate
R += self.bias_model.lambda0[None,:]
# Compute the sum of weighted sum of impulse responses
H = self.weight_model.W_effective[:,:,None] * \
self.impulse_model.g
H = np.transpose(H, [2,0,1])
for k2 in range(self.K):
R[:,k2] += np.tensordot(F, H[:,:,k2], axes=([2,1], [0,1]))
return R
else:
assert isinstance(proc, int) and proc < self.K, "Proc must be an int"
# Compute the rate
R = np.zeros((T,))
# Background rate
R += self.bias_model.lambda0[proc]
# Compute the sum of weighted sum of impulse responses
H = self.weight_model.W_effective[:,proc,None] * \
self.impulse_model.g[:,proc,:]
R += np.tensordot(F, H, axes=([1,2], [0,1]))
return R
def _poisson_log_likelihood(self, S, R):
"""
Compute the log likelihood of a Poisson matrix with rates R
:param S: Count matrix
:param R: Rate matrix
:return: log likelihood
"""
return (S * np.log(R) - R*self.dt).sum()
def heldout_log_likelihood(self, S, F=None):
"""
Compute the held out log likelihood of a data matrix S.
:param S: TxK matrix of event counts
:return: log likelihood of those counts under the current model
"""
R = self.compute_rate(S=S, F=F)
return self._poisson_log_likelihood(S, R)
# def heldout_log_likelihood(self, S, F=None):
# self.add_data(S, F=F)
# hll = self.log_likelihood(indices=-1)
# self.data_list.pop()
# return hll
def log_prior(self):
# Get the parameter priors
lp = 0
# lp += self.bias_model.log_probability()
lp += self.weight_model.log_probability()
# lp += self.impulse_model.log_probability()
# lp += self.network.log_probability()
return lp
def log_likelihood(self, indices=None):
"""
Compute the joint log probability of the data and the parameters
:return:
"""
ll = 0
if indices is None: