版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36022260/article/details/83099444
如果你可以使用深度学习或者找到其他方法解决循环,通常比直接使用For循环更快。
看下面例子:
import numpy as np
import time
a = np.random.rand(1000000)
b = np.random.rand(1000000)
tic = time.time()
c = np.dot(a,b)
print(c)
toc = time.time()
print("Vecterized 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(c)
print("For Loop:"+str(1000*(toc-tic))+"ms")
结果如下:
249788.55150159978
Vecterized version:3.9856433868408203ms
249788.55150160525
For Loop:1425.093412399292ms
# 内置函数
import numpy as np
v = np.array([1,2,3,4])
u = np.exp(v)
print(list(v)
print(u)
# For循环
u = np.zeros(n,1)
for i in range(n):
u[i] = math.exp(v[i])
Python / numpy vectors
import numpy as np
a = np.random.randn(5)
a = np.random.randn((5,1))
a = np.random.randn((1,5))
在python编程时尽量把秩为1的数组和行向量区分开。