Word2vec: learn a vector by predicting its neighbors
Word2vec
Derive CBOW and skip-gram gradients, compare softmax and negative sampling, and inspect a reproducible small training objective.
word2vecLearn coordinates by asking about nearby words
In an invented corpus, blue bird flies and red bird flies share two words and one pattern. blue fish swims and red fish swims share another. A one-hot representation assigns every distinct word its own perpendicular axis, so bird is no closer to fish than to any other distinct word. Could a training task give those coordinates a more useful structure?
Word2vec learns lookup-table vectors through predictions about nearby words. Skip-gram takes a center word and predicts surrounding words. Continuous bag of words, CBOW, averages surrounding input vectors and predicts the center. A vector is useful here when it helps the chosen prediction task; no dictionary definition or synonym label is supplied. Architecture paper, §§3.1–3.2
The predictions share parameters across occurrences. Every occurrence of bird uses the same input row, so its updates accumulate evidence from different contexts. This also sets a limit: the basic model gives one input vector to a word type, not a different vector for each sense or sentence. Contextual embeddings address a different representation problem.
The corpus does not establish that context similarity equals synonymy. Opposites can fit the same frame: in the invented phrases water is hot and water is cold, the local neighbors alone do not identify that contrast. Treat similarity as a behavior to evaluate, not a definition of meaning.
Choose the event, then choose the objective
Two parameter tables and a fixed window
Let V be the vocabulary size and D the embedding dimension. Store an input table U and an output table W, both with V rows and D columns. Rows u_c and w_o serve different roles even when c and o name the same word. For a skip-gram center c, the hidden vector is h=u_c; the output logit for candidate o is w_oᵀh. Full softmax gives a normalized distribution over output words:
This is the basic softmax formulation in the second Word2vec paper. Normalizing over all V words makes a training event cost depend on V. Skip-gram paper, equation 2
With window radius one, blue bird flies produces the directed pairs (blue,bird), (bird,blue), (bird,flies) and (flies,bird). A sentence boundary ends the window. The complete demo contains the four sentences from the introduction plus three additional copies of blue bird flies: 21 tokens, six vocabulary words and 28 skip-gram events. It adds no BOS or EOS target.
Our implementation minimizes the mean loss over M constructed events:
The paper writes an average over center positions with an inner context sum. For the same fixed event collection, the paper’s value is M/T times this event mean, where T is the number of center tokens. The minimizers are unchanged by a positive global factor, but gradient magnitudes and effective step sizes change. Record the normalization when reproducing an update or loss value.
CBOW averages occurrences, including duplicates
For context occurrences c_1,…,c_m, CBOW uses:
The target is the center word. Near a boundary, fewer context occurrences are available; the denominator is their actual count. A singleton sentence supplies no nonempty context and contributes no CBOW event. Our seven three-token sentences produce 21 CBOW events. The architecture paper describes averaging the shared projection; word order within that context is lost. Architecture paper, §3.1
For one target o, let δ_j=p(j|h)−1[j=o]. Differentiating the negative log softmax gives:
The last operation accumulates by vocabulary row. If the context IDs are [0,0,1], row 0 receives 2g/3 and row 1 receives g/3. Deduplicating the context would change its mean; assigning instead of adding would lose one occurrence’s gradient. The program uses indexed accumulation and checks it with finite differences.
Negative sampling changes the learning problem
Skip-gram with negative sampling, SGNS, asks a binary discrimination question for the observed output and each sampled noise output. Define σ(s)=1/(1+exp(−s)) and softplus(s)=log(1+exp(s)). For a positive pair (c,o) and K explicitly supplied noise draws n_k:
Equivalently, maximize log σ on the positive logit and log σ of each negated noise logit. The paper defines an expectation over noise draws; a sampled list provides a stochastic estimate of that objective. Its negative-sampling objective is distinct from NCE and from the normalized softmax likelihood. Skip-gram paper, §2.2, equation 4
For each scored occurrence with binary target y∈1, differentiating binary cross-entropy gives:
Repeated noise indices contribute repeatedly. A noise draw may name a word that occurs in a real context elsewhere; “negative” describes the sampled training role, not a verified statement that the pair can never occur.
The paper uses a noise distribution proportional to a fractional power of unigram frequency. With positive training counts C(j):
Counts [1,16] therefore give probabilities [1/9,8/9], compared with [1/17,16/17] for raw frequency and [1/2,1/2] for uniform noise. The exponent is a reported choice, not a universal theorem of optimal sampling. The pinned author code constructs a finite table with power 0.75. Paper, §2.2 Pinned C, lines 43–67
Our default draws are with replacement and may include the positive target. An optional exclusion removes that target and renormalizes the noise distribution; this changes the objective. The pinned C loop instead skips a draw that equals the positive target, so the number of applied negatives can be smaller than the requested count. These policies should not be silently treated as the same sampler. Pinned C, lines 465–483
SGNS sigmoid values do not sum to one over the vocabulary. With three zero logits their binary scores sum to 1.5. They are not direct inputs to a language-model perplexity calculation. Applying a new normalization afterward defines a different scoring model and does not turn the trained binary objective into a softmax likelihood.
Hierarchical softmax is a normalized alternative
A binary tree assigns one leaf to each vocabulary word and one vector to each internal decision node. Along the root-to-word path, multiply the chosen branch probabilities. If a left branch has probability σ(a_rᵀh) and a right branch has probability 1−σ(a_rᵀh), let ε_r be +1 for left and −1 for right:
The leaf probabilities sum to one because every internal node divides its incoming probability between two children. Scoring a target requires O(D L_o) work for a path of length L_o, rather than evaluating V leaf logits. The paper uses a Huffman tree to give frequent words shorter paths. Skip-gram paper, §2.1, equation 3
Depth depends on the tree. For three equally frequent words with code lengths 1,2,2, the average length is 5/3, slightly greater than log₂3. “Logarithmic average cost” is not the exact inequality that every path, or every finite average, is at most log₂V. A binary tree may have a deepest path of V−1 edges. Huffman weighting and the distribution over evaluated targets matter. This article explains the tree alternative but the executable lab below implements full softmax and SGNS.
Stable arithmetic keeps large logits usable
Directly computing exp(2000) overflows ordinary floating point. Subtracting the largest logit preserves softmax probabilities and gives a stable log partition:
The implementation computes softplus with np.logaddexp and evaluates sigmoid separately on positive and negative arguments. A very small probability can round to zero in the displayed softmax while the negative log likelihood remains finite through the shifted-log calculation. If dot products or gradients themselves exceed the supported floating-point range, the code reports an error.
Run three objectives without comparing unlike scores
Save the block as word2vec.py. It requires NumPy; the checked environment is Python 3.12.4 with NumPy 1.26.4. Run python3 word2vec.py. Input is a list of already tokenized sentences; case and Unicode forms are preserved. The program prints the vocabulary, count vector, full training events, fixed noise draws, separate parameter tables and loss traces.
"""Original small Word2vec objective lab; NumPy 1.26.4.
Full-softmax CBOW/skip-gram and explicitly fixed SGNS draws. Deterministic batch
steps are teaching choices, not the threaded author C implementation. No claim
of semantic quality, calibrated SGNS probabilities or hierarchical softmax.
"""
from collections import Counter
import json,math
import numpy as np
def integer(x,minimum=1):
if type(x) is not int or x<minimum:raise ValueError('Integer outside supported range')
return x
def vocabulary(sentences):
if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Supply tokenized sentences')
rows=[]
for row in sentences:
if not isinstance(row,(list,tuple)) or any(not isinstance(w,str) or not w or any(0xD800<=ord(c)<=0xDFFF for c in w) for w in row):raise ValueError('Nonempty Unicode tokens without surrogates required')
rows.append(list(row))
counts=Counter(w for row in rows for w in row);words=tuple(sorted(counts))
if not words:raise ValueError('No training words')
return {'words':words,'index':{w:i for i,w in enumerate(words)},'counts':np.array([counts[w] for w in words],dtype=float),'sentences':rows}
def examples(vocab,window=1,kind='skipgram'):
integer(window)
if kind not in ('skipgram','cbow'):raise ValueError('Choose skipgram or cbow')
result=[]
for row in vocab['sentences']:
ids=[vocab['index'][w] for w in row]
for i,center in enumerate(ids):
context=[ids[j] for j in range(max(0,i-window),min(len(ids),i+window+1)) if j!=i]
if kind=='cbow' and context:result.append({'input':context,'target':center})
if kind=='skipgram':result.extend({'input':[center],'target':target} for target in context)
return result
def initialize(size,dim=3,seed=7):
integer(size);integer(dim);integer(seed,0);rng=np.random.default_rng(seed)
return {k:rng.uniform(-.1,.1,(size,dim)) for k in ('input','output')}
def matrices(model):
if not isinstance(model,dict) or set(model)!= {'input','output'}:raise ValueError('Input and output matrices required')
a,b=(np.asarray(model[k],dtype=float) for k in ('input','output'))
if a.ndim!=2 or not all(a.shape) or b.shape!=a.shape or not np.isfinite(a).all() or not np.isfinite(b).all():raise ValueError('Finite matching vocabulary-by-dimension matrices required')
return a,b
def ids(values,size,empty=False):
if not isinstance(values,(list,tuple)) or (not values and not empty) or any(type(i) is not int or not 0<=i<size for i in values):raise ValueError('Valid vocabulary index list required')
return list(values)
def sigmoid(values):
x=np.asarray(values,dtype=float);out=np.empty_like(x);positive=x>=0
out[positive]=1/(1+np.exp(-x[positive]));e=np.exp(x[~positive]);out[~positive]=e/(1+e)
return out
def loss_gradient(model,inputs,target,negative=None):
a,b=matrices(model);inputs=ids(inputs,len(a));ids([target],len(a))
with np.errstate(over='raise',invalid='raise',divide='raise'):
try:
h=a[inputs].mean(axis=0);da=np.zeros_like(a);db=np.zeros_like(b)
if negative is None:
scores=b@h;shifted=scores-scores.max();weights=np.exp(shifted);prob=weights/weights.sum()
loss=float(np.log(weights.sum())-shifted[target]);delta=prob.copy();delta[target]-=1
db=delta[:,None]*h;dh=delta@b
diagnostics={'kind':'softmax','probabilities':prob.tolist(),'probability_sum':float(prob.sum())}
else:
targets=[target]+ids(negative,len(a),empty=True);scores=b[targets]@h
signs=np.ones(len(targets));signs[0]=-1
loss=float(np.logaddexp(0,signs*scores).sum());delta=sigmoid(scores);delta[0]-=1
np.add.at(db,targets,delta[:,None]*h);dh=delta@b[targets]
diagnostics={'kind':'sgns','draws':targets[1:],'logits':scores.tolist(),'binary_scores':sigmoid(scores).tolist()}
np.add.at(da,inputs,dh/len(inputs))
except FloatingPointError as error:raise ValueError('Objective arithmetic overflow') from error
if not math.isfinite(loss) or not np.isfinite(da).all() or not np.isfinite(db).all():raise ValueError('Nonfinite objective or gradient')
return loss,{'input':da,'output':db},diagnostics
def noise_distribution(counts,power=.75,exclude=None):
c=np.asarray(counts,dtype=float)
if c.ndim!=1 or not len(c) or not np.isfinite(c).all() or np.any(c<=0):raise ValueError('Positive finite training counts required')
if isinstance(power,bool) or not isinstance(power,(int,float)) or not math.isfinite(power) or not 0<=power<=1:raise ValueError('Noise power must lie in [0,1]')
logweights=power*np.log(c);weights=np.exp(logweights-logweights.max())
if exclude is not None:ids([exclude],len(c));weights[exclude]=0
if not weights.sum():raise ValueError('No supported negative target remains')
return weights/weights.sum()
def fixed_negatives(rows,counts,k=2,seed=11,exclude_positive=False):
integer(k,0);integer(seed,0)
if type(exclude_positive) is not bool:raise ValueError('Boolean exclusion policy required')
rng=np.random.default_rng(seed);result=[]
for row in rows:
distribution=noise_distribution(counts,exclude=row['target'] if exclude_positive and k else None)
result.append({**row,'negative':rng.choice(len(distribution),size=k,replace=True,p=distribution).tolist()})
return result
def batch(model,rows):
a,b=matrices(model)
if not isinstance(rows,(list,tuple)) or not rows:raise ValueError('Nonempty event list required')
gradient={'input':np.zeros_like(a),'output':np.zeros_like(b)};loss=0.
for row in rows:
value,g,_=loss_gradient(model,row['input'],row['target'],row.get('negative'))
loss+=value
for key in gradient:gradient[key]+=g[key]
for key in gradient:gradient[key]/=len(rows)
return loss/len(rows),gradient
def train(initial,rows,steps=60,rate=1.):
integer(steps,0)
if isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Positive finite initial step required')
matrices(initial);model={k:np.array(v,dtype=float,copy=True) for k,v in initial.items()};value,grad=batch(model,rows);trace=[value]
for _ in range(steps):
norm=sum(float(np.sum(g*g)) for g in grad.values())
if norm<1e-24:break
step=rate
for attempt in range(40):
candidate={k:model[k]-step*grad[k] for k in model}
try:new,ng=batch(candidate,rows)
except ValueError:new=math.inf
if new<=value-1e-4*step*norm:break
step*=.5
else:raise ValueError('No decreasing step found')
model,value,grad=candidate,new,ng;trace.append(value)
return model,trace
def demo():
text=[['blue','bird','flies'],['red','bird','flies'],['blue','fish','swims'],['red','fish','swims']]+[['blue','bird','flies']]*3
vocab=vocabulary(text);sg=examples(vocab);cbow=examples(vocab,kind='cbow');fixed=fixed_negatives(sg,vocab['counts'])
initial=initialize(len(vocab['words']));runs={}
for name,rows in [('skipgram_softmax',sg),('cbow_softmax',cbow),('sgns_fixed_draws',fixed)]:
model,trace=train(initial,rows)
runs[name]={'events':len(rows),'loss_trace':trace,'input_vectors':model['input'].tolist(),'output_vectors':model['output'].tolist()}
hand={'input':np.array([[1.,0.],[0.,1.],[1.,1.]]),'output':np.zeros((3,2))}
soft,softgrad,sd=loss_gradient(hand,[0,1],2);neg,ng,nd=loss_gradient(hand,[0],1,[2,2])
return {'training':text,'vocabulary':list(vocab['words']),'counts':vocab['counts'].tolist(),'skipgram_events':sg,'cbow_events':cbow,
'noise_distribution_power075':noise_distribution(vocab['counts']).tolist(),'fixed_negative_events':fixed,'runs':runs,
'hand':{'softmax_loss':soft,'softmax':sd,'softmax_output_gradient':softgrad['output'].tolist(),'sgns_loss':neg,'sgns':nd,'sgns_output_gradient':ng['output'].tolist()},
'scope':'Original small fixed-window corpus. Batch mean per event; fixed replacement noise draws may include the positive target. Exact chain-rule mean-CBOW gradients; no threaded C, random windows, subsampling, hierarchical softmax or semantic-quality reproduction.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))
The seven-sentence experiment starts each objective from the same seeded tables. After 60 accepted batch steps, mean skip-gram softmax loss changes from about 1.792461 to 0.680052; CBOW softmax changes from 1.791993 to 0.775125; fixed-draw SGNS changes from 2.079576 to 1.525548. These are three different objectives, with different events and output semantics. Their raw numbers do not rank embedding quality.
The optimizer holds both the positive events and the sampled negatives fixed. It evaluates a complete batch gradient, then halves a proposed step until a sufficient-decrease condition holds. This makes the displayed descent trace refer to one function. Resampling the noise each time would change the sampled function and make a direct before/after comparison noisier. Large-scale Word2vec commonly uses stochastic updates; this small deterministic procedure is a teaching choice, not a reproduction of author training speed.
The pinned C implementation also differs in details beyond sampling. Its CBOW forward pass averages the input vectors, while its input-row update adds the accumulated error without another division by the number of contexts. Our implementation deliberately differentiates the declared mean exactly. Do not use its gradient checks as proof that the C optimizer follows the same update convention. Pinned C, lines 432–496
For a hand check, set input rows to [1,0], [0,1], [1,1] and all output rows to zero. Context [0,1] has h=[0.5,0.5], every softmax output has probability 1/3, and target 2 has loss ln3. The output gradients are [1/6,1/6], [1/6,1/6] and [−1/3,−1/3]. Input gradients are zero at that instant because all output rows are zero; subsequent output updates can make them nonzero.
Actual cost of this inspectable implementation
Let T be the input token count and S the sentence count. Vocabulary counting takes expected O(T+S) hash operations and sorting V types costs O(V log V), treating bounded-length token operations as units. A fixed radius R constructs O(TR) skip-gram events; storing full CBOW contexts also uses O(TR) index entries. String hashing and comparison add costs dependent on token length.
The mathematical dense-softmax event costs O(VD+mD) for m input occurrences. The SGNS score and sparse gradient contributions need O((K+m)D), but this lab allocates and checks full V×D gradient/parameter arrays per call. Its implemented per-event work therefore still includes O(VD), and its dense gradient storage is O(VD). It does not demonstrate the sparse-update speed advantage of a production SGNS implementation. Noise distributions are also rebuilt per event in fixed_negatives; computing their noise weights adds O(MV) work here, in addition to drawing and storing MK samples.
Each batch step scans the event list, and each rejected backtracking proposal adds another complete objective evaluation. The code bounds that search to 40 proposals. Report event count, gradient representation and evaluation count alongside an optimizer timing; a short mathematical loss formula is not the whole runtime.
Nearby words provide supervision, not a meaning certificate
Vocabulary pruning, tokenization, dynamic windows, frequent-word subsampling, dimensionality and output-vector choice all affect the learned representation. This lab keeps a fixed vocabulary and has no special UNK input row. A new spelling cannot be looked up without a separate policy; fastText shares character-subword parameters, while GloVe fits weighted co-occurrence statistics.
The original papers also discuss efficiency choices and phrase representations. Those are distinct from simply averaging word vectors: an idiomatic phrase need not be represented well by its constituent sum. Their full phrase algorithm, experimental settings and claimed gains are outside this lab’s verified implementation.
Evaluate on the intended task with fixed data and preprocessing. Intrinsic similarities, analogies and downstream accuracy measure different behavior; one should not replace another without justification. Frequency, polysemy and social associations in training data can affect the resulting neighborhoods. The miniature corpus and a falling training objective cannot establish reliable semantic generalization. See embedding evaluation.
Predict an update, then question the measurement
1. Understanding: which way does the prediction point?
For blue bird flies with radius one, list the skip-gram events and the CBOW event whose target is bird. Would joining the next sentence before constructing the window be harmless?
Answer: Skip-gram gives blue→bird, bird→blue, bird→flies and flies→bird. The center CBOW event uses [blue,flies] to predict bird. Joining sentences would add context pairs across the boundary and change the training data; the program intentionally stops each window at its sentence boundary.
2. Hand calculation: zero output rows
Use the supplied three-row hand model. Find the softmax loss and output gradients for input context [0,1], target 2. For input [0], positive target 1 and noise draws [2,2], find the SGNS loss and the gradient of output row 2.
Answer: The mean context is [0.5,0.5]. The softmax loss is ln3 and the output gradients are [1/6,1/6], [1/6,1/6], [−1/3,−1/3]. In SGNS, all three logits are zero, giving 3ln2. Each occurrence of negative row 2 contributes [0.5,0], so their sum is [1,0]. Keeping only one copy would compute a different loss and gradient.
3. Counterexample: context order and repeated indices
With context IDs [0,0,1] and hidden gradient g, how much reaches each input row? Would [0,1] give the same hidden vector? Explain why sorting and deduplicating are different operations.
Answer: Row 0 receives 2g/3 and row 1 receives g/3. The hidden vector is (2u_0+u_1)/3, generally different from (u_0+u_1)/2. Reordering the same occurrences preserves the mean; removing a duplicate changes multiplicity, the mean and its gradient. Accumulate by index rather than overwriting a shared row.
4. Transfer: a lower training number
An SGNS run has lower final loss than another run using a different noise distribution and negative count. Is that evidence of better semantic vectors? Can you compute language perplexity directly from the sigmoid scores?
Answer: No to both. Changing the noise distribution or count changes the discrimination task and loss scale. Compare representations using the same relevant evaluation setup instead. Independent sigmoid scores need not sum to one over output words, so their logs are not a normalized language-model likelihood. Keep the objective, sampling policy and evaluation claim separate.
Keep the architecture, objective and implementation versions distinct
The architecture paper was first submitted in January 2013; the linked v3 is the September 2013 revision. The separate October 2013 paper develops negative sampling and other extensions. Citing the first paper alone should not imply that every later training detail is part of that first version. Architecture paper Skip-gram extensions
The reviewed author-code snapshot is commit 20c129a, dated July 16, 2017. Its root license is Apache-2.0; the original Python exposition and implementation here do not copy or execute that C code. Source checking covered the CBOW/skip-gram definitions, softmax and negative-sampling equations, the displayed tree path, the noise-table code and the selected CBOW update block. The scoped record does not certify the whole repository, all benchmarks or human peer review. All training sentences, gradients, experiments and exercises in this article are original.
Make a prediction, then check
CBOW averages three context occurrences with IDs [0,0,1]. If the hidden-vector gradient is g, what reaches input row0?
Learning objectives
- Build CBOW and skip-gram events without crossing sentence boundaries.
- Derive gradients for averaged context and repeated negative indices.
- Separate full softmax, tree probabilities and the SGNS binary objective.
- Report sampling, normalization and evaluation choices precisely.
Prerequisites & connections
Explore related knowledge →References
- Efficient Estimation of Word Representations in Vector Space, v3
Tomas Mikolov; Kai Chen; Greg Corrado; Jeffrey Dean · 2013 - Distributed Representations of Words and Phrases and their Compositionality, v1
Tomas Mikolov; Ilya Sutskever; Kai Chen; Greg Corrado; Jeffrey Dean · 2013 - Author Word2vec C implementation, pinned snapshot
Tomas Mikolov and word2vec contributors · 2017
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-08 · Codex single-AI-author technical check: scoped architecture and negative-sampling papers plus pinned author C; nine paired equations, event versus center normalization, strict mean-CBOW gradients, full softmax versus binary SGNS and noise policies, normalized hierarchical paths with a three-leaf depth counterexample, stable arithmetic, actual dense complexity and four explained exercises. Original fixed-window toy data and deterministic batch objectives; not semantic quality, C reproduction or human peer review.
- Both languages align on nine displayed equations, four explained exercises and three scoped sources. Checked 28 skip-gram versus21 CBOW events, M/T normalization, duplicate input/noise accumulation, three equal-probability Huffman leaves and mean depth5/3 greater than log2(3). Kept the distinctions between positive hits, exclusion, resampling and the pinned C skip behavior.
- Production suite executes actual MDX:20 original gradient/boundary tests,3 article math cases and6 publication checks. Finite differences, zero-output hand gradients, fixed-noise loss endpoints and exponent laws verified. Dense allocation/validation costs remain stated; the training curves do not rank semantic quality.
- Four original SVGs bind the exact MDX results; eight figure tests check data, arithmetic, bars and bilingual references. Isolated18 language/width combinations and four fallback fonts passed after isolating the harness from the Astro development toolbar. Actual desktop/mobile screenshots inspected. Full article browser acceptance recorded separately; no human peer review or upstream code execution.
Source locations checked:
- Efficient Estimation of Word Representations in Vector Space, v3 · Scoped sections3.1–3.2, cached text190–233: averaged shared CBOW projection and skip-gram context prediction. v1 January16, v3 September7. No adopted benchmark claims.
- Distributed Representations of Words and Phrases and their Compositionality, v1 · Scoped§2–2.3 opening: dual tables, full/hierarchical softmax, negative sampling and noise power; PDF page3 inspected for equations2–4. Phrase algorithm and experimental tables not fully reviewed.
- Author Word2vec C implementation, pinned snapshot · Lines43–67 and432–496: noise table, CBOW average, sampling and input update. Apache-2.0 root license identified; no C execution, whole-repository audit or copied implementation.
Related topics