Suppose I have an optimization problem to solve using R
, optimx
. Is there any way I can extract the parameters and objective function values over time?
f<-function(x){
return(sum(abs(x)))
}
gr<-function(x){
return(sign(x))
}
opt=optimx::optimx(runif(2),f,gr,method="BFGS")
The goal is trying to make such plot:
I think we can manually do it with Gradient Decent with following code, but how I can I do it in optimx
?
x=c(0.5,1.5)
alpha=0.1
max_iter=20
x_trace=matrix(rep(0,max_iter*2),ncol=2)
for (i in 1:max_iter){
x=x-alpha*gr(x)
x_trace[i,]=x
}
f_trace=apply(x_trace,1,f)