Python小练习:向量之间的距离度量

Python小练习:向量之间的距离度量

作者:凯鲁嘎吉 - 博客园 http://www.cnblogs.com/kailugaji/

本文主要用Python实现三种常见的向量之间的距离度量方式:

1)曼哈顿距离(Manhattan distance, L1范数):$d(x,y) = \sum\limits_{i = 1}^n {\left| {{x_i} - {y_i}} \right|} $

2)欧氏距离(Euclidean distance,L2范数):$d(x,y) = \sqrt {\sum\limits_{i = 1}^n {{{({x_i} - {y_i})}^2}} } $

3)余弦相似度(Cosine similarity):$d(x,y) = \frac{{x{y^T}}}{{\left\| x \right\|\left\| y \right\|}}$

其中,$x,y \in \mathbb{R}{^{1 \times n}}$

1. loss_test.py

 1 # -*- coding: utf-8 -*-
 2 # Author:凯鲁嘎吉 Coral Gajic
 3 # https://www.cnblogs.com/kailugaji/
 4 # Python小练习:向量之间的距离度量
 5 # Python实现两向量之间的:
 6 # 1)曼哈顿距离(Manhattan distance, L1范数)
 7 # 2)欧氏距离(Euclidean distance,L2范数)
 8 # 3)余弦相似度(Cosine similarity)
 9 import torch
10 import torch.nn.functional as F
11 # 自己写的距离度量函数
12 def compute_l1_similarity(e1, e2): # L1距离
13     return torch.abs(e1 - e2).sum(-1)
14 def compute_l2_similarity(e1, e2): # L2距离
15     return ((e1 - e2)**2).sum(-1).sqrt()
16     # 注意:这里开根号了,没平方
17 def compute_cosine_similarity(e1, e2): # cosine距离
18     e1 = e1 / torch.norm(e1, dim=-1, p=2, keepdim=True)
19     e2 = e2 / torch.norm(e2, dim=-1, p=2, keepdim=True)
20     similarity = torch.mul(e1, e2).sum(1) # mul: 点乘
21     return similarity
22     # 后两行也可替换为:
23     # similarity = torch.mm(e1, torch.t(e2)) # mm: 相乘,torch.t: 转置
24     # return torch.diag(similarity) # 只取对角线元素
25 
26 torch.manual_seed(1)
27 n = 3 # 样本个数
28 m = 5 # 样本维度
29 # 仅考虑e1的第i个样本和e2的第i个样本之间计算距离
30 # 不考虑e1的i个样本和e2的第j个样本之间的距离(i≠j)
31 e1 = torch.rand(n, m)
32 e2 = torch.rand(n, m)
33 print('原始数据为:\n', e1, '\n', e2)
34 loss_l1_1 = torch.zeros(n)
35 loss_l2_1 = torch.zeros(n)
36 # 自己写的距离度量函数
37 loss_l1 = compute_l1_similarity(e1, e2)
38 loss_l2 = compute_l2_similarity(e1, e2)
39 loss_cosine = compute_cosine_similarity(e1, e2)
40 # pytorch库里自带的距离度量函数
41 for i in range(n):
42     loss_l1_1[i] = torch.dist(e1[i], e2[i], p=1)
43     loss_l2_1[i] = torch.dist(e1[i], e2[i], p=2)
44 loss_cosine_1 = F.cosine_similarity(e1, e2)
45 # 第一个结果是自己写的函数
46 # 第二个结果是pytorch库里自带的函数
47 # n是多少,就出来多少个值
48 print('两者的曼哈顿距离为:\n', loss_l1, '\n', loss_l1_1)
49 print('两者的欧式距离为:\n', loss_l2, '\n', loss_l2_1)
50 print('两者的余弦相似度为:\n', loss_cosine, '\n', loss_cosine_1)

2. 结果

D:\ProgramData\Anaconda3\python.exe "D:/Python code/2023.3 exercise/loss/loss_test.py"
原始数据为:
 tensor([[0.7576, 0.2793, 0.4031, 0.7347, 0.0293],
        [0.7999, 0.3971, 0.7544, 0.5695, 0.4388],
        [0.6387, 0.5247, 0.6826, 0.3051, 0.4635]]) 
 tensor([[0.4550, 0.5725, 0.4980, 0.9371, 0.6556],
        [0.3138, 0.1980, 0.4162, 0.2843, 0.3398],
        [0.5239, 0.7981, 0.7718, 0.0112, 0.8100]])
两者的曼哈顿距离为:
 tensor([1.5195, 1.4075, 1.1176]) 
 tensor([1.5195, 1.4075, 1.1176])
两者的欧式距离为:
 tensor([0.7873, 0.6938, 0.5498]) 
 tensor([0.7873, 0.6938, 0.5498])
两者的余弦相似度为:
 tensor([0.8395, 0.9767, 0.9345]) 
 tensor([0.8395, 0.9767, 0.9345])

Process finished with exit code 0

注意:这里只是求向量之间的距离度量,并不是矩阵范数。上下两个结果分别为自己根据距离定义写的函数、pytorch自带的函数,可以看到得到的结果是一致的。

3. 参考文献

[1] 相似性度量 – 凯鲁嘎吉 – 博客园

[2] 向量范数与矩阵范数 – 凯鲁嘎吉 – 博客园

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章