-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsurvival.py
More file actions
3746 lines (3162 loc) · 163 KB
/
survival.py
File metadata and controls
3746 lines (3162 loc) · 163 KB
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
import torch
import torch.nn as nn
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
from torch.autograd import Function
from scipy.integrate import dblquad
from nde import NDE
class PhiInv(nn.Module):
def __init__(self, phi):
super(PhiInv, self).__init__()
self.phi = phi
def forward(self, y, max_iter=400, tol=1e-10):
with torch.no_grad():
"""
# We will only run newton's method on entries which do not have
# a manual inverse defined (via .inverse)
inverse = self.phi.inverse(y)
assert inverse.shape == y.shape
no_inverse_indices = torch.isnan(inverse)
# print(no_inverse_indices)
# print(y[no_inverse_indices].shape)
t_ = newton_root(
self.phi, y[no_inverse_indices], max_iter=max_iter, tol=tol,
t0=torch.ones_like(y[no_inverse_indices])*1e-10)
inverse[no_inverse_indices] = t_
t = inverse
"""
t = newton_root(self.phi, y, max_iter=max_iter, tol=tol)
topt = t.clone().detach().requires_grad_(True)
f_topt = self.phi(topt)
return self.FastInverse.apply(y, topt, f_topt, self.phi)
class FastInverse(Function):
'''
Fast inverse function. To avoid running the optimization
procedure (e.g., Newton's) repeatedly, we pass in the value
of the inverse (obtained from the forward pass) manually.
In the backward pass, we provide gradients w.r.t (i) `y`, and
(ii) `w`, which are any parameters contained in PhiInv.phi. The
latter is implicitly given by furnishing derivatives w.r.t. f_topt,
i.e., the function evaluated (with the current `w`) on topt. Note
that this should contain *values* approximately equal to y, but
will have the necessary computational graph built up, but detached
from y.
'''
@staticmethod
def forward(ctx, y, topt, f_topt, phi):
ctx.save_for_backward(y, topt, f_topt)
ctx.phi = phi
return topt
@staticmethod
def backward(ctx, grad):
y, topt, f_topt = ctx.saved_tensors
phi = ctx.phi
with torch.enable_grad():
# Call FakeInverse once again, in order to allow for higher
# order derivatives to be taken.
z = PhiInv.FastInverse.apply(y, topt, f_topt, phi)
# Find phi'(z), i.e., take derivatives of phi(z) w.r.t z.
f = phi(z)
dev_z = torch.autograd.grad(f.sum(), z, create_graph=True)[0]
# To understand why this works, refer to the derivations for
# inverses. Note that when taking derivatives w.r.t. `w`, we
# make use of autodiffs automatic application of the chain rule.
# This automatically finds the derivative d/dw[phi(z)] which
# when multiplied by the 3rd returned value gives the derivative
# w.r.t. `w` contained by phi.
return grad/dev_z, None, -grad/dev_z, None
def log_survival(t, shape, scale, risk):
return -(torch.exp(risk + shape*torch.log(t) - shape*torch.log(scale))) # used log transform to avoid numerical issue
def survival(t, shape, scale, risk):
return torch.exp(log_survival(t, shape, scale, risk))
def log_density(t,shape,scale,risk):
log_hazard = risk + shape*torch.log(t) - shape*torch.log(scale )\
+ torch.log(1/t) + torch.log(shape)
return log_hazard + log_survival(t, shape, scale, risk)
#DCSurvival 版本
# newtwon_root is used during phi_inverse
# def newton_root(phi, y, t0=None, max_iter=2000, tol=1e-10, guarded=False):
# '''
# Solve
# f(t) = y
# using the Newton's root finding method.
# Parameters
# ----------
# f: Function which takes in a Tensor t of shape `s` and outputs
# the pointwise evaluation f(t).
# y: Tensor of shape `s`.
# t0: Tensor of shape `s` indicating the initial guess for the root.
# max_iter: Positive integer containing the max. number of iterations.
# tol: Termination criterion for the absolute difference |f(t) - y|.
# By default, this is set to 1e-14,
# beyond which instability could occur when using pytorch `DoubleTensor`.
# guarded: Whether we use guarded Newton's root finding method.
# By default False: too slow and is not necessary most of the time.
# Returns:
# Tensor `t*` of size `s` such that f(t*) ~= y
# '''
# if t0 is None:
# t = torch.zeros_like(y)
# else:
# t = t0.clone().detach()
# s = y.size()
# for it in range(max_iter):
# with torch.enable_grad():
# f_t = phi(t.requires_grad_(True))
# fp_t = torch.autograd.grad(f_t.sum(), t)[0]
# assert not torch.any(torch.isnan(fp_t))
# assert f_t.size() == s
# assert fp_t.size() == s
# g_t = f_t - y
# # Terminate algorithm when all errors are sufficiently small.
# if (torch.abs(g_t) < tol).all():
# break
# if not guarded:
# t = t - g_t / fp_t
# else:
# step_size = torch.ones_like(t)
# for num_guarded_steps in range(2000):
# t_candidate = t - step_size * g_t / fp_t
# f_t_candidate = phi(t_candidate.requires_grad_(True))
# g_candidate = f_t_candidate - y
# overstepped_indices = torch.abs(g_candidate) > torch.abs(g_t)
# if not overstepped_indices.any():
# t = t_candidate
# print(num_guarded_steps)
# break
# else:
# step_size[overstepped_indices] /= 2.
# assert torch.abs(g_t).max() < tol, \
# "t=%s, f(t)-y=%s, y=%s, iter=%s, max dev:%s" % (t, g_t, y, it, g_t.max())
# assert t.size() == s
# return t
###Gen-AC版本
def newton_root(phi, y, t0=None, max_iter=200, tol=1e-10):
'''
Solve
f(t) = y
using the Newton's root finding method.
Parameters
----------
f: Function which takes in a Tensor t of shape `s` and outputs
the pointwise evaluation f(t).
y: Tensor of shape `s`.
t0: Tensor of shape `s` indicating the initial guess for the root.
max_iter: Positive integer containing the max. number of iterations.
tol: Termination criterion for the absolute difference |f(t) - y|.
By default, this is set to 1e-14,
beyond which instability could occur when using pytorch `DoubleTensor`.
Returns:
Tensor `t*` of size `s` such that f(t*) ~= y
'''
if t0 is None:
t = torch.zeros_like(y) # why not 0.5?
else:
t = t0.detach().clone()
s = y.size()
for it in range(max_iter):
if hasattr(phi,'ndiff'):
f_t = phi(t)
fp_t = phi.ndiff(t,ndiff=1)
else:
with torch.enable_grad():
f_t = phi(t.requires_grad_(True))
fp_t = torch.autograd.grad(f_t.sum(), t)[0]
assert not torch.any(torch.isnan(fp_t))
assert f_t.size() == s
assert fp_t.size() == s
g_t = f_t - y
# Terminate algorithm when all errors are sufficiently small.
if (torch.abs(g_t) < tol).all():
break
t = t - g_t / fp_t
# error if termination criterion (tol) not met.
assert torch.abs(g_t).max() < tol, "t=%s, f(t)-y=%s, y=%s, iter=%s, max dev:%s" % (t, g_t, y, it, g_t.max())
assert t.size() == s
return t
# Only sampling use bisection root
def bisection_root(phi, y, lb=None, ub=None, increasing=True, max_iter=100, tol=1e-10):
'''
Solve
f(t) = y
using the bisection method.
Parameters
----------
f: Function which takes in a Tensor t of shape `s` and outputs
the pointwise evaluation f(t).
y: Tensor of shape `s`.
lb, ub: lower and upper bounds for t.
increasing: True if f is increasing, False if decreasing.
max_iter: Positive integer containing the max. number of iterations.
tol: Termination criterion for the difference in upper and lower bounds.
By default, this is set to 1e-10,
beyond which instability could occur when using pytorch `DoubleTensor`.
Returns:
Tensor `t*` of size `s` such that f(t*) ~= y
'''
if lb is None:
lb = torch.zeros_like(y)
if ub is None:
ub = torch.ones_like(y)
assert lb.size() == y.size()
assert ub.size() == y.size()
assert torch.all(lb < ub)
f_ub = phi(ub)
f_lb = phi(lb)
assert torch.all(
f_ub >= f_lb) or not increasing, 'Need f to be monotonically non-decreasing.'
assert torch.all(
f_lb >= f_ub) or increasing, 'Need f to be monotonically non-increasing.'
assert (torch.all(
f_ub >= y) and torch.all(f_lb <= y)) or not increasing, 'y must lie within lower and upper bound. max min y=%s, %s. ub, lb=%s %s' % (y.max(), y.min(), ub, lb)
assert (torch.all(
f_ub <= y) and torch.all(f_lb >= y)) or increasing, 'y must lie within lower and upper bound. y=%s, %s. ub, lb=%s %s' % (y.max(), y.min(), ub, lb)
for it in range(max_iter):
t = (lb + ub)/2
f_t = phi(t)
if increasing:
too_low, too_high = f_t < y, f_t >= y
lb[too_low] = t[too_low]
ub[too_high] = t[too_high]
else:
too_low, too_high = f_t > y, f_t <= y
lb[too_low] = t[too_low]
ub[too_high] = t[too_high]
assert torch.all(ub - lb > 0. - tol), "lb: %s, ub: %s, tol: %s" % (lb, ub, tol)
assert torch.all(ub - lb <= tol)
return t
def bisection_default_increasing(phi, y,tol):
'''
Wrapper for performing bisection method when f is increasing.
'''
return bisection_root(phi, y, increasing=True,tol= tol)
def bisection_default_decreasing(phi, y):
'''
Wrapper for performing bisection method when f is decreasing.
'''
return bisection_root(phi, y, increasing=False)
class MixExpPhi(nn.Module):
'''
Sample net for phi involving the sum of 2 negative exponentials.
phi(t) = m1 * exp(-w1 * t) + m2 * exp(-w2 * t)
Network Parameters
==================
mix: Tensor of size 2 such that such that (m1, m2) = softmax(mix)
slope: Tensor of size 2 such that exp(m1) = w1, exp(m2) = w2
Note that this implies
i) m1, m2 > 0 and m1 + m2 = 1.0
ii) w1, w2 > 0
'''
def __init__(self, init_w=None):
import numpy as np
super(MixExpPhi, self).__init__()
if init_w is None:
self.mix = nn.Parameter(torch.tensor(
[np.log(0.2), np.log(0.8)], requires_grad=True))
self.slope = nn.Parameter(
torch.log(torch.tensor([1e1, 1e6], requires_grad=True)))
else:
assert len(init_w) == 2
assert init_w[0].numel() == init_w[1].numel()
self.mix = nn.Parameter(init_w[0])
self.slope = nn.Parameter(init_w[1])
def forward(self, t):
s = t.size()
t_ = t.flatten()
nquery, nmix = t.numel(), self.mix.numel()
mix_ = torch.nn.functional.softmax(self.mix)
exps = torch.exp(-t_[:, None].expand(nquery, nmix) *
torch.exp(self.slope)[None, :].expand(nquery, nmix))
ret = torch.sum(mix_ * exps, dim=1)
return ret.reshape(s)
class InnerGenerator(nn.Module):
def __init__(self, OuterGenerator,device, Nz=100):
super(InnerGenerator, self).__init__()
self.device = device
self.model = nn.Sequential(
nn.Linear(1, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 1)
).to(device)
self.mu = nn.Parameter(torch.rand(1))
self.beta = nn.Parameter(torch.rand(1))
self.M = self.sample_M(Nz)
for param in OuterGenerator.parameters():
param.requires_grad = False
self.psi = OuterGenerator
def resample_M(self, Nz):
self.M = self.sample_M(Nz)
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N).view(-1,1)).view(-1))
def sample_M(self, N):
# 创建随机张量,转换形状为 [N, 1],符合线性层输入要求
random_tensor = torch.rand(N, 1, device=self.device)
# 通过模型处理,输出的张量需要再次确保为一维
output_tensor = self.model(random_tensor)
return torch.exp(output_tensor.view(-1))
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N,1, device=self.device).view(-1,1)).view(-1))
def forward(self, t):
with torch.autograd.set_detect_anomaly(True):
s = t.size()
t_ = t.flatten()
nquery, nmix = t.numel(), self.M.numel()
exps = torch.exp(-t_[:, None].expand(nquery, nmix) *
self.M[None, :].expand(nquery, nmix))
ret = torch.exp(self.mu)*t_+torch.exp(self.beta)*(1-torch.mean(exps, dim=1))
return self.psi(ret.reshape(s))
class InnerGenerator2(nn.Module):
def __init__(self, OuterGenerator,device, Nz=100):
super(InnerGenerator2, self).__init__()
self.device = device
self.model = nn.Sequential(
nn.Linear(1, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 1)
).to(device)
self.mu = nn.Parameter(torch.rand(1))
self.beta = nn.Parameter(torch.rand(1))
self.M = self.sample_M(Nz)
for param in OuterGenerator.parameters():
param.requires_grad = False
self.psi = OuterGenerator
def resample_M(self, Nz):
self.M = self.sample_M(Nz)
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N).view(-1,1)).view(-1))
def sample_M(self, N):
# 创建随机张量,转换形状为 [N, 1],符合线性层输入要求
random_tensor = torch.rand(N, 1, device=self.device)
# 通过模型处理,输出的张量需要再次确保为一维
output_tensor = self.model(random_tensor)
return torch.exp(output_tensor.view(-1))
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N,1, device=self.device).view(-1,1)).view(-1))
def forward(self, t):
with torch.autograd.set_detect_anomaly(True):
s = t.size()
t_ = t.flatten()
nquery, nmix = t.numel(), self.M.numel()
exps = torch.exp(-t_[:, None].expand(nquery, nmix) *
self.M[None, :].expand(nquery, nmix))
ret = torch.exp(self.mu)*t_+torch.exp(self.beta)*(1-torch.mean(exps, dim=1))
return self.psi(ret.reshape(s))
class MixExpPhiStochastic(nn.Module):
'''
Sample net for phi involving the mean of Nz negative exponentials.
phi(t) = mean(exp(-wi * t))
Network Parameters
==================
slope: Tensor of size Nz such that exp(m1) = w1, ..., exp(mN) = wN
Note that this implies
w1, ..., wN > 0
'''
def __init__(self, device, Nz=100):
super(MixExpPhiStochastic, self).__init__()
self.device = device # 存储设备信息
self.model = nn.Sequential(
nn.Linear(1, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 10),
nn.LeakyReLU(0.2, inplace=True),
nn.Linear(10, 1)
).to(device) # 将模型移到指定的设备
self.M = self.sample_M(Nz) # 现在 self.sample_M 会使用 self.device
def sample_M(self, N):
# 创建随机张量,转换形状为 [N, 1],符合线性层输入要求
random_tensor = torch.rand(N, 1, device=self.device)
# 通过模型处理,输出的张量需要再次确保为一维
output_tensor = self.model(random_tensor)
return torch.exp(output_tensor.view(-1))
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N,1, device=self.device).view(-1,1)).view(-1))
def resample_M(self, Nz):
self.M = self.sample_M(Nz)
# def sample_M(self, N):
# return torch.exp(self.model(torch.rand(N).view(-1,1)).view(-1))
def forward(self, t):
with torch.autograd.set_detect_anomaly(True):
s = t.size()
t_ = t.flatten()
nquery, nmix = t.numel(), self.M.numel()
exps = torch.exp(-t_[:, None].expand(nquery, nmix) *
self.M[None, :].expand(nquery, nmix))
ret = torch.mean(exps, dim=1)
return ret.reshape(s)
def ndiff(self, t, ndiff=0):
s = t.size()
t_ = t.flatten()
nquery, nmix = t.numel(), self.M.numel()
exps = torch.pow(-self.M[None, :].expand(nquery, nmix),ndiff) * \
torch.exp(-t_[:, None].expand(nquery, nmix) *
self.M[None, :].expand(nquery, nmix))
ret = torch.mean(exps, dim=1)
return ret.reshape(s)
class Copula(nn.Module):
def __init__(self, phi, device):
super(Copula, self).__init__()
self.phi = phi.to(device)
self.phi_inv = PhiInv(phi).to(device)
self.device = device # 存储设备信息
def forward(self, y, mode='cdf', others=None, tol=1e-10):
y = y.to(self.device) # 确保输入在正确的设备上
if not y.requires_grad:
y.requires_grad_(True)
ndims = y.size()[1]
inverses = self.phi_inv(y, tol=tol)
cdf = self.phi(inverses.sum(dim=1))
if mode == 'cdf':
return cdf
if mode == 'pdf':
cur = cdf
for dim in range(ndims):
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim].to(self.device)
return cur
if mode == 'pdf2':
numerator = self.phi.ndiff(inverses.sum(dim=1), ndiff=ndims)
denominator = torch.prod(self.phi.ndiff(inverses, ndiff=1), dim=1)
return numerator / denominator
elif mode == 'cond_cdf':
target_dims = others['cond_dims']
cur = cdf
for dim in target_dims:
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True, retain_graph=True)[0][:, dim].to(self.device)
numerator = cur
trunc_cdf = self.phi(inverses[:, target_dims])
cur = trunc_cdf
for dim in range(len(target_dims)):
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim].to(self.device)
denominator = cur
return numerator / denominator
class MixExpPhi2FixedSlope(nn.Module):
def __init__(self, init_w=None):
super(MixExpPhi2FixedSlope, self).__init__()
self.mix = nn.Parameter(torch.tensor(
[np.log(0.25)], requires_grad=True))
self.slope = torch.tensor([1e1, 1e6], requires_grad=True)
def forward(self, t):
z = 1./(1+torch.exp(-self.mix[0]))
return z * torch.exp(-t * self.slope[0]) + (1-z) * torch.exp(-t * self.slope[1])
class SurvivalCopula(nn.Module):
# for known parametric survival marginals, e.g., Weibull distributions
def __init__(self, phi, device, num_features, tol, hidden_size=32, max_iter = 2000):
super(SurvivalCopula, self).__init__()
self.tol = tol
self.phi = phi
self.phi_inv = PhiInv(phi).to(device)
self.net_t = nn.Sequential(
nn.Linear(num_features, hidden_size),
nn.Linear(hidden_size, 1),
)
self.net_c = nn.Sequential(
nn.Linear(num_features, hidden_size),
nn.Linear(hidden_size, 1),
)
self.shape_t = nn.Parameter(torch.tensor(1.0)) # Event Weibull Shape
self.scale_t = nn.Parameter(torch.tensor(1.0)) # Event Weibull Scale
self.shape_c = nn.Parameter(torch.tensor(1.0)) # Censoring Weibull Shape
self.scale_c = nn.Parameter(torch.tensor(1.0)) # Censoring Weibull Scale
def forward(self, x, t, c, max_iter = 2000):
# the Covariates for Event and Censoring Model
x_beta_t = self.net_t(x).squeeze()
x_beta_c = self.net_c(x).squeeze()
# In event density, censoring entries should be 0
event_log_density = c * log_density(t, self.shape_t, self.scale_t, x_beta_t)
censoring_log_density = (1-c) * log_density(t, self.shape_c, self.scale_c, x_beta_c)
S_E = survival(t, self.shape_t, self.scale_t, x_beta_t)
S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
ndims = y.size()[1]
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
logL = event_log_density + c * torch.log(cur1) + censoring_log_density + (1-c) * torch.log(cur2)
return torch.sum(logL)
def cond_cdf(self, y, mode='cond_cdf', others=None, tol=1e-8):
if not y.requires_grad:
y = y.requires_grad_(True)
ndims = y.size()[1]
inverses = self.phi_inv(y, tol=self.tol)
cdf = self.phi(inverses.sum(dim=1))
if mode == 'cdf':
return cdf
if mode == 'pdf':
cur = cdf
for dim in range(ndims):
# TODO: Only take gradients with respect to one dimension of y at at time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
return cur
elif mode =='cond_cdf':
target_dims = others['cond_dims']
# Numerator
cur = cdf
for dim in target_dims:
# TODO: Only take gradients with respect to one dimension of y at a time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True, retain_graph=True)[0][:, dim]
numerator = cur
# Denominator
trunc_cdf = self.phi(inverses[:, target_dims])
cur = trunc_cdf
for dim in range(len(target_dims)):
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
denominator = cur
return numerator/denominator
class DCSurvival(nn.Module):
# with neural density estimators
def __init__(self, phi, device, num_features, tol, hidden_size=32, hidden_surv = 32, max_iter = 2000):
super(DCSurvival, self).__init__()
self.tol = tol
self.phi = phi
self.phi_inv = PhiInv(phi).to(device)
self.sumo_e = NDE(num_features, layers = [hidden_size,hidden_size,hidden_size], layers_surv = [hidden_surv,hidden_surv,hidden_surv], dropout = 0.)
self.sumo_c = NDE(num_features, layers = [hidden_size,hidden_size,hidden_size], layers_surv = [hidden_surv,hidden_surv,hidden_surv], dropout = 0.)
def forward(self, x, t, c, max_iter = 2000):
S_E, density_E = self.sumo_e(x, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
# S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
S_C, density_C = self.sumo_c(x, t, gradient = True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
# logL = event_log_density + c * torch.log(cur1) + censoring_log_density + (1-c) * torch.log(cur2)
# why not:
# logL = ((c==1) | (c==0)) * event_log_density + ((c==1) | (c==0)) * torch.log(cur1) + ((c==2) | (c==3)) * censoring_log_density + ((c==2) | (c==3)) * torch.log(cur2)
# print(c)
logL = (c==1) * event_log_density + (c==1) * torch.log(cur1) + (c==0) *censoring_log_density + (c==0) * torch.log(cur2)
return torch.sum(logL)
class HACSurv_2D(nn.Module):
# 使用神经密度估计
def __init__(self, phi, device, num_features, tol, hidden_size=32, hidden_surv=32, max_iter=2000):
super(HACSurv_2D, self).__init__()
self.tol = tol
self.phi = phi
self.phi_inv = PhiInv(phi).to(device)
self.sumo_e = NDE(num_features, layers=[hidden_size, hidden_size, hidden_size], layers_surv=[hidden_surv, hidden_surv, hidden_surv], dropout=0.)
self.sumo_c = NDE(num_features, layers=[hidden_size, hidden_size, hidden_size], layers_surv=[hidden_surv, hidden_surv, hidden_surv], dropout=0.)
def forward(self, x, t, c, max_iter=2000, selected_indicators=[1,0]):
S_E, density_E = self.sumo_e(x, t, gradient=True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
S_C, density_C = self.sumo_c(x, t, gradient=True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# 验证生存函数的合法性
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Copula 部分导数计算
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter=max_iter)
cdf = self.phi(inverses.sum(dim=1))
cur1 = torch.autograd.grad(cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(cdf.sum(), y, create_graph=True)[0][:, 1]
# 根据选择的事件指示器调整 logL 的计算
indicator_1, indicator_2 = selected_indicators
logL = (c == indicator_1) * (event_log_density + torch.log(cur1)) + \
(c == indicator_2) * (censoring_log_density + torch.log(cur2))
return torch.sum(logL)
def cond_cdf(self, y, mode='cond_cdf', others=None, tol=1e-8):
if not y.requires_grad:
y = y.requires_grad_(True)
ndims = y.size()[1]
inverses = self.phi_inv(y, tol=self.tol)
cdf = self.phi(inverses.sum(dim=1))
if mode == 'cdf':
return cdf
if mode == 'pdf':
cur = cdf
for dim in range(ndims):
# TODO: Only take gradients with respect to one dimension of y at at time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
return cur
elif mode =='cond_cdf':
target_dims = others['cond_dims']
# Numerator
cur = cdf
for dim in target_dims:
# TODO: Only take gradients with respect to one dimension of y at a time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True, retain_graph=True)[0][:, dim]
numerator = cur
# Denominator
trunc_cdf = self.phi(inverses[:, target_dims])
cur = trunc_cdf
for dim in range(len(target_dims)):
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
denominator = cur
return numerator/denominator
def survival(self, t, X):
with torch.no_grad():
result = self.sumo_e.survival(X, t)
return result
def survival_withCopula_joint_CIF_(self, t,x , max_iter = 2000):
S_E, density_E = self.sumo_e(x, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
# S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
S_C, density_C = self.sumo_c(x, t, gradient = True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
Result = density_E.squeeze()*cur1
return Result
def survival_withCopula_condition_CIF_intergral(self, t,x , max_iter = 2000):
S_E, density_E = self.sumo_e(x, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
# S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
S_C, density_C = self.sumo_c(x, t, gradient = True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
# print(S_C)
Result = density_E.squeeze()*cur1/S_C
return Result
def survival_withCopula_condition_CIF_No_intergral(self, t,x , max_iter = 2000):
S_E, density_E = self.sumo_e(x, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
# S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
S_C, density_C = self.sumo_c(x, t, gradient = True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
# logL = event_log_density + c * torch.log(cur1) + censoring_log_density + (1-c) * torch.log(cur2)
# why not:
# logL = ((c==1) | (c==0)) * event_log_density + ((c==1) | (c==0)) * torch.log(cur1) + ((c==2) | (c==3)) * censoring_log_density + ((c==2) | (c==3)) * torch.log(cur2)
# print(c)
Result =1- cdf/S_C
return Result
class HACSurv_2D_shared(nn.Module):
# 使用神经密度估计
def __init__(self, phi, device, num_features, tol, hidden_size=32, hidden_surv=32, max_iter=2000):
super(HACSurv_2D_shared, self).__init__()
self.tol = tol
self.phi = phi
self.phi_inv = PhiInv(phi).to(device)
# self.sumo_e = NDE(num_features, layers=[hidden_size, hidden_size, hidden_size], layers_surv=[hidden_surv, hidden_surv, hidden_surv], dropout=0.)
# self.sumo_c = NDE(num_features, layers=[hidden_size, hidden_size, hidden_size], layers_surv=[hidden_surv, hidden_surv, hidden_surv], dropout=0.)
self.sumo_e = NDE(hidden_size, layers = [hidden_size,hidden_size], layers_surv = [hidden_surv,hidden_surv,hidden_surv], dropout = 0)
self.sumo_c = NDE(hidden_size, layers = [hidden_size,hidden_size], layers_surv = [hidden_surv,hidden_surv,hidden_surv], dropout = 0)
self.shared_embedding = nn.Sequential(
nn.Linear(num_features, hidden_size),
nn.Tanh(),
nn.Linear(hidden_size, hidden_size),
# nn.Tanh(),
# nn.Linear(hidden_size, hidden_size),
# nn.Tanh(),
# nn.Linear(hidden_size, hidden_size),
)
def forward(self, x, t, c, max_iter=2000, selected_indicators=[0, 1]):
x_shared = self.shared_embedding(x)
S_E, density_E = self.sumo_e(x_shared, t, gradient=True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
S_C, density_C = self.sumo_c(x_shared, t, gradient=True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# 验证生存函数的合法性
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Copula 部分导数计算
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter=max_iter)
cdf = self.phi(inverses.sum(dim=1))
cur1 = torch.autograd.grad(cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(cdf.sum(), y, create_graph=True)[0][:, 1]
# 根据选择的事件指示器调整 logL 的计算
indicator_1, indicator_2 = selected_indicators
logL = (c == indicator_1) * (event_log_density + torch.log(cur1)) + \
(c == indicator_2) * (censoring_log_density + torch.log(cur2))
return torch.sum(logL)
def cond_cdf(self, y, mode='cond_cdf', others=None, tol=1e-8):
if not y.requires_grad:
y = y.requires_grad_(True)
ndims = y.size()[1]
inverses = self.phi_inv(y, tol=self.tol)
cdf = self.phi(inverses.sum(dim=1))
if mode == 'cdf':
return cdf
if mode == 'pdf':
cur = cdf
for dim in range(ndims):
# TODO: Only take gradients with respect to one dimension of y at at time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
return cur
elif mode =='cond_cdf':
target_dims = others['cond_dims']
# Numerator
cur = cdf
for dim in target_dims:
# TODO: Only take gradients with respect to one dimension of y at a time
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True, retain_graph=True)[0][:, dim]
numerator = cur
# Denominator
trunc_cdf = self.phi(inverses[:, target_dims])
cur = trunc_cdf
for dim in range(len(target_dims)):
cur = torch.autograd.grad(
cur.sum(), y, create_graph=True)[0][:, dim]
denominator = cur
return numerator/denominator
def survival(self, t, X):
with torch.no_grad():
x_shared = self.shared_embedding(X)
result = self.sumo_e.survival(x_shared, t)
return result
def survival_withCopula_joint_CIF_(self, t,x , max_iter = 2000):
x_shared = self.shared_embedding(x)
S_E, density_E = self.sumo_e(x_shared, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()
# S_C = survival(t, self.shape_c, self.scale_c, x_beta_c)
S_C, density_C = self.sumo_c(x_shared, t, gradient = True)
S_C = S_C.squeeze()
censoring_log_density = torch.log(density_C).squeeze()
# Check if Survival Function of Event and Censoring are in [0,1]
assert (S_E >= 0.).all() and (
S_E <= 1.+1e-10).all(), "t %s, output %s" % (t, S_E, )
assert (S_C >= 0.).all() and (
S_C <= 1.+1e-10).all(), "t %s, output %s" % (t, S_C, )
# Partial derivative of Copula using ACNet
y = torch.stack([S_E, S_C], dim=1)
inverses = self.phi_inv(y, max_iter = max_iter)
cdf = self.phi(inverses.sum(dim=1))
# TODO: Only take gradients with respect to one dimension of y at at time
cur1 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 0]
cur2 = torch.autograd.grad(
cdf.sum(), y, create_graph=True)[0][:, 1]
Result = density_E.squeeze()*cur1
return Result
def survival_withCopula_condition_CIF_intergral(self, t,x , max_iter = 2000):
x_shared = self.shared_embedding(x)
S_E, density_E = self.sumo_e(x_shared, t, gradient = True)
S_E = S_E.squeeze()
event_log_density = torch.log(density_E).squeeze()