LoginSignup
3
5

More than 3 years have passed since last update.

ベクトル化による計算効率の良さをPythonで実感する

Posted at

ベクトル化が必要な理由

n次元ベクトルのwとxがあったとき、$z = w_1x_1 + w_2x_2...w_nx_n$を計算するのにfor文だと効率が悪い。
ベクトル化すると$z = w^Tx + b$とすることで効率よく計算できる。
Pythonだと以下のコードで比較できる。

import numpy as np
import time

a = np.random.rand(1000000)
b = np.random.rand(1000000)

tic = time.time()
c = np.dot(a, b)
toc = time.time()
print(f'{"Vectrized version":20}:{str(1000 * (toc-tic))} ms')

c = 0
tic = time.time()
for i in range(1000000):
    c += a[i] * b[i]
toc = time.time()
print(f'{"For loop":20}:{str(1000 * (toc-tic))} ms')
Vectrized version   :3.9501190185546875 ms
For loop            :1007.7228546142578 ms

指数演算で

1000000次元ベクトル$v$に指数演算を実行したいとする。

import numpy as np
import time
import math

v = np.random.rand(1000000)
u = np.zeros((1000000, 1))
tic = time.time()
u = np.exp(v)
toc = time.time()
print(f'{"Vectrized version":20}:{str(1000 * (toc-tic))} ms')

c = 0
tic = time.time()
for i in range(1000000):
    u[i] = math.exp(v[i])
toc = time.time()
print(f'{"For loop":20}:{str(1000 * (toc-tic))} ms')
Vectrized version   :3.992319107055664 ms
For loop            :857.1090698242188 ms

まとめ

ベクトル化したものとしていないもので約300倍もの差が出ている。
for-loopを使いたくなったときは使わずに済む方法を考えるようにしたい。

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5