Language models, retrieval, prompting, and language adaptation · Count-based and distributed representations · LNG003 · Model
Word2vec continuous bag of words (CBOW)
Learns word vectors by predicting a center word from its surrounding words. Averaging context representations makes training efficient and produces useful similarity features when a contextual model would be too…
In CodeSplash
A CodeSplash method runs this entry in Python and R. Set it up from the method's page.
- Word vectors Verified in Python and R
Do it in CodeSplash Run it on your own data, in Python or R.
- Availability
- Runs in CodeSplash
- Code example
- Complete calculation
- Who ran it
- CodeSplash's own run
- CodeSplash's run
- Verified in Python and R through discover.word_vectors. The reference's example ran in Python and R here, and they agree.
- The reference's record
- Python: The chapter's authors report running it; there is no record for this entry alone. R: Reviewed but not run: R wasn't available to the reference's authors.
Purpose
Learns word vectors by predicting a center word from its surrounding words. Averaging context representations makes training efficient and produces useful similarity features when a contextual model would be too expensive. It is self-supervised: text supplies prediction targets.
Question / objective
Which word vectors make a center word predictable from its unordered surrounding context?
Architecture / computational structure
Context embeddings are averaged or summed before a prediction head. Learned quantities are input/output embedding tables and any hierarchical-softmax parameters; window width and negative-sample count are hyperparameters.
Assumptions
Bagged context discards word order and gives each word one vector despite polysemy.
Formula / computational definition
Let h=mean_{c in C} v_c for context C; optimize -log softmax(Uh)_w for center word w, often using hierarchical softmax or a sampling approximation. Input vectors v and output matrix U are separate learned parameters.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Context window, vector dimension, minimum count, subsampling, negative samples or tree configuration, and training passes.
Fitting, fine-tuning, and adaptation
Fit on unlabeled domain text; for adaptation continue training cautiously or refit jointly with general text. Freeze embeddings in a downstream classifier initially, then unfreeze if labels suffice. Validate downstream utility and neighborhood drift rather than only training loss.
How to use and calibrate
Use held-out downstream tasks and domain-specific retrieval; analogy accuracy alone is incomplete and can depend on preprocessing. Use development data for settings and an independent test set for the final estimate. Report uncertainty across examples or seeds when the evaluation design supports it; model scores and self-assessments are not automatically calibrated probabilities of correctness.
Example application
Create inexpensive word features for classifying a domain-specific document collection.
Interpretation / pitfalls
Watch out
Frequency, corpus composition, and social biases shape nearest neighbors. The code below isolates one stated component; successful execution does not validate model quality or reproduce the cited experiment.
Python and R code examples
Full implementation route: Gensim Word2Vec with CBOW mode is a documented Python route. R can call that implementation through reticulate; a native averaging-and-softmax example can be written in R torch without claiming identical optimized training.
Example scope: CBOW context averaging and exact small-vocabulary softmax loss.
Dependencies: Python 3 standard library; base R; shared setup above. No model downloads or external services.
Validation: Python component executed in the combined example script; R counterpart supplied but not runtime-tested here. All numbers are synthetic.
Python and R
The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.
Complete calculation — CBOW context averaging and exact small-vocabulary softmax loss.
Shared setup for this chapter
import math
def softmax(xs):
m = max(xs)
es = [math.exp(x-m) for x in xs]
return [e/sum(es) for e in es]
def dot(a, b):
return sum(x*y for x, y in zip(a, b))
def matvec(matrix, vector):
return [dot(row, vector) for row in matrix]
def meanvec(rows):
return [sum(row[j] for row in rows)/len(rows) for j in range(len(rows[0]))]
def sigmoid(x):
return 1/(1+math.exp(-x))
def nll(probabilities):
return -sum(math.log(p) for p in probabilities)
context = [[1.0, 0.0], [0.0, 1.0]]
h = meanvec(context)
p = softmax([dot(u, h) for u in [[1, 1], [-1, 0], [0, -1]]])
print(h, -math.log(p[0]))
Complete calculation — CBOW context averaging and exact small-vocabulary softmax loss.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
context <- rbind(c(1,0), c(0,1))
h <- colMeans(context)
p <- softmax(drop(rbind(c(1,1), c(-1,0), c(0,-1)) %*% h))
print(list(context=h, loss=-log(p[1])))
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG003.