Why one-hot vectors carry no similarity, and how raw co-occurrence vectors on the Brown corpus rank dog nearer car than cat.
The notebook carries the source, the install step and every run below, so nothing has to be on your machine. Open it, then choose Runtime › Run all.
Colab opens it read only. Click Copy to Drive to keep your changes.
python3 vsm.py onehot
Every pair of distinct one-hot vectors has cosine exactly 0, so cat is no nearer dog than democracy.
python3 vsm.py toy
The three-row table of the chapter, checked by hand: dog and cat have cosine 1, car has 0 with both.
python3 vsm.py brown
Window of five words each side on raw counts. dog comes out nearer car than cat, because every row is mostly the.
python3 vsm.py stop
Remove the 100 most frequent contexts and the order becomes the right one, at the price of much smaller cosines.
"""Chapter 6 on real text: how well do raw co-occurrence vectors measure meaning?
onehot every pair of distinct one-hot vectors has cosine 0
toy the three-row table of the chapter, checked by hand
brown window of 5 words each side, Brown corpus, raw counts
stop the same, with the 100 most frequent words removed as contexts
python3 vsm.py all
The lesson is in the gap between the last two. On raw counts the vectors for
dog and car are MORE similar than those for dog and cat, because every row is
dominated by the, a, and, of. Remove the 100 commonest contexts and the order
becomes the right one, at the price of much smaller cosines. Chapter 7 does the
principled version of that repair.
Install: pip install nltk, then python3 -m nltk.downloader brown
"""
import argparse
import math
import re
from collections import Counter
PAIRS = [("dog", "cat"), ("dog", "horse"), ("dog", "car"), ("car", "road"),
("doctor", "nurse"), ("doctor", "hospital")]
TARGETS = ["dog", "cat", "car", "horse", "doctor", "nurse", "hospital", "road"]
WINDOW = 5
def cosine(a, b):
dot = sum(a[k] * b[k] for k in a if k in b)
return dot / math.sqrt(sum(v * v for v in a.values()) * sum(v * v for v in b.values()))
def brown_tokens():
from nltk.corpus import brown
return [x.lower() for x in brown.words() if re.fullmatch(r"[a-z]+", x.lower())]
def cooccur(tokens, drop=frozenset()):
rows = {t: Counter() for t in TARGETS}
for i, w in enumerate(tokens):
if w in rows:
for j in range(max(0, i - WINDOW), min(len(tokens), i + WINDOW + 1)):
if j != i and tokens[j] not in drop:
rows[w][tokens[j]] += 1
return rows
def onehot():
print("one-hot: cos(cat, dog) = cos(cat, democracy) = 0 for any two distinct words")
def toy():
rows = {"dog": Counter(pet=2, feed=1), "cat": Counter(pet=2, feed=1), "car": Counter(drive=3)}
print("cos(dog, cat) = %.4f cos(dog, car) = %.4f"
% (cosine(rows["dog"], rows["cat"]), cosine(rows["dog"], rows["car"])))
def brown_run(stop):
tokens = brown_tokens()
freq = Counter(tokens)
drop = {w for w, _ in freq.most_common(100)} if stop else frozenset()
rows = cooccur(tokens, drop)
print("tokens %d, window %d, contexts removed: %d" % (len(tokens), WINDOW, len(drop)))
print(" counts of the targets:", {t: freq[t] for t in TARGETS})
for a, b in PAIRS:
print(" cos(%s, %s) = %.3f (they co-occur %d times)" % (a, b, cosine(rows[a], rows[b]), rows[a][b]))
if not stop:
for t in ("dog", "car"):
print(" row of %s, top contexts:" % t, rows[t].most_common(6))
def main():
ap = argparse.ArgumentParser()
ap.add_argument("part", choices=["onehot", "toy", "brown", "stop", "all"])
part = ap.parse_args().part
if part in ("onehot", "all"): onehot()
if part in ("toy", "all"): toy()
if part in ("brown", "all"): brown_run(False)
if part in ("stop", "all"): brown_run(True)
if __name__ == "__main__":
main()