Python:矩阵函数的梯度

Python: Gradient of matrix function

我想计算以下函数的梯度 h(x) = 0.5 x.T * A * x + b.T + x。

现在我将 A 设置为 (2,2) 矩阵。

def function(x):
    return 0.5 * np.dot(np.dot(np.transpose(x), A), x) + np.dot(np.transpose(b), x)

其中

A = A = np.zeros((2, 2))
n = A.shape[0]
A[range(n), range(n)] = 1

a (2,2) 主对角线为1且

的矩阵
b = np.ones(2) 

对于给定的点 x = (1,1) numpy.gradient returns 一个空列表。

x = np.ones(2)  
result = np.gradient(function(x))

但是我不应该得到这样的东西:grad(f((1,1)) = (x1 + 1, x2 + 1) = (2, 2).

感谢任何帮助。

您似乎想执行符号微分或自动微分,而 np.gradient 不会。 sympy 是符号数学包,autograd 是 numpy 自动微分包。例如,使用 autograd:

import autograd.numpy as np
from autograd import grad

def function(x):
    return 0.5 * np.dot(np.dot(np.transpose(x), A), x) + np.dot(np.transpose(b), x)

A = A = np.zeros((2, 2))
n = A.shape[0]
A[range(n), range(n)] = 1
b = np.ones(2)
x = np.ones(2)
grad(function)(x)

输出:

array([2., 2.])