如何获取深度学习模型中输出相对于输入的偏导数?

How to get access to the partial derivatives of output with respect to inputs in deep learning model?

我想在keras中创建自己的损失函数,其中包含导数。例如,

def my_loss(x):
    def y_loss(y_true,y_pred):
        res = K.gradients(y_pred,x)
        return res
    return y_loss

已定义,并且

model = Sequential()
model.add(Dense(10, input_dim=2, activation='sigmoid'))
model.add(Dense(1, activation='linear'))
model_loss = my_loss(x=model.input)
model.compile(loss=model_loss, optimizer='adam')

现在因为输入是二维的,

K.gradients(y_pred,x)

必须是二维向量。 但是,我不知道如何获得梯度中的每个标量。我最终想要的是 y_pred 对 x 的所有二阶导数。有什么方便的方法可以得到吗?


类似于post,但是这个post把二维变量分成了两个一维变量。有没有其他方法可以在不分离输入的情况下获得梯度?

如果你想要拉普拉斯算子,为什么不使用具有所有二阶导数的 tf.hessians? Laplacian 应该等于 Hessian 矩阵的迹(按身份)

https://www.tensorflow.org/api_docs/python/tf/hessians

不幸的是,Keras 没有方便的方法来获取梯度的每个分量。因此,我使用tensorflow解决了这个问题。

if f if 对象函数带有变量 x=(x1,x2)

X=tf.placeholder(tf.float32,shape=(None,2))
f=f(X)#assume it is defined'

那么df/dx_1就是

tf.gradients(f,x)[0][:,0]

df/dx_2 是

tf.gradients(f,x)[0][:,1]

d^2f/dx_1^2 是

tf.gradietns(tf.gradients(f,x))[0][:,0]

d^2f/dx_2^2 是

tf.gradietns(tf.gradients(f,x))[0][:,1]

d^2f/dx_1dx_2 是

tf.gradietns(tf.gradients(f,x)[0][:,0])[0][:,1]

我相信有更好的方法,但我找不到。