Python NumPy计算欧氏距离(Euclidean Distance)

article/2025/9/18 7:13:27

欧氏距离定义: 欧氏距离( Euclidean distance)是一个通常采用的距离定义,它是在m维空间中两个点之间的真实距离。


在二维和三维空间中的欧式距离的就是两点之间的距离,二维的公式是:
begin{equation} d = sqrt{(X_1 – Y_1)^2 + (X_2 – Y_2)^2}end{equation}
三维的公式是:
begin{equation} d = sqrt{(X_1 – Y_1)^2 + (X_2 – Y_2)^2 + (X_3 – Y_3)^2}end{equation}
推广到n维空间,欧式距离的公式是:
begin{equation} d = sqrt{(X_1 – Y_1)^2 + (X_2 – Y_2)^2 + (X_3 – Y_3)^2 + … (X_d – Y_d)}end{equation}

求3维两点距离:

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

import numpy as np

from matplotlib import pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

from mpl_toolkits.mplot3d import proj3d

 

 

coords1 = [1, 2, 3]

coords2 = [4, 5, 6]

 

fig = plt.figure(figsize=(7,7))

ax = fig.add_subplot(111, projection='3d')

 

ax.scatter((coords1[0], coords2[0]),

        (coords1[1], coords2[1]),

        (coords1[2], coords2[2]),

         color="k", s=150)

 

ax.plot((coords1[0], coords2[0]),

        (coords1[1], coords2[1]),

        (coords1[2], coords2[2]),

         color="r")

 

ax.set_xlabel('X')

ax.set_ylabel('Y')

ax.set_zlabel('Z')

 

ax.text(x=2.5, y=3.5, z=4.0, s='d = 5.19')

 

 

plt.title('Euclidean distance between 2 3D-coordinates')

 

plt.show()

Screen Shot 2015-11-30 at 3.53.09 PM

经典Python实现 (vs) NumPy实现

 

 

1

2

3

4

5

# 样本数据

coords1 = [1, 2, 3]

coords2 = [4, 5, 6]

np_c1 = np.array(coords1)

np_c2 = np.array(coords2)

 

 

1

2

3

4

5

6

7

8

# 经典 For循环

 

