paddle.fluid.layers.cos_sim(X, Y)[source]

Cosine Similarity Operator

\(Out = \frac{X^T * Y}{(\sqrt{X^T * X} * \sqrt{Y^T * Y})}\)

The input X and Y must have the same shape, except that the 1st dimension of input Y could be just 1 (different from input X), which will be broadcasted to match the shape of input X before computing their cosine similarity.

Both the input X and Y can carry the LoD (Level of Details) information, or not. But the output only shares the LoD information with input X.

  • X (Variable) – The 1st input of cos_sim op, LoDTensor with shape [N_1, N_2, ..., N_k], the data type is float32.

  • Y (Variable) – The 2nd input of cos_sim op, Tensor with shape [N_1 or 1, N_2, ..., N_k], the data type is float32.


A Variable holding LoDTensor representing the output of cosine(X, Y).


import paddle.fluid as fluid
x ='x', shape=[3, 7], dtype='float32')
y ='y', shape=[1, 7], dtype='float32')
out = fluid.layers.cos_sim(x, y)