📜  使用 NumPy 计算欧几里得距离

📅  最后修改于: 2022-05-13 01:55:01.671000             🧑  作者: Mango

使用 NumPy 计算欧几里得距离

简单来说,无论维度如何,欧几里得距离都是两点之间最短的距离。在本文中求欧几里得距离,我们将使用 NumPy 库。该库用于以非常有效的方式操作多维数组。让我们讨论几种通过 NumPy 库求欧几里得距离的方法。

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

Python3
# 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)


Python3
# 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))


Python3
# 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

方法 #2:使用 dot()

Python3

# 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

方法 #3:使用 square() 和 sum()

Python3

# 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