用NumPy计算欧几里得距离

用NumPy计算欧几里得距离

简单地说,欧几里得距离是两点之间最短的距离,而不考虑维度。在本文中,为了找到欧氏距离,我们将使用NumPy库。这个库用于以一种非常有效的方式处理多维数组。让我们来讨论一下用NumPy库查找欧氏距离的几种方法。

方法#1:使用linalg.norm()

# Python code to find Euclidean distance
# using linalg.norm()
 
import numpy as np
 
# initializing points in
# numpy arrays
point1 = np.array((1, 2, 3))
point2 = np.array((1, 1, 1))
 
# calculating Euclidean distance
# using linalg.norm()
dist = np.linalg.norm(point1 - point2)
 
# printing Euclidean distance
print(dist)

输出:

2.23606797749979

方法二:使用dot()

# Python code to find Euclidean distance
# using dot()
 
import numpy as np
 
# initializing points in
# numpy arrays
point1 = np.array((1, 2, 3))
point2 = np.array((1, 1, 1))
 
# subtracting vector
temp = point1 - point2
 
# doing dot product
# for finding
# sum of the squares
sum_sq = np.dot(temp.T, temp)
 
# Doing squareroot and
# printing Euclidean distance
print(np.sqrt(sum_sq))

输出:

2.23606797749979

方法三:使用square()和sum()

# Python code to find Euclidean distance
# using sum() and square()
 
import numpy as np
 
# initializing points in
# numpy arrays
point1 = np.array((1, 2, 3))
point2 = np.array((1, 1, 1))
 
# finding sum of squares
sum_sq = np.sum(np.square(point1 - point2))
 
# Doing squareroot and
# printing Euclidean distance
print(np.sqrt(sum_sq))

输出:

2.23606797749979

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程