{"licence":{"name":"CC BY-SA 4.0","spdx":"CC-BY-SA-4.0","url":"https://creativecommons.org/licenses/by-sa/4.0/","attribution":"Atlas, a bilingual technical dictionary (https://cmaintz.github.io/tech-atlas/)"},"id":"ai/cosine-similarity","url":{"en":"https://cmaintz.github.io/tech-atlas/en/terms/ai/cosine-similarity/","da":"https://cmaintz.github.io/tech-atlas/da/terms/ai/cosine-similarity/"},"term":{"en":"Cosine similarity","da":"Cosinuslighed"},"aka":{"en":[],"da":[]},"domain":["ai"],"cluster":"retrieval","layer":"theory","status":"current","summary":{"en":"A score from -1 to 1 for how closely two lists of numbers point the same way, used to tell how alike two embeddings are in meaning.","da":"En score fra -1 til 1 for, hvor meget to lister af tal peger i samme retning, brugt til at afgøre, hvor ens to embeddings er i betydning."},"body":{"formal":{"en":"A measure of likeness between two embeddings based on the angle between them, ignoring their length; 1 means the same direction, 0 means unrelated and -1 means opposite.","da":"Et mål for lighed mellem to embeddings baseret på vinklen mellem dem, uden hensyn til deres længde; 1 betyder samme retning, 0 betyder ingen sammenhæng og -1 betyder modsat."},"plain":{"en":"Like comparing two arrows by which way they point, not how long they are - two people walking north are going the same way even if one walks much further.","da":"Som at sammenligne to pile efter, hvilken vej de peger, ikke hvor lange de er - to personer, der går mod nord, går samme vej, selvom den ene går meget længere."},"inPractice":{"en":"An IT supporter in a municipality tests the new help search; the embedding of “reset my password” scores 0.86 against the article “forgot your login” and 0.12 against “parking at the town hall”.","da":"En IT-supporter i en kommune tester den nye hjælpesøgning; embeddingen af “nulstil min adgangskode” scorer 0,86 mod artiklen “glemt dit login” og 0,12 mod “parkering ved rådhuset”."},"whyItMatters":{"en":"It is the usual measure in meaning-based search, but a high score only means “is about the same thing”, not “is correct” or “answers the question”.","da":"Det er den sædvanlige målestok i betydningsbaseret søgning, men en høj score betyder kun “handler om det samme”, ikke “er korrekt” eller “besvarer spørgsmålet”."}},"deepDive":{"en":"For vectors a and b the definition is cos(a, b) = (a · b) / (‖a‖ ‖b‖) = Σ aᵢbᵢ / (√Σ aᵢ² · √Σ bᵢ²). It is invariant to positive scaling of either vector, which is why it became the default in vector-space information retrieval: a long document with the same term proportions as a short one gets the same score. With non-negative vectors such as TF-IDF weights, as in the classic treatment in Manning, Raghavan and Schütze, the range is 0 to 1; only dense embeddings with signed components use the full −1 to 1 range. Pearson correlation is the cosine of mean-centred vectors.\n\nFor L2-normalised vectors, cosine similarity equals the dot product, and squared Euclidean distance is ‖a − b‖² = 2 − 2 cos(a, b), so ranking by cosine, by inner product and by Euclidean distance gives the same order. Vector databases exploit this: normalising at ingestion lets them use a fast inner-product kernel. The equivalence breaks if a model was trained for unnormalised inner product (DPR, for example, used the raw dot product) or if vectors are truncated, as with Matryoshka embeddings, without renormalising. Cosine distance, 1 − cos, is widely used as a dissimilarity but is not a true metric because it violates the triangle inequality; angular distance, arccos(cos)/π, is. Some index structures assume a metric, which is one reason engines expose the distance function as an explicit index parameter that must match the model.\n\nThe numeric value is less informative than the formal range suggests. Many transformer embeddings are anisotropic, occupying a narrow cone of the space (Ethayarajh, 2019), so unrelated texts can still score 0.6 or higher and negative scores are rare. Scores are therefore only comparable within one model and one version; a threshold such as \"above 0.8 counts as a match\" must be calibrated per model on labelled pairs and will not transfer when the model is changed. Steck, Ekanadham and Kallus (2024) showed that for some learned embeddings, cosine similarity can yield arbitrary results because the training objective leaves the scaling of individual dimensions undetermined, a reminder that the measure inherits whatever geometry the training imposed.\n\nComputation is d multiply-adds per pair, cheap enough for brute-force comparison of a query with tens of thousands of vectors using SIMD or GPU kernels, but approximate nearest-neighbour indexes are needed at millions of vectors. Compressed representations change the arithmetic: int8 scalar quantization keeps cosine ranking close to float32, while binary quantization replaces it with Hamming distance on sign bits and is normally followed by rescoring the top candidates with full-precision vectors.","da":"For vektorerne a og b er definitionen cos(a, b) = (a · b) / (‖a‖ ‖b‖) = Σ aᵢbᵢ / (√Σ aᵢ² · √Σ bᵢ²). Den er invariant over for positiv skalering af hver af vektorerne, og derfor blev den standard i vektorrumsmodellen for informationssøgning: Et langt dokument med samme fordeling af termer som et kort får samme score. Med ikke-negative vektorer som TF-IDF-vægte, som i den klassiske fremstilling hos Manning, Raghavan og Schütze, er intervallet 0 til 1; kun tætte embeddings med fortegnsbærende komponenter bruger hele intervallet fra −1 til 1. Pearson-korrelation er cosinus mellem middelværdicentrerede vektorer.\n\nFor L2-normaliserede vektorer er cosinuslighed lig med prikproduktet, og den kvadrerede euklidiske afstand er ‖a − b‖² = 2 − 2 cos(a, b), så rangering efter cosinus, indre produkt og euklidisk afstand giver samme rækkefølge. Det udnytter vektordatabaser: Normaliseres vektorerne ved indlæsning, kan de bruge en hurtig kerne til indre produkt. Ækvivalensen bryder sammen, hvis en model er trænet til unormaliseret indre produkt (DPR brugte fx det rå prikprodukt), eller hvis vektorer afkortes, som ved Matryoshka-embeddings, uden at blive normaliseret igen. Cosinusafstand, 1 − cos, bruges bredt som forskellighedsmål, men er ikke en egentlig metrik, fordi den bryder trekantsuligheden; vinkelafstand, arccos(cos)/π, er. Nogle indeksstrukturer forudsætter en metrik, hvilket er én grund til, at søgemaskiner gør afstandsfunktionen til en eksplicit indeksparameter, der skal passe til modellen.\n\nTalværdien siger mindre, end det formelle interval antyder. Mange transformer-embeddings er anisotrope og optager en smal kegle af rummet (Ethayarajh, 2019), så urelaterede tekster kan stadig score 0,6 eller mere, og negative scorer er sjældne. Scorer kan derfor kun sammenlignes inden for samme model og version; en tærskel som \"over 0,8 tæller som match\" skal kalibreres pr. model på mærkede par og kan ikke overføres, når modellen skiftes. Steck, Ekanadham og Kallus (2024) viste, at cosinuslighed for visse lærte embeddings kan give vilkårlige resultater, fordi træningsmålet lader skaleringen af de enkelte dimensioner være ubestemt, hvilket minder om, at målet arver den geometri, træningen har påført.\n\nBeregningen er d multiplikationer og additioner pr. par, billigt nok til at sammenligne en forespørgsel med titusinder af vektorer ved brute force med SIMD- eller GPU-kerner, men ved millioner af vektorer kræves indeks til approksimativ nærmeste-nabo-søgning. Komprimerede repræsentationer ændrer regnestykket: int8-skalarkvantisering holder cosinusrangeringen tæt på float32, mens binær kvantisering erstatter den med Hamming-afstand på fortegnsbit og normalt efterfølges af genberegning af de øverste kandidater med vektorer i fuld præcision."},"edges":[{"type":"requires","to":"ai/embedding","why":{"en":"It only has meaning when the numbers being compared are embeddings placed so that closeness reflects meaning.","da":"Den giver kun mening, når de tal, der sammenlignes, er embeddings placeret, så nærhed afspejler betydning."},"confidence":"high","strength":"primary"},{"type":"used-with","to":"ai/embedding-model","confidence":"high","strength":"normal"},{"type":"used-with","to":"ai/nearest-neighbour-search","confidence":"high","strength":"normal"}],"depth":2,"sources":[{"title":"Jurafsky & Martin, Speech and Language Processing (ch. 6, Vector Semantics and Embeddings)","tier":"textbook"},{"title":"Manning, Raghavan & Schütze, Introduction to Information Retrieval","tier":"textbook","publisher":"Cambridge University Press"}],"draft":true}