2024.6.28 指定要素の自動微分【torch】
PuTorchの自動微分を行うメソッドであるbackwardはスカラ型の要素のみに適用可能である。ベクトルや行列全体に対して適用することはできない。
code:p01.py
import torch as pt
A = pt.tensor(1,1],0,1,2,0,[3,1, dtype=pt.float)
A.requires_grad = True
A = pt.tensor(1,0,2,2,0],[0,1,3,1,1, dtype=pt.float)
A.requires_grad = True
X = A @ B
X.backward()
こんなエラーが生じる
RuntimeError: grad can be implicitly created only for scalar outputs
添字を用いて対象を1要素に指定すれば、適用することができる。
code:p02.py
import torch as pt
A = pt.tensor(1,1],0,1,2,0,[3,1, dtype=pt.float, requires_grad=True)
B = pt.tensor(1,0,2,2,0],[0,1,3,1,1, dtype=pt.float, requires_grad=True)
print('A =\n', A)
print('B =\n', B)
X = A @ B
X3,2.backward()
print('A.grad =\n', A.grad)
print('B.grad =\n', B.grad)
上の結果は行列積の仕組みから自明であるが、$ (i, j) 要素に対する勾配は$ Aの$ i行目と$ Bの$ j列目となる。
code:result.txt[
A =
tensor([1., 1.,
0., 1.,
2., 0.,
3., 1.], requires_grad=True)
B =
tensor([1., 0., 2., 2., 0.,
0., 1., 3., 1., 1.], requires_grad=True)
A.grad =
tensor([0., 0.,
0., 0.,
0., 0.,
2., 3.])
B.grad =
tensor([0., 0., 3., 0., 0.,
q 0., 0., 1., 0., 0.])