import numpy as np from nltk.collocations import BigramCollocationFinder # 1. Corpus tokenization & co-occurrence finder (window_size=3 means ±2 words context) words = "the quick brown fox jumps over the lazy dog".split() finder = BigramCollocationFinder.from_words(words, window_size=3) # 2. Get dense co-occurrence matrix (C) and vocabulary mapping vocab = sorted(list(set(words))) v_to_idx = {w: i for i, w in enumerate(vocab)} C = np.zeros((len(vocab), len(vocab))) for (w1, w2), freq in finder.ngram_fd.items(): if w1 in v_to_idx and w2 in v_to_idx: C[v_to_idx[w1], v_to_idx[w2]] = freq # 3. Vectorized PPMI calculation N = C.sum() sum_w1, sum_w2 = C.sum(axis=1), C.sum(axis=0) expected = np.outer(sum_w1, sum_w2) / N # Avoid division/log by zero warnings by masking zero elements with np.errstate(divide='ignore', invalid='ignore'): pmi = np.log2(C * N / (np.outer(sum_w1, sum_w2))) ppmi = np.maximum(0, np.nan_to_num(pmi, nan=0.0, neginf=0.0)) print(ppmi)