gradによる勾配ベクトルの計算【torch】
grad(arg1, arg2)
arg1 ... 勾配ベクトルを計算する対象となるスカラ値
arg2 ... 勾配を求める座標、複数のテンソルに分割されていてもよい、requires_grad=Trueが必要
2変数を独立した引数として渡す例。、戻り値は長さ2のタプルで返され、それぞれに$ \partial f / \partial x, \partial f/\partial y が格納されている。
code:p1.py
import torch as pt
from torch.autograd import grad
def himmelblau(x, y):
return (x**2 + y - 11)**2 + (x + y**2 - 7)**2
x = pt.tensor(0, dtype=pt.float, requires_grad=True)
y = pt.tensor(0, dtype=pt.float, requires_grad=True)
f = himmelblau(x, y)
g = grad(f, (x, y), create_graph=True)
print(g)
'''
(tensor(-14., grad_fn=<AddBackward0>), tensor(-22., grad_fn=<AddBackward0>))
'''
勾配を求める座標 x, y に requires_grad=True が必要であった。
2変数を長さが2のベクトルとして渡す例。戻り値は長さ1のタプルで返される。
code:p.py
import torch as pt
from torch.autograd import grad
def himmelblau(x):
return (x0**2 + x1 - 11)**2 + (x0 + x1**2 - 7)**2 x = pt.tensor(0, 0, dtype=pt.float, requires_grad=True) f = himmelblau(x)
g = grad(f, x, create_graph=True)
print(g)
'''
'''