栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

torch.nn.functional.cosine

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

torch.nn.functional.cosine

概述

根据官网文档的描述,其中 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]
    ]
]
"""

假设有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)

结果如下:

tensor([0.9558, 0.9839])

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

具体求解如下:

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))

运行结果如下:

tensor(0.9558)
tensor(0.9839)

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

from scipy import spatial

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

运行结果如下:

0.95577900872195

同理:

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

运行结果如下:

0.9838699100999074
按照dim=1求余弦相似:
output = F.cosine_similarity(input1, input2, dim=1)
print(output)

运行结果如下:

tensor([0.9734, 0.9972])

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

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

运行结果:0.973417168333576

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

运行结果:

0.9971641204866132

结果与F.cosine_similarity相符合。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/300490.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号