-
Notifications
You must be signed in to change notification settings - Fork 2
/
models.py
99 lines (64 loc) · 2.69 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
import torch
from Nets import *
import numpy as np
#from sksurv.linear_model.coxph import BreslowEstimator
from os import path
import os
def LOG(x):
return torch.log(x+1e-20*(x<1e-20))
class Weibull_log_linear:
def __init__(self, nf, mu, sigma, device) -> None:
#torch.manual_seed(0)
self.nf = nf
self.mu = torch.tensor([mu], device=device).type(torch.float32)
self.sigma = torch.tensor([sigma], device=device).type(torch.float32)
self.coeff = torch.rand((nf,), device=device)
def survival(self,t,x):
return torch.exp(-1*torch.exp((LOG(t)-self.mu-torch.matmul(x, self.coeff))/torch.exp(self.sigma)))
def cum_hazard(self, t,x):
return torch.exp((LOG(t)-self.mu-torch.matmul(x, self.coeff))/torch.exp(self.sigma))
def hazard(self, t,x):
return self.cum_hazard(t,x)/(t*torch.exp(self.sigma))
def PDF(self,t,x):
return self.survival(t,x) * self.hazard(t,x)
def CDF(self, t,x ):
return 1 - self.survival(t,x)
def enable_grad(self):
self.sigma.requires_grad = True
self.mu.requires_grad = True
self.coeff.requires_grad = True
def parameters(self):
return [self.sigma, self.mu, self.coeff]
def rvs(self, x, u):
tmp = LOG(-1*LOG(u))*torch.exp(self.sigma)
tmp1 = torch.matmul(x, self.coeff) + self.mu
return torch.exp(tmp+tmp1)
class Weibull_log:
def __init__(self, nf, mu, sigma, hidden_layers, device) -> None:
self.nf = nf
self.mu = torch.tensor([mu],device=device).type(torch.float32)
self.sigma = torch.tensor([sigma], device=device).type(torch.float32)
self.net = Risk_Net(nf, hidden_layers, device)
def survival(self,t,x):
return torch.exp(-1*torch.exp((LOG(t)-self.mu-self.net(x))/torch.exp(self.sigma)))
def cum_hazard(self, t,x):
return torch.exp((LOG(t)-self.mu-self.net(x))/torch.exp(self.sigma))
def hazard(self, t,x):
return self.cum_hazard(t,x)/(t*torch.exp(self.sigma))
def PDF(self,t,x):
return self.survival(t,x) * self.hazard(t,x)
def CDF(self, t,x ):
return 1 - self.survival(t,x)
def enable_grad(self):
self.sigma.requires_grad = True
self.mu.requires_grad = True
def parameters(self):
return [self.sigma, self.mu]+ list(self.net.parameters())
def rvs(self, x, u):
tmp = LOG(-1*LOG(u))*torch.exp(self.sigma)
tmp1 = self.net(x) + self.mu
return torch.exp(tmp+tmp1)
if __name__ == "__main__":
w = Weibull_log(10, 1,1,[10,1])
t = torch.ones(1000)
x = torch.ones((1000,10))