The Company It Keeps

Sequential DataMedium+20 XP+20

The Company It Keeps

Word2vec rests on one idea: a word is characterised by the words around it. To use that idea you first need the neighbourhood itself as a vector — the average of the embeddings of the tokens surrounding a position, with that position's own token left out.

Task: write context_vectors(embeddings, tokens, window), returning one context vector per position in tokens, each component rounded to 4 decimal places.

  • embeddings is the lookup table: row iii is the vector for token id iii.
  • tokens is a sequence of token ids. The same id may appear at several positions.
  • The context of position iii is every position from i−wi - wi−w to i+wi + wi+w except iii itself, where www is window.
  • Positions that fall outside the sequence simply do not exist. The window is cut short at the ends, never padded.
  • The context vector is the elementwise mean of the embedding rows at those context positions.
  • If a position has no context at all, return a vector of zeros as wide as a row of the table.

Notice what this vector is not. It is a bag: shuffle the neighbours and it does not change. That is enough to learn which words keep company with which, and it is exactly why it is not enough to read a sentence.

the
cat
sat
on
the
warm
mat
centre: sat · context: the, cat, on, the

Every position gives another training example. Billions of them, free, from any text at all — no labelling required.

Examples

embeddings = [[1.0, 0.0], [0.0, 1.0], [2.0, 2.0]]
tokens = [0, 1, 2]
window = 1
returns [[0.0, 1.0], [1.5, 1.0], [0.0, 1.0]]
embeddings = [[1.0, 2.0, 3.0], [4.0, 0.0, 1.0], [0.0, 5.0, 2.0], [2.0, 2.0, 2.0]]
tokens = [0, 1, 2, 3, 1]
window = 2
returns [[2.0, 2.5, 1.5], [1.0, 3.0, 2.3333], [2.75, 1.0, 1.75], [2.6667, 1.6667, 1.3333], [1.0, 3.5, 2.0]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run