【问题标题】:calculating the Gradient and the Hessian in R在 R 中计算梯度和 Hessian
【发布时间】:2015-01-28 10:29:09
【问题描述】:

如你所知,函数的梯度是以下向量:

Hessian 矩阵如下:

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

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

假设给定函数 f(x,y) = x^2 * x^3,我们需要计算点 (x=1, y=2) 的 Gradient 和 Hessian。

说了这么多,我在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

那么,问题是我做错了什么?

谢谢。

【问题讨论】:

  • 附带说明,我也 tried Wolfram|Alpha 但也未能得到正确的结果...
  • dummy &lt;- function(x) {(x[1]^2)*(x[2]^3)};grad(func=dummy, x=c(1,2));hessian(func=dummy, x=c(1,2))
  • Khashaa,是的,我现在明白我的错误了,谢谢 :)。

标签: r calculus derivative


【解决方案1】:

可以使用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

【讨论】:

  • @AS 供将来参考,请加载 sos 包。它使搜索关键术语变得容易。在您的情况下,您只需键入 ???hessian 即可跟踪此功能和包。
【解决方案2】:

以下代码是所提供答案的扩展。它处理您拥有函数值而不是实际函数的情况。这里函数有 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);

【讨论】:

    猜你喜欢
    • 2015-07-12
    • 1970-01-01
    • 2015-06-17
    • 2020-05-26
    • 1970-01-01
    • 2020-03-31
    • 1970-01-01
    • 1970-01-01
    • 2012-08-18
    相关资源
    最近更新 更多