DEV Community

Trey Tomes
Trey Tomes

Posted on Edited on

Understanding Cosine Similarity

The source for this notebook is available from my GitHub Gist here.

Spend some time working with natural language processing and it seems to come up just about everywhere. How does it work?

This notebook demonstrates how to use cosine similarity to compare words letter-by-letter based on their physical location on a QWERTY keyboard.

The keyPos map is a hand-built set of X, Y vectors that roughly specify the physical location of each key relative to the other.

keyPos = {
    "`": {"x": 0, "y": 0},
    "1": {"x": 1, "y": 0},
    "2": {"x": 2, "y": 0},
    "3": {"x": 3, "y": 0},
    "4": {"x": 4, "y": 0},
    "5": {"x": 5, "y": 0},
    "6": {"x": 6, "y": 0},
    "7": {"x": 7, "y": 0},
    "8": {"x": 8, "y": 0},
    "9": {"x": 9, "y": 0},
    "0": {"x": 10, "y": 0},
    "-": {"x": 11, "y": 0},
    "=": {"x": 12, "y": 0},

    char(9): {"x": 0, "y": 1},
    "q": {"x": 1, "y": 1},
    "w": {"x": 2, "y": 1},
    "e": {"x": 3, "y": 1},
    "r": {"x": 4, "y": 1},
    "t": {"x": 5, "y": 1},
    "y": {"x": 6, "y": 1},
    "u": {"x": 7, "y": 1},
    "i": {"x": 8, "y": 1},
    "o": {"x": 9, "y": 1},
    "p": {"x": 10, "y": 1},
    "[": {"x": 11, "y": 1},
    "]": {"x": 12, "y": 1},

    "a": {"x": 1, "y": 2},
    "s": {"x": 2, "y": 2},
    "d": {"x": 3, "y": 2},
    "f": {"x": 4, "y": 2},
    "g": {"x": 5, "y": 2},
    "h": {"x": 6, "y": 2},
    "j": {"x": 7, "y": 2},
    "k": {"x": 8, "y": 2},
    "l": {"x": 9, "y": 2},
    ";": {"x": 10, "y": 2},
    "'": {"x": 11, "y": 2},

    "z": {"x": 1, "y": 3},
    "x": {"x": 2, "y": 3},
    "c": {"x": 3, "y": 3},
    "v": {"x": 4, "y": 3},
    "b": {"x": 5, "y": 3},
    "n": {"x": 6, "y": 3},
    "m": {"x": 7, "y": 3},
    ",": {"x": 10, "y": 3},
    ".": {"x": 11, "y": 3},
    "/": {"x": 12, "y": 3},

    " ": {"x": 5, "y": 4},
}
Enter fullscreen mode Exit fullscreen mode

The baseKeyMap maps the shifted variants of each character back to their original so we can grab the (x, y) position from keyPos.

baseKeyMap = {
    "!": "1",
    "@": "2",
    "#": "3",
    "$": "4",
    "%": "5",
    "^": "6",
    "&": "7",
    "*": "8",
    "(": "9",
    ")": "0",
    "_": "-",
    "+": "=",
    "{": "[",
    "}": "]",
    "|": ";",
    ":": "'",
    "<": ",",
    ">": ".",
    "?": "/",
    "~": "`",
}
Enter fullscreen mode Exit fullscreen mode

Now that the data's all in place, we need a set of functions to convert individual words into a "bag of keys". In our example, a bag of keys is an unordered collection that tracks multiplicity, e.g. "good" becomes {"d": 1, "g": 1", "o": 2}

Its cheap, and easy to understand, but "taco" and "coat" will be seen as identical.

baseKey = function(c)
    "Maps a character to the physical key it belongs to."
    if baseKeyMap.hasIndex(c) then return baseKeyMap[c]
    if c >= "A" and c <= "Z" then return c.lower
    return c
end function

keyUnit = function(c)
    "Returns the normalized x, y vector for a physical key."
    k = baseKey(c)
    if keyPos.hasIndex(k) then
        p = keyPos[k]
        norm = sqrt(p.x * p.x + p.y * p.y)
        if norm > 0 then
            return {"x": p.x / norm, "y": p.y / norm}
        end if
    end if
    return {"x": 0, "y": 0}
end function

cosKey = function(c1, c2)
    "Cosine similarity between two keys is the dot product of their unit vectors."
    u1 = keyUnit(c1)
    u2 = keyUnit(c2)
    return u1.x * u2.x + u1.y * u2.y
end function

wordVec = function(w)
    "Returns a bag of keys for a word: key to count."
    bag = {}
    for c in w
        k = baseKey(c)
        if bag.hasIndex(k) then
            bag[k] = bag[k] + 1
        else
            bag[k] = 1
        end if
    end for

    // Each "bag" is a map of the characters in the incoming word
    // to the number of times that character appears.
    return bag
end function
Enter fullscreen mode Exit fullscreen mode

There are 2 ways to compare words: cosWord converts 2 words into bags-of-keys, normalizes them, then takes their dot product. Ta-da! The angle between the words!

cosSeq solves the "taco" vs "coat" problem by introducing a character sequence dependency into the equation.

bagDot = function(bag1, bag2)
    "Dot product of two bags of keys."
    dotProduct = 0
    for kv in bag1
        k = kv.key
        c1 = kv.value
        c2 = 0
        if bag2.hasIndex(k) then
            c2 = bag2[k]
        end if
        dotProduct = dotProduct + c1 * c2
    end for
    return dotProduct
