for-loop的计算时间较长,可通过vectorization来提高运算速率。
import numpy as np
import time
a=np.random.rand(1000000)
b=np.random.rand(1000000)
tic=time.time()
c=np.dot(a,b)#vectorized
toc=time.time()
print("vectorized version:"+str(1000*(toc-tic))+'ms')
c=0
tic=time.time()
for i in range(1000000):
c+=a[i]*b[i]
toc=time.time()
print("for loop:"+str(1000*(toc-tic))+'ms')
上面运算的结果为:
- vectorized version:0.957489013671875ms
- for loop:399.930477142334ms
其他还有一些简单的运算都可以避免for-loop,例如:
- u=np.exp(v)
- u=np.log(v)
- u=np.abs(v)
(Andrew Ng)