calculating the Gradient and the Hessian in R

混江龙づ霸主 提交于 2019-12-03 08:55:49

You can use the pracma library, such as:

library(pracma)

dummy <- function(x) {
  z <- x[1]; y <- x[2]
  rez <- (z^2)*(y^3)
  rez
}

grad(dummy, c(1,2))
[1] 16 12

hessian(dummy, c(1,2))
     [,1] [,2]
[1,]   16   24
[2,]   24   12

The following code is an extension of the answer provided. It treats the case where you have the values of the function and not the actual function. Here the function has 1 parameter. The Grad function calculates in a single point. If you have 3 parameters then you need to provide them to x0 with c(x1,x2,x3).

#i is an index, s_carvone$val contains the values of the function
dummy <- function(i) 
{
  return (s_carvone$val[i])
}

#function that calculates the gradient in a specific point i
calc_grad <- function(i)
{
  return (pracma::grad(dummy, x0=i, heps=1))
}

#calculates the derivative from point 2 to 61
first_derivative = unlist(purrr::map(calc_grad, .x = c(2:61)));

plot(first_derivative);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!