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.0714
#> -0.0027
#> -0.0145
#>  0.0361
#> -0.0832
#>  0.0811
#> -0.1210
#> -0.0159
#>  0.0029
#> -0.0501
#> -0.0331
#> -0.0553
#>  0.0300
#> -0.0510
#>  0.0043
#> -0.0119
#> -0.0288
#>  0.0003
#> -0.1126
#> -0.0392
#> -0.0599
#>  0.0022
#> -0.1022
#> -0.0574
#>  0.1004
#>  0.0188
#> -0.0231
#> -0.0623
#>  0.1287
#>  0.1311
#> ... [the output was truncated (use n=-1 to disable)]
#> [ CPUFloatType{100} ]