r - 使用 Deriv 包求导 wrt 向量

标签 r autodiff

我正在探索 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/

相关文章:

多次运行一段代码,更改 R 中的某些参数(如 SAS 中的宏)

r - 如何通过获取先前的值来增加 xts 对象中的观察数量?

r - R中的SVM:“预测变量必须是数字或有序的。”

python - 查找函数的梯度 : Sympy vs. Jax

python - 当 `tape.watch(x)` 在 TensorFlow 中已经是 `x` 时调用 `tf.Variable` 是否可以?

cntk - 微软CNTK自动微分

python - Tensorflow:对前向和后向传递使用不同的表达式

R:如何停止在绘图图表上将百分比四舍五入到小数点后 0 位?

r - 在某些值的连续运行中创建计数器