評價此頁

CosineSimilarity#

class torch.nn.modules.distance.CosineSimilarity(dim=1, eps=1e-08)[源]#

dim 維度上計算 x1x_1x2x_2 之間的餘弦相似度。

similarity=x1x2max(x12x22,ϵ).\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}.
引數
  • dim (int, optional) – 計算餘弦相似度的維度。預設為:1

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

形狀
  • Input1: (1,D,2)(\ast_1, D, \ast_2) 其中 D 是在 dim 位置上的維度。

  • Input2: (1,D,2)(\ast_1, D, \ast_2),其維度數與 x1 相同,在 dim 維度上與 x1 匹配,並在其他維度上與 x1 可廣播。

  • Output: (1,2)(\ast_1, \ast_2)

示例

>>> input1 = torch.randn(100, 128)
>>> input2 = torch.randn(100, 128)
>>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
>>> output = cos(input1, input2)
forward(x1, x2)[源]#

執行前向傳播。

返回型別

張量