numpy:计算向量范数

匿名 (未验证) 提交于 2019-12-03 00:26:01
import numpy as np
# 计算欧氏距离 s1 = np.array([ 0,1.2,1.5,0,0,0,0,0,0]) s2 = np.array([1.2,0,0.8,0,0,0,0,0,0]) op1 = np.sqrt(np.sum(np.square(s1 - s2))) op2 = np.linalg.norm(s1-s2)
print("op1:",op1,"op2:",op2)
op1: 1.835755975068582 op2: 1.835755975068582 
#计算曼哈顿距离 op1 = np.sum(np.abs(s1 - s2)) op2 = np.linalg.norm(s1- s2,ord=1) print("op1:",op1,"op2:",op2)
op1: 3.0999999999999996 op2: 3.0999999999999996 
#计算切比雪夫距离 op1 = np.abs(s1-s2).max() op2 = np.linalg.norm(s1-s2,ord=np.inf) print("op1:",op1,"op2:",op2)
op1: 1.2 op2: 1.2 
  • 计算余弦距离:
#余弦距离 op1 =  np.dot(s1,s2) / np.sqrt(np.square(s1).sum()) * np.sqrt(np.square(s2).sum()) op2 = np.dot(s1, s2) / np.linalg.norm(s1, ord=2)*np.linalg.norm(s2,ord=2) print("op1:",op1,"op2:",op2)
op1: 0.9009480101943569 op2: 0.9009480101943569 
  • 汉明距离
  • 两个等长字符串s1与s2之间的汉明距离定义为将其中一个变为另外一个所需要作的最小替换次数。
    例如字符串“1111”与“1001”之间的汉明距离为2。
  • 应用:信息编码(为了增强容错性,应使得编码间的最小汉明距离尽可能大)
v1=np.array([1,1,0,1,0,1,0,0,1])   v2=np.array([0,1,1,0,0,0,1,1,1])   # 不为0 的元素的下标   smstr = np.nonzero(v1 - v2) print("smstr:",smstr) #距离是sm sm = np.shape(smstr[0])[0] print("sm:",sm) 
smstr: (array([0, 2, 3, 5, 6, 7], dtype=int64),) sm: 6 
np.shape(smstr[0])
(6,) 

参考:https://blog.csdn.net/qq_19707521/article/details/78479532

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!