This question is related to Applying Cost Functions in R
I would like to know how to save the coefficients generated for each iteration of optim
. trace=TRUE
enables me to get the coefficients for each iteration printed, but how can I save them?
Example code:
set.seed(1)
X <- matrix(rnorm(1000), ncol=10) # some random data
Y <- sample(0:1, 100, replace=TRUE)
# Implement Sigmoid function
sigmoid <- function(z) {
g <- 1/(1+exp(-z))
return(g)
}
cost.glm <- function(theta,X) {
m <- nrow(X)
g <- sigmoid(X%*%theta)
(1/m)*sum((-Y*log(g)) - ((1-Y)*log(1-g)))
}
X1 <- cbind(1, X)
df <- optim(par=rep(0,ncol(X1)), fn = cost.glm, method='CG',
X=X1, control=list(trace=TRUE))
Which outputs:
Conjugate gradients function minimizer Method: Fletcher Reeves tolerance used in gradient test=2.00089e-11 0 1 0.693147 parameters 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 0.00000 i> 1 3 0.662066 parameters -0.01000 -0.01601 -0.06087 0.14891 0.04123 0.03835 -0.01898 0.00637 0.02954 -0.01423 -0.07544 i> 2 5 0.638548 parameters -0.02366 -0.03733 -0.13803 0.32782 0.09034 0.08082 -0.03978 0.01226 0.07120 -0.02925 -0.16042 i> 3 7 0.630501 parameters -0.03478 -0.05371 -0.19149 0.43890 0.11960 0.10236 -0.04935 0.01319 0.10648 -0.03565 -0.20408 i> 4 9 0.627570.......
And df
does not contain any information on the coefficients, but only displays the final coefficients and the final cost:
str(df)
List of 5 $ par : num [1:11] -0.0679 -0.1024 -0.2951 0.6162 0.124 ... $ value : num 0.626 $ counts : Named int [1:2] 53 28 ..- attr(*, "names")= chr [1:2] "function" "gradient" $ convergence: int 0 $ message : NULL