版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jiaoyangdetian/article/details/81668334
import numpy as np def numpyWork1(): # 矩阵的求和运算 one = np.array([[1, 0, 1, 3, 4, 1], [2, 1, 4, 2, 3, 0], [3, 5, 4, 1, 3, 2], [2, 6, 3, 1, 3, 8], [9, 1, 2, 1, 5, 0], ]) two = np.sum(one, axis= 0) # 每一列求和,得到的新矩阵 three = np.sum(one, axis= 1) # 每一行求和,得到的新矩阵 print('two=', two) print('three=', three) return def numpyWork2(): # 两个向量相乘 one = np.array([3, 5, 8, 10, 9, 2, 4, 5, 1]) two = np.array([2, 3, 4, 2, 6, 7, 9, 10, 2]) three = np.multiply(one, two) print('three=', three) return def numpyWork3(): # 矩阵的欧氏距离 one = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 3, 9, 7, 8, 9], [1, 2, 6, 4, 8, 6, 7, 8, 9]]) two = np.array([[2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 8, 6, 7, 12, 9, 10], [2, 3, 4, 9, 2, 7, 8, 9, 10]]) dist1 = np.linalg.norm(one - two) # 矩阵的欧氏距离 dist2 = np.square(one - two) print('one=', one) print('two=', two) print('dist1=', dist1) # 此处为一个数值 print('dist2=', dist2) return def EuclideanDistances(A, B): # 两个矩阵求欧氏距离 - - - 偏慢(网上提供的方法) BT = B.transpose() vecProd = A * BT SqA = A.getA()**2 sumSqA = np.matrix(np.sum(SqA, axis=1)) sumSqAEx = np.tile(sumSqA.transpose(), (1, vecProd.shape[1])) SqB = B.getA()**2 sumSqB = np.sum(SqB, axis=1) sumSqBEx = np.tile(sumSqB, (vecProd.shape[0], 1)) SqED = sumSqBEx + sumSqAEx - 2*vecProd ED = (SqED.getA())**0.5 return np.matrix(ED) def EuclideanDistancesBetter(): # 矩阵与向量的欧氏距离计算速度很快,根据数学公式计算的,算起来较快,推荐使用 one = np.array([[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [2, 3, 4, 5, 6, 7, 8, 9, 10, 11], [15, 16, 17, 18, 19, 20, 21, 22, 23, 24], [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], ]) two = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) result_ed1 = np.linalg.multi_dot([one, two]) # 两个矩阵向量的欧氏距离 result_ed2 = 1 / (1 + result_ed1) print('result_ed1= ', result_ed1) # result_ed1= [ 385 440 1155 85] print('result_ed2= ', result_ed2) # result_ed2= [0.00259067 0.00226757 0.00086505 0.01162791] return #numpyWork1(): # 矩阵的求和运算 #numpyWork2(): # 两个向量相乘 #numpyWork3() # 矩阵的欧氏距离 #EuclideanDistances(A, B): # 两个矩阵求欧氏距离 - - - 偏慢 #EuclideanDistancesBetter() # 矩阵与向量的欧氏距离计算速度很快(推荐使用)