"""
numpy 常用的几个函数具体应用个, 如: np.dot, np.outer, np.multiply
"""
import time
import numpy as np
x1 = [9, 2, 5, 0, 0, 7, 5, 0, 0, 0, 9, 2, 5, 0, 0]
x2 = [9, 2, 2, 9, 0, 9, 2, 5, 0, 0, 9, 2, 5, 0, 0]
"""
np.dot 一维内积:
1) 一维内积,得到一个值,两个向量各自对应位置相乘后再相.
2)多维,满足矩阵相乘.
如: 一维,x1=[a1,a2,a3], x2=[b1,b2,b3] dot(x1,x2) = a1*b + a2*b2 + a3*b3
"""
tic = time.process_time()
dot = 0
for i in range(len(x1)):
dot += x1[i]*x2[i]
toc = time.process_time()
print("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
tic = time.process_time()
dot = np.dot(x1, x2)
toc = time.process_time()
print("dot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
"""
np.dot 多维矩阵相乘,按矩阵相乘逻辑进行,
如: 矩阵A^m*n * 矩阵B^n*z, 得到矩阵C^m*z
计算过程。 矩阵A中i所在的行,* 矩阵B,i所在的列。 即矩阵A的行,要与矩阵B的列数相同。
矩阵相乘, numpy 明显比数组循环快。
"""
W = np.random.rand(3,len(x1))
tic = time.process_time()
gdot = np.zeros(W.shape[0])
for i in range(W.shape[0]):
for j in range(len(x1)):
gdot[i] += W[i,j]*x1[j]
toc = time.process_time()
print ("gdot = " + str(gdot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
tic = time.process_time()
dot = np.dot(W,x1)
toc = time.process_time()
print ("gdot = " + str(dot) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
"""
outer 外积:
numpy.outer(x1, x2) ,x1确定结果的行数, x2确定结果的列数,
"自己感觉,x1中每个元素都要跟x2中所有元素相乘 , 不像内积,跟自己对应位置相乘(这个好像是一维数组情况下),矩阵相乘也有些类似。
1) x1,x2是两个数组,如果x1,x2是高维数组,函数会自动将其flatten成1维
2) 输出是 len(x1) * len(x2)的数组,数组元素为 result[i,j] = x1[i] * x2[j]
3) 计算公式如下 :
x1=[a1,a2,a3], x2=[b1,b2,b3]
result=[
[a1*b1, a1*b2, a1*b3] ,
[a2*b1, a2*b2, a2*b3] ,
[a3*b1, a3*b2, a3*b3]
]
"""
tic = time.process_time()
outer = np.zeros((len(x1),len(x2)))
for i in range(len(x1)):
for j in range(len(x2)):
outer[i, j] = x1[i]*x2[j]
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
tic = time.process_time()
outer = np.outer(x1,x2)
toc = time.process_time()
print ("outer = " + str(outer) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
"""
np.multiply(x1,x2):
1)对应位置相乘
2)输出 一维数组
如:x1=[a1,a2,a3], x2=[b1,b2,b3],
numpy.multiply(x1, x2) = [a1*b1, a2*b2, a3*b3], x1与x2的shape要一致。
"""
tic = time.process_time()
mul = np.zeros(len(x1))
for i in range(len(x1)):
mul[i] = x1[i]*x2[i]
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")
tic = time.process_time()
mul = np.multiply(x1,x2)
toc = time.process_time()
print ("elementwise multiplication = " + str(mul) + "\n ----- Computation time = " + str(1000*(toc - tic)) + "ms")