绘制优化的迭代与r中的logliklihood值

时间:2017-10-24 06:40:43

标签: r

我有最大似然估计函数,我正在使用optim函数。我想绘制迭代输出与logliklihood值。

这是我的复杂功能的一个非常相似的例子:

y <- rnorm(1000,2,2)
myfunc <- function(x){
  fn <- function(theta) { sum ( 0.5*(xvec - theta[1])^2/theta[2] + 0.5* log(theta[2]) ) }
  optim(theta <- c(0,5), fn, hessian=TRUE,method = "L-BFGS-B",lower=c(0,0),control = list(trace=1))

} 

输出结果为:

iter  10 value 12.001318
final  value 12.001318 

iter 10是迭代步骤。 value 12.001318是logliklihood价值。

我的函数返回100。我知道我需要先存储它们然后绘制它们。但是如何在R中做到这一点?

有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

有几种选择。选项1:在REPORT = 1列表中添加control,并在每一步打印功能值。您必须以某种方式处理此打印数据,可能使用sink()然后删除额外的文本。选项2:一次运行optim一次迭代并存储值。然后,您可以轻松存储对数似然值并绘制它。这两个选项的部分代码如下所示。

# generating random values
set.seed(10)
y <- rnorm(1000,2,2)

#### option 1 ####
# intermediate results printed
myfunc <- function(xvec){
  fn <- function(theta) { sum ( 0.5*(xvec - theta[1])^2/theta[2] + 0.5* log(theta[2]) ) }
  optim(theta <- c(0,5), fn, hessian=TRUE,method = "L-BFGS-B",lower=c(0,0),control = list(trace=1,REPORT=1))
}

# running optimization with input y
myfunc(y)

# would need to copy values or otherwise post process to make plot


#### option 2 ####
# running optimization one iteration at a time
fn <- function(theta) { sum ( 0.5*(y - theta[1])^2/theta[2] + 0.5* log(theta[2]) ) }
# storing log likelihood values
loglvals <- fn(c(0,5))

# initializing variables
temp1par <- c(0,0)

# running the loop
for(i in 1:100){

  temp1 <- optim(theta <- ifelse(i==1,1,0)*c(0,5)+ifelse(i==1,0,1)*temp1par, fn, hessian=TRUE,method = "L-BFGS-B",lower=c(0,0),control = list(trace=1,REPORT=1,maxit=1))
  temp1par <- temp1$par
  loglvals <- c(loglvals,temp1$value)
}

# plotting results
# trimming the length of loglvals because the function converged
# before the loop calling optim stopped
# simply using unique to specify when it the optim didn't return new values
plot(seq(0,length(unique(loglvals)),1)
     ,loglvals[seq(1,length(unique(loglvals))+1,1)]
     ,ylab='log likelihood'
     ,xlab='iteration')