Language models, retrieval, prompting, and language adaptation · Count-based and distributed representations · LNG004 · Model
Skip-gram with negative sampling (SGNS)
Predicts neighboring words from a center word, emphasizing useful distributional representations rather than normalized sentence likelihoods. Negative sampling makes a large vocabulary practical.
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
Predicts neighboring words from a center word, emphasizing useful distributional representations rather than normalized sentence likelihoods. Negative sampling makes a large vocabulary practical. It differs materially from CBOW in prediction direction and training signals, so both are documented while size variants are consolidated.
Question / objective
Which word-context pairs are more likely than draws from a chosen noise distribution?
Architecture / computational structure
Two embedding tables score center-context dot products. Positive and noise pairs contribute logistic terms; learned vectors are parameters, while negative count and noise exponent configure training.
Assumptions
Noise choices alter the learned geometry.
Formula / computational definition
Maximize log sigma(u_c^T v_w)+sum_{j=1}^k E_{n_j~P_n} log sigma(-u_{n_j}^T v_w), where w is the center, c a positive context, n_j noise words, and sigma the logistic function.
Parameters and notation
Learned parameters: identified in the architecture subsection. Hyperparameters, design and inference choices: Embedding width, context radius, k negatives, noise distribution, frequent-word subsampling, and minimum frequency.
Fitting, fine-tuning, and adaptation
Train with sampled logistic loss and hold out documents for downstream evaluation. Continue training on new text with a controlled learning rate and mixed corpora to reduce drift. Freeze or tune vectors in a labeled task; LoRA is generally unnecessary for these small tables.
How to use and calibrate
Compare retrieval and classification utility, neighbor stability, and performance on rare versus common words. Avoid treating sampled training loss as language-model perplexity. 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
Find specialized terms used in similar contexts within a scientific abstract collection.
Interpretation / pitfalls
Watch out
Dot products are not automatically calibrated probabilities; one vector cannot resolve contextual senses. 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 skip-gram and negative sampling supports Python; R can use reticulate or implement the explicit pairwise logistic objective with R torch.
Example scope: Exact SGNS loss for one positive and two sampled negative pairs.
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 — Exact SGNS loss for one positive and two sampled negative pairs.
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)
v, positive = [0.5, -0.2], [0.4, 0.1]
negatives = [[-0.5, 0.3], [0.2, 0.8]]
loss = -math.log(sigmoid(dot(v, positive)))
loss -= sum(math.log(sigmoid(-dot(v, u))) for u in negatives)
print(loss)
Complete calculation — Exact SGNS loss for one positive and two sampled negative pairs.
Shared setup for this chapter
softmax <- function(x) {
shifted <- exp(x-max(x))
shifted/sum(shifted)
}
v <- c(0.5,-0.2); positive <- c(0.4,0.1)
negatives <- rbind(c(-0.5,0.3), c(0.2,0.8))
loss <- -log(plogis(sum(v * positive))) - sum(log(plogis(-drop(negatives %*% v))))
print(loss)
Sources
- Source 1arxiv.org
From the CodeSplash reference, entry LNG004.