Shortcuts

余弦相似度

class torch.nn.CosineSimilarity(dim=1, eps=1e-08)[源代码]

返回x1x_1x2x_2之间的余弦相似度,沿dim计算。

similarity=x1x2max(x12x22,ϵ).\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}.
Parameters
  • dim (int, 可选) – 计算余弦相似度的维度。默认值:1

  • eps (float, 可选) – 用于避免除零的小值。 默认值: 1e-8

Shape:
  • 输入1: (1,D,2)(\ast_1, D, \ast_2) 其中 D 位于位置 dim

  • Input2: (1,D,2)(\ast_1, D, \ast_2), same number of dimensions as x1, matching x1 size at dimension dim,

    并且在其他维度上与 x1 可广播。

  • 输出: (1,2)(\ast_1, \ast_2)

Examples::
>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
>>> output = cos(input1, input2)
优云智算