深度学习要求我们解决多个复杂的方程,而且是针对数百万和数十亿行的方程。在Python中运行循环来解决这些方程是非常慢的,此时,向量化是最佳的解决方案。
例如,要计算以下多线性回归方程中数百万行的y值。
我们可以用向量化代替循环。
m1,m2,m3...
的值是通过使用对应于x1,x2,x3...
的数百万个值来解决上述方程而确定的(为了简单起见,只看一个简单的乘法步骤)
创建数据
>>> import numpy as np
>>> # 设置 m 的初始值
>>> m = np.random.rand(1,5)
array([[0.49976103, 0.33991827, 0.60596021, 0.78518515, 0.5540753]])
>>> # 500万行的输入值
>>> x = np.random.rand(5000000,5)
使用循环
import numpy as np
m = np.random.rand(1,5)
x = np.random.rand(5000000,5)
total = 0
tic = time.process_time()
for i in range(0,5000000):
total = 0
for j in range(0,5):
total = total + x[i][j]*m[0][j]
zer[i] = total
toc = time.process_time()
print ("Computation time = " + str((toc - tic)) + "seconds")
####Computation time = 28.228 seconds
使用向量化
tic = time.process_time()
#dot product
np.dot(x,m.T)
toc = time.process_time()
print ("Computation time = " + str((toc - tic)) + "seconds")
####Computation time = 0.107 seconds
np.dot
在后端实现了向量的矩阵乘法。与python中的循环相比,它的速度提高了165倍。