当前位置:   article > 正文

torch.nn.functional.cosine_similarity使用详解

torch.nn.functional.cosine_similarity

更多、更及时内容欢迎留意微信公众号小窗幽记机器学习

概述

根据官网文档的描述,其中 dim表示沿着对应的维度计算余弦相似。那么怎么理解呢?
首先,先介绍下所谓的dim:

a = torch.tensor([[ [1, 2], [3, 4] ], [ [5, 6], [7, 8] ] ], dtype=torch.float)
print(a.shape)
"""
[
    [
        [1, 2],
        [3, 4]
    ],
    [
        [5, 6],
        [7, 8]
    ]
]
"""
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

在这里插入图片描述

假设有2个矩阵:[[1, 2], [3, 4]] 和 [[5, 6], [7, 8]], 求2者的余弦相似。

按照dim=0求余弦相似:

import torch.nn.functional as F
input1 = torch.tensor([[1, 2], [3, 4]], dtype=torch.float)
input2 = torch.tensor([[5, 6], [7, 8]], dtype=torch.float)
output = F.cosine_similarity(input1, input2, dim=0)
print(output)
  • 1
  • 2
  • 3
  • 4
  • 5

结果如下:

tensor([0.9558, 0.9839])
  • 1

那么,这个数值是怎么得来的?是按照

在这里插入图片描述

具体求解如下:

print(F.cosine_similarity(torch.tensor([1,3], dtype=torch.float) , torch.tensor([5,7], dtype=torch.float), dim=0))
print(F.cosine_similarity(torch.tensor([2,4], dtype=torch.float) , torch.tensor([6,8], dtype=torch.float), dim=0))
  • 1
  • 2

运行结果如下:

tensor(0.9558)
tensor(0.9839)
  • 1
  • 2

可以用scipy.spatial进一步佐证:

from scipy import spatial

dataSetI = [1,3]
dataSetII = [5,7]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
print(result)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

运行结果如下:

0.95577900872195
  • 1

同理:

dataSetI = [2,4]
dataSetII = [6,8]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
print(result)
  • 1
  • 2
  • 3
  • 4

运行结果如下:

0.9838699100999074
  • 1

按照dim=1求余弦相似:

output = F.cosine_similarity(input1, input2, dim=1)
print(output)
  • 1
  • 2

运行结果如下:

tensor([0.9734, 0.9972])
  • 1

同理,用用scipy.spatial进一步佐证:

dataSetI = [1,2]
dataSetII = [5,6]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
print(result)
  • 1
  • 2
  • 3
  • 4

运行结果:0.973417168333576

dataSetI = [3,4]
dataSetII = [7,8]
result = 1 - spatial.distance.cosine(dataSetI, dataSetII)
print(result)
  • 1
  • 2
  • 3
  • 4

运行结果:

0.9971641204866132
  • 1

结果与F.cosine_similarity相符合。

【更多、更及时内容欢迎留意微信公众号小窗幽记机器学习

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/42224
推荐阅读
  

闽ICP备14008679号