v9.1.1
Menu

Word2Vec Skip-gram

hardFREEWord EmbeddingsNLP 1: Foundations

Implement skip-gram training pair generation for Word2Vec.

In the skip-gram model, given a center word, we predict the context words within a window. Generate all (center_word, context_word) training pairs.

Write skipgram_pairs(words, window).

Input:

  • words: a list of words (the text already split on spaces)
  • window: window size W (integer)

For each word at position i, context words are at positions max(0, i-W) to min(n-1, i+W), excluding position i itself.

Output: A list of tuples (center_word, context_word) in order of center word position, and for each center word, context words from left to right.

Example

Input
I love NLP deeply
2
Output
[('I', 'love'), ('I', 'NLP'), ('love', 'I'), ('love', 'NLP'), ('love', 'deeply'), ('NLP', 'I'), ('NLP', 'love'), ('NLP', 'deeply'), ('deeply', 'love'), ('deeply', 'NLP')]
Reasoning
  • Inputs: words is the text split into n=4n = 4 tokens: "I" (position 0), "love" (1), "NLP" (2), "deeply" (3). window is W=2W = 2 neighbours on each side.
  • Each word's window: position ii sees positions max⁡(0,i−2)\max(0, i-2) through min⁡(3,i+2)\min(3, i+2), minus ii itself. "I" gets 1, 2 (nothing to its left); "love" gets 0, 2, 3; "NLP" gets 0, 1, 3; "deeply" gets 1, 2 (the text ends on its right).
  • Pairs: each center word is paired with its context words, left to right, giving [('I', 'love'), ('I', 'NLP'), ('love', 'I'), ('love', 'NLP'), ('love', 'deeply'), ('NLP', 'I'), ('NLP', 'love'), ('NLP', 'deeply'), ('deeply', 'love'), ('deeply', 'NLP')].
  • Count check: 2+3+3+2=102 + 3 + 3 + 2 = 10 pairs. Away from the edges a word would get 2W=42W = 4 neighbours (16 pairs in total); the boundaries clip that.
  • Notice: pairs come in mirrored couples, e.g. (I, NLP) and (NLP, I), because "within WW positions" is symmetric. Casing is preserved, so "NLP" stays upper case.

Constraints

  • Window size W means W words to the left and W words to the right
  • Handle boundary positions (beginning/end of text)
  • Preserve original word casing
  • Output pairs in positional order

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.