r - 无法让 partykit 包的 mob 函数进行单变量 MLE 拟合

标签 r oop party

我无法让 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) 

Error in UseMethod("estfun") : no applicable method for 'estfun' applied to an object of class "fitdistr" The above error message does not appear when glm is used instead of fitdistr

# estfun runs OK outside of call to mob! 
estfun(logit(PimaIndiansDiabetes$diabetes,PimaIndiansDiabetes$glucose)) 

最佳答案

原则上,使用 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

因此:

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"

您定义的 estfun() 函数由于以下两个原因不起作用:(1) 它不是一个可以被使用的方法 estfun.fitdistr()由通过包的 NAMESPACE 使用的通用函数 sandwich::estfun() 调用。 (2) 它没有计算正确的数量:它是对数似然,但我们需要对数密度相对于两个参数的导数,并在每次观察时进行评估。后者将是一个 n x 2 矩阵。

我认为手动计算 Gamma 分布的得分函数应该不会太难。但这也应该已经在某些 R 包中可用,可能是 gamlss.dist 或其他包。

关于r - 无法让 partykit 包的 mob 函数进行单变量 MLE 拟合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35972200/

相关文章:

r - 如何在不更改值的情况下将 R 中的因子格式转换为数字格式?

r - 对于每组汇总数据帧中所有变量的平均值(ddply?拆分?)

r - 将函数应用于 R 中的不同 data.frames

javascript - 类型和 OO 耦合了吗?

r - 显示带有 "print"的推理树节点值

r - 并行训练 cforest

Rvest 网络抓取返回空字符

java 对象在不设置的情况下发生变化

c# - 为什么私有(private)成员变量可以被类实例改变?