第3章回帰のための線形ニューラルネットワーク
3.1.2. Vectorization for Speed3.1.2 速さのためのベクトル化
When training our models, we typically want to process whole minibatches of examples simultaneously. Doing this efficiently requires that we vectorize the calculations and leverage fast linear algebra libraries rather than writing costly for-loops in Python.
英語のヒント
モデルを訓練するときは、普通、事例のミニバッチ全体を同時に処理したい。これを効率よく行うには、Pythonで費用のかかるforループを書くのではなく、計算をベクトル化し、高速な線形代数のライブラリを活用する必要がある。
To see why this matters so much, let’s consider two methods for adding vectors. To start, we instantiate two 10,000-dimensional vectors containing all 1s. In the first method, we loop over the vectors with a Python for-loop. In the second, we rely on a single call to
+.英語のヒント
これがなぜそれほど大事なのかを見るために、ベクトルを足す二つの方法を考えよう。まず、すべて1を含む10,000次元のベクトルを二つ作る。一つ目の方法では、Pythonのforループでベクトルを順にたどる。二つ目では、
+を1回呼び出すことに頼る。n = 10000
a = torch.ones(n)
b = torch.ones(n)Now we can benchmark the workloads. First, we add them, one coordinate at a time, using a for-loop.
英語のヒント
では、作業量を比べてみよう。まず、forループを使って、座標を一つずつ足していく。
c = torch.zeros(n)
t = time.time()
for i in range(n):
c[i] = a[i] + b[i]
f'{time.time() - t:.5f} sec''0.17802 sec'Alternatively, we rely on the reloaded
+ operator to compute the elementwise sum.英語のヒント
あるいは、再定義された
+演算子に頼って、要素ごとの和を計算する。t = time.time()
d = a + b
f'{time.time() - t:.5f} sec''0.00036 sec'The second method is dramatically faster than the first. Vectorizing code often yields order-of-magnitude speedups. Moreover, we push more of the mathematics to the library so we do not have to write as many calculations ourselves, reducing the potential for errors and increasing portability of the code.
英語のヒント
二つ目の方法は、一つ目より劇的に速い。コードをベクトル化すると、桁違いの高速化が得られることが多い。さらに、数学の多くをライブラリに任せるので、自分で書く計算が少なくて済み、誤りの可能性が減り、コードの移植性が高まる。