如何計(jì)算向量的距離使用短例子

計(jì)算距離

In [25]: def distance(x,y):
    m_x = np.array(x)
    m_y = np.array(y)
    result = sum((m_x - m_y)*np.transpose(m_x - m_y))
    return math.sqrt(float(result))

Test:

In [172]: distance([5,10],[7,8])
Out[172]: 2.8284271247461903

需要注意的是numpy的數(shù)據(jù)類型和原始類型是不同的,numpy進(jìn)行了封裝。參見(jiàn)這里這里

scipy庫(kù),包含了十幾種不同的距離計(jì)算方法

>> scipy.spatial.distance
>> help(scipy.spatial.distance)
...
braycurtis       -- the Bray-Curtis distance.
       canberra         -- the Canberra distance.
       chebyshev        -- the Chebyshev distance.
       cityblock        -- the Manhattan distance.
       correlation      -- the Correlation distance.
       cosine           -- the Cosine distance.
       dice             -- the Dice dissimilarity (boolean).
       euclidean        -- the Euclidean distance.
       hamming          -- the Hamming distance (boolean).
       jaccard          -- the Jaccard distance (boolean).
       kulsinski        -- the Kulsinski distance (boolean).
       mahalanobis      -- the Mahalanobis distance.
       matching         -- the matching dissimilarity (boolean).
       minkowski        -- the Minkowski distance.
       rogerstanimoto   -- the Rogers-Tanimoto dissimilarity (boolean).
       russellrao       -- the Russell-Rao dissimilarity (boolean).
       seuclidean       -- the normalized Euclidean distance.
       sokalmichener    -- the Sokal-Michener dissimilarity (boolean).
       sokalsneath      -- the Sokal-Sneath dissimilarity (boolean).
       sqeuclidean      -- the squared Euclidean distance.
       wminkowski       -- the weighted Minkowski distance.
       yule             -- the Yule dissimilarity (boolean).

sklearn庫(kù),著名的python機(jī)器學(xué)習(xí)庫(kù)

sklearn.metrics.pairwise.pairwise_distances
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容