mindspore.ops.cosine_similarity

mindspore.ops.cosine_similarity(x1, x2, dim=1, eps=1e-08)[source]

Calculate cosine similarity between x1 and x2 along the axis, dim.

\[\text{similarity} = \dfrac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)}\]

Note

Currently, broadcast of input is not supported.

Parameters
  • x1 (Tensor) – The first input Tensor.

  • x2 (Tensor) – The second input Tensor.

  • dim (int, optional) – Axis for calculating cosine similarity. Default: 1 .

  • eps (float, optional) – Minimal value to avoid division by zero. Default: 1e-08 .

Returns

Tensor, cosine similarity between x1 and x2.

Raises

TypeError – If the dtype of x1 or x2 is neither float16 nor float32.

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import ops
>>> x1 = ms.Tensor([[-0.0256, 0.0127, -0.2475, 0.2316, 0.8037],
...                 [0.5809, -1.2712, -0.7038, -0.2558, 0.7494]], dtype=ms.float32)
>>> x2 = ms.Tensor([[-0.6115, -0.1965, -0.8484, 0.2389, 0.2409],
...                 [1.8940, -2.1997, 0.1915, 0.0856, 0.7542]], dtype=ms.float32)
>>> output = ops.cosine_similarity(x1, x2)
>>> print(output)
[0.4843164  0.81647635]