# NOT RUN {
### Example optimizing Rosenbrock 2D function
### Note that this example is not stochastic, as the
### function is not evaluated in expectation based on
### batches of data, but rather it has a given absolute
### form that never varies.
### Warning: this optimizer is meant for convex functions
### (Rosenbrock's is not convex)
library(stochQN)
fr <- function(x) { ## Rosenbrock Banana function
x1 <- x[1]
x2 <- x[2]
100 * (x2 - x1 * x1)^2 + (1 - x1)^2
}
grr <- function(x) { ## Gradient of 'fr'
x1 <- x[1]
x2 <- x[2]
c(-400 * x1 * (x2 - x1 * x1) - 2 * (1 - x1),
200 * (x2 - x1 * x1))
}
Hvr <- function(x, v) { ## Hessian of 'fr' by vector 'v'
x1 <- x[1]
x2 <- x[2]
H <- matrix(c(1200 * x1^2 - 400*x2 + 2,
-400 * x1, -400 * x1, 200),
nrow = 2)
as.vector(H %*% v)
}
### Initial values of x
x_opt = as.numeric(c(0, 2))
cat(sprintf("Initial values of x: [%.3f, %.3f]\n",
x_opt[1], x_opt[2]))
### Will use constant step size throughout
### (not recommended)
step_size = 1e-3
### Initialize the optimizer
optimizer = SQN_free()
### Keep track of the iteration number
curr_iter <- 0
### Run a loop for severa, iterations
### (Note that some iterations might require more
### than 1 calculation request)
for (i in 1:200) {
req <- run_SQN_free(optimizer, x_opt, step_size)
if (req$task == "calc_grad") {
update_gradient(optimizer, grr(req$requested_on$req_x))
} else if (req$task == "calc_hess_vec") {
update_hess_vec(optimizer,
Hvr(req$requested_on$req_x, req$requested_on$req_vec))
}
### Track progress every 10 iterations
if (req$info$iteration_number > curr_iter) {
curr_iter <- req$info$iteration_number
}
if ((curr_iter %% 10) == 0) {
cat(sprintf(
"Iteration %3d - Current function value: %.3f\n",
req$info$iteration_number, fr(x_opt)))
}
}
cat(sprintf("Current values of x: [%.3f, %.3f]\n",
x_opt[1], x_opt[2]))
# }
Run the code above in your browser using DataLab