-
Notifications
You must be signed in to change notification settings - Fork 4
/
xgboost_survival_v1.R
47 lines (45 loc) · 1.18 KB
/
xgboost_survival_v1.R
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
library(xgboost)
#define objective function and evaluation function
mylossobj2<-function(preds, dtrain) {
labels <- getinfo(dtrain, "label") #labels<-dtrain$label
#print(labels)
censor<-attr(dtrain,"censor")
ord<-order(labels)
ran=rank(labels)
#print(ord)
#foo<<-censor
#compute the first gradient
d=censor[ord] #status
etas=preds[ord] #linear predictor
haz<-as.numeric(exp(etas)) #w[i]
#print(haz)
rsk<-rev(cumsum(rev(haz))) #W[i]
P<-outer (haz,rsk,'/')
P[upper.tri(P)] <- 0
grad<- -(d-P%*%d)
grad=grad[ran]
#derive hessian
# H1=outer(haz,rsk^2,'/')
# H1=t(t(H1)*rsk)
H1=P
H2=outer(haz^2,rsk^2,'/')
H=H1-H2
H[upper.tri(H)]=0
hess=H%*%d
hess=hess[ran]
# Return the result as a list
return(list(grad = grad, hess = hess))
}
evalerror2 <- function(preds, dtrain) {
labels <- getinfo(dtrain, "label") #labels<-dtrain$label
censor<-attr(dtrain,"censor") #not working!
#foo<<-censor
#compute the first gradient
ord<-order(labels)
d=censor[ord] #status
etas=preds[ord] #linear predictor
haz<-as.numeric(exp(etas)) #w[i]
rsk<-rev(cumsum(rev(haz)))
err <- -sum(d*(etas-log(rsk)))
return(list(metric = "deviance", value = err))
}