end function

bagNorm = function(bag)
    "Euclidean norm of a bag of keys."
    sum = 0
    for kv in bag
        sum = sum + kv.value * kv.value
    end for
    return sqrt(sum)
end function

cosWord = function(w1, w2)
    "Returns the cosine similarity between two words, via their bags of keys."
    v1 = wordVec(w1)
    v2 = wordVec(w2)
    norm1 = bagNorm(v1)
    norm2 = bagNorm(v2)
    if norm1 > 0 and norm2 > 0 then
        return bagDot(v1, v2) / (norm1 * norm2)
    end if
    return 0
end function

cosSeq = function(w1, w2)
    "Cosine similarity between two words, via aligned key sequences."
    if len(w1) == 0 or len(w2) == 0 then return 0
    if len(w1) != len(w2) then return cosWord(w1, w2)

    // If the words are different lengths the bag of keys is enough;
    // words of the same length and bag shape (e.g. coat, taco) need an additional position component in their vector.

    // `total` is the sum of the dot products between the keys of the 2 words.
    total = 0
    for i in range(0, len(w1) - 1)
        total = total + cosKey(w1[i], w2[i])
    end for
    return total / len(w1)
end function
Enter fullscreen mode Exit fullscreen mode

The "corpus" is a list of items you might find in a kitchen. You could put anything in here; the matcher simply compares the input word to the list and sorts it by distance.

corpus = [
    "flour",
    "sugar",
    "salt",
    "pepper",
    "water",
    "oil",
    "butter",
    "egg",
    "milk",
    "yeast",
    "baking",
    "soda",
    "vanilla",
    "cinnamon",
    "nutmeg",
    "garlic",
    "onion",
    "tomato",
    "potato",
    "carrot",
    "celery",
    "spinach",
    "lettuce",
    "rice",
    "pasta",
    "bread",
    "cheese",
    "chicken",
    "beef",
    "pork",
    "fish",
    "shrimp",
    "tofu",
    "beans",
    "lentils",
    "oats",
    "honey",
    "cocoa",
    "almond",
    "peanut",
    "cashew",
    "sesame",
    "cumin",
    "paprika",
    "thyme",
    "rosemary",
    "oregano",
    "basil",
    "sage",
    "dill",
    "chives",
    "ginger",
    "turmeric",
    "coriander",
    "fennel",
    "anise",
    "cardamom",
    "cloves",
    "allspice",
    "chili",
    "salsa",
    "gravy",
    "broth",
    "stock",
]
Enter fullscreen mode Exit fullscreen mode
word = input("Enter a word: ")
// word = "walt"

matches = []

for j in corpus
    // score = cosWord(word, corpus[j]) // just bag-of-words
    score = cosSeq(word, j) // bag-of-words with an addition sequence check if needed
    distance = sqrt(2 - 2 * score)
    matches.push {
        "score": score,
        "distance": distance,
        "word": j,
    }
end for

matches = matches.sort("distance")

for m in matches[:5]
    print word + " <-> " + m.word + ": cosine " + str(m.score) + ", distance " + str(m.distance)
end for
Enter fullscreen mode Exit fullscreen mode
Enter a word: paprika
paprika <-> paprika: cosine 1, distance 0
paprika <-> vanilla: cosine 0.968309, distance 0.251758
paprika <-> lentils: cosine 0.940247, distance 0.345697
paprika <-> lettuce: cosine 0.894082, distance 0.460255
paprika <-> chicken: cosine 0.875434, distance 0.499131
Enter fullscreen mode Exit fullscreen mode

The input word is compared with each word in the corpus, giving the cosine score along with the "distance" between the words. Smaller is better for a good match.

Running this example

You'll need to install a couple of tools to run this notebook for yourself.

Miniscript 2

Download the compiler that matches your OS. You'll need command-line MiniScript to use the VS.Code extension. Extract it somewhere that makes sense a keep a copy of the path to the executable.

vscode-miniscript2

Grab the latest release. You need the .vsix. Open this from the VS.Code Extensions tab, or run code --install-extension miniscript2.vsix" from a terminal.

Reload your VS.Code after the extension is installed, then you should be able to open and run this notebook for yourself.

Top comments (3)

Collapse
 
treytomes profile image
Trey Tomes •

The whole idea needs something more. I got caught up in the tech demo and didn't drop enough prose here. :-)

QWERTY keyboard proximity is great if you're prone to fat-fingering; if my fingers slipped and I wrote "tood" instead of "good" a similarity search like this could be useful. I had to fix a bug just yesterday where someone used a forward-slash in a database instead of a period, so it happens.

Shared meaning though! That requires a different kind of positional mapping! Instead of mapping letters to (x, y) values, you would need to measure entire words against a (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, etc.) coordinate plane! It just wouldn't do for a tiny demo.

But yeah, the article was fun to build and code-heavy.

Collapse
 
joestrout profile image
JoeStrout •

Love it! It's a great demonstration for people who already understand what the point of it is.

However, for people new to the concept, I feel like they're likely to miss the point. Especially since comparing words according to how similar their QWERTY keyboard locations are isn't a very useful thing to do. 😅 Could you add a few words relating this to, say, how neural networks encode semantic meanings?

Collapse
 
dataspryva profile image
Dataspryva •

Keyboard proximity makes cosine a measure of typing resemblance; a high score says nothing about shared meaning :)