我正在探索 autodiff,我想使用 Deriv
来计算函数与向量的导数。我写
library(numDeriv)
library(Deriv)
h = function(x) c(1,2)%*%x
grad(h,c(1,2)) #ok
#[1] 1 2
dh=Deriv(h,x='x')
#Error in c(1, 2) %*% 1 : non-conformable arguments
dh(c(1,2))
有人有好的方法吗?
从help(Deriv)
来看,似乎应该能够让参数成为一个向量
here is a side effect with vector length. E.g. in Deriv(~a+bx, c("a", "b")) the result is c(a = 1, b = x). To avoid the difference in lengths of a and b components (when x is a vector), one can use an optional parameter combine Deriv(~a+bx, c("a", "b"), combine="cbind") which gives cbind(a = 1, b = x) producing a two column matrix which is probably the desired result here.
我想避免使每个向量分量成为函数的不同参数。
例如上面的 numDeriv
让我们可以轻松地对 rt 向量进行导数 x
最佳答案
这是一个答案; to 包以不同的方式处理多个维度。
library(numDeriv)
library(Deriv)
h = function(x,y) c(1,2) %*% c(x,y)
grad(\(x) h(x[1], x[2]),c(1,2))
dh = Deriv(h)
dh(c(1,2))
关于r - 使用 Deriv 包求导 wrt 向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69876390/