第2章準備
2.5.4. Gradients and Python Control Flow2.5.4 勾配とPythonの制御フロー
So far we reviewed cases where the path from input to output was well defined via a function such as
z = x * x * x. Programming offers us a lot more freedom in how we compute results. For instance, we can make them depend on auxiliary variables or condition choices on intermediate results. One benefit of using automatic differentiation is that even if building the computational graph of a function required passing through a maze of Python control flow (e.g., conditionals, loops, and arbitrary function calls), we can still calculate the gradient of the resulting variable. To illustrate this, consider the following code snippet where the number of iterations of the while loop and the evaluation of the if statement both depend on the value of the input a.英語のヒント
ここまでは、入力から出力への経路が
z = x * x * xのような関数ではっきり定まっている場合を見てきた。プログラミングでは、結果の計算のしかたにずっと多くの自由がある。たとえば、補助的な変数に依存させたり、中間結果によって選択を変えたりできる。自動微分を使う利点の一つは、関数の計算グラフを作るのにPythonの制御フロー(たとえば条件分岐、ループ、任意の関数呼び出し)の迷路を通る必要があったとしても、得られた変数の勾配を計算できることである。これを示すために、次のコードの断片を考えよう。ここではwhileループの反復回数とif文の評価がどちらも入力aの値に依存する。def f(a):
b = a * 2
while b.norm() < 1000:
b = b * 2
if b.sum() > 0:
c = b
else:
c = 100 * b
return cBelow, we call this function, passing in a random value, as input. Since the input is a random variable, we do not know what form the computational graph will take. However, whenever we execute
f(a) on a specific input, we realize a specific computational graph and can subsequently run backward.英語のヒント
下では、この関数を、無作為な値を入力として渡して呼び出す。入力は確率変数なので、計算グラフがどんな形をとるかはわからない。しかし、特定の入力に対して
f(a)を実行するたびに、特定の計算グラフが実現され、その後でbackwardを実行できる。a = torch.randn(size=(), requires_grad=True)
d = f(a)
d.backward()Even though our function
f is, for demonstration purposes, a bit contrived, its dependence on the input is quite simple: it is a linear function of a with piecewise defined scale. As such, f(a) / a is a vector of constant entries and, moreover, f(a) / a needs to match the gradient of f(a) with respect to a.英語のヒント
関数
fは、実演のためにやや作り込まれているが、入力への依存はとても単純である。区分的に定義された倍率をもつ、aの線形関数である。そのため、f(a) / aは成分が一定のベクトルであり、さらにf(a) / aは、aについてのf(a)の勾配と一致するはずである。a.grad == d / atensor(True)Dynamic control flow is very common in deep learning. For instance, when processing text, the computational graph depends on the length of the input. In these cases, automatic differentiation becomes vital for statistical modeling since it is impossible to compute the gradient a priori.
英語のヒント
動的な制御フローは深層学習ではとてもよくある。たとえば文章を処理するとき、計算グラフは入力の長さに依存する。こうした場合、勾配を前もって計算することはできないので、統計モデリングでは自動微分が欠かせなくなる。