评价此页

torch.nn.functional.cosine_similarity#

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

返回 x1 和 x2 之间的余弦相似度,沿着 dim 计算。x1 和 x2 必须可以广播到共同的形状。dim 指的是此共同形状中的维度。输出的 dim 维度被挤压(参见 torch.squeeze()),导致输出张量维度减少 1。

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 (Tensor) – 第一个输入。

  • x2 (Tensor) – 第二个输入。

  • dim (int, optional) – 计算余弦相似度的维度。默认值:1

  • eps (float, optional) – 避免除以零的小值。默认值:1e-8

示例

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