一、理論分析
首先從理論上介紹 一下,矩陣之間歐氏距離的快速計算,參考了@frankzd
二、**分析
def euclidean_dist(x, y):
"""args:
x: pytorch variable, with shape [m, d]
y: pytorch variable, with shape [n, d]
returns:
dist: pytorch variable, with shape [m, n]
"""m, n = x.size(0), y.size(0)
# xx經過pow()方法對每單個資料進行二次方操作後,在axis=1 方向(橫向,就是第一列向最後一列的方向)加和,此時xx的shape為(m, 1),經過expand()方法,擴充套件n-1次,此時xx的shape為(m, n)
xx = torch.pow(x, 2).sum(1, keepdim=true).expand(m, n)
# yy會在最後進行轉置的操作
yy = torch.pow(y, 2).sum(1, keepdim=true).expand(n, m).t()
dist = xx + yy
# torch.addmm(beta=1, input, alpha=1, mat1, mat2, out=none),這行表示的意思是dist - 2 * x * yt
dist.addmm_(1, -2, x, y.t())
# clamp()函式可以限定dist內元素的最大最小範圍,dist最後開方,得到樣本之間的距離矩陣
dist = dist.clamp(min=1e-12).sqrt() # for numerical stability
return dist
三、demo演示
接下來用乙個簡單的demo實現(也便於自己查驗最後結果是否正確)
import torch
def euclidean_dist(x, y):
m, n = x.size(0), y.size(0)
xx = torch.pow(x, 2).sum(1, keepdim=true).expand(m, n)
yy = torch.pow(y, 2).sum(1, keepdim=true).expand(n, m).t()
dist = xx + yy
dist.addmm_(1, -2, x, y.t())
dist = dist.clamp(min=1e-12).sqrt() # for numerical stability
return dist
if __name__ == '__main__':
x = torch.tensor([[1.0, 2.0, 3.0, 4.0], [2.0, 5.0, 7.0, 9.0]])
y = torch.tensor([[3.0, 1.0, 2.0, 5.0], [2.0, 3.0, 4.0, 6.0]])
dist_matrix = euclidean_dist(x, y)
print(dist_matrix)
最後輸出的結果為:
tensor([[2.6458, 2.6458],[7.6158, 4.6904]])
計算矩陣的歐式距離
對於knn演算法,難點在於計算測試集中每一樣本到訓練集中每一樣本的歐氏距離,即計算兩個矩陣之間的歐氏距離。現就計算歐式距離提出三種方法。歐式距離 歐幾里得度量 1274107?fromtitle 歐式距離 fromid 2809635 fr aladdin 分別對訓練集和測試集中的資料進行迴圈遍歷,...
R語言 歐式距離的快速計算方法
裡面提供了一種運算方法,如下 mat system.time system.time mat7 print mat7 1 6,1 6 用這種方法,可以計算四百萬條資料,用時22s左右 使用這種方法,開始除錯自己的資料。在除錯中,需要注意的是mat4這個矩陣。首先是mat1和t mat1 要可以進行加...
常見距離計算方法
不能直接走兩點連線的直線,紅 藍 黃距離一樣長 西洋棋中,國王走一步可以移動到相鄰8個方格中的任意乙個,如下圖。a到b的距離為紅色線,需要走4步,和綠色線距離是相同的。閔氏距離不是一種距離,而是一組距離的定義,是對多個距離度量公式的概括性的表述。兩個n維變數a x11,x12,x1n 與b x21,...