歡迎您光臨本站 註冊首頁

計算Python Numpy向量之間的歐氏距離實例

←手機掃碼閱讀     月球人 @ 2020-06-05 , reply:0

計算Python Numpy向量之間的歐氏距離,已知vec1和vec2是兩個Numpy向量,歐氏距離計算如下:

import numpy
dist = numpy.sqrt(numpy.sum(numpy.square(vec1 - vec2)))

或者直接:

dist = numpy.linalg.norm(vec1 - vec2)

補充知識:Python中計算兩個數據點之間的歐式距離,一個點到數據集中其他點的距離之和

如下所示:

計算數兩個數據點之間的歐式距離

 import numpy as np def ed(m, n): return np.sqrt(np.sum((m - n) ** 2)) i = np.array([1, 1]) j = np.array([3, 3]) distance = ed(i, j) print(distance)


在jupyter 中運輸代碼輸出結果如下:

計算一個點到數據集中其他點的距離之和

 from scipy import * import pylab as pl all_points = rand(500, 2) pl.plot(all_points[:, 0], all_points[:, 1], 'b.') pl.show()


在jupyter 中運輸代碼輸出結果如下:

 from scipy import * import pylab as pl all_points = rand(500, 2) pl.plot(all_points[:, 0], all_points[:, 1], 'b.') pl.show()


定義函數計算距離

def cost(c, all_points): #指定點,all_points:為集合類的所有點
return sum(sum((c - all_points) ** 2, axis=1) ** 0.5)


[月球人 ] 計算Python Numpy向量之間的歐氏距離實例已經有237次圍觀

http://coctec.com/docs/python/shhow-post-237024.html