プリンキピア

第2章準備

2.5.1. A Simple Function2.5.1 簡単な関数

Let’s assume that we are interested in differentiating the function y=2𝐱⊤𝐱 with respect to the column vector 𝐱. To start, we assign x an initial value.
英語のヒント
列ベクトル𝐱について関数y=2𝐱⊤𝐱を微分することに関心があるとしよう。まず、xに初期値を代入する。
x = torch.arange(4.0)
x
tensor([0., 1., 2., 3.])
Before we calculate the gradient of y 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 𝐱.
英語のヒント
𝐱についてのyの勾配を計算する前に、それを保存する場所が必要である。一般に、導関数をとるたびに新しいメモリを割り当てることは避ける。深層学習では、同じパラメータについて導関数を何度も繰り返し計算する必要があり、メモリが足りなくなるおそれがあるからである。ベクトル𝐱についてのスカラー値関数の勾配は、𝐱と同じ形状のベクトル値になることに注意してほしい。
# Can also create x = torch.arange(4.0, requires_grad=True)
x.requires_grad_(True)
x.grad  # The gradient is None by default
We now calculate our function of x and assign the result to y.
英語のヒント
では、xの関数を計算し、その結果をyに代入しよう。
y = 2 * torch.dot(x, x)
y
tensor(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.grad
tensor([ 0.,  4.,  8., 12.])
We already know that the gradient of the function y=2𝐱⊤𝐱 with respect to 𝐱 should be 4𝐱. We can now verify that the automatic gradient computation and the expected result are identical.
英語のヒント
関数y=2𝐱⊤𝐱の𝐱についての勾配は4𝐱になるはずだとすでにわかっている。自動で計算した勾配と、期待される結果が同じであることを確かめられる。
x.grad == 4 * x
tensor([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.grad
tensor([1., 1., 1., 1.])