Skip to contents

Cosine_similarity

Usage

torch_cosine_similarity(x1, x2, dim = 2L, eps = 1e-08)

Arguments

x1

(Tensor) First input.

x2

(Tensor) Second input (of size matching x1).

dim

(int, optional) Dimension of vectors. Default: 1

eps

(float, optional) Small value to avoid division by zero. Default: 1e-8

cosine_similarity(x1, x2, dim=1, eps=1e-8) -> Tensor

Returns cosine similarity between x1 and x2, computed along dim.

$$ \mbox{similarity} = \frac{x_1 \cdot x_2}{\max(\Vert x_1 \Vert _2 \cdot \Vert x_2 \Vert _2, \epsilon)} $$

Examples

if (torch_is_installed()) {

input1 = torch_randn(c(100, 128))
input2 = torch_randn(c(100, 128))
output = torch_cosine_similarity(input1, input2)
output
}
#> torch_tensor
#>  0.0305
#> -0.0182
#>  0.0420
#>  0.1624
#> -0.0298
#>  0.1531
#> -0.0605
#>  0.0000
#> -0.0160
#> -0.0241
#>  0.0530
#> -0.0665
#> -0.0217
#> -0.0156
#> -0.1495
#> -0.0518
#>  0.0479
#> -0.0701
#>  0.0126
#> -0.0778
#> -0.0188
#>  0.0288
#> -0.0369
#> -0.0133
#> -0.0499
#> -0.0711
#>  0.0695
#>  0.0328
#> -0.1419
#>  0.0098
#> ... [the output was truncated (use n=-1 to disable)]
#> [ CPUFloatType{100} ]