テンソルの勾配
勾配とは変化量を表す値であり、多くの機械学習アルゴリズムが勾配を用いて解の探索を行っている。Pytorchのテンソル型は勾配についての情報を扱う機能をもつ。
テンソルの生成時に、名前付き引数requires_gradにTrueを与えることで、そのテンソルは勾配を扱えるようになる。
code:tensor_kobai1.py
import torch as pt
x = pt.tensor(1., dtype=pt.float, requires_grad=True)
print(type(x))
print(x)
結果は次のようになり、テンソルxに勾配を扱うための設定が与えられたことが確認できる。
code:Result.txt
<class 'torch.Tensor'>
tensor(1., requires_grad=True)
上記のテンソルはpt.float型として生成した。
下記のように整数型から構成されるテンソルは勾配を扱うことはできない。
code:tensor_kobai2.py
import torch as pt
x = pt.tensor(1, dtype=pt.int, requires_grad=True)
print(type(x))
print(x)
code:(結果).py
RuntimeError: Only Tensors of floating point and complex dtype can require gradients
浮動小数点数や複素数から構成されたテンソルのみ勾配を扱うことができる。