Word2Vec: skip-gram, CBOW and negative sampling
Study Word2Vec skip-gram and CBOW, hierarchical softmax, negative sampling and their evaluation protocols.
After this lesson you can
- Construct context pairs with explicit window and subsampling rules.
- Derive softmax and negative-sampling gradients, including repeated indices.
- Explain hierarchical softmax, noise distributions and collision policies.
- Evaluate embeddings with coverage and training settings documented.
Before you start
- 17Embedding lookup table and its sparse gradientLarge-vocabulary softmax costDistributional hypothesisTerm-document and word-context matrices
- 12Noise-contrastive estimation
- 11Logistic regressionLogistic loss as Bernoulli likelihood
- 07Huffman codingPrefix code
- 06Learning-rate schedulesSGD convergence for convex problems
Learning words by predicting neighbors
When you read “the cat sleeps on the sofa,” each word occurs alongside others. If “dog” and “cat” appear in similar contexts, a prediction task may encourage their representations to share information. That similarity is a possibility to measure, not a guaranteed consequence of training. Static vectors also mix all uses of a word.
In the previous Neural probabilistic language model, an ordered window predicted the next token via a normalized distribution. Here the objective changes: for each center word we predict neighboring words, or vice versa. The objective produces useful embeddings for some tasks, but a pair score is not necessarily a next-word probability in text.
Mikolov and colleagues proposed log-bilinear architectures capable of training representations on large corpora. In their Table 5, with 783 million news words, three epochs and 300-dimensional vectors, CBOW achieved 36.1% total accuracy on their analogy test and skip-gram 53.3%. Their times were one and three days respectively under that protocol. These are results of that experiment, not a prediction for every corpus, machine or task.
From one sentence to many examples
The sentence “el gato duerme” with radius one produces directed pairs (el, gato), (gato, el), (gato, duerme) and (duerme, gato), without crossing sentence boundaries. Each pair has a center and a context. Repetitions can occur: “gato gato” contributes two directed occurrences, not one pair type.
A fixed window of maximum radius permits distances from 1 to . If radius is sampled uniformly from for each center, a position at distance survives with probability , before boundaries or discarded words. Thus closer words participate more often. If words are removed before windows are built, distance is measured in the surviving sequence, not the original.
Skip-gram and full softmax
Let vocabulary size be words and dimension . Each word has an input vector and output vector ; these are two learned tables, not two names for one matrix. In skip-gram, the center selects and softmax scores possible contexts:
For several observed contexts you can sum or average losses, always stating the convention. First differentiate one pair; write . The identity gives
The observed-context error subtracts its vector; all output vectors participate in the sum. A direct implementation therefore needs dot products of dimension per pair, plus normalization. No output row becomes sparse for free merely because there is one positive label.
CBOW: a prediction from the set
CBOW reverses the task. Given nonempty context , it averages and predicts the center with . Context order is lost in this operation. With , each context occurrence contributes to the row it looked up. If a word occurs several times, the chain rule sums those contributions. For the output table, .
Using a sum instead of a mean changes forward and gradient scale. State this in comparisons, along with treatment of boundaries and empty contexts. Quality differences between CBOW and skip-gram depend on corpus, implementation and evaluation, not an architectural theorem.
A tree of normalized decisions
Hierarchical softmax places one word at each leaf of a binary tree. Each internal node has vector and, for center , assigns probability to one branch and to the other. If is 1 for the branch receiving the sigmoid and 0 for its complement, the product along ‘s path is
At a leaf, incoming mass is its probability. At each node the two branch masses sum to incoming mass; by induction all leaves sum to one. For a visited node, if , that step’s loss has derivative with respect to . Thus the gradient multiplies that scalar by , and the gradient sums scalars multiplied by the path’s vectors.
A Huffman code minimizes frequency-weighted mean length among binary prefix codes. This favors short paths for frequent words, but does not guarantee all have length : a highly unbalanced tree can reach depth . Actual cost per word is proportional to times path length. In a balanced tree it is .
Negative sampling: another classification problem
Instead of normalizing over the full vocabulary, SGNS trains a binary classifier: observed pair has label one and each noise pair has label zero. With samples and , loss is
Define and . The chain rule gives
The last two expressions are individual-path contributions, not necessarily the full gradient of those rows. If two samples share an index, their contributions sum in the same row. If the positive word can also appear as a negative, both paths accumulate. The formulas describe the derivative of a scalar loss using the same pre-step parameters; updating a row midway through calculation changes the algorithm.
For each negative logit, when is finite: a small step on that isolated logit reduces it. In a simultaneous vector update, other interactions also change dot products; “attract” and “repel” are local intuitions, not guarantees that each Euclidean distance decreases or increases at every step.
The next simulation applies those derivatives to a reproducible sequence of toy pairs. Compare several values of , noise power and learning rate: every configuration starts from the same vectors, but changing also changes later draws. Plotted distances do not replace the dot product optimized by SGNS.
NCE also distinguishes data and noise, but explicitly uses noise-distribution values in its objective. NEG uses samples and is not equivalent to exactly maximizing softmax, nor does it alone produce a normalized context distribution. The 2013 paper, sections 2.1 and 2.2, distinguishes both objectives.
To see where classification comes from, fix center and suppose positives are drawn from (“datos” means data) and, per positive, independent negatives are drawn from without rejecting collisions. Among all examples in that mixture, the probability that a pair with context comes from data is
Logistic loss is cross-entropy of those labels. If , and each logit can be chosen independently, its optimum satisfies . This identity describes an idealized population problem: products of two finite-dimensional tables couple logits and need not reach every optimum. If either mass is zero, the corresponding optimum may be at an infinite limit. Rejecting positive context changes the joint negative distribution, so this formula cannot be applied without rederiving it. Goldberg and Levy develop this objective interpretation.
Noise, collisions and frequent words
For count of each included word, a common empirical choice is
The exponent compresses relative differences compared with the raw unigram but does not make the distribution uniform. The paper tested that power against unigram and uniform and observed better results on its tasks; it does not prove 3/4 is optimal for every corpus.
There are several legitimate policies for a negative sample equal to the positive. With replacement until negatives distinct from the positive are obtained, each independent draw has distribution for , provided . Negatives may repeat each other. By contrast, the original code skips a collision without replacing it, so it can use fewer than effective negatives. The resulting objective and distributions differ: record the variant.
Frequency and effective window also change examples. For relative frequency and threshold , the paper gives discard probability . The C code instead calculates retention . The difference affects pair count; a comparison must state the version used. Decreasing learning rate during training is another recipe choice, not an objective property.
Two tables initialized entirely to zero produce zero gradients for these bilinear products. If input is random and output starts at zero, output can receive gradients from the first step; input starts receiving them once output is nonzero.
Evaluation has its own protocol
You can query cosine neighbors in the input table, output table or their sum, but state which you use. Avoid division by zero norms. For , a common rule finds the vector closest to and excludes question words. Reporting only percentage on answerable questions is insufficient: also count the total, questions with out-of-vocabulary terms and number actually evaluated.
In Table 1 of Mikolov and colleagues, 2013, NEG-5 obtains 59% total analogy accuracy without subsampling and 60% with threshold ; HS-Huffman obtains 47% and 55%, respectively. They used 300-dimensional vectors and one billion words of internal Google news. Those numbers are not results of the labs below and do not establish which method wins on a small corpus.
Labs
SGNS from scratch
The lab builds pairs, noise and accumulated gradients with repeated indices. A small sample checks the pipeline in Pyodide; training on millions of tokens must be local if it exceeds the browser time limit. Neighbors and analogies can only be cited when produced by an actual run with vocabulary and coverage declared.
The cell starts from real excerpts of two chapters of part one of Don Quixote from Project Gutenberg, without network access. Vocabulary comes from the first; the second only checks coverage and known pairs. Rejecting identical excerpts does not detect partial matches. Vectors from this sample test the pipeline, not semantic evaluation.
"""SGNS en NumPy: muestra real muy pequeña, no una evaluación semántica.
Fragmentos de la primera parte de Don Quijote, capítulos I y II, Project
Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Dominio público declarado en EE. UU.; consulta la ley local y las condiciones
de uso de la marca https://www.gutenberg.org/policy/license.html .
La celda predeterminada usa únicamente estos fragmentos y no accede a red.
Para corpus grandes usa un proceso local y comprueba sus derechos.
"""
import math
import re
import unicodedata
from collections import Counter
import numpy as np
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
TOKEN = re.compile(r'\w+', re.UNICODE)
SEED = 17060
def tokenize(text):
return TOKEN.findall(unicodedata.normalize('NFC', text).lower())
def vocabulary(sentences, minimum=1):
counts = Counter(word for sentence in sentences for word in sentence)
words = sorted((w for w, n in counts.items() if n >= minimum),
key=lambda w: (-counts[w], w))
if len(words) < 2:
raise ValueError('El vocabulario necesita al menos dos palabras')
index = {word: i for i, word in enumerate(words)}
return words, index, np.array([counts[word] for word in words], dtype=float)
def noise_distribution(counts, power=.75):
counts = np.asarray(counts, dtype=float)
if (counts.ndim != 1 or not np.isfinite(counts).all() or
np.any(counts < 0) or not np.any(counts > 0) or
not math.isfinite(power) or power <= 0):
raise ValueError('Recuentos o exponente inválidos')
weights = np.zeros_like(counts)
mask = counts > 0
logs = np.log(counts[mask])
weights[mask] = np.exp(power * (logs - logs.max()))
return weights / weights.sum()
def sampled_contexts(sentences, index, counts, window, subsample, rng):
"""Filtra por el paper y después elige un radio por centro superviviente."""
total = counts.sum()
frequency = counts / total
if window < 1 or subsample < 0:
raise ValueError('Ventana o submuestreo inválido')
for sentence in sentences:
ids = [index[w] for w in sentence if w in index]
if subsample:
ids = [i for i in ids if rng.random() < min(1., math.sqrt(subsample / frequency[i]))]
for pos, center in enumerate(ids):
radius = int(rng.integers(1, window + 1))
for j in range(max(0, pos - radius), min(len(ids), pos + radius + 1)):
if j != pos:
yield center, ids[j]
def negatives(q, positives, k, rng, cdf=None):
"""Muestras independientes por par, condicionales a no ser el positivo."""
if k < 1:
raise ValueError('k debe ser positivo')
if np.any(q[positives] >= 1.):
raise ValueError('No hay masa de ruido fuera del positivo')
if cdf is None:
cdf = np.cumsum(q)
cdf[-1] = 1.
result = np.searchsorted(cdf, rng.random((len(positives), k)), side='right')
rejected = result == positives[:, None]
while np.any(rejected):
result[rejected] = np.searchsorted(cdf, rng.random(int(rejected.sum())), side='right')
rejected = result == positives[:, None]
return result
def sigmoid(x):
# Válido para números finitos de cualquier signo sin overflow.
out = np.empty_like(x)
mask = x >= 0
out[mask] = 1. / (1. + np.exp(-x[mask]))
exp_x = np.exp(x[~mask])
out[~mask] = exp_x / (1. + exp_x)
return out
def batch_loss_grad(E, U, centers, positives, negative_ids):
"""Media por par y acumulación exacta cuando se repiten índices."""
v = E[centers]
u_pos = U[positives]
u_neg = U[negative_ids]
positive_scores = np.sum(v * u_pos, axis=1)
negative_scores = np.einsum('bd,bkd->bk', v, u_neg)
n = len(centers)
loss = (np.logaddexp(0., -positive_scores).sum() +
np.logaddexp(0., negative_scores).sum()) / n
gp = (sigmoid(positive_scores) - 1.) / n
gn = sigmoid(negative_scores) / n
grad_E = np.zeros_like(E)
grad_U = np.zeros_like(U)
grad_v = gp[:, None] * u_pos + np.einsum('bk,bkd->bd', gn, u_neg)
np.add.at(grad_E, centers, grad_v)
np.add.at(grad_U, positives, gp[:, None] * v)
np.add.at(grad_U, negative_ids, gn[:, :, None] * v[:, None, :])
return float(loss), grad_E, grad_U
def gradcheck():
rng = np.random.default_rng(SEED)
E = rng.normal(0, .2, (4, 3))
U = rng.normal(0, .2, (4, 3))
# Repite centros y negativos, y comparte una fila positiva con otra negativa.
centers = np.array([0, 0, 2])
pos = np.array([1, 1, 3])
neg = np.array([[2, 2], [3, 2], [1, 1]])
_, dE, dU = batch_loss_grad(E, U, centers, pos, neg)
errors = {}
for name, table, grad in [('E', E, dE), ('U', U, dU)]:
maximum = 0.
for idx in np.ndindex(table.shape):
before = table[idx]
table[idx] = before + 1e-6
plus = batch_loss_grad(E, U, centers, pos, neg)[0]
table[idx] = before - 1e-6
minus = batch_loss_grad(E, U, centers, pos, neg)[0]
table[idx] = before
maximum = max(maximum, abs((plus - minus) / 2e-6 - grad[idx]))
assert maximum < 1e-7, (name, maximum)
errors[name] = maximum
return errors
def fit_sgns(sentences, words, index, counts, epochs, dim, window, k, rate,
seed, subsample=0., batch_size=32):
rng = np.random.default_rng(seed)
q = noise_distribution(counts)
cdf = np.cumsum(q)
cdf[-1] = 1.
E = rng.normal(0., .1, (len(words), dim))
U = np.zeros((len(words), dim))
history = []
for epoch in range(epochs):
pending, total_loss, number = [], 0., 0
def update(pairs):
centers = np.array([p[0] for p in pairs], dtype=np.int64)
positives = np.array([p[1] for p in pairs], dtype=np.int64)
neg = negatives(q, positives, k, rng, cdf)
# Solo materializar gradientes de filas presentes, acumulando los
# índices repetidos antes de escribir cada fila una sola vez.
e_rows, local_centers = np.unique(centers, return_inverse=True)
u_rows, local_outputs = np.unique(np.concatenate([positives, neg.ravel()]),
return_inverse=True)
local_pos = local_outputs[:len(positives)]
local_neg = local_outputs[len(positives):].reshape(neg.shape)
loss, dE, dU = batch_loss_grad(E[e_rows], U[u_rows], local_centers,
local_pos, local_neg)
if not np.isfinite(loss) or not np.isfinite(dE).all() or not np.isfinite(dU).all():
raise ValueError('Pérdida o gradiente no finito')
E[e_rows] -= rate * dE
U[u_rows] -= rate * dU
return loss * len(pairs), len(pairs)
for pair in sampled_contexts(sentences, index, counts, window, subsample, rng):
pending.append(pair)
if len(pending) == batch_size:
value, size = update(pending)
total_loss += value
number += size
pending = []
if pending:
value, size = update(pending)
total_loss += value
number += size
history.append({'epoch': epoch + 1, 'pairs': number,
'mean_loss': total_loss / number if number else None})
return E, U, history
def neighbors(word, words, E, count=5):
if word not in words:
return []
norms = np.linalg.norm(E, axis=1)
index = words.index(word)
if norms[index] <= 1e-12:
return []
similarities = np.full(len(words), -np.inf)
valid = norms > 1e-12
similarities[valid] = (E[valid] @ E[index]) / (norms[valid] * norms[index])
similarities[index] = -np.inf
order = np.argsort(-similarities, kind='stable')
return [(words[i], float(similarities[i])) for i in order[:count] if np.isfinite(similarities[i])]
def main_small():
train, valid = tokenize(TRAIN), tokenize(VALID)
if train == valid:
raise ValueError('Fragmentos idénticos')
words, index, counts = vocabulary([train])
E, _, history = fit_sgns([train], words, index, counts, epochs=8,
dim=6, window=2, k=2, rate=.1, seed=SEED,
subsample=.01)
known = [w for w in valid if w in index]
pairs = list(sampled_contexts([valid], index, counts, 2, 0.,
np.random.default_rng(SEED + 1)))
print('Gradcheck error absoluto máximo:', gradcheck())
print('Tokens train/valid:', len(train), len(valid), '| OOV valid:', len(valid) - len(known))
print('Pares valid con palabras conocidas:', len(pairs),
'| se filtran OOV antes de crear la ventana')
print('Historial train:', history)
print('Vecinos de entrada de', words[0], ':', neighbors(words[0], words, E))
print('La pérdida de entrenamiento es exploratoria y cambia con los pares y negativos sorteados.')
print('Los fragmentos son demasiado pequeños para conclusiones semánticas; no hay test.')
if __name__ == '__main__':
main_small()Compare with Gensim
The reader can train skip-gram, CBOW, hierarchical softmax and negative sampling on text8. For comparison, fix corpus, splits, vocabulary, dimensions, seed and options, and explain differences in subsampling and collisions. Gensim documentation states that reproducibility across processes requires controlling the hash and using one worker; multiple workers for performance measurement change that condition. The text8 catalog does not confirm a license: check provenance and terms before redistribution.
The local cell requires NumPy, Gensim and compatible dependencies. It downloads text8 to a configurable cache, verifies published size and MD5 and records calculated SHA-256. The Gensim catalog says it found no text8 license: check provenance and usage terms before redistribution. Contiguous blocks of 2000 words are split into training, validation and test; these are artificial cuts and do not guarantee document separation or absence of duplicates. Vocabulary is built only from training.
The analogy benchmark loads from a pinned revision and its repository includes Apache 2.0; check terms applicable to the file. SHA-256 of received bytes is calculated, but checked against an external source only if you supply a reliable value in ORYON_ANALOGIES_SHA256. Analogies and text test are exploratory because several models are examined. Coverage and invalid norms are counted separately.
With ORYON_VERIFY_SHORT=1, 20,000 tokens, one epoch and 128 evenly spaced questions are used: this checks the pipeline, not a conclusive comparison. In that short run all 128 questions were out of vocabulary, so no analogy could be evaluated. Normal mode provides training on text8 and the full benchmark. ORYON_WORKERS chooses Gensim workers, initially 1; SHORT requires 1. Subsampling is disabled to align that decision, but batch updates, learning rate and collisions still differ between implementations.
"""SGNS en NumPy: muestra real muy pequeña, no una evaluación semántica.
Fragmentos de la primera parte de Don Quijote, capítulos I y II, Project
Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Dominio público declarado en EE. UU.; consulta la ley local y las condiciones
de uso de la marca https://www.gutenberg.org/policy/license.html .
La celda predeterminada usa únicamente estos fragmentos y no accede a red.
Para corpus grandes usa un proceso local y comprueba sus derechos.
"""
import math
import re
import unicodedata
from collections import Counter
import numpy as np
TRAIN = 'En un lugar de la Mancha, de cuyo nombre no quiero acordarme'
VALID = 'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo'
TOKEN = re.compile(r'\w+', re.UNICODE)
SEED = 17060
def tokenize(text):
return TOKEN.findall(unicodedata.normalize('NFC', text).lower())
def vocabulary(sentences, minimum=1):
counts = Counter(word for sentence in sentences for word in sentence)
words = sorted((w for w, n in counts.items() if n >= minimum),
key=lambda w: (-counts[w], w))
if len(words) < 2:
raise ValueError('El vocabulario necesita al menos dos palabras')
index = {word: i for i, word in enumerate(words)}
return words, index, np.array([counts[word] for word in words], dtype=float)
def noise_distribution(counts, power=.75):
counts = np.asarray(counts, dtype=float)
if (counts.ndim != 1 or not np.isfinite(counts).all() or
np.any(counts < 0) or not np.any(counts > 0) or
not math.isfinite(power) or power <= 0):
raise ValueError('Recuentos o exponente inválidos')
weights = np.zeros_like(counts)
mask = counts > 0
logs = np.log(counts[mask])
weights[mask] = np.exp(power * (logs - logs.max()))
return weights / weights.sum()
def sampled_contexts(sentences, index, counts, window, subsample, rng):
"""Filtra por el paper y después elige un radio por centro superviviente."""
total = counts.sum()
frequency = counts / total
if window < 1 or subsample < 0:
raise ValueError('Ventana o submuestreo inválido')
for sentence in sentences:
ids = [index[w] for w in sentence if w in index]
if subsample:
ids = [i for i in ids if rng.random() < min(1., math.sqrt(subsample / frequency[i]))]
for pos, center in enumerate(ids):
radius = int(rng.integers(1, window + 1))
for j in range(max(0, pos - radius), min(len(ids), pos + radius + 1)):
if j != pos:
yield center, ids[j]
def negatives(q, positives, k, rng, cdf=None):
"""Muestras independientes por par, condicionales a no ser el positivo."""
if k < 1:
raise ValueError('k debe ser positivo')
if np.any(q[positives] >= 1.):
raise ValueError('No hay masa de ruido fuera del positivo')
if cdf is None:
cdf = np.cumsum(q)
cdf[-1] = 1.
result = np.searchsorted(cdf, rng.random((len(positives), k)), side='right')
rejected = result == positives[:, None]
while np.any(rejected):
result[rejected] = np.searchsorted(cdf, rng.random(int(rejected.sum())), side='right')
rejected = result == positives[:, None]
return result
def sigmoid(x):
# Válido para números finitos de cualquier signo sin overflow.
out = np.empty_like(x)
mask = x >= 0
out[mask] = 1. / (1. + np.exp(-x[mask]))
exp_x = np.exp(x[~mask])
out[~mask] = exp_x / (1. + exp_x)
return out
def batch_loss_grad(E, U, centers, positives, negative_ids):
"""Media por par y acumulación exacta cuando se repiten índices."""
v = E[centers]
u_pos = U[positives]
u_neg = U[negative_ids]
positive_scores = np.sum(v * u_pos, axis=1)
negative_scores = np.einsum('bd,bkd->bk', v, u_neg)
n = len(centers)
loss = (np.logaddexp(0., -positive_scores).sum() +
np.logaddexp(0., negative_scores).sum()) / n
gp = (sigmoid(positive_scores) - 1.) / n
gn = sigmoid(negative_scores) / n
grad_E = np.zeros_like(E)
grad_U = np.zeros_like(U)
grad_v = gp[:, None] * u_pos + np.einsum('bk,bkd->bd', gn, u_neg)
np.add.at(grad_E, centers, grad_v)
np.add.at(grad_U, positives, gp[:, None] * v)
np.add.at(grad_U, negative_ids, gn[:, :, None] * v[:, None, :])
return float(loss), grad_E, grad_U
def gradcheck():
rng = np.random.default_rng(SEED)
E = rng.normal(0, .2, (4, 3))
U = rng.normal(0, .2, (4, 3))
# Repite centros y negativos, y comparte una fila positiva con otra negativa.
centers = np.array([0, 0, 2])
pos = np.array([1, 1, 3])
neg = np.array([[2, 2], [3, 2], [1, 1]])
_, dE, dU = batch_loss_grad(E, U, centers, pos, neg)
errors = {}
for name, table, grad in [('E', E, dE), ('U', U, dU)]:
maximum = 0.
for idx in np.ndindex(table.shape):
before = table[idx]
table[idx] = before + 1e-6
plus = batch_loss_grad(E, U, centers, pos, neg)[0]
table[idx] = before - 1e-6
minus = batch_loss_grad(E, U, centers, pos, neg)[0]
table[idx] = before
maximum = max(maximum, abs((plus - minus) / 2e-6 - grad[idx]))
assert maximum < 1e-7, (name, maximum)
errors[name] = maximum
return errors
def fit_sgns(sentences, words, index, counts, epochs, dim, window, k, rate,
seed, subsample=0., batch_size=32):
rng = np.random.default_rng(seed)
q = noise_distribution(counts)
cdf = np.cumsum(q)
cdf[-1] = 1.
E = rng.normal(0., .1, (len(words), dim))
U = np.zeros((len(words), dim))
history = []
for epoch in range(epochs):
pending, total_loss, number = [], 0., 0
def update(pairs):
centers = np.array([p[0] for p in pairs], dtype=np.int64)
positives = np.array([p[1] for p in pairs], dtype=np.int64)
neg = negatives(q, positives, k, rng, cdf)
# Solo materializar gradientes de filas presentes, acumulando los
# índices repetidos antes de escribir cada fila una sola vez.
e_rows, local_centers = np.unique(centers, return_inverse=True)
u_rows, local_outputs = np.unique(np.concatenate([positives, neg.ravel()]),
return_inverse=True)
local_pos = local_outputs[:len(positives)]
local_neg = local_outputs[len(positives):].reshape(neg.shape)
loss, dE, dU = batch_loss_grad(E[e_rows], U[u_rows], local_centers,
local_pos, local_neg)
if not np.isfinite(loss) or not np.isfinite(dE).all() or not np.isfinite(dU).all():
raise ValueError('Pérdida o gradiente no finito')
E[e_rows] -= rate * dE
U[u_rows] -= rate * dU
return loss * len(pairs), len(pairs)
for pair in sampled_contexts(sentences, index, counts, window, subsample, rng):
pending.append(pair)
if len(pending) == batch_size:
value, size = update(pending)
total_loss += value
number += size
pending = []
if pending:
value, size = update(pending)
total_loss += value
number += size
history.append({'epoch': epoch + 1, 'pairs': number,
'mean_loss': total_loss / number if number else None})
return E, U, history
def neighbors(word, words, E, count=5):
if word not in words:
return []
norms = np.linalg.norm(E, axis=1)
index = words.index(word)
if norms[index] <= 1e-12:
return []
similarities = np.full(len(words), -np.inf)
valid = norms > 1e-12
similarities[valid] = (E[valid] @ E[index]) / (norms[valid] * norms[index])
similarities[index] = -np.inf
order = np.argsort(-similarities, kind='stable')
return [(words[i], float(similarities[i])) for i in order[:count] if np.isfinite(similarities[i])]
def main_small():
train, valid = tokenize(TRAIN), tokenize(VALID)
if train == valid:
raise ValueError('Fragmentos idénticos')
words, index, counts = vocabulary([train])
E, _, history = fit_sgns([train], words, index, counts, epochs=8,
dim=6, window=2, k=2, rate=.1, seed=SEED,
subsample=.01)
known = [w for w in valid if w in index]
pairs = list(sampled_contexts([valid], index, counts, 2, 0.,
np.random.default_rng(SEED + 1)))
print('Gradcheck error absoluto máximo:', gradcheck())
print('Tokens train/valid:', len(train), len(valid), '| OOV valid:', len(valid) - len(known))
print('Pares valid con palabras conocidas:', len(pairs),
'| se filtran OOV antes de crear la ventana')
print('Historial train:', history)
print('Vecinos de entrada de', words[0], ':', neighbors(words[0], words, E))
print('La pérdida de entrenamiento es exploratoria y cambia con los pares y negativos sorteados.')
print('Los fragmentos son demasiado pequeños para conclusiones semánticas; no hay test.')
# Esta segunda celda es autocontenida: las funciones anteriores no dependen
# de un archivo externo.
import gzip
import hashlib
import json
import os
import time
import urllib.request
from pathlib import Path
import gensim
from gensim.models import Word2Vec
URL = 'https://github.com/RaRe-Technologies/gensim-data/releases/download/text8/text8.gz'
MD5 = '68799af40b6bda07dfa47a32612e5364'
SIZE = 33182058
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
CACHE = Path(os.environ.get('ORYON_TEXT8_CACHE', str(Path.home() / '.cache' / 'oryon-text8')))
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'word2vec_text8_output'))
DIM = 30 if SHORT else 100
EPOCHS = 1 if SHORT else 5
MAX_WORDS = 20000 if SHORT else None
WINDOW, NEGATIVE, MIN_COUNT = 2, 5, 2
WORKERS = int(os.environ.get('ORYON_WORKERS', '1'))
if WORKERS < 1 or (SHORT and WORKERS != 1):
raise ValueError('ORYON_WORKERS debe ser positivo; SHORT exige un trabajador')
ANALOGY_REV = '20c129af10659f7c50e86e3be406df663beff438'
ANALOGY_URL = ('https://raw.githubusercontent.com/tmikolov/word2vec/' +
ANALOGY_REV + '/questions-words.txt')
def get_text8():
CACHE.mkdir(parents=True, exist_ok=True)
path = CACHE / 'text8.gz'
if not path.exists():
part = CACHE / 'text8.gz.part'
try:
with urllib.request.urlopen(URL, timeout=60) as response, part.open('wb') as out:
total = 0
while True:
block = response.read(1024 * 1024)
if not block:
break
total += len(block)
if total > SIZE:
raise ValueError('text8.gz excede el tamaño publicado')
out.write(block)
if part.stat().st_size != SIZE:
raise ValueError('Tamaño de text8.gz incorrecto')
md5 = hashlib.md5()
with part.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
md5.update(block)
if md5.hexdigest() != MD5:
raise ValueError('MD5 de text8.gz no coincide')
os.replace(part, path)
finally:
if part.exists():
part.unlink()
md5, sha = hashlib.md5(), hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
md5.update(block)
sha.update(block)
if path.stat().st_size != SIZE or md5.hexdigest() != MD5:
raise ValueError('La copia de text8 no coincide con el catálogo de Gensim')
return path, sha.hexdigest()
def get_analogies():
# Fuente versionada, no se ejecuta código remoto. El digest calculado
# identifica los bytes recibidos; sin un hash externo no los autentica.
with urllib.request.urlopen(ANALOGY_URL, timeout=60) as response:
raw = response.read(2_000_001)
if len(raw) > 2_000_000:
raise ValueError('Fichero de analogías demasiado grande')
sha = hashlib.sha256(raw).hexdigest()
expected = os.environ.get('ORYON_ANALOGIES_SHA256')
if expected is not None:
if not re.fullmatch(r'[0-9a-fA-F]{64}', expected):
raise ValueError('ORYON_ANALOGIES_SHA256 debe tener 64 dígitos hexadecimales')
if sha != expected.lower():
raise ValueError('SHA-256 de analogías diferente del esperado')
questions, section = [], None
for line in raw.decode('utf-8').splitlines():
if line.startswith(': '):
section = line[2:].strip()
elif line.strip():
fields = tuple(line.lower().split())
if section is None or len(fields) != 4:
raise ValueError('Formato inesperado del benchmark')
questions.append((section, fields))
if len(questions) != 19544:
raise ValueError('Número inesperado de preguntas')
if SHORT:
# Selección equiespaciada y determinista en todas las categorías.
chosen = [questions[i] for i in np.linspace(0, len(questions) - 1, 128, dtype=int)]
else:
chosen = questions
return chosen, {'url': ANALOGY_URL, 'revision': ANALOGY_REV, 'sha256_calculado': sha,
'hash_externo_comprobado': expected is not None,
'total_fuente': len(questions), 'seleccionadas': len(chosen),
'seleccion': '128 índices equiespaciados' if SHORT else 'todas',
'licencia_repositorio': 'Apache 2.0; comprobar condiciones para el archivo y su uso',
'split': 'benchmark externo de test exploratorio, sin usar para selección'}
def read_sentences(path, limit):
# Cortes artificiales de 2000 tokens, iguales para ambas implementaciones.
# No se trata de fronteras de documentos de Wikipedia.
sentences, sentence, carry, count = [], [], '', 0
def consume(word):
nonlocal count, sentence
if limit is not None and count >= limit:
return
if not word.isalpha() or not word.isascii() or word != word.lower():
raise ValueError('text8 tiene formato inesperado')
sentence.append(word)
count += 1
if len(sentence) == 2000:
sentences.append(sentence)
sentence = []
with gzip.open(path, 'rt', encoding='ascii') as stream:
while limit is None or count < limit:
chunk = stream.read(65536)
if not chunk:
if carry:
consume(carry)
break
parts = (carry + chunk).split()
if chunk[-1].isspace():
carry = ''
else:
carry = parts.pop() if parts else carry + chunk
for word in parts:
if limit is not None and count >= limit:
break
consume(word)
if sentence:
sentences.append(sentence)
if len(sentences) < 10:
raise ValueError('Faltan bloques para separar entrenamiento, validación y test')
return sentences
def split_sentences(sentences):
# Contiguos y sin cruzar bloques ni construir vocabulario con validación/test.
first = int(len(sentences) * .8)
second = int(len(sentences) * .9)
return sentences[:first], sentences[first:second], sentences[second:]
def context_metrics(sentences, index, E, chunk_size=4096):
# Pares originales adyacentes; no crear puentes al descartar OOV.
# La suma por bloques evita guardar millones de tuplas o puntuaciones.
norms = np.linalg.norm(E, axis=1)
left, right = [], []
candidates, covered, valid_count, total = 0, 0, 0, 0.
def flush():
nonlocal valid_count, total
if not left:
return
a, b = np.asarray(left), np.asarray(right)
valid = (norms[a] > 1e-12) & (norms[b] > 1e-12)
a, b = a[valid], b[valid]
if len(a):
scores = np.einsum('ij,ij->i', E[a], E[b]) / (norms[a] * norms[b])
total += float(np.sum(scores, dtype=np.float64))
valid_count += len(a)
left.clear()
right.clear()
for sentence in sentences:
for a, b in zip(sentence, sentence[1:]):
candidates += 1
if a in index and b in index:
covered += 1
left.append(index[a])
right.append(index[b])
if len(left) >= chunk_size:
flush()
flush()
return {'candidate_pairs': candidates, 'covered_pairs': covered,
'cosine_pairs': valid_count,
'mean_pair_cosine': total / valid_count if valid_count else None}
def analogies(words, E, questions):
index = {word: i for i, word in enumerate(words)}
norms = np.linalg.norm(E, axis=1)
valid_vectors = norms > 1e-12
unit = np.zeros_like(E)
unit[valid_vectors] = E[valid_vectors] / norms[valid_vectors, None]
groups = {}
pending = []
def flush():
if not pending:
return
targets = np.stack([item[1] for item in pending])
scores = targets @ unit.T
scores[:, ~valid_vectors] = -np.inf
for i, (group, _, rows, expected) in enumerate(pending):
scores[i, rows[:3]] = -np.inf
if not np.isfinite(scores[i]).any():
group['invalid'] += 1
continue
predicted = words[int(np.argmax(scores[i]))]
group['evaluated'] += 1
group['correct'] += int(predicted == expected)
pending.clear()
for section, question in questions:
a, b, c, expected = question
group = groups.setdefault(section, {'total': 0, 'oov': 0, 'invalid': 0,
'evaluated': 0, 'correct': 0})
group['total'] += 1
if any(word not in index for word in question):
group['oov'] += 1
continue
rows = [index[w] for w in question]
if any(not valid_vectors[i] for i in rows):
group['invalid'] += 1
continue
# Suma de vectores unitarios, como 3CosAdd de Gensim.
target = unit[rows[1]] - unit[rows[0]] + unit[rows[2]]
if np.linalg.norm(target) <= 1e-12:
group['invalid'] += 1
continue
pending.append((group, target, rows, expected))
# Acota la matriz temporal de puntuaciones a 32 × vocabulario.
if len(pending) >= 32:
flush()
flush()
totals = {key: sum(group[key] for group in groups.values())
for key in ('total', 'oov', 'invalid', 'evaluated', 'correct')}
for group in list(groups.values()) + [totals]:
group['accuracy'] = group['correct'] / group['evaluated'] if group['evaluated'] else None
return {'total': totals, 'categories': groups}
def report_vectors(words, E, validation, test, questions):
index = {w: i for i, w in enumerate(words)}
queries = ['king', 'queen', 'computer', 'language']
return {'table': 'entrada',
'neighbors': {w: neighbors(w, words, E) for w in queries},
'analogies': analogies(words, E, questions),
'validation': context_metrics(validation, index, E),
'test': context_metrics(test, index, E)}
def main_text8():
path, sha = get_text8()
questions, benchmark = get_analogies()
sentences = read_sentences(path, MAX_WORDS)
train, validation, test = split_sentences(sentences)
words, index, counts = vocabulary(train, minimum=MIN_COUNT)
protocol = {'short': SHORT, 'url': URL, 'compressed_md5': MD5,
'compressed_sha256_measured': sha, 'seed': SEED,
'split': 'bloques contiguos 80/10/10; cortes artificiales de 2000 palabras',
'tokens': {name: sum(map(len, part)) for name, part in
[('train', train), ('validation', validation), ('test', test)]},
'vocabulary': len(words), 'minimum_count': MIN_COUNT, 'dimension': DIM,
'epochs': EPOCHS, 'window': WINDOW, 'negative': NEGATIVE,
'subsampling': 'desactivado en ambos para alinear', 'noise_power': .75,
'license': 'El catálogo de gensim-data indica license: not found; verificar derechos.',
'workers': WORKERS, 'analogies': benchmark,
'reproducibility': 'workers=1 y PYTHONHASHSEED fijo favorecen reproducibilidad; '
'varios trabajadores introducen variación de orden.',
'limitations': 'Split por bloques no garantiza separación por documento ni ausencia de duplicados; '
'test se consulta para varios modelos y se considera exploratorio. '
'Analogías consultadas para varios modelos: test exploratorio. '
'Las duraciones de NumPy incluyen inicialización; las de Gensim excluyen '
'creación de vocabulario y modelo. Evaluación no incluida en ninguna.'}
results = {'protocol': protocol, 'gensim_version': gensim.__version__,
'numpy_version': np.__version__, 'models': {}}
print('Protocolo:', protocol)
print('Gradcheck NumPy:', gradcheck())
started = time.perf_counter()
E, U, history = fit_sgns(train, words, index, counts, EPOCHS, DIM, WINDOW,
NEGATIVE, .025, SEED, subsample=0., batch_size=128)
results['models']['numpy_sgns'] = {'training_seconds': time.perf_counter() - started,
'history': history, **report_vectors(words, E, validation, test, questions)}
del E, U
for sg in (1, 0):
for objective in ('negative', 'hs'):
model = Word2Vec(vector_size=DIM, window=WINDOW,
min_count=MIN_COUNT, sg=sg,
negative=NEGATIVE if objective == 'negative' else 0,
hs=int(objective == 'hs'), ns_exponent=.75,
sample=0., shrink_windows=True, workers=WORKERS,
seed=SEED, epochs=EPOCHS, alpha=.025, min_alpha=.0001)
model.build_vocab(train)
started = time.perf_counter()
model.train(train, total_examples=model.corpus_count, epochs=EPOCHS)
training_seconds = time.perf_counter() - started
name = ('skipgram' if sg else 'cbow') + '_' + objective
vector_words = list(model.wv.index_to_key)
assert set(vector_words) == set(words), 'Vocabularios de entrenamiento diferentes'
result = report_vectors(vector_words, model.wv.vectors, validation, test, questions)
result['training_seconds'] = training_seconds
results['models'][name] = result
del model
OUTPUT.mkdir(parents=True, exist_ok=True)
(OUTPUT / 'metrics.json').write_text(json.dumps(results, ensure_ascii=False, indent=2),
encoding='utf-8')
print('Modelos:', results['models'])
print('Salida:', OUTPUT / 'metrics.json')
print('Los cosenos y el benchmark son exploratorios; SHORT solo verifica el recorrido.')
print('El propio usa SGD por lotes, tasa constante y negativos condicionados; '
'Gensim usa otra optimización, tasa decreciente y su implementación de colisiones.')
if __name__ == '__main__':
main_text8()npm run lab and open the connection link.Exercises
Step 1 of 3. What is the derivative of softplus(-s) with respect to s?
import numpy as np
def build_noise_table(counts, power=0.75):
pass
def sample_negatives(q, positive, k, rng):
passFurther connections
Classification-based estimation relates to Noise-contrastive estimation and prefix codes to Huffman coding. The next lesson studies conditions connecting SGNS to a shifted PMI matrix and how those conditions change with the noise distribution.