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, optional) – Dimension of vectors to compute cosine similarity. Default is 1.

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

Returns

Tensor, a Tensor representing cosine similarity between x1 and x2 along axis.

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

>>> paddle.seed(1)
>>> x1 = paddle.randn(shape=[2, 3])
>>> x2 = paddle.randn(shape=[2, 3])

>>> result = paddle.nn.functional.cosine_similarity(x1, x2, axis=0)
>>> print(result)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[ 0.97689527,  0.99996042, -0.55138415])