- Categories:
VECTOR_COSINE_SIMILARITY¶
Computes the cosine similarity between two vectors.
Cosine similarity is based on the angle between two vectors in a multi-dimensional space; the magnitude of the vectors is not
considered. The cosine similarity value is the inner product of the vectors divided by the product of their lengths. The cosine
similarity is always in the interval [-1, 1]
. For example, identical vectors have a cosine similarity of 1
, two
orthogonal vectors have a similarity of 0
, and two opposite vectors have a similarity of -1
.
Syntax¶
VECTOR_COSINE_SIMILARITY( <vector>, <vector> )
Arguments¶
vector
The VECTOR value to calculate the angle from.
vector
The VECTOR value to calculate the angle to.
Returns¶
Returns a FLOAT value, in the interval [-1, 1]
which indicates the
cosine similarity between the two input vectors.
Usage notes¶
Due to computational optimizations in the vector comparison functions, floating-point errors may be slightly larger than usual (e.g. about 1e-4).
Examples¶
This example calls the VECTOR_COSINE_SIMILARITY function to find the vector closest to [1,2,3]
.
SELECT a, VECTOR_COSINE_SIMILARITY(a, [1,2,3]::VECTOR(FLOAT, 3)) AS similarity
FROM vectors
ORDER BY similarity DESC
LIMIT 1;
+-------------------------+
| [1, 2.2, 3] | 0.9990... |
+-------------------------+