Re: [R] Save parameters from optim during iteration procedure

From: Uwe Ligges <ligges_at_statistik.uni-dortmund.de>
Date: Mon 16 May 2005 - 00:49:17 EST

Camarda, Carlo Giovanni wrote:

> Dear R-users,
> I am going to try to be as clearer as possible, showing also an example.
> 1) I have a function (in my real case it's much more complex)
> 2) I use "optim" to minimize
> 3) I want to use as method L-BFGS-B for several reasons
> 4) I know I could use "trace=6" (in "control") in order to see "live"
> the procedure
> 5) I would like to see separately the values of my parameters during
> each iteration (what, on the screen, are the values of X)
> 6) Hence I would need to know the way of asking R to save somewhere the
> values of X during the optimization procedure
> 7) I have already tried to use "write.table" into the function I want to
> minimize (in the example with comments), but it gave me more values that
> I would need
>
> Might you know a solution?
>
> EXAMPLE:
> ###### function
> fun <- function(param){
> a <- param[1]
> b <- param[2]
> r <- sqrt(a^2+b^2)
> res <- -10 * sin(r)/r
> #write.table(x=b, file="B.txt", append=TRUE, sep=",",
> col.names=FALSE,
> # row.names=FALSE)

This way you get each step where the function is *evaluated*, which might be much more than each iteration step of the optimization.

> return(res)
> }
>
> ######## optimization procedure
> ott <- optim(par=c(-1,1),
> fn =fun,
> method = c("L-BFGS-B"),
> control=c(trace=6)
> )

For example, you can sink() temorarily into a file and extract the relevant lines (beginning with "X = ") afterwards.

Uwe Ligges

> ######### what I would need to save
> [...]
> X = -0.292893 0.292893
> [...]
> X = 0.0942275 -0.0942275
> [...]
> X = -0.00110391 0.00110391
> [...]
> X = 1.93949e-006 -1.93949e-006
> [...]
> X = -4.98008e-013 4.98008e-013
> [...]
>
>
>
> Thanks in advance,
> Carlo Giovanni Camarda
>
>
>
> Camarda Carlo Giovanni
> Max Planck Institute for Demographic Research
> Konrad-Zuse-Strasse 1
> 18057 Rostock, Germany
>
> Tel: +49 (0)381 2081 172
> Fax: +49 (0)381 2081 472
> Camarda@demogr.mpg.de
>
>
>
>
> +++++
> This mail has been sent through the MPI for Demographic Rese...{{dropped}}
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html Received on Mon May 16 00:58:16 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:31:46 EST