快捷键

torch.nn.functional.cosine_similarity

torch.nn.functional.cosine_similarity(x1, x2, dim=1, eps=1e-8) → Tensor

返回 x1x2 之间的余弦相似度,沿 dim 计算。 x1x2 必须广播到公共形状。 dim 指的是这个公共形状中的维度。输出维度的 dim 被压缩(见 torch.squeeze() ),结果输出张量少一个维度。

similarity=x1x2max(x12,ϵ)max(x22,ϵ)\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2, \epsilon) \cdot \max(\Vert x_2 \Vert _2, \epsilon)}

支持类型提升。

参数:
  • x1(张量)- 第一个输入。

  • x2(张量)- 第二个输入。

  • dim(int,可选)- 计算余弦相似度的维度。默认:1

  • eps(浮点数,可选)- 避免除以零的小值。默认:1e-8

示例:

>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> output = F.cosine_similarity(input1, input2)
>>> print(output)

© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源