第2章準備
2.5.1. A Simple Function2.5.1 簡単な関数
Let’s assume that we are interested in differentiating the function with respect to the column vector . To start, we assign
x an initial value.英語のヒント
列ベクトルについて関数を微分することに関心があるとしよう。まず、
xに初期値を代入する。x = torch.arange(4.0)
xtensor([0., 1., 2., 3.])Before we calculate the gradient of with respect to , we need a place to store it. In general, we avoid allocating new memory every time we take a derivative because deep learning requires successively computing derivatives with respect to the same parameters a great many times, and we might risk running out of memory. Note that the gradient of a scalar-valued function with respect to a vector is vector-valued with the same shape as .
英語のヒント
についてのの勾配を計算する前に、それを保存する場所が必要である。一般に、導関数をとるたびに新しいメモリを割り当てることは避ける。深層学習では、同じパラメータについて導関数を何度も繰り返し計算する必要があり、メモリが足りなくなるおそれがあるからである。ベクトルについてのスカラー値関数の勾配は、と同じ形状のベクトル値になることに注意してほしい。
# Can also create x = torch.arange(4.0, requires_grad=True)
x.requires_grad_(True)
x.grad # The gradient is None by defaultWe now calculate our function of
x and assign the result to y.英語のヒント
では、
xの関数を計算し、その結果をyに代入しよう。y = 2 * torch.dot(x, x)
ytensor(28., grad_fn=<MulBackward0>)We can now take the gradient of
y with respect to x by calling its backward method. Next, we can access the gradient via x’s grad attribute.英語のヒント
これで、
yのbackwardメソッドを呼び出せば、xについての勾配をとれる。次に、xのgrad属性で勾配を取り出せる。y.backward()
x.gradtensor([ 0., 4., 8., 12.])We already know that the gradient of the function with respect to should be . We can now verify that the automatic gradient computation and the expected result are identical.
英語のヒント
関数のについての勾配はになるはずだとすでにわかっている。自動で計算した勾配と、期待される結果が同じであることを確かめられる。
x.grad == 4 * xtensor([True, True, True, True])Now let’s calculate another function of
x and take its gradient. Note that PyTorch does not automatically reset the gradient buffer when we record a new gradient. Instead, the new gradient is added to the already-stored gradient. This behavior comes in handy when we want to optimize the sum of multiple objective functions. To reset the gradient buffer, we can call x.grad.zero_() as follows:英語のヒント
今度は
xの別の関数を計算し、その勾配をとろう。新しい勾配を記録するとき、PyTorchは勾配のバッファを自動でリセットしないことに注意してほしい。代わりに、新しい勾配はすでに保存されている勾配に足される。この振る舞いは、複数の目的関数の和を最適化したいときに役に立つ。勾配のバッファをリセットするには、次のようにx.grad.zero_()を呼び出せばよい。x.grad.zero_() # Reset the gradient
y = x.sum()
y.backward()
x.gradtensor([1., 1., 1., 1.])