Cosine similarity explained

In data analysis, cosine similarity is a measure of similarity between two non-zero vectors defined in an inner product space. Cosine similarity is the cosine of the angle between the vectors; that is, it is the dot product of the vectors divided by the product of their lengths. It follows that the cosine similarity does not depend on the magnitudes of the vectors, but only on their angle. The cosine similarity always belongs to the interval

[-1,1].

For example, two proportional vectors have a cosine similarity of 1, two orthogonal vectors have a similarity of 0, and two opposite vectors have a similarity of -1. In some contexts, the component values of the vectors cannot be negative, in which case the cosine similarity is bounded in

[0,1]

.

For example, in information retrieval and text mining, each word is assigned a different coordinate and a document is represented by the vector of the numbers of occurrences of each word in the document. Cosine similarity then gives a useful measure of how similar two documents are likely to be, in terms of their subject matter, and independently of the length of the documents.[1]

The technique is also used to measure cohesion within clusters in the field of data mining.[2]

One advantage of cosine similarity is its low complexity, especially for sparse vectors: only the non-zero coordinates need to be considered.

Other names for cosine similarity include Orchini similarity and Tucker coefficient of congruence; the Otsuka–Ochiai similarity (see below) is cosine similarity applied to binary data.

Definition

The cosine of two non-zero vectors can be derived by using the Euclidean dot product formula:

AB =\left\|A\right\|\left\|B\right\|\cos\theta

Given two n-dimensional vectors of attributes, A and B, the cosine similarity,, is represented using a dot product and magnitude as

cosinesimilarity=SC(A,B):=\cos(\theta)={AB\over\|A\|\|B\|}=

n
\sum\limits
i=1
{AiBi
}{
n
\sqrt{\sum\limits
i=1
2}}
{A
i

n
\sqrt{\sum\limits
i=1
2}}
{B
i

},

where

Ai

and

Bi

are the

i

th components of vectors

A

and

B

, respectively.

The resulting similarity ranges from -1 meaning exactly opposite, to 1 meaning exactly the same, with 0 indicating orthogonality or decorrelation, while in-between values indicate intermediate similarity or dissimilarity.

For text matching, the attribute vectors A and B are usually the term frequency vectors of the documents. Cosine similarity can be seen as a method of normalizing document length during comparison. In the case of information retrieval, the cosine similarity of two documents will range from

0\to1

, since the term frequencies cannot be negative. This remains true when using TF-IDF weights. The angle between two term frequency vectors cannot be greater than 90°.

If the attribute vectors are normalized by subtracting the vector means (e.g.,

A-\bar{A}

), the measure is called the centered cosine similarity and is equivalent to the Pearson correlation coefficient. For an example of centering,

ifA=[A1,

T,
A
2]

then\bar{A}=\left[

(A1+A2),
2
(A1+A2)
2

\right]T,

soA-\bar{A}=\left[

(A1-A2),
2
(-A1+A2)
2

\right]T.

Cosine distance

When the distance between two unit-length vectors is defined to be the length of their vector difference then\operatorname(\mathbf A, \mathbf B)= \sqrt= \sqrt= \sqrt\,.

Nonetheless the cosine distance[3] is often defined without the square root or factor of 2:

cosinedistance=DC(A,B):=1-SC(A,B).

It is important to note that, by virtue of being proportional to squared Euclidean distance, the cosine distance is not a true distance metric; it does not exhibit the triangle inequality property — or, more formally, the Schwarz inequality — and it violates the coincidence axiom. To repair the triangle inequality property while maintaining the same ordering, one can convert to Euclidean distance \sqrt or angular distance . Alternatively, the triangular inequality that does work for angular distances can be expressed directly in terms of the cosines; see below.

Angular distance and similarity

The normalized angle, referred to as angular distance, between any two vectors

A

and

B

is a formal distance metric and can be calculated from the cosine similarity.[4] The complement of the angular distance metric can then be used to define angular similarity function bounded between 0 and 1, inclusive.

