计算R中的梯度和Hessian

时间:2015-01-28 10:29:09

标签: r calculus derivative

如您所知,函数的渐变是以下向量:

the Gradient

和Hessian是以下矩阵:

the Hessian

现在,我想知道,有没有办法在R中为给定点的用户定义函数计算这些?

首先,我找到了一个名为numDeriv的包,它似乎具有必要的功能gradhessian,但现在我无法得到正确的结果......因此,这是我的工作流程:

假设我们给出函数f(x,y)= x ^ 2 * x ^ 3,我们需要计算点(x = 1,y = 2)处的梯度和Hessian。 / p>

据说,我在R:

中定义了这个函数
dummy <- function(x,y) {
  rez <- (z^2)*(y^3)
  rez
}

然后按以下方式使用grad

grad(func=dummy, x=1, y=2)

给我结果16 - 问题是这只是渐变矢量的第一个值,正确的版本是

[16, 12]

hessian

相同
hessian(func=dummy, x=1, y=2)

给我的1x1矩阵的值为16而不是2x2矩阵

     [,1] [,2]
[1,]   16   24
[2,]   24   12

所以,问题是我做错了什么?

谢谢。

2 个答案:

答案 0 :(得分:14)

您可以使用pracma库,例如:

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

答案 1 :(得分:0)

以下代码是所提供答案的扩展。它处理的是具有函数值而不是实际函数的情况。这里的函数有1个参数。 Grad函数在单个点中计算。如果你有3个参数,那么你需要用c(x1,x2,x3)将它们提供给x0。

#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);
相关问题