我无法使用 partykit 包的 mob 函数来进行单变量 MLE 拟合。
# Trying to convert vignette example here https://cran.r-project.org/web/packages/partykit/vignettes/mob.pdf on page 7 to do univariate MLE gamma fits.
data("PimaIndiansDiabetes", package = "mlbench")
library("partykit")
library("fitdistrplus")
# Generating some fake data to replace the example data.
op <- options(digits = 3)
set.seed(123)
x <- rgamma(nrow(PimaIndiansDiabetes), shape = 5, rate = 0.1)
PimaIndiansDiabetes$diabetes<-x
PimaIndiansDiabetes$glucose<-x
#Hopefully this change to the formula means fit a gamma to just the diabetes vector of values!
pid_formula <- diabetes ~ 1 | pregnant + pressure + triceps + insulin + mass + pedigree + age
#Defining my own, negative of log likelihood since mob will minimize it.
estfun<-function(z) {-logLik(z)}
#replacing the call to glm that is successful in the vignette example.
class(fitdistr) <- append(class(fitdistr),estfun)
logit <- function(y, x, start = NULL, weights = NULL, offset = NULL, ...) {
fitdistr(y, "gamma")
}
#fail! The mob() function still does not see my artificially created estfun().
pid_tree <- mob(pid_formula, data = PimaIndiansDiabetes, fit = logit)
Run Code Online (Sandbox Code Playgroud)
UseMethod("estfun") 中的错误:没有适用于 'estfun' 的方法应用于类“fitdistr”的对象 当使用 glm 而不是 fitdistr 时,不会出现上述错误消息
# estfun runs OK outside of call to mob!
estfun(logit(PimaIndiansDiabetes$diabetes,PimaIndiansDiabetes$glucose))
Run Code Online (Sandbox Code Playgroud)
原则上,mob()用于您想做的事情是可行的,但是对于该estfun()方法应该做什么以及如何调用它存在误解。
mob() 需要来自模型对象的以下信息来执行树的构建:
coef(object)。logLik(object)。estfun(object)。见vignette("sandwich-OOP", package = "sandwich")介绍。对于类"fitdistr"的对象,前两个可用,但后者不可用:
methods(class = "fitdistr")
## [1] coef logLik print vcov
## see '?methods' for accessing help and source code
Run Code Online (Sandbox Code Playgroud)
因此:
f <- fitdistr(x, "gamma")
coef(f)
## shape rate
## 5.022 0.103
logLik(f)
## 'log Lik.' -3404 (df=2)
sandwich::estfun(f)
## Error in UseMethod("estfun") :
## no applicable method for 'estfun' applied to an object of class "fitdistr"
Run Code Online (Sandbox Code Playgroud)
由于estfun()以下两个原因,您定义的函数不起作用:(1) 它不是一种estfun.fitdistr()可以由sandwich::estfun()通过包的NAMESPACE. (2) 它没有计算正确的数量:它是对数似然,但我们需要关于两个参数的对数密度的导数,并在每次观察时进行评估。后者将是一个 nx 2 矩阵。
我认为手工计算伽马分布的得分函数应该不会太难。但这也应该在某些 R 包中已经可用,也可能在gamlss.dist其他包中可用。