Table of Contents
Shortcuts

# CosineSimilarity

class torch.nn.CosineSimilarity(dim=1, eps=1e-08)

  Returns cosine similarity between x 1 x_1 x 1​ and x 2 x_2 x 2​, computed along dim.

  similarity=x 1⋅x 2 max⁡(∥x 1∥2⋅∥x 2∥2,ϵ).\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}. similarity=max(∥x 1​∥2​⋅∥x 2​∥2​,ϵ)x 1​⋅x 2​​.
  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)(∗1​,D,∗2​) where D is at position dim

    - Input2: (∗1,D,∗2)(\ast_1, D, \ast_2)(∗1​,D,∗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)(∗1​,∗2​)

  Examples::

        >>> input1 = torch.randn(100, 128)
        >>> input2 = torch.randn(100, 128)
        >>> cos = nn.CosineSimilarity(dim=1, eps=1e-6)
        >>> output = cos(input1, input2)

## Docs

Access comprehensive developer documentation for PyTorch

View Docs

## Tutorials

Get in-depth tutorials for beginners and advanced developers

View Tutorials

## Resources

Find development resources and get your questions answered

View Resources

To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: Cookies Policy.