Rate this Page
โ˜… โ˜… โ˜… โ˜… โ˜…

CosineSimilarity#

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

Returns cosine similarity between x1x_1 and x2x_2, computed along dim.

similarity=x1โ‹…x2maxโก(โˆฅx1โˆฅ2โ‹…โˆฅx2โˆฅ2,ฯต).\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}.
Parameters
  • dim (int, optional) โ€“ Dimension where cosine similarity is computed. Default: 1

  • eps (float, optional) โ€“ Small value to avoid division by zero. Default: 1e-8

Shape:
  • Input1: (โˆ—1,D,โˆ—2)(\ast_1, D, \ast_2) where D is at position dim

  • Input2: (โˆ—1,D,โˆ—2)(\ast_1, D, \ast_2), same number of dimensions as x1, matching x1 size at dimension dim, and broadcastable with x1 at other dimensions.

  • Output: (โˆ—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)
forward(x1, x2)[source]#

Runs the forward pass.

Return type

Tensor