計(jì)算Python Numpy向量之間的歐氏距離實(shí)例
計(jì)算Python Numpy向量之間的歐氏距離,已知vec1和vec2是兩個(gè)Numpy向量,歐氏距離計(jì)算如下:
import numpydist = numpy.sqrt(numpy.sum(numpy.square(vec1 - vec2)))
或者直接:
dist = numpy.linalg.norm(vec1 - vec2)
補(bǔ)充知識(shí):Python中計(jì)算兩個(gè)數(shù)據(jù)點(diǎn)之間的歐式距離,一個(gè)點(diǎn)到數(shù)據(jù)集中其他點(diǎn)的距離之和
如下所示:
計(jì)算數(shù)兩個(gè)數(shù)據(jù)點(diǎn)之間的歐式距離
import numpy as npdef 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 中運(yùn)輸代碼輸出結(jié)果如下:
計(jì)算一個(gè)點(diǎn)到數(shù)據(jù)集中其他點(diǎn)的距離之和
from scipy import *import pylab as pl all_points = rand(500, 2)pl.plot(all_points[:, 0], all_points[:, 1], ’b.’)pl.show()
在jupyter 中運(yùn)輸代碼輸出結(jié)果如下:
from scipy import *import pylab as pl all_points = rand(500, 2)pl.plot(all_points[:, 0], all_points[:, 1], ’b.’)pl.show()
定義函數(shù)計(jì)算距離
def cost(c, all_points): #指定點(diǎn),all_points:為集合類的所有點(diǎn)return sum(sum((c - all_points) ** 2, axis=1) ** 0.5)
以上這篇計(jì)算Python Numpy向量之間的歐氏距離實(shí)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Ajax實(shí)現(xiàn)文件上傳功能(Spring MVC)2. 基于javaweb+jsp實(shí)現(xiàn)學(xué)生宿舍管理系統(tǒng)3. idea設(shè)置代碼格式化的方法步驟4. asp createTextFile生成文本文件支持utf85. Java Synchronized的使用詳解6. Python 簡介7. Vue發(fā)布訂閱模式實(shí)現(xiàn)過程圖解8. 使用EF Code First搭建簡易ASP.NET MVC網(wǎng)站并允許數(shù)據(jù)庫遷移9. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條10. xml創(chuàng)建節(jié)點(diǎn)(根節(jié)點(diǎn)、子節(jié)點(diǎn))