def eucldist_forloop(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    dist = 0

    for (x, y) in zip(coords1, coords2):

        dist += (x - y)**2

    return dist**0.5

 

 

1

2

3

4

5

# 生成器表达式

 

def eucldist_generator(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    return sum((x - y)**2 for x, y in zip(coords1, coords2))**0.5

 

 

1

2

3

4

5

# NumPy版本

 

def eucldist_vectorized(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    return np.sqrt(np.sum((coords1 - coords2)**2))

 

 

1

2

3

# NumPy 内建函数

 

np.linalg.norm(np_c1 - np_c2)

 

 

1

2

3

4

print(eucldist_forloop(coords1, coords2))

print(eucldist_generator(coords1, coords2))

print(eucldist_vectorized(np_c1, np_c2))

print(np.linalg.norm(np_c1 - np_c2))

 

Screen Shot 2015-11-30 at 4.04.47 PM
timeit比较执行效率:

 

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

import numpy as np

from matplotlib import pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

from mpl_toolkits.mplot3d import proj3d

 

coords1 = [1, 2, 3]

coords2 = [4, 5, 6]

np_c1 = np.array(coords1)

np_c2 = np.array(coords2)

 

 

def eucldist_forloop(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    dist = 0

    for (x, y) in zip(coords1, coords2):

        dist += (x - y)**2

    return dist**0.5

 

 

def eucldist_generator(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    return sum((x - y)**2 for x, y in zip(coords1, coords2))**0.5

 

 

def eucldist_vectorized(coords1, coords2):

    """ Calculates the euclidean distance between 2 lists of coordinates. """

    return np.sqrt(np.sum((coords1 - coords2)**2))

 

 

import timeit

import random

random.seed(123)

 

from numpy.linalg import norm as np_linalg_norm

 

funcs = ('eucldist_forloop', 'eucldist_generator', 'eucldist_vectorized', 'np_linalg_norm')

times = {f:[] for f in funcs}

orders_n = [10**i for i in range(1, 8)]

for n in orders_n:

 

    c1 = [random.randint(0,100) for _ in range(n)]

    c2 = [random.randint(0,100) for _ in range(n)]

    np_c1 = np.array(c1)

    np_c2 = np.array(c2)

 

    assert(eucldist_forloop(c1, c2)

           == eucldist_generator(c1, c2)

           == eucldist_vectorized(np_c1, np_c2)

           == np_linalg_norm(np_c1 - np_c2)

           )

 

    times['eucldist_forloop'].append(min(timeit.Timer('eucldist_forloop(c1, c2)',

            'from __main__ import c1, c2, eucldist_forloop').repeat(repeat=50, number=1)))

    times['eucldist_generator'].append(min(timeit.Timer('eucldist_generator(c1, c2)',

            'from __main__ import c1, c2, eucldist_generator').repeat(repeat=50, number=1)))

    times['eucldist_vectorized'].append(min(timeit.Timer('eucldist_vectorized(np_c1, np_c2)',

            'from __main__ import np_c1, np_c2, eucldist_vectorized').repeat(repeat=50, number=1)))

    times['np_linalg_norm'].append(min(timeit.Timer('np_linalg_norm(np_c1 - np_c2)',

            'from __main__ import np_c1, np_c2, np_linalg_norm').repeat(repeat=50, number=1)))

 

 

labels = {'eucldist_forloop': 'for-loop',

          'eucldist_generator': 'generator expression (comprehension equiv.)',

          'eucldist_vectorized': 'NumPy vectorization',

          'np_linalg_norm': 'numpy.linalg.norm'

          }

 

def plot(times, orders_n, labels):

 

    colors = ('cyan', '#7DE786', 'black', 'blue')

    linestyles = ('-', '-', '--', '--')

    fig = plt.figure(figsize=(11,10))

    for lb,c,l in zip(labels.keys(), colors, linestyles):

        plt.plot(orders_n, times[lb], alpha=1, label=labels[lb],

                 lw=3, color=c, linestyle=l)

    plt.xlabel('sample size n (items in the list)', fontsize=14)

    plt.ylabel('time per computation in seconds', fontsize=14)

    plt.xlim([min(orders_n) / 10, max(orders_n)* 10])

    plt.legend(loc=2, fontsize=14)

    plt.grid()

    plt.xticks(fontsize=16)

    plt.yticks(fontsize=16)

    plt.xscale('log')

    plt.yscale('log')

    plt.title('Python for-loop/generator expr. vs. NumPy vectorized code', fontsize=18)

    plt.show()

 

 

plot(times, orders_n, labels)

Screen Shot 2015-11-30 at 4.23.19 PM

文章转载自: http://blog.topspeedsnail.com/archives/954


http://chatgpt.dhexx.cn/article/Njq57kHQ.shtml

相关文章

Euclidean division

In arithmetic, Euclidean division – or division with remainder – is the process of dividing one integer (the dividend) by another (the divisor), in a way that produces an integer quotient and a natural number remainder strictly smaller than the absolute …

PRN(20201012):Improved updating of Euclidean distance maps and Voronoi diagrams

[*] Lau B , Sprunk C , Burgard W . Improved updating of Euclidean distance maps and Voronoi diagrams[C]// IEEE/RSJ International Conference on Intelligent Robots & Systems. IEEE, 2010. 本文对[*]中的Occupancy Map to Euclidean Distance Maps算法进行python…

java余弦距离_使用TensorFlow实现余弦距离/欧氏距离(Euclideandistance)以及Attention矩阵的计算...

最近在使用tensorflow完成句子相似度建模等任务时常常会用到各种距离的计算,而且有很多论文提出了Attention机制,所以这里就介绍一下如何使用tensorflow实现上述各种功能。 这里首先假定我们的输入是两个四维的Tensor,然后我们需要计算的是其…

点云检测--欧式聚类Euclidean Cluster

1.版本要求 版本: >PCL1.3 2.简介 欧式聚类是点云聚类的一种重要方法,利用点云中点与点之间的欧式距离进行聚类,当点与点之间的欧式距离小于设定的阈值则视为一类。欧式聚类是车辆前方障碍物检测的重要方法。 3.数据 本例中使用的点云数据&#…

Voxblox: Incremental 3D Euclidean Signed Distance Fields for On-Board MAV Planning

作者: 19届 lz 日期:2022-3-2 论文:《Voxblox: Incremental 3D Euclidean Signed Distance Fields for On-Board MA V Planning》 整个系统功能分为两部分: 将传入的传感器数据合并到 TSDF 中(第 IV 节)&…

3D点云处理:点云聚类--FEC: Fast Euclidean Clustering for Point Cloud Segmentation

文章目录 聚类结果一、论文内容1.1 Ground Surface Removal1.2 Fast Euclidean Clustering题外:欧几里得聚类Fast Euclidean ClusteringFEC利用具有点索引顺序的逐点方案的浅显理解 1.3 源码中问题说明 二、参考 聚类结果 原始代码中采用的是pcl中的搜索方式&#…

euclidean loss

个人感觉相当于L2范式开平方,也相当于针对两个向量的欧氏距离开平方 说的更直白点就是两个向量对应位置相减得到每个位置的差,然后把每个位置的差开平方再相加 前向传播cpp代码: template <typename Dtype> void EuclideanLossLayer<Dtype>::Forward_cpu(const vec…

Euclidean, Manhattan, hop-count distance 区别

欧式距离&#xff08;Euclidean Distance&#xff09; 二维空间的公式 其中&#xff0c; 为点 与点 之间的欧氏距离&#xff1b; 为点 到原点的欧氏距离。 曼哈顿距离&#xff08;Manhattan Distance &#xff09; 两点在南北方向上的距离加上在东西方向上的距离&#xff0c;…

扩展Euclidean算法求乘法逆原理详解与算法实现

【利用扩展Euclidean算法求乘法逆】 1. Equipment &#xff08;1&#xff09; operating system version &#xff1a;WIN 10 &#xff08;2&#xff09; CPU instruction set: x 64 &#xff08;3&#xff09; software &#xff1a;Visual Studio 2019 2. process Probl…

NEO4J-相似度算法04-欧几里得距离算法(euclidean)应用场景简介

说明&#xff1a;使用neo4j算法库时需引入跟neo4j数据库对应的算法库插件或自定义算法库 1.简介 欧几里德距离算法原理是计算n维坐标系中点与点之间地距离&#xff0c;如在三维坐标系中点A(p1,p2,p3),点B(q1,q2,q3),两个点之间得距离则为 &#xff1a;, 如果在n维坐标系中&…

欧几里德算法、拓展欧几里德、中国剩余定理

目录 欧几里德算法&#xff08;Euclidean algorithm&#xff09;&#xff08;辗转相除法&#xff09;拓展欧几里德算法中国剩余定理作业1&#xff1a;作业2&#xff1a; 欧几里德算法&#xff08;Euclidean algorithm&#xff09;&#xff08;辗转相除法&#xff09; 欧几里德…

logit回归模型_一文读懂条件Logistic回归

在医学研究中,为了控制一些重要的混杂因素,经常会把病例和对照按年龄,性别等条件进行配对,形成多个匹配组。各匹配组的病例数和对照人数是任意的,比如一个病例和若干个对照匹配即1:1,在医学上称作“1:1病历对照研究”,常见还有1:M(M <=3),即1个病例和1或2或3个对照…

目标检测-定位蒸馏:logit蒸馏与feature蒸馏之争

定位蒸馏 &#xff08;LD, CVPR 2022&#xff09; 先上我们文章和代码&#xff1a; 论文标题&#xff1a; Localization Distillation for Dense Object Detection 论文地址&#xff1a; https://arxiv.org/abs/2102.12252 代码地址1&#xff1a; https://github.com/HikariTJU…

biogeme-nest_logit-cnblog

biogeme-nest_logit 基础数据&#xff1a; optima.dat 变量的描述&#xff1a;出处 OccupStat&#xff1a;职业TimePT&#xff1a;公共交通通行时间TimeCar&#xff1a;小汽车通行时间MarginalCostPT&#xff1a;公共交通总成本CostCarCHF&#xff1a;小汽车的总汽油成本dis…

必看 logit回归分析步骤汇总

Logit回归分析用于研究X对Y的影响&#xff0c;并且对X的数据类型没有要求&#xff0c;X可以为定类数据&#xff08;可以做虚拟变量设置&#xff09;&#xff0c;也可以为定量数据&#xff0c;但要求Y必须为定类数据&#xff0c;并且根据Y的选项数&#xff0c;使用相应的数据分析…

PyTorch logit函数

1.PyTorch vs TensorFlow tensorflow是静态图&#xff0c;需要你把啥都准备好&#xff0c;然后它像个傻子一样执行&#xff0c;tensorflow&#xff0c;目前业界更适合部署&#xff0c;毕竟是静态图&#xff0c;infer的时候速度快。 pytorch&#xff0c;它会在执行的时候&…

logit回归模型_详解 Logit/Probit 模型中的 completely determined 问题

NEW!连享会推文专辑:Stata资源 | 数据处理 | Stata绘图 | Stata程序结果输出 | 回归分析 | 时间序列 | 面板数据 | 离散数据交乘调节 | DID | RDD | 因果推断 | SFA-TFP-DEA文本分析+爬虫 | 空间计量 | 学术论文 | 软件工具 连享会学习群-常见问题解答汇总:👉 WD 主页…

Logit Adjust

Logit Adjust BER 我们在分类问题中常用的误分类函数使得分类器最终学到的分布&#xff1a; P ( y ∣ x ) ∝ P ( y ) P ( x ∣ y ) P(y|x) \propto P(y)P(x|y) P(y∣x)∝P(y)P(x∣y) 假设在一个不平衡猫狗二分类问题中&#xff0c;狗是一个小类&#xff0c;只有整个数据集的…

logit

1.为什么需要logit回归? 线性回归不稳健 异常点对拟合直线的影响很大 so linear不适合做分类问题 2.为什么要sigmoid&#xff1f;sigmoid能做什么&#xff1f; y0&#xff0c;1是离散问题,直接建立方程 函数不连续——损失函数不可导——参数无法用梯度法优化 所以我们由 …

Logit 是怎么算的?

从知乎借几张图来描述&#xff0c;先看看odds 是什么&#xff1f; 然后Logit 就 是 Log of odds&#xff1a;