GloVe and implicit factorization: why word embeddings work
Study GloVe, co-occurrence ratios and the assumptions connecting SGNS to shifted PMI.
After this lesson you can
- Explain and differentiate the weighted GloVe objective.
- Derive the expected SGNS optimum and its shifted-PMI special case.
- Analyze collision policies, finite-rank constraints and comparisons with SVD.
- Evaluate pretrained and learned embeddings under documented protocols.
Before you start
Counting and predicting are not separate worlds
A co-occurrence matrix summarizes how often each context appears alongside each word. Skip-gram traverses examples and learns to distinguish observed pairs from noise. The recipes look different but depend on the same events if built with the same window and filtering.
The relationship does not make the algorithms interchangeable. Objective, dimension, weights and training procedure determine the approximation ultimately obtained. In this lesson we build a regression on counts and see under which assumptions SGNS products have an objective expressible through PMI.
Ice, steam and a probe
Let be co-occurrence mass of context with center word and . Ratio depends on both the relationship and probe frequency. If too, one way to compare words is when the denominator is positive.
In Table 1 of Pennington, Socher and Manning, on a corpus of 6 billion tokens, the published ratio for probe “solid” is 8.9 comparing “ice” with “steam.” For “gas” it is 0.085; “water,” 1.36; and “fashion,” 0.96. The first two distinguish the pair in opposite directions; the others are closer to one. This describes associations observed in that corpus, not a universal semantic law.
Table probabilities and ratios are rounded separately. For example, dividing printed values and gives approximately 8.64, not exactly 8.9. In your own calculation use available counts or probabilities and declare rounding. If the denominator is zero, the ratio is undefined over the reals whether the numerator is positive or zero.
From ratios to GloVe
For probes with and , the ratio argument seeks a word-vector difference that, when related to a context vector, encodes the log ratio:
The paper proposes constraints on that relationship’s form and on exchanging words and contexts. With an exponential choice compatible with them, it reaches a log-bilinear equation. Since , terms depending on one word can be represented by biases. The resulting fit proposes
This motivates a model family with structural choices and a limited-dimensional approximation. It does not prove every log matrix has an exact factorization in the chosen dimension or that learned differences must be interpretable.
The GloVe objective visits only pairs with :
Also define , but code must not evaluate and multiply by zero afterward: that yields an undefined expression. Work directly with positive entries. The authors chose and in their experiments; these are empirical choices. The function downweights rare pairs and caps frequent-pair weight. Its exponent is not the same parameter as the SGNS noise-distribution exponent, even though both may equal 0.75.
A count histogram says how many entries are in each range; summing weights says how much weight they receive. Loss contribution also depends on squared residual, which changes during training. Therefore the loss fraction per range cannot be inferred from the histogram alone.
Gradients and AdaGrad
For a positive entry, write , and . That entry’s gradient contributions are
In a sum or minibatch, accumulate every occurrence of the same index before updating. Each derivative above uses parameters from the same state; updating one vector and using the changed result to calculate the other produces a different rule. A finite-difference check should include repeated indices.
AdaGrad accumulates squared gradients coordinate by coordinate. One convention is and . The placement of , initial and whether is a per-pair gradient or batch sum affect the trajectory. An implementation using other conventions can be valid but must declare them.
For neighbor queries, the authors used the sum in their experiments. You can also inspect each table separately if stated: neighbors and cosines may change. The sum has no unique interpretation guaranteed by the objective either, because different transformations of both tables can preserve input-context products.
The matrix hidden in SGNS
In Negative sampling you observed pairs and generated noise contexts. Now fix a set of effective pairs after chosen filtering or windowing. Let be counts, , and .
First suppose each negative is drawn independently from , even if it matches the positive context. In expected loss, a specific cell and logit have two coefficients:
If and , then . The derivative vanishes at and the second derivative is strictly negative. Thus the unique scalar maximum is
If additionally , that expression becomes shifted PMI:
The derivation by Levy and Goldberg treats cell products as free variables. Sufficiently large dimension can represent a finite score matrix, but low dimension couples cells. Moreover, this is the optimum of an exact expectation, not a promise that SGD with finite samples and a given budget reaches it.
Boundary cases change the answer: if and , the supremum is reached only as tends to ; if and , as it tends to ; if both are zero, that term does not constrain . Neither of the first two has a finite maximum. Nor can an undefined cell be replaced by zero and equality claimed verified.
What about the previous lab?
The previous lesson’s lab excludes the positive context and replaces collisions until negatives are obtained. For each positive it uses for , if . Therefore candidate ‘s negative coefficient is
The free maximum becomes when both terms are positive. In general it does not equal PMI minus . If is also proportional to count raised to 0.75, it is not the unsmoothed empirical marginal either. A faithful check must compare against this formula or implement and label another variant allowing collisions and using the same effective pairs’ marginal.
Factorizing with finite-dimensional vectors couples products of different cells. The next figure trains on the lab’s same synthetic matrix with exact expectation over negatives. Adjust dimension and steps and compare matrices and their scatter: capacity can be sufficient without finitely many steps guaranteeing the optimum.
Shifted PPMI clips negative values using and is often represented sparsely. That clipping changes values, including unobserved pairs. SVD minimizes unweighted squared error over the chosen matrix; SGNS optimizes logistic loss with different weights. Their low-rank factors and neighbors can differ even from the same counts.
What was actually compared
Transferring hyperparameters means fixing what is comparable: corpus, splits, vocabulary, window, discarding, context distribution, dimension, seed and evaluation. Also state how SVD factors become vectors: , and can yield different cosines.
In Levy, Goldberg and Dagan, 2015, Table 2, the “vanilla” scenario gives 0.422 for SVD and 0.401 for SGNS on SimLex. Table 3’s configuration described as word2vec gives 0.402 and 0.423. Several decisions change simultaneously, so the difference cannot be attributed to one. Table 4 selects configurations on test as an “oracle” experiment; it must not be confused with independent evaluation.
GloVe results also depend on corpus and size. In original Table 2, 300-dimensional GloVe trained on 6 billion (6000 million) tokens obtains 71.7% total on analogies; the 42 billion (42 000 million) row obtains 75.0%. The latter is the 75% cited in the paper’s abstract. Neither figure comes from our labs.
A generative discourse model
RAND-WALK, by Arora and colleagues, models a slowly changing latent discourse vector . For each state, word-emission probability has form
Nearby words are generated under similar discourses. Under the paper’s assumptions about vector spread, partition concentration and small shifts, Theorem 2.2 obtains for its size-two window an approximate relation , with an error term. The approximation depends on those assumptions: it is not an identity for every corpus or a claim that every trained embedding is isotropic.
If two relationships induce similar association differences across many probes, vector differences can be close under the model’s additional conditions. This explains why a linear analogy can work; it does not prove every semantic relation is an exact translation or a correct answer implies understanding.
Labs
GloVe with AdaGrad
We build co-occurrences weighted by inverse distance and optimize only positive entries. The lab should display losses, gradcheck and neighbors generated from a clearly sourced corpus. Dimension and Pyodide sample size are chosen after measuring actual time; the reader can train a larger version locally.
The cell uses the same short excerpts from different chapters of Don Quixote from Project Gutenberg as the previous lesson. The first supplies training co-occurrences; the second only reports coverage. Checking excerpts are not identical does not detect partial overlap. SGNS reuses the previous cell’s implementation with subsampling disabled; GloVe uses a fixed window and inverse-distance weight, while SGNS uses dynamic radius and another objective. The sample checks the pipeline and does not allow semantic-quality comparisons.
"""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.')
# Código SGNS procedente de la celda vigente m17-l06; en esta práctica el
# submuestreo se desactiva y se imprime la diferencia entre ventanas.
GLOVE_SEED = 17070
def cooccurrences(sentences, index, radius):
counts = Counter()
for sentence in sentences:
# Excluir pares con OOV sin unir los extremos a través del hueco.
for i, word in enumerate(sentence):
if word not in index:
continue
for j in range(max(0, i - radius), min(len(sentence), i + radius + 1)):
if j != i and sentence[j] in index:
counts[(index[word], index[sentence[j]])] += 1. / abs(i - j)
items = sorted(counts.items())
if not items:
raise ValueError('No hay coocurrencias con el vocabulario de entrenamiento')
rows = np.array([pair[0][0] for pair in items], dtype=np.int64)
cols = np.array([pair[0][1] for pair in items], dtype=np.int64)
values = np.array([pair[1] for pair in items], dtype=float)
return rows, cols, values
def glove_loss_grad(W, C, b, d, rows, cols, values, xmax=100., power=.75):
if np.any(~np.isfinite(values)) or np.any(values <= 0):
raise ValueError('Solo se admiten coocurrencias positivas finitas')
residual = np.sum(W[rows] * C[cols], axis=1) + b[rows] + d[cols] - np.log(values)
weight = np.minimum((values / xmax) ** power, 1.)
scale = 2. * weight * residual
dW, dC, db, dd = np.zeros_like(W), np.zeros_like(C), np.zeros_like(b), np.zeros_like(d)
np.add.at(dW, rows, scale[:, None] * C[cols])
np.add.at(dC, cols, scale[:, None] * W[rows])
np.add.at(db, rows, scale)
np.add.at(dd, cols, scale)
return float(np.sum(weight * residual ** 2)), dW, dC, db, dd
def glove_gradcheck():
rng = np.random.default_rng(GLOVE_SEED)
arrays = [rng.normal(0., .2, (3, 2)), rng.normal(0., .2, (3, 2)),
rng.normal(0., .2, 3), rng.normal(0., .2, 3)]
rows, cols = np.array([0, 0, 2]), np.array([1, 1, 0])
values = np.array([.5, 2., 100.])
_, *analytic = glove_loss_grad(*arrays, rows, cols, values)
errors = []
for table, grad in zip(arrays, analytic):
error = 0.
for idx in np.ndindex(table.shape):
value = table[idx]
table[idx] = value + 1e-6
plus = glove_loss_grad(*arrays, rows, cols, values)[0]
table[idx] = value - 1e-6
minus = glove_loss_grad(*arrays, rows, cols, values)[0]
table[idx] = value
error = max(error, abs((plus - minus) / 2e-6 - grad[idx]))
assert error < 1e-6, error
errors.append(error)
return errors
def train_glove(rows, cols, values, vocab_size, dim, epochs, rate, seed):
rng = np.random.default_rng(seed)
W = rng.normal(0., .1, (vocab_size, dim))
C = rng.normal(0., .1, (vocab_size, dim))
b = np.zeros(vocab_size)
d = np.zeros(vocab_size)
params = [W, C, b, d]
accumulators = [np.zeros_like(param) for param in params]
history = []
for epoch in range(epochs + 1):
loss, *grads = glove_loss_grad(*params, rows, cols, values)
if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grads):
raise ValueError('GloVe produjo pérdida o gradiente no finitos')
history.append({'epoch': epoch, 'loss_sum': loss})
if epoch < epochs:
for param, acc, grad in zip(params, accumulators, grads):
acc += grad * grad
param -= rate * grad / (np.sqrt(acc) + 1e-8)
return params, history
def loss_by_frequency(params, rows, cols, values):
W, C, b, d = params
residual = np.sum(W[rows] * C[cols], axis=1) + b[rows] + d[cols] - np.log(values)
weight = np.minimum((values / 100.) ** .75, 1.)
contribution = weight * residual ** 2
bins = [values < 1, (values >= 1) & (values < 10),
(values >= 10) & (values < 100), values >= 100]
result = []
for label, mask in zip(['x<1', '1≤x<10', '10≤x<100', 'x≥100'], bins):
result.append({'bin': label, 'pairs': int(mask.sum()),
'weight_sum': float(weight[mask].sum()),
'weighted_loss': float(contribution[mask].sum())})
return result
def main_glove():
train, valid = tokenize(TRAIN), tokenize(VALID)
if train == valid:
raise ValueError('Fragmentos idénticos')
words, index, counts = vocabulary([train])
rows, cols, values = cooccurrences([train], index, radius=2)
params, history = train_glove(rows, cols, values, len(words), dim=100,
epochs=15, rate=.04, seed=GLOVE_SEED)
# Misma entrada del corpus, radio máximo y semilla declarada, pero SGNS usa
# ventana dinámica, pares sin peso inverso y objetivo diferente.
E, _, sgns_history = fit_sgns([train], words, index, counts, epochs=15,
dim=100, window=2, k=2, rate=.04,
seed=GLOVE_SEED, subsample=0., batch_size=32)
valid_known = sum(word in index for word in valid)
print('Gradcheck GloVe, errores absolutos:', glove_gradcheck())
print('Corpus Gutenberg, tokens train/valid:', len(train), len(valid),
'| OOV valid:', len(valid) - valid_known, '| pares positivos:', len(values))
print('GloVe: pérdida por época', history)
print('SGNS: pérdida por época', sgns_history)
print('GloVe: tramos de frecuencia y pérdida real:', loss_by_frequency(params, rows, cols, values))
print('Vecinos de GloVe W+C:', neighbors(words[0], words, params[0] + params[1]))
print('Vecinos SGNS de entrada:', neighbors(words[0], words, E))
print('GloVe usa ventana fija y peso 1/distancia; SGNS, radio uniforme dinámico '
'y ruido condicionado. Las pérdidas y vecinos no demuestran superioridad.')
print('AdaGrad completo por lote, acumulador 0, epsilon fuera de la raíz; '
'entrenamiento corto en muestra mínima. Validación solo informa cobertura.')
if __name__ == '__main__':
main_glove()The expected optimum and rank constraints
A small fully specified matrix allows calculating the expected optimum and measuring its difference from learned products. To check the classical formula, noise must permit collisions and match the pair marginal; a conditioned variant requires the previous section’s formula. Seeds and observed results are reported without assuming higher dimension wins in a short run. An empirical comparison of methods also needs real data.
The first control uses an explicit synthetic matrix with all cells positive, two seeds, two dimensions and exact noise expectation. It compares the independent variant permitting collisions with the previous lesson’s exclusion and replacement. The second uses real excerpts, smoothed noise and SPPMI SVD; neighbors are exploratory without a semantic test. Correlation or dimensional improvement is not guaranteed. Comparing semantic quality requires a larger corpus and evaluation.
"""SGNS esperado y PPMI-SVD en un control explícito y una muestra real.
La primera matriz es un modelo sintético declarado, no datos de lenguaje.
La segunda procede de los fragmentos de Don Quijote de m17-l06, primera
parte, capítulos I y II, Project Gutenberg 2000:
https://www.gutenberg.org/files/2000/2000-0.txt . La ficha declara dominio
público en EE. UU.; consulta https://www.gutenberg.org/policy/license.html .
No se usan muestras negativas aleatorias: se suma su esperanza exacta.
"""
import math
import re
import unicodedata
import numpy as np
SEED = 17071
K = 2
SYNTHETIC = np.array([[12., 4., 3., 1.], [3., 11., 2., 4.],
[1., 2., 10., 7.], [5., 1., 4., 10.]])
REAL_DOCUMENTS = ['En un lugar de la Mancha, de cuyo nombre no quiero acordarme',
'Hechas, pues, estas prevenciones, no quiso aguardar más tiempo']
def pair_counts(documents, radius=2):
sentences = [re.findall(r'\w+', unicodedata.normalize('NFC', text).lower()) for text in documents]
words = sorted({token for sentence in sentences for token in sentence})
index = {word: i for i, word in enumerate(words)}
counts = np.zeros((len(words), len(words)), dtype=float)
for sentence in sentences:
for i, word in enumerate(sentence):
for j in range(max(0, i - radius), min(len(sentence), i + radius + 1)):
if j != i:
counts[index[word], index[sentence[j]]] += 1.
return words, counts
def expected_coefficients(A, k, power, exclude):
if A.ndim != 2 or np.any(A < 0) or not np.isfinite(A).all() or not np.isfinite(A.sum()) or A.sum() <= 0:
raise ValueError('La matriz debe tener recuentos finitos no negativos')
if not isinstance(k, (int, np.integer)) or k < 1 or not math.isfinite(power) or power <= 0:
raise ValueError('k debe ser entero positivo y power finito positivo')
marginal = A.sum(axis=0)
q = marginal ** power
q /= q.sum()
if exclude and np.any(q >= 1.):
raise ValueError('No hay soporte de ruido distinto del positivo')
if exclude:
scaled = A / (1. - q)[None, :]
# Suma explícita por candidatos distintos de j: evita cancelar dos
# cantidades grandes cuando las demás contribuciones son pequeñas.
B = np.empty_like(A, dtype=float)
for j in range(A.shape[1]):
B[:, j] = k * q[j] * np.sum(scaled[:, np.arange(A.shape[1]) != j], axis=1)
else:
B = k * A.sum(axis=1, keepdims=True) * q[None, :]
return q, B
def targets(A, B):
# None al imprimir indica que no hay óptimo escalar finito para la celda.
mask = (A > 0) & (B > 0)
target = np.zeros_like(A)
target[mask] = np.log(A[mask] / B[mask])
return target, mask
def sigmoid(x):
result = np.empty_like(x)
positive = x >= 0
result[positive] = 1. / (1. + np.exp(-x[positive]))
exp_x = np.exp(x[~positive])
result[~positive] = exp_x / (1. + exp_x)
return result
def loss_derivative(scores, A, B):
normalizer = A.sum()
loss = np.sum(A * np.logaddexp(0., -scores) + B * np.logaddexp(0., scores)) / normalizer
grad = (-A * sigmoid(-scores) + B * sigmoid(scores)) / normalizer
return float(loss), grad
def check_gradient(A, B):
scores = np.arange(A.size, dtype=float).reshape(A.shape) / 10 - .5
_, grad = loss_derivative(scores, A, B)
max_error = 0.
for idx in np.ndindex(A.shape):
old = scores[idx]
scores[idx] = old + 1e-6
plus = loss_derivative(scores, A, B)[0]
scores[idx] = old - 1e-6
minus = loss_derivative(scores, A, B)[0]
scores[idx] = old
max_error = max(max_error, abs((plus - minus) / 2e-6 - grad[idx]))
assert max_error < 1e-7, max_error
return max_error
def fit(A, B, dim, seed, steps=160, rate=.8):
rng = np.random.default_rng(seed)
W = rng.normal(0., .12, (A.shape[0], dim))
C = rng.normal(0., .12, (A.shape[1], dim))
for _ in range(steps):
scores = W @ C.T
loss, grad = loss_derivative(scores, A, B)
grad_W, grad_C = grad @ C, grad.T @ W
if not math.isfinite(loss) or not np.isfinite(grad_W).all() or not np.isfinite(grad_C).all():
raise ValueError('Entrenamiento no finito')
W -= rate * grad_W
C -= rate * grad_C
scores = W @ C.T
loss, grad = loss_derivative(scores, A, B)
target, mask = targets(A, B)
delta = scores[mask] - target[mask]
rmse = float(np.sqrt(np.mean(delta ** 2))) if len(delta) else None
corr = None
if len(delta) > 1 and np.std(scores[mask]) > 1e-12 and np.std(target[mask]) > 1e-12:
corr = float(np.corrcoef(scores[mask], target[mask])[0, 1])
return {'dimension': dim, 'seed': seed, 'steps': steps, 'loss': loss,
'gradient_norm_scores': float(np.linalg.norm(grad)),
'finite_target_cells': int(mask.sum()), 'rmse_finite_cells': rmse,
'correlation_finite_cells': corr}, W, scores
def shifted_ppmi(A, q, k):
total = A.sum()
p_word = A.sum(axis=1) / total
ratio = np.zeros_like(A)
valid = (A > 0) & (p_word[:, None] > 0) & (q[None, :] > 0)
ratio[valid] = (A / total)[valid] / (k * p_word[:, None] * q[None, :])[valid]
result = np.zeros_like(A)
result[valid] = np.maximum(np.log(ratio[valid]), 0.)
return result
def neighbors(words, matrix, word, count=4):
idx = words.index(word)
norms = np.linalg.norm(matrix, axis=1)
if norms[idx] <= 1e-12:
return []
score = np.full(len(words), -np.inf)
valid = norms > 1e-12
score[valid] = (matrix[valid] @ matrix[idx]) / (norms[valid] * norms[idx])
score[idx] = -np.inf
return [(words[i], float(score[i])) for i in np.argsort(-score)[:count] if np.isfinite(score[i])]
def main():
# Comprueba soporte: filas con una sola clase observada no generan ruido
# de esa misma clase si se excluye el positivo y se repone.
toy = np.array([[2., 0., 0.], [0., 3., 0.]])
q_toy, B_toy = expected_coefficients(toy, 2, power=1., exclude=True)
assert np.allclose(q_toy, [2/5, 3/5, 0.])
assert np.allclose(B_toy, [[0., 4., 0.], [6., 0., 0.]])
_, mask_toy = targets(toy, B_toy)
assert not mask_toy.any() # Todos los óptimos son límites o libres.
for name, A in [('sintético completo', SYNTHETIC)]:
for excluded in (False, True):
q, B = expected_coefficients(A, K, power=1., exclude=excluded)
target, mask = targets(A, B)
if not excluded:
# q es la marginal empírica de los mismos pares y no hay ceros.
shifted = np.log(A * A.sum() / (A.sum(axis=1)[:, None] * A.sum(axis=0)[None, :])) - np.log(K)
assert np.allclose(target, shifted)
assert np.max(np.abs(loss_derivative(target, A, B)[1])) < 1e-12
print(name, '| exclusión del positivo:', excluded, '| q:', q.tolist())
print('Coeficiente negativo B:', B.tolist())
print('Gradcheck de scores:', check_gradient(A, B))
print('Objetivos finitos:', [[float(target[i, j]) if mask[i, j] else None
for j in range(A.shape[1])] for i in range(A.shape[0])])
for dim in (2, A.shape[0]):
for seed in (SEED, SEED + 1):
result, _, scores = fit(A, B, dim, seed)
print('Resultado SGNS esperado:', result, '| scores:', scores.tolist())
words, A = pair_counts(REAL_DOCUMENTS)
q, B = expected_coefficients(A, K, power=.75, exclude=False)
M = shifted_ppmi(A, q, K)
U, singular, _ = np.linalg.svd(M, full_matrices=False)
rank = min(4, len(singular))
# UΣ: variante explícita de SVD, no una equivalencia con SGNS.
svd_vectors = U[:, :rank] * singular[:rank]
metrics, W, _ = fit(A, B, dim=rank, seed=SEED)
query = 'no'
print('Corpus real Gutenberg: tokens únicos:', len(words), '| eventos:', int(A.sum()),
'| celdas positivas:', int(np.count_nonzero(A)), '| rango SVD:', rank)
print('Comparación exploratoria, objetivo SGNS esperado:', metrics)
print('Vecinos de entrada SGNS para', query, ':', neighbors(words, W, query))
print('Vecinos UΣ para', query, ':', neighbors(words, svd_vectors, query))
print('El control sintético admite colisiones o las excluye según se indica; '
'el corpus real usa ruido suavizado y admite colisiones.')
print('No hay garantía de convergencia, ni de superioridad o similitud semántica en estos fragmentos.')
if __name__ == '__main__':
main()Pretrained vectors
The Stanford page distributes pretrained vectors and declares PDDL 1.0 for those data. Its Wikipedia 2014 and Gigaword 5 archive contains vectors of several dimensions and is presented as an 822 MB download. Verify provenance, integrity and available space before use. Comparison with custom vectors must use the same questions and publish coverage; corpora and training budgets still differ.
This local cell requires NumPy, SciPy, Gensim and huggingface_hub. It reproduces functions from the previous lesson’s current cell to train SGNS on text8, and reads official 50-dimensional GloVe vectors without extracting every ZIP member. It verifies the SHA-256 of Stanford’s archive on Hugging Face. The ZIP is about 862 MB according to its metadata and downloads into the shared cache even in short mode if absent. Stanford states PDDL 1.0 for vectors; the text8 catalog does not confirm a license and requires separate review of its terms.
ORYON_VERIFY_SHORT=1 uses 20,000 tokens, one epoch, 128 evenly spaced analogies and only the first 10,000 GloVe vectors. Coverage changes when vocabulary is limited, so SHORT only checks the pipeline. In the short run GloVe covered 43 of those 128 questions and SGNS trained on the subset covered none; this is not a conclusive comparison. Normal mode uses the full battery and loaded vocabulary. Coverage is reported and test is exploratory when inspecting both models. Similarity uses only four published SimLex examples, not the full benchmark. The models were trained with different data and budgets; pretraining overlap with evaluation has not been ruled out.
"""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.')
# Esta celda copia el laboratorio vigente m17-l06 y añade la lectura GloVe.
# No depende del archivo de informes ni de que otra celda conserve variables.
import zipfile
from scipy.stats import spearmanr
from huggingface_hub import hf_hub_download
GLOVE_REV = '1db2080b2d94def6e5b0386a523102f9d8849e9d'
GLOVE_SHA = '6471382cdd837544bf3ac72497a38715e845897d265b2b424b4761832009c837'
GLOVE_MEMBER = 'glove.6B.50d.txt'
# Cuatro ejemplos de la tabla 2 de SimLex-999, no todo el conjunto.
# Hill, Reichart y Korhonen: https://aclanthology.org/J15-4004.pdf
SIMLEX_EXAMPLES = [('dirty', 'narrow', .30), ('student', 'pupil', 9.40),
('smart', 'dumb', .60), ('attention', 'awareness', 8.73)]
def official_glove():
# Se descarga a la caché común de Hugging Face, sin copiar el ZIP.
# Fuente: https://huggingface.co/stanfordnlp/glove/blob/main/glove.6B.zip
path = Path(hf_hub_download(repo_id='stanfordnlp/glove', filename='glove.6B.zip',
revision=GLOVE_REV))
digest = hashlib.sha256()
with path.open('rb') as stream:
for block in iter(lambda: stream.read(1024 * 1024), b''):
digest.update(block)
if digest.hexdigest() != GLOVE_SHA:
raise ValueError('SHA-256 de GloVe no coincide con el publicado')
return path
def load_glove(path, max_words):
words, vectors = [], []
seen = set()
with zipfile.ZipFile(path) as archive:
info = archive.getinfo(GLOVE_MEMBER)
if info.file_size > 2_000_000_000:
raise ValueError('Miembro GloVe de tamaño inesperado')
with archive.open(info) as stream:
for raw in stream:
parts = raw.decode('utf-8').split()
if len(parts) != 51 or parts[0] in seen:
raise ValueError('Fila duplicada o dimensión inesperada')
vector = np.asarray(parts[1:], dtype=np.float32)
if not np.isfinite(vector).all():
raise ValueError('Vector no finito')
words.append(parts[0])
vectors.append(vector)
seen.add(parts[0])
if max_words is not None and len(words) >= max_words:
break
if not words:
raise ValueError('No se han leído vectores')
return words, np.stack(vectors)
def similarity_examples(words, vectors):
index = {word: i for i, word in enumerate(words)}
norms = np.linalg.norm(vectors, axis=1)
details, predicted, gold = [], [], []
for a, b, rating in SIMLEX_EXAMPLES:
if a not in index or b not in index:
details.append({'pair': [a, b], 'status': 'oov'})
continue
i, j = index[a], index[b]
if norms[i] <= 1e-12 or norms[j] <= 1e-12:
details.append({'pair': [a, b], 'status': 'zero_norm'})
continue
cosine = float(np.dot(vectors[i], vectors[j]) / (norms[i] * norms[j]))
details.append({'pair': [a, b], 'status': 'covered', 'cosine': cosine, 'human': rating})
predicted.append(cosine)
gold.append(rating)
rho = None
if len(gold) >= 2 and np.std(gold) > 0 and np.std(predicted) > 0:
rho = float(spearmanr(predicted, gold).statistic)
return {'source': 'Cuatro ejemplos de tabla 2 SimLex-999; no es el benchmark completo',
'total': len(SIMLEX_EXAMPLES), 'covered': len(gold), 'spearman': rho, 'details': details}
def evaluate_same(words, vectors, questions, valid, test):
output = report_vectors(words, vectors, valid, test, questions)
output['simlex_examples'] = similarity_examples(words, vectors)
return output
def main_pretrained():
text8, text_sha = get_text8()
questions, benchmark = get_analogies()
parts = read_sentences(text8, MAX_WORDS)
train, valid, test = split_sentences(parts)
words, index, counts = vocabulary(train, minimum=MIN_COUNT)
start = time.perf_counter()
E, U, history = fit_sgns(train, words, index, counts, EPOCHS, dim=50, window=WINDOW,
k=NEGATIVE, rate=.025, seed=SEED, subsample=0., batch_size=128)
elapsed = time.perf_counter() - start
own = evaluate_same(words, E, questions, valid, test)
own['training_seconds'], own['history'] = elapsed, history
del E, U
archive = official_glove()
# SHORT demuestra el recorrido con un prefijo del vocabulario: cobertura
# diferente y resultados no comparables al banco completo.
pretrained_words, pretrained = load_glove(archive, max_words=10000 if SHORT else None)
glove = evaluate_same(pretrained_words, pretrained, questions, valid, test)
result = {'protocol': {'short': SHORT, 'seed': SEED,
'text8_sha256_measured': text_sha, 'analogies': benchmark,
'glove_repo': 'stanfordnlp/glove', 'glove_revision': GLOVE_REV,
'glove_sha256_verified': GLOVE_SHA, 'member': GLOVE_MEMBER,
'glove_vectors_loaded': len(pretrained_words),
'limitations': 'GloVe y SGNS usaron corpus y presupuestos distintos; '
'el test se inspecciona para varios modelos. '
'Las cuatro parejas SimLex no representan el conjunto completo. '
'SHORT limita el vocabulario GloVe y no es concluyente; '
'se desconoce posible solapamiento de preentrenamiento y test.'},
'models': {'sgns_text8': own, 'glove_pretrained': glove}}
OUTPUT.mkdir(parents=True, exist_ok=True)
(OUTPUT / 'glove_comparison.json').write_text(json.dumps(result, ensure_ascii=False, indent=2),
encoding='utf-8')
print('Resultados y cobertura:', result)
print('Guardado:', OUTPUT / 'glove_comparison.json')
if __name__ == '__main__':
main_pretrained()npm run lab and open the connection link.Exercises
Step 1 of 3. What is the derivative of a log σ(s)+b log σ(−s)?
import numpy as np
def glove_loss_and_grads(W, Wt, b, bt, rows, cols, X):
passFurther connections
Objective differences connect with Low-rank approximation and updates with AdaGrad. The next lesson studies embedding evaluation, what analogies hide and what happens to out-of-vocabulary words.