Table of Contents
Shortcuts

# torch.nn.functional.cosine_similarity

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

  Returns cosine similarity between `x1` and `x2`, computed along dim. `x1` and `x2` must be broadcastable to a common shape. `dim` refers to the dimension in this common shape. Dimension `dim` of the output is squeezed (see `torch.squeeze()`), resulting in the output tensor having 1 fewer dimension.

  similarity=x 1⋅x 2 max⁡(∥x 1∥2,ϵ)⋅max⁡(∥x 2∥2,ϵ)\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2, \epsilon) \cdot \max(\Vert x_2 \Vert _2, \epsilon)} similarity=max(∥x 1​∥2​,ϵ)⋅max(∥x 2​∥2​,ϵ)x 1​⋅x 2​​

  Supports type promotion.

  Parameters:

    - x1 (Tensor) – First input.

    - x2 (Tensor) – Second input.

    - dim (int, optional) – Dimension along which cosine similarity is computed. Default: 1

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

  Example:

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

## 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.