When the vector elements may be positive or negative:

angulardistance=D\theta:=

\arccos(cosinesimilarity)
\pi

=

\theta
\pi

angularsimilarity=S\theta:=1-angulardistance=1-

\theta
\pi

Or, if the vector elements are always positive:

angulardistance=D\theta:=

2 ⋅ \arccos(cosinesimilarity)
\pi

=

2\theta
\pi

angularsimilarity=S\theta:=1-angulardistance=1-

2\theta
\pi
Unfortunately, computing the inverse cosine function is slow, making the use of the angular distance more computationally expensive than using the more common (but not metric) cosine distance above.

L2-normalized Euclidean distance

Another effective proxy for cosine distance can be obtained by

L2

normalisation of the vectors, followed by the application of normal Euclidean distance. Using this technique each term in each vector is first divided by the magnitude of the vector, yielding a vector of unit length. Then the Euclidean distance over the end-points of any two vectors is a proper metric which gives the same ordering as the cosine distance (a monotonic transformation of Euclidean distance; see below) for any comparison of vectors, and furthermore avoids the potentially expensive trigonometric operations required to yield a proper metric. Once the normalisation has occurred, the vector space can be used with the full range of techniques available to any Euclidean space, notably standard dimensionality reduction techniques. This normalised form distance is often used within many deep learning algorithms.

Otsuka–Ochiai coefficient

In biology, there is a similar concept known as the Otsuka–Ochiai coefficient named after Yanosuke Otsuka (also spelled as Ōtsuka, Ootsuka or Otuka,[5] Japanese: 大塚 弥之助)[6] and Akira Ochiai (Japanese: 落合 明),[7] also known as the Ochiai–Barkman[8] or Ochiai coefficient,[9] which can be represented as:

K=

|A\capB|
\sqrt{|A| x |B|
}Here,

A

and

B

are sets, and

|A|

is the number of elements in

A

. If sets are represented as bit vectors, the Otsuka–Ochiai coefficient can be seen to be the same as the cosine similarity. It is identical to the score introduced by Godfrey Thomson.[10]

In a recent book,[11] the coefficient is tentatively misattributed to another Japanese researcher with the family name Otsuka. The confusion arises because in 1957 Akira Ochiai attributes the coefficient only to Otsuka (no first name mentioned)[7] by citing an article by Ikuso Hamai (Japanese: 浜井 生三),[12] who in turn cites the original 1936 article by Yanosuke Otsuka.[6]

Properties

The most noteworthy property of cosine similarity is that it reflects a relative, rather than absolute, comparison of the individual vector dimensions. For any positive constant

a

and vector

V

, the vectors

V

and

aV

are maximally similar. The measure is thus most appropriate for data where frequency is more important than absolute values; notably, term frequency in documents.However more recent metrics with a grounding in information theory, such as Jensen–Shannon, SED, and triangular divergence have been shown to have improved semantics in at least some contexts.[13]

Cosine similarity is related to Euclidean distance as follows. Denote Euclidean distance by the usual

\|A-B\|

, and observe that

\|A-B\|2=(A-B)(A-B)=\|A\|2+\|B\|2-2(AB)

(polarization identity)

by expansion. When and are normalized to unit length,

\|A\|2=\|B\|2=1

so this expression is equal to

2(1-\cos(A,B)).

In short, the cosine distance can be expressed in terms of Euclidean distance as

DC(A,B)=

\|A-B\|2
2

when\|A\|2=\|B\|2=1

.

The Euclidean distance is called the chord distance (because it is the length of the chord on the unit circle) and it is the Euclidean distance between the vectors which were normalized to unit sum of squared values within them.

Null distribution: For data which can be negative as well as positive, the null distribution for cosine similarity is the distribution of the dot product of two independent random unit vectors. This distribution has a mean of zero and a variance of

1/n

(where

n

is the number of dimensions), and although the distribution is bounded between -1 and +1, as

n

