[英]plot the iterations of optim vs the logliklihood values in r
我有一個最大似然估計函數,我正在使用optim
函數。 我想繪制迭代輸出與對數似然值。
這是一個與我的復雜函數非常相似的例子:
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
是對數似然值。
我的函數返回100
個。 我知道我需要先存儲它們,然后再繪制它們。 但是如何在 R 中做到這一點呢?
有什么幫助嗎?
有幾個選項。 選項1:在control
列表中添加REPORT = 1
,每一步都會打印函數值。 您必須以某種方式處理這些打印數據,可能是使用sink()
然后刪除多余的文本。 選項 2:一次運行optim
一次迭代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')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.