使用 SciPy 计算 Minkowski 距离
闵可夫斯基距离是欧几里得距离和曼哈顿距离的广义形式,是两点之间的距离。它主要用于向量的距离相似性。
SciPy 为我们提供了一个名为 minkowski 的函数,该函数返回两点之间的 Minkowski 距离。让我们看看如何使用 SciPy 库计算两点之间的 Minkowski 距离 -
示例
# Importing the SciPy library输出结果fromscipy.spatialimport distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
print(A, B)
((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12))
示例
# Importing the SciPy libraryfromscipy.spatialimport distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
# Computing the Minkowski distance输出结果minkowski_distance = distance.minkowski(A, B, p=3)
print('Minkowski Distance b/w', A, 'and', B, 'is: ', minkowski_distance)
Minkowski Distance b/w (1, 2, 3, 4, 5, 6) and (7, 8, 9, 10, 11, 12) is:10.902723556992836
我们已经用order(p)= 3计算了闵可夫斯基距离。但是当阶数为 2 时,它将代表欧几里得距离,而当阶数为 1 时,它将代表曼哈顿距离。让我们用下面给出的例子来理解它 -
示例
# Importing the SciPy library输出结果fromscipy.spatialimport distance
# Defining the points
A = (1, 2, 3, 4, 5, 6)
B = (7, 8, 9, 10, 11, 12)
A, B
((1, 2, 3, 4, 5, 6), (7, 8, 9, 10, 11, 12))
示例
# minkowski and manhattan distance输出结果minkowski_distance_with_order1 = distance.minkowski(A, B, p=1)
print('Minkowski Distance of order(P)1:',minkowski_distance_with_order1, '\nManhattan Distance: ',manhattan_distance)
Minkowski Distance of order(P)1: 36.0Manhattan Distance: 36
示例
# minkowski and euclidean distance输出结果minkowski_distance_with_order2 = distance.minkowski(A, B, p=2)
print('Minkowski Distance of order(P)2:',minkowski_distance_order_2, '\nEuclidean
Distance: ',euclidean_distance)
Minkowski Distance of order(P)2: 14.696938456699069Euclidean Distance: 14.696938456699069
以上是 使用 SciPy 计算 Minkowski 距离 的全部内容, 来源链接: utcz.com/z/317264.html