grows large the distribution is increasingly well-approximated by the normal distribution.[14] [15] Other types of data such as bitstreams, which only take the values 0 or 1, the null distribution takes a different form and may have a nonzero mean.[16]

Triangle inequality for cosine similarity

The ordinary triangle inequality for angles (i.e., arc lengths on a unit hypersphere) gives us that

|~\angle{AC}-\angle{CB}~|\le~\angle{AB}~\le~\angle{AC}~+~\angle{CB}~.

Because the cosine function decreases as an angle in radians increases, the sense of these inequalities is reversed when we take the cosine of each value:

\cos(\angle{AC}-\angle{CB})\ge\cos(\angle{AB})\ge\cos(\angle{AC}+\angle{CB}).

Using the cosine addition and subtraction formulas, these two inequalities can be written in terms of the original cosines,

\cos(A,C)\cos(C,B)+\sqrt{\left(1-\cos(A,C)2\right)\left(1-\cos(C,B)2\right)}\geq\cos(A,B),

\cos(A,B)\geq\cos(A,C)\cos(C,B)-\sqrt{\left(1-\cos(A,C)2\right)\left(1-\cos(C,B)2\right)}.

This form of the triangle inequality can be used to bound the minimum and maximum similarity of two objects A and B if the similarities to a reference object C is already known. This is used for example in metric data indexing, but has also been used to accelerate spherical k-means clustering[17] the same way the Euclidean triangle inequality has been used to accelerate regular k-means.

Soft cosine measure

A soft cosine or ("soft" similarity) between two vectors considers similarities between pairs of features.[18] The traditional cosine similarity considers the vector space model (VSM) features as independent or completely different, while the soft cosine measure proposes considering the similarity of features in VSM, which help generalize the concept of cosine (and soft cosine) as well as the idea of (soft) similarity.

For example, in the field of natural language processing (NLP) the similarity among features is quite intuitive. Features such as words, n-grams, or syntactic n-grams[19] can be quite similar, though formally they are considered as different features in the VSM. For example, words “play” and “game” are different words and thus mapped to different points in VSM; yet they are semantically related. In case of n-grams or syntactic n-grams, Levenshtein distance can be applied (in fact, Levenshtein distance can be applied to words as well).

For calculating soft cosine, the matrix is used to indicate similarity between features. It can be calculated through Levenshtein distance, WordNet similarity, or other similarity measures. Then we just multiply by this matrix.

Given two -dimension vectors

a

and

b

, the soft cosine similarity is calculated as follows:

\begin{align} \operatorname{soft\cosine}1(a,b)=

N
\sum\nolimitssijaibj
i,j
N
\sqrt{\sum\nolimitssijaiaj
i,j
N
\sqrt{\sum\nolimits
i,j

sijbibj}}, \end{align}

where .

If there is no similarity between features (for), the given equation is equivalent to the conventional cosine similarity formula.

The time complexity of this measure is quadratic, which makes it applicable to real-world tasks. Note that the complexity can be reduced to subquadratic.[20] An efficient implementation of such soft cosine similarity is included in the Gensim open source library.

See also

External links

Notes and References

  1. [Amit Singhal|Singhal, Amit]
  2. P.-N. Tan, M. Steinbach & V. Kumar, Introduction to Data Mining, Addison-Wesley (2005),, chapter 8; page 500.
  3. Web site: CosineDistance – Wolfram Language & System Documentation Center . Wolfram Research (2007) . wolfram.com.
  4. Web site: COSINE DISTANCE, COSINE SIMILARITY, ANGULAR COSINE DISTANCE, ANGULAR COSINE SIMILARITY. 2020-07-11. www.itl.nist.gov.
  5. Omori, Masae . Geological idea of Yanosuke Otuka, who built the foundation of neotectonics (geoscientist) . Earth Science . 2004 . 58 . 4 . 256–259 . 10.15080/agcjchikyukagaku.58.4_256 .
  6. Otsuka, Yanosuke . The faunal character of the Japanese Pleistocene marine Mollusca, as evidence of the climate having become colder during the Pleistocene in Japan . Bulletin of the Biogeographical Society of Japan . 1936 . 6 . 16 . 165–170.
  7. Ochiai, Akira . Zoogeographical studies on the soleoid fishes found in Japan and its neighhouring regions-II . Bulletin of the Japanese Society of Scientific Fisheries . 1957 . 22 . 9 . 526–530 . 10.2331/suisan.22.526 . free .
  8. Book: Barkman, Jan J. . Phytosociology and Ecology of Cryptogamic Epiphytes: Including a Taxonomic Survey and Description of Their Vegetation Units in Europe . Van Gorcum . 1958 . Assen.
  9. Book: Romesburg , H. Charles . [{{Google books|ZuIPv7OKm10C|page=149|plainurl=yes}} Cluster Analysis for Researchers ]. Lifetime Learning Publications . 1984 . Belmont, California . 149 .
  10. Thomson, Godfrey . A hierarchy without a general factor . British Journal of Psychology . 1916 . 8 . 271–281 .
  11. Book: Howarth, Richard J. . [{{Google books|MNwlDwAAQBAJ|page=421|plainurl=yes}} Dictionary of Mathematical Geosciences: With Historical Notes ]. Springer . 2017 . Cham . 421 . 10.1007/978-3-319-57315-1 . 978-3-319-57314-4 . 67081034 . […] attributed by him to “Otsuka” [?A. Otsuka of the Dept. of Fisheries, Tohoku University]..
  12. Hamai, Ikuso . Stratification of community by means of "community coefficient" (continued) . Japanese Journal of Ecology . 1955 . 5 . 1 . 41–45 . 10.18960/seitai.5.1_41 .
  13. A Tale of Four Metrics . Connor . Richard . 2016 . Springer . Tokyo . 10.1007/978-3-319-46759-7_16 . Similarity Search and Applications .
  14. Spruill, Marcus C. . 2007 . Asymptotic distribution of coordinates on high dimensional spheres . Electronic Communications in Probability . 12 . 234–247 . 10.1214/ECP.v12-1294. free .
  15. Web site: Distribution of dot products between two random unit vectors in RD . CrossValidated .
  16. Graham L. Giller . 2012. The Statistical Properties of Random Bitstreams and the Sampling Distribution of Cosine Similarity . Giller Investments Research Notes . 20121024/1 . 10.2139/ssrn.2167044. 123332455.
  17. Schubert. Erich. Lang. Andreas. Feher. Gloria. 2021. Reyes. Nora. Connor. Richard. Kriege. Nils. Kazempour. Daniyal. Bartolini. Ilaria. Schubert. Erich. Chen. Jian-Jia. Accelerating Spherical k-Means. Similarity Search and Applications. Lecture Notes in Computer Science. 13058 . en. Cham. Springer International Publishing. 217–231. 10.1007/978-3-030-89657-7_17 . 2107.04074 . 978-3-030-89657-7. 235790358 .
  18. Sidorov. Grigori. Gelbukh. Alexander. Gómez-Adorno. Helena. Pinto. David. Soft Similarity and Soft Cosine Measure: Similarity of Features in Vector Space Model. Computación y Sistemas. 18. 3. 491–504. 10.13053/CyS-18-3-2043. 7 October 2014. 29 September 2014.
  19. Book: Sidorov. Grigori. Advances in Computational Intelligence. 7630. Velasquez . Francisco. Stamatatos. Efstathios . Gelbukh. Alexander. Chanona-Hernández. Liliana. LNAI 7630. 978-3-642-37798-3. 1–11. 10.1007/978-3-642-37798-3_1. Lecture Notes in Computer Science. 2013.
  20. Novotný . Vít . The 27th ACM International Conference on Information and Knowledge Management . 2018 . Torun, Italy . Implementation Notes for the Soft Cosine Measure . 1808.09407 . 1639–1642 . Association for Computing Machinery . 10.1145/3269206.3269317 . 978-1-4503-6014-2 .