上吴恩达老师的课,介绍了python中向量化操作的速度和for循环的速度不是一个量级,故通过实验进行直观体会:
实验环境:windows10 python 3.7 jupyter
import numpy as np
import time
# 设置随机种子,保证每次生成的随机数不同
rd = np.random.RandomState(round(time.time()))
#随机浮点数
a = rd.random(1000000)
b = rd.random(1000000)
# 随机整数矩阵
A = rd.randint(-2, 3, (10000, 100)) # 随机生成[-2,3)的整数,1000x100的矩阵
B = rd.randint(-2, 3, (10000, 100))
V = rd.randint(-100,100, (100,30))
# A = np.array([[1,2],[3,4]])
# V = np.array([[1,1],[2,2]])
# a = np.array([[1,1,1],[1,1,1]])
# b = np.array([[2,2],[2,2],[2,2]])
#测试向量内积
tic = time.time()
#如果操作数是向量,则dot返回内积;如果是矩阵,则返回外积即矩阵乘法
c1 = np.dot(a,b) #对于向量内积,还可以使用numpy.inner
toc = time.time()
print("向量化的一维向量内积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(c1)+'\n')
tic = time.time()
c2=0
for i in range(len(a)):
c2 += a[i]*b[i]
toc = time.time()
print("循环的一维向量内积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(c2)+'\n')
#测试矩阵内积
tic = time.time()
C = np.vdot(A,B)
toc = time.time()
print("向量化的矩阵内积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(C)+'\n')
tic = time.time()
c2=0
size = A.shape
for i in range(size[0]):
for j in range(size[1]):
c2 += A[i,j] * B[i,j]
toc = time.time()
print("循环的矩阵内积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(c2)+'\n')
#测试矩阵外积
tic = time.time()
C1 = np.matmul(A,V)
toc = time.time()
print("向量化的矩阵外积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(C1)+'\n')
size1 =A.shape
size2 =V.shape
C2 = np.zeros((size1[0],size2[1])) #需要矩阵形状
tic = time.time()
for i in range(size1[0]):
for j in range(size2[1]):
for k in range(size1[1]):
C2[i,j] += A[i,k] * V[k,j]
toc = time.time()
print("循环的矩阵外积运算时长:"+str((toc-tic)*1000)+" ms")
print("结果为:"+str(C2)+'\n')
结果: