cosine_similarity

paddle.nn.functional. cosine_similarity ( x1, x2, axis=1, eps=1e-08 ) [source]

Compute cosine similarity between x1 and x2 along axis.

Parameters
  • x1 (Tensor) – First input. float32/double.

  • x2 (Tensor) – Second input. float32/double.

  • axis (int) – Dimension of vectors to compute cosine similarity. Default is 1.

  • eps (float) – Small value to avoid division by zero. Default is 1e-8.

Returns: a Tensor representing cosine similarity between x1 and x2 along axis. Return Type: Tensor

Examples

Case 0:
    x1 = [[0.8024077  0.9927354  0.27238318 0.8344984 ]
         [0.48949873 0.5797396  0.65444374 0.66510963]
         [0.1031398  0.9614342  0.08365563 0.6796464 ]
         [0.10760343 0.7461209  0.7726148  0.5801006 ]]
    x2 = [[0.62913156 0.1536727  0.9847992  0.04591406]
         [0.9098952  0.15715368 0.8671125  0.3156102 ]
         [0.4427798  0.54136837 0.5276275  0.32394758]
         [0.3769419  0.8535014  0.48041078 0.9256797 ]]
    axis = 1
    eps = 1e-8
    Out: [0.5275037  0.8368967  0.75037485 0.9245899]
Code Examples:
import paddle
import paddle.nn as nn
import numpy as np

np.random.seed(0)
x1 = np.random.rand(2,3)
x2 = np.random.rand(2,3)
x1 = paddle.to_tensor(x1)
x2 = paddle.to_tensor(x2)
result = paddle.nn.functional.cosine_similarity(x1, x2, axis=0)
print(result)
# [0.99806249 0.9817672  0.94987036]