I am exploring autodiff, and I would like to use Deriv
for computing a derivative of a function wrt to a vector. I write
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))
Does anyone have a good way to do this?
From help(Deriv)
, it seems like one should be able to let the argument be a vector
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.
I would like to avoid making each of the vector components a different argument to the function.
For example numDeriv
above lets us easily take a derivative wrt vector x
CodePudding user response:
This is an answer; The to packages handles multiple dimensions differently.
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))
CodePudding user response:
Here is a solution using not Deriv
but madness,
a really neat package.
We basically create an object that is the thing we would like to take the derivative with respect to (in this case x
), and then as we apply functions to that object, the derivatives are collected.
We get the evaluated derivative using this function, as we do with grad
in numDeriv
.
library(madness)
h = function(x){t(x)%*%matrix(c(2,1),nrow=2,ncol=1)}
x=matrix(c(1,1),nrow=2,ncol=1)
gd=function(h,x){
x=madness(val=x)
z=h(x)
attr(z,"dvdx")
}
gd(h,x)
# [,1] [,2]
#[1,] 2 1