这篇文章遵循这个问题:https ://stackoverflow.com/questions/31234329/rpart-user-defined-implementation
我对可以使用自定义标准处理树生长的工具非常感兴趣,这样我就可以测试不同的模型。
我尝试使用 partykit R 包来生长一棵树,其拆分规则由 Cox 模型的负对数似然给出(在 Cox 模型的情况下为对数准似然)并且拟合了 Cox 模型在每一片叶子上。
据我了解阅读有关 MOB 函数的小插图,有两种方法可以实现我自己的拆分标准,即让 fit 函数返回列表或模型对象。
出于我的目的,我尝试了这两种解决方案,但未能成功。
解决方案 1:返回一个列表对象:
我以“mob”小插曲中的“乳腺癌数据集”为例。
我试过这个:
cox1 = function(y,x, start = NULL, weights = NULL, offset = NULL, ...,
estfun = FALSE, object = TRUE){
res_cox = coxph(formula = y ~ x )
list(
coefficients = res_cox$coefficients,
objfun = - res_cox$loglik[2],
object = res_cox)
}
mob(formula = Surv(time, cens) ~ horTh + pnodes - 1 | age + tsize + tgrade + progrec +
estrec + menostat ,
data = GBSG2 ,
fit = cox1,
control = mob_control(alpha = 0.0001) )
有一个关于 X 矩阵奇点的警告,并且 mob 函数是一个具有单个节点的树(即使 alpha 值较小)。
请注意,在运行 coxph 函数时,X 矩阵没有奇点问题:
res_cox = coxph( formula = Surv(time, cens) ~ horTh + pnodes ,
data = GBSG2 )
解决方案 2:返回一个 coxph.object :
我试过这个:
cox2 = function(y,x, start = NULL, weights = NULL, offset = NULL, ... ){
res_cox = coxph(formula = y ~ x )
}
logLik.cox2 <- function(object, ...)
structure( - object$loglik[2], class = "logLik")
mob(formula = Surv(time, cens) ~ horTh + pnodes - 1 | age + tsize + tgrade + progrec +
estrec + menostat ,
data = GBSG2 ,
fit = cox2,
control = mob_control(alpha = 0.0001 ) )
所以这次我沿着“progrec”变量进行了拆分:
Model-based recursive partitioning (cox2)
Model formula:
Surv(time, cens) ~ horTh + pnodes - 1 | age + tsize + tgrade +
progrec + estrec + menostat
Fitted party:
[1] root
| [2] progrec <= 21: n = 281
| xhorThno xhorThyes xpnodes
| 0.19306661 NA 0.07832756
| [3] progrec > 21: n = 405
| xhorThno xhorThyes xpnodes
| 0.64810352 NA 0.04482348
Number of inner nodes: 1
Number of terminal nodes: 2
Number of parameters per node: 3
Objective function: 1531.132
Warning message:
In coxph(formula = y ~ x) : X matrix deemed to be singular; variable 2
我想知道我的解决方案 1 有什么问题。
我还为回归问题尝试了类似的方法并得到了相同的结果,以单叶结尾:
data("BostonHousing", package = "mlbench")
BostonHousing <- transform(BostonHousing,
chas = factor(chas, levels = 0:1, labels = c("no", "yes")),
rad = factor(rad, ordered = TRUE))
linear_reg = function(y,x, start = NULL, weights = NULL, offset = NULL, ...,
estfun = FALSE, object = TRUE){
res_lm = glm(formula = y ~ x , family = "gaussian")
list(
coefficients = res_lm$coefficients,
objfun = res_lm$deviance,
object = res_lm )
}
mob( formula = medv ~ log(lstat) + I(rm^2) | zn + indus + chas + nox +
+ age + dis + rad + tax + crim + b + ptratio,
data = BostonHousing ,
fit = linear_reg)
另外我想知道使用“将模型拟合到节点中”和“进行拆分”的变量是否没有问题。
先感谢您。
我可能还有其他关于partykit 功能的问题。