# PyTorch如何計算高維度Tenosr之間的PairwiseDistance和CosineSimilarity?

# 假設features_anchor為多個Tensor，我們可以透過torch.mean(dim=0, keepdims=True)來獲得Tensor的平均中心位置。這篇文章提出了很簡單的例子，介紹參數dim=0和dim=1的主要差異簡單來說，可以把dim=0想成是不同Tensor間相加取平均；dim=1則是相同Tensor內相加取平均s = tensor([[0., 1., 2.],                 [3., 4., 5.]], dtype=torch.float64)dim=0時：s = torch.mean(s, dim=0)tensor([1.5000, 2.5000, 3.5000], dtype=torch.float64)；其中1.5=(0.0+3.0)/2, 2.5=(1.0+4.0)/2, 3.5=(2.0+5.0)/2dim=1時：s2 = torch.mean(s, dim=1)tensor([1., 4.], dtype=torch.float64)；其中1.0=(0.0+1.0+2.0)/3， 4.0=(3.0+4.0+5.0)/3====================================================================# 假設features_anchor為中心點features_anchor = features_anchor.mean(dim=0, keepdims=True) # 計算多個tensor的平均中心位置features = features # 測試樣本之特徵# 計算PairwiseDistancepdist = nn.PairwiseDistance(p=2)pdist(features_anchor, features) # 計算中心點Prototype與所有testing features的distance# 使用Cosine similaritycos = nn.CosineSimilarity(dim=1, eps=1e-6)cos(features_anchor, features)   # 計算中心點Prototype與所有testing features的cosine similarity

--

--

--

## More from Yanwei Liu

Machine Learning | Deep Learning | https://linktr.ee/yanwei

Love podcasts or audiobooks? Learn on the go with our new app.

## Yanwei Liu

Machine Learning | Deep Learning | https://linktr.ee/yanwei