torch.autograd.backward
1. Jacobian matrix
In vector calculus, the Jacobian matrix is the matrix of all first-order partial derivatives of a vector-valued function. When the matrix is a square matrix, both the matrix and its determinant are referred to as the Jacobian in literature.
Suppose is a function which takes as input the vector and produces as output the vector . Then the Jacobian matrix of is an matrix, usually defined and arranged as follows:
or, component-wise:
2. Examples
假设:
则有:
令
所以:
假设,则结果为:
>>> import torch
>>> x = torch.tensor([[1, 2]], requires_grad=True)
>>> y = torch.zeros(1,2)
>>> y[0,0] = 2 * x[0,0] + x[0,1] ** 2
>>> y[0,1] = x[0,0] ** 2 + 2 * x[0,1] ** 3
>>> print(x, y)
tensor([[ 1, 2]]) tensor([[ 6., 17.]])
>>> y.backward(torch.tensor([[1,0]]), retain_graph=True)
>>> print(x.grad)
tensor([[ 2, 4]])
>>> x.grad.zero_()
>>> y.backward(torch.tensor([[0,1]]), retain_graph=True)
>>> print(x.grad)
tensor([[ 2, 24]])
>>> x.grad.zero_()
>>> y.backward(torch.tensor([[1,2]]), retain_graph=True)
>>> print(x.grad)
tensor([[ 6, 52]])
>>> x.grad.zero_()
>>> y.backward(torch.tensor([[2,1]]), retain_graph=True)
>>> print(x.grad)
tensor([[ 6, 32]])
复制代码
即:
(k1,k2)=(1,0)
1 * [2, 4] + 0 * [2, 24] = [2, 4]
(k1,k2)=(0,1)
0 * [2, 4] + 1 * [2, 24] = [2, 24]
(k1,k2)=(1,2)
1 * [2, 4] + 2 * [2, 24] = [6, 52]
(k1,k2)=(2,1)
2 * [2, 4] + 1 * [2, 24] = [6, 32]