Q2. Co-occurrence Embeddings (20 points) Consider the technique of embedding words to…
- User
Q2. Co-occurrence Embeddings (20 points)
Consider the technique of embedding words to vectors using counts of context co-occurrences, as taught in class.
Here we will implement this technique to find embeddings for each unique word in the Shakespeare corpus. Later in the assignment, we will compare them to word embeddings learnt using Word2vec.
Download data - do not change
import requests import numpy as np from tqdm.notebook import tqdm import time
url = "https://raw.githubusercontent.com/karpathy/char-rnn/master/data/tinyshakespeare/input.txt" response = requests.get(url) response.raise_for_status() # Raise an exception for invalid HTTP status codes text_data = response.text len(text_data), text_data[:100]
preprocessing - do not change
text_data = response.text text_data = text_data.replace(',',' , ').replace('.',' . ').replace('?',' ? ').replace('!',' ! ') text_data = text_data.replace(' ', ' ') text_data = text_data.replace('\n\n','\n').replace('\n',' ') text_data = ' ' + text_data + ' ' len(text_data), text_data[:100]
data = text_data.split(' ') vocab = list(set(data)) revmap = {v:k for k,v in enumerate(vocab)} # dictionary to map words to indices
counts = np.zeros(shape=(len(vocab), len(vocab))) assert counts.shape == (18118, 18118)
span_length = 5 start_time = time.time()
IMPLEMENT HERE
for i,w in tqdm(enumerate(data), total=len(data)):
Hint: calculate co-occurrences in each window
Hint: calculate PPMI values using co-occurrences
ppmi = ...
Hint: Find L2 norms to convinently calculate cosine similiarity scores
ppmi_norms = ...
END OF IMPLEMENTATION
print("--- %s seconds ---" % (time.time() - start_time))
Note down this Training Time
assert ppmi.shape == (len(vocab), len(vocab)) assert counts[revmap['First'],revmap['Citizen:']] == 44. np.testing.assert_allclose(ppmi[revmap['First'],revmap['Citizen:']], 4.024266, rtol=1e-3)
- Assistantpython
for i, w in tqdm(enumerate(data), total=len(data)): w_idx = revmap[w] start = max(0, i - span_length) end = min(len(data), i + span_length + 1) for j in range(start, end): if j != i: context_word = data[j] c_idx = revmap[context_word] counts[w_idx, c_idx] += 1 # Compute total co-occurrences total_cooccurrences = counts.sum() # Compute counts per word and per context word counts_w = counts.sum(axis=1) # sum over contexts counts_c = counts.sum(axis=0) # sum over words # Get indices where counts are non-zero w_indices, c_indices = counts.nonzero() # Numerator and denominator for PPMI calculation ppmi_numer = counts[w_indices, c_indices] * total_cooccurrences ppmi_denom = counts_w[w_indices] * counts_c[c_indices] # Compute PPMI values ppmi_values = np.log2(ppmi_numer / ppmi_denom) ppmi_values = np.maximum(0, ppmi_values) # Create PPMI matrix ppmi = np.zeros_like(counts) ppmi[w_indices, c_indices] = ppmi_values # Find L2 norms for cosine similarity calculations ppmi_norms = np.linalg.norm(ppmi, axis=1)