CosineSimilarity

class paddle.nn. CosineSimilarity ( axis=1, eps=1e-8 ) [源代码]

CosineSimilarity

计算 x1 与 x2 沿 axis 维度的余弦相似度。

参数

  • axis (int) - 指定计算的维度,会在该维度上计算余弦相似度,默认值为 1。

  • eps (float) - 很小的值,防止计算时分母为 0,默认值为 1e-8。

返回

无

代码示例

>>> import paddle
>>> import paddle.nn as nn

>>> x1 = paddle.to_tensor(
...     [
...         [1.0, 2.0, 3.0],
...         [2.0, 3.0, 4.0],
...     ],
...     dtype="float32",
... )
>>> x2 = paddle.to_tensor(
...     [
...         [8.0, 3.0, 3.0],
...         [2.0, 3.0, 4.0],
...     ],
...     dtype="float32",
... )

>>> cos_sim_func = nn.CosineSimilarity(axis=0)
>>> result = cos_sim_func(x1, x2)
>>> print(result)
Tensor(shape=[3], dtype=float32, place=Place(cpu), stop_gradient=True,
[0.65079135, 0.98058069, 1.        ])