补充资料——自己实现极大似然估计(最大似然估计)MLE

这篇文章给了我一个启发,我们可以自己用已知分布的密度函数进行组合,然后构建一个新的密度函数啦,然后用极大似然估计MLE进行估计。

代码和结果演示
代码:
 
   
  1. #取出MASS包这中的数据
  2. data(geyser,package="MASS")
  3. head(geyser)
  4. attach(geyser)
  5. par(bg='lemonchiffon')
  6. hist(waiting,freq=F,col="lightcoral")
  7. #freq=F要加上,否则就无法添加线了
  8. lines(density(waiting),lwd=2,col="cadetblue4")
  9. #根据图像,我们认为其在前后分别是两个正态分布函数的组合
  10. #定义 log‐likelihood 函数
  11. LL<-function(params,data){
  12. #参数"params"是一个向量,
  13. #依次包含了五个参数: p,mu1,sigma1,mu2,sigma2.
  14. #参数"data",是观测数据。
  15. t1<-dnorm(data,params[2],params[3])
  16. t2<-dnorm(data,params[4],params[5])
  17. #f是概率密度函数
  18. f<-params[1]*t1+(1-params[1])*t2
  19. #混合密度函数
  20. ll<-sum(log(f))
  21. #log‐likelihood 函数
  22. return(-ll)
  23. #nlminb()函数是最小化一个函数的值,
  24. #但我们是要最大化 log‐likeilhood 函数
  25. #所以需要在“ ll”前加个“ ‐”号。
  26. }
  27. #估计函数####optim####
  28. # debugonce(nlminb)
  29. geyser.res<-nlminb(c(0.5,50,10,80,10),LL,data=waiting,
  30. lower=c(0.0001,-Inf,0.0001,
  31. -Inf,0.0001),
  32. upper=c(0.9999,Inf,Inf,Inf,Inf))
  33. #初始值为 p=0.5,mu1=50,sigma1=10,mu2=80,sigma2=10
  34. #初始值也会被传递给LL
  35. #LL 是被最小化的函数。
  36. #data 是估计用的数据(传递给我们的LL)
  37. #lower 和 upper 分别指定参数的上界和下界。
  38. #查看拟合的参数
  39. geyser.res$par
  40. #拟合的效果
  41. #解释变量
  42. X<-seq(40,120,length=100)
  43. #读出估计的参数
  44. p<-geyser.res$par[1]
  45. mu1<-geyser.res$par[2]
  46. sig1<-geyser.res$par[3]
  47. mu2<-geyser.res$par[4]
  48. sig2<-geyser.res$par[5]
  49. #将估计的参数函数代入原密度函数。
  50. f<-p*dnorm(X,mu1,sig1)+(1-p)*dnorm(X,mu2,sig2)
  51. #作出数据的直方图
  52. hist(waiting,probability=T,col='lightpink3',
  53. ylab="Density",ylim=c(0,0.04),
  54. xlab="Eruption waiting times"
  55. )
  56. #画出拟合的曲线
  57. lines(X,f,col='lightskyblue3',lwd=2)
  58. detach(geyser)

调试的说明
nlminb函数:
nlminb(c(0.5,50,10,80,10),LL,data=waiting,
                   lower=c(0.0001,-Inf,0.0001,
                           -Inf,0.0001),
                   upper=c(0.9999,Inf,Inf,Inf,Inf))
 
   
  1. function (start, objective, gradient = NULL, hessian = NULL,
  2. ..., scale = 1, control = list(), lower = -Inf, upper = Inf)
  3. {
  4. par <- setNames(as.double(start), names(start))
  5. n <- length(par)
  6. iv <- integer(78 + 3 * n)
  7. v <- double(130 + (n * (n + 27))/2)
  8. .Call(C_port_ivset, 2, iv, v)
  9. if (length(control)) {
  10. nms <- names(control)
  11. if (!is.list(control) || is.null(nms))
  12. stop("'control' argument must be a named list")
  13. pos <- pmatch(nms, names(port_cpos))
  14. if (any(nap <- is.na(pos))) {
  15. warning(sprintf(ngettext(length(nap), "unrecognized control element named %s ignored",
  16. "unrecognized control elements named %s ignored"),
  17. paste(sQuote(nms[nap]), collapse = ", ")), domain = NA)
  18. pos <- pos[!nap]
  19. control <- control[!nap]
  20. }
  21. ivpars <- pos <= 4
  22. vpars <- !ivpars
  23. if (any(ivpars))
  24. iv[port_cpos[pos[ivpars]]] <- as.integer(unlist(control[ivpars]))
  25. if (any(vpars))
  26. v[port_cpos[pos[vpars]]] <- as.double(unlist(control[vpars]))
  27. }
  28. obj <- quote(objective(.par, ...))

  29. rho <- new.env(parent = environment())

  30. assign(".par", par, envir = rho)
  31. grad <- hess <- low <- upp <- NULL
  32. if (!is.null(gradient)) {
  33. grad <- quote(gradient(.par, ...))
  34. if (!is.null(hessian)) {
  35. if (is.logical(hessian))
  36. stop("logical 'hessian' argument not allowed. See documentation.")
  37. hess <- quote(hessian(.par, ...))
  38. }
  39. }
  40. if (any(lower != -Inf) || any(upper != Inf)) {
  41. low <- rep_len(as.double(lower), length(par))
  42. upp <- rep_len(as.double(upper), length(par))
  43. }
  44. else low <- upp <- numeric()
  45. .Call(C_port_nlminb, obj, grad, hess, rho, low, upp, d = rep_len(as.double(scale),
  46. length(par)), iv, v)
  47. iv1 <- iv[1L]
  48. list(par = get(".par", envir = rho), objective = v[10L],
  49. convergence = (if (iv1 %in% 3L:6L) 0L else 1L), iterations = iv[31L],
  50. evaluations = c(`function` = iv[6L], gradient = iv[30L]),
  51. message = if (19 <= iv1 && iv1 <= 43) {
  52. if (any(B <- iv1 == port_cpos)) sprintf("'control' component '%s' = %g, is out of range",
  53. names(port_cpos)[B], v[iv1]) else sprintf("V[IV[1]] = V[%d] = %g is out of range (see PORT docu.)",
  54. iv1, v[iv1])
  55. } else port_msg(iv1))
  56. }
par最先获得了初始值
obj <- quote(objective(.par, ...))
让obj表示一个名为 objective,接受形参.par和...的函数,即我们传入的对数似然函数
rho <- new.env(parent = environment())
创建新环境
assign(".par", par, envir = rho)
par赋给 rho环境中的 .par变量
.Call(C_port_nlminb, obj, grad, hess, 
        rho, low, upp, d = rep_len(as.double(scale),  length(par)), iv, v)
C_port_nlminb在名为stats.dll的包里,我用reflector和VS都没能看到什么东西,唉,最关键的东西是缺失的。
此时rho包含了参数的初始值,而obj接受.par和多出来的data,即参数初始值和数据。
nlminb 函数的帮助文档里提到:
...
Further arguments to be supplied to objective.
即在这里是传递给对数似然函数的更多参数,这里是data,之所以LL的第一个参数不需要传入是因为我们在源码看到其是.par,也可以在帮助文档看到:
objective
Function to be minimized. Must return a scalar value. The first argument to objective is the vector of parameters to be optimized, whose initial values are supplied through start(start 参数). Further arguments (fixed during the course of the optimization) to objective may be specified as well (see ...(参数)).

---------------------------------------
参考:
原文档:




附件列表

 

转载于:https://www.cnblogs.com/xuanlvshu/p/6354033.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值