makeSmart | R Documentation |
This function allows you to convert a non-smart numerical gradient to a SMART Gradient
makeSmart(fn, gr, ..., gr.args = list())
fn |
A function to be minimized (or maximized), |
gr |
is an optional generic gradient function of type: gr(fun, x, ...) and it returns the gradient for the "BFGS" |
... |
Further arguments to be passed to fn and gr. |
gr.args |
Specific arguments to 'gr' needs to be passed. |
library(lbfgs) library(stats) myfun <- function(x) { 100 * (x[2] - x[1]^2)^2 + (1 - x[1])^2} mygrad <- function(fun,x) { h = 0.001 grad <- numeric(2) grad[1] <- (fun(x + c(h,0)) - fun(x - c(h,0))) / (2 * h) grad[2] <- (fun(x + c(0,h)) - fun(x - c(0,h))) / (2 * h) return (grad) } mySmartgrad = smartGrad::makeSmart(fn = myfun, gr = mygrad) x_initial = rnorm(2) result1 <- stats::optim(par = x_initial, fn = myfun, gr = mySmartgrad, method = c("BFGS"), hessian = FALSE) result2 <- lbfgs::lbfgs(myfun, mySmartgrad, vars = x_initial)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.