Module contents
Lesson 8 of 24Core 85 min

Using and evaluating word embeddings: analogies, subwords, bias and limits

Evaluate embeddings through analogies, task performance, subword composition, association tests and polysemy.

After this lesson you can

  • Compare 3CosAdd and 3CosMul under explicit candidate conventions.
  • Distinguish intrinsic from extrinsic evaluation and report coverage.
  • Explain subword composition and out-of-vocabulary limitations.
  • Analyze projections, association tests and static polysemy carefully.

Before you start

A representation useful for what?

Two representations can produce similar neighbors yet behave differently on a task. If you want to classify reviews, solving analogies is insufficient to show the system understands polarity. If you want to find similar terms, high classification accuracy does not prove neighbors are reliable either. Evaluation needs a question, data and a decision about what counts as success.

Previous lessons obtained vectors through counts and prediction. Now we examine them from several angles: word relationships, out-of-vocabulary composition, social associations and different uses of one word. No isolated test defines a representation’s entire quality.

In query a:b::c:?a:b::c:?, seek candidate xx completing a relationship, for example “Paris is to France as Berlin is to Germany.” 3CosAdd uses normalized vectors aˉ,bˉ,cˉ,xˉ\bar a,\bar b,\bar c,\bar x and offset

r=bˉ−aˉ+cˉ,arg⁡max⁡x  cos⁡(xˉ,r).r=\bar b-\bar a+\bar c,\qquad \underset{x}{\arg\max}\;\cos(\bar x,r).

If all four vectors are nonzero and r≠0r\ne0, ranking is the same as maximizing cos⁡(x,b)−cos⁡(x,a)+cos⁡(x,c)\cos(x,b)-\cos(x,a)+\cos(x,c): the common positive factor 1/∥r∥1/\|r\| is omitted. Scores are generally not numerically equal. If r=0r=0, cosine with rr is undefined. Normalizing each term before combining matters: summing original vectors can produce a different search.

Levy and Goldberg observed that very large similarity can dominate the sum. Their 3CosMul alternative converts each cosine to h(x,y)=(1+cos⁡(x,y))/2h(x,y)=(1+\cos(x,y))/2 and scores

h(x,b) h(x,c)h(x,a)+ε,ε=0,001.\frac{h(x,b)\,h(x,c)}{h(x,a)+\varepsilon},\qquad \varepsilon=0{,}001.

This is a specific convention: shifting to [0,1][0,1] and the small ε\varepsilon placement affect the result. Multiplying negative cosines without explaining the changed objective is insufficient. In the paper’s Table 3, their embeddings obtained 53.98% with 3CosAdd and 59.09% with 3CosMul on MSR; on GOOGLE, 62.70% and 66.72%. These figures belong to their protocol and do not guarantee the product wins on every set.

An implementation must decide whether aa, bb or cc can be returned. Nissim, van Noord and van der Goot showed this changes results: in their GoogleNews evaluation, 3CosAdd micro accuracy on Google Analogy changed from 0.74 with the restriction to 0.21 without it. They note the second term is often returned, though sometimes the third appears. Exclusion may suit a test’s distinct-relation criterion; hiding it makes results harder to interpret.

InteractiveChange criterion and candidates

The vectors and their Spanish names form a toy geometry, with no corpus or training. The plane shows their actual coordinates, not a PCA projection; the dashed line represents r = b − a + c after normalizing the inputs.

estenortesuroestediagonalsubebajaceror

r = (−1.00, 0.00). The highest eligible score belongs to oeste.

Candidates, coordinates, and score 3CosAdd
CandidateVectorResult
este(1.00, 0.00)Excluded
norte(0.00, 1.00)Excluded
sur(0.00, −1.00)Excluded
oeste · first(−1.00, 0.00)1.0000
diagonal(0.80, 0.60)−0.8000
sube(0.50, 0.87)−0.5000
baja(0.50, −0.87)−0.5000
cero(0.00, 0.00)Zero norm

3CosAdd computes cos(x, r). 3CosMul computes h(x,b)·h(x,c)/(h(x,a)+0.001), with h=(1+cos)/2. All inputs and candidates are normalized; norms up to 10⁻¹² count as zero. Displayed coordinates and scores are rounded. For ranking, scores are rounded to twelve decimal places and ties are resolved alphabetically by the original Spanish names. 3CosMul does not require r to be nonzero. The ratio may exceed one and is not a probability.

Scoring
Queryeste : norte :: sur : ?
Best candidateoeste
Score1.0000
Explore explicit geometry and compare additive and multiplicative analogies without attributing vectors to a trained model.

Intrinsic and extrinsic

Intrinsic evaluation examines representation properties: similarity against human judgments, neighbors or analogies. Spearman correlation compares ranks, not numerical distances; ties need a convention such as average ranks. If all values are equal or too few pairs remain, correlation is undefined. Missing words and zero-norm vectors must be counted, not silently removed from the denominator. Comparing on the common subset also helps distinguish quality differences from coverage differences.

Extrinsic evaluation measures a system on a task, such as sentiment classification. One test may average review-token embeddings and train a classifier with frozen vectors. Another may also tune embeddings using labels. To attribute observations, keep splits, tokenization, head architecture and budget as comparable as possible; state which parameters receive gradients. The result jointly reflects representation, head, data and optimization. Intrinsic improvement and extrinsic deterioration are possible because their metrics and signals differ.

The review dataset of Maas and colleagues contains 25,000 labeled training examples and 25,000 test examples, plus unlabeled reviews. Separate validation from training before choosing hyperparameters and retain test for final evaluation. Consulting test while choosing models makes it exploratory. Whether unlabeled test texts trained vectors also matters: this is a transductive condition distinct from never seeing them.

A word from fragments

A subword embedding can share parameters between forms containing identical character sequences. Bojanowski and colleagues add boundary markers < and >, extract n-grams of lengths 3 through 6 in their configuration and represent a word through fragment contributions. For “where,” trigrams are <wh, whe, her, ere and re>; the paper also includes an identifier for the known full word.

To limit memory, a hash maps n-grams to buckets with learned vectors. Different fragments can land in the same bucket and share parameters. The paper uses FNV-1a and two million buckets. fastText code includes signed UTF-8 byte compatibility details, so a teaching hash must not be presented as equivalent without testing. Fewer buckets can increase collisions for a particular collection, but do not guarantee a neighbor or metric worsens on every run.

An unseen word can receive a vector composed from its n-grams. That permits a query, not a guarantee that fragments learned a useful representation or every typo has good neighbors. In Gensim, word in model.wv may return true for an out-of-vocabulary word because its vector can be constructed; word in model.wv.key_to_index asks whether a word entry exists in the vocabulary. An export containing only word vectors may lack the buckets needed to generate new vectors.

In Table 1 of Bojanowski and colleagues, with their data and protocol, English Rare Words gets correlation 43 for skip-gram and 47 with their subword model and OOV composition, on the published scale. For English WS353 they report 72 and 71 respectively. In Table 2, English syntactic analogies change from 70.1% to 74.9%, while semantic analogies change from 78.5% to 77.8%; questions containing words outside training were excluded. There is no universal improvement across all tasks.

The next figure builds a vector from buckets with an explicit rule and parameters. It is a model for understanding composition and collisions; its neighbors are not an evaluation of trained fastText.

InteractiveCompose a word with buckets

Normalized word: ciberseguridad. The markers < and > are added and fragments of 3 to 6 code points are extracted. Each bucket is calculated by summing code points modulo 13; each occurrence contributes its vector even if the fragment repeats.

Each bar counts distinct fragments of the word that share a bucket. Orange bars show collisions; empty buckets have zero height. The vertical scale adjusts to the maximum shown. Change the bucket count to compare the distribution.

06Bucket 0: 4 distinct fragments0Bucket 1: 4 distinct fragments1Bucket 2: 2 distinct fragments2Bucket 3: 3 distinct fragments3Bucket 4: 4 distinct fragments4Bucket 5: 5 distinct fragments5Bucket 6: 3 distinct fragments6Bucket 7: 5 distinct fragments7Bucket 8: 4 distinct fragments8Bucket 9: 6 distinct fragments9Bucket 10: 3 distinct fragments10Bucket 11: 3 distinct fragments11Bucket 12: 4 distinct fragments12
Fragments and buckets
FragmentBucketDistinct fragments in that bucket
<ci44
cib33
ibe55
ber14
ers55
rse55
seg75
egu96
gur96
uri113
rid75
ida33
dad113
ad>124
<cib113
cibe04
iber22
bers124
erse22
rseg44
segu75
egur63
guri103
urid75
rida04
idad124
dad>84
<cibe84
ciber103
ibers04
berse96
erseg14
rsegu44
segur44
eguri75
gurid63
urida04
ridad96
idad>96
<ciber55
cibers84
iberse103
berseg84
ersegu14
rsegur14
seguri55
egurid33
gurida124
uridad96
ridad>63

Composed vector: (0.119, 16.003, −3.038, 17.868).

Candidates in the same toy model, by cosine (Spanish words)
WordCosine
bicicleta0.926
ciberseguro0.884
seguridad0.813
ciberataque0.803
perro0.772
universidad0.750

This is a mathematical toy model: each bucket’s four components are generated from seed 17080 plus the index and a pseudorandom normal draw; they have not been trained. Neighbors do not measure semantic similarity. The simple hash matches the teaching exercise and does not aim to reproduce FNV or every fastText implementation choice. Changing the bucket count can alter collisions and neighbor order; it does not guarantee worse quality.

13
N-gram occurrences50
Buckets with distinct fragments13
Dimension4
Enter a word and inspect fragments, buckets and neighbors calculated with the same toy model.

Measuring association is not measuring a person

Association bias in embeddings is a property of relationships measured among vectors under a choice of words and method. Texts can contain stereotypes; geometry learned from them can reflect those. That geometry alone is not a measure of authors’ personalities, a correct description of social groups or a direct measure of harm in an application.

Suppose you define a unit direction gg, for example by the difference of two nonidentical vectors. The scalar projection of xx is x⊤gx^\top g and simplified geometric neutralization is

x′=x−(x⊤g)g,x′⊤g=0.x'=x-(x^\top g)g,\qquad x'^\top g=0.

The equality shows that component is removed. It does not show associations encoded in other directions or distances disappear. If x′=0x'=0, its cosine becomes undefined. Declare words defining gg, evaluated words and any control direction; one dimension does not exhaust identities or language about gender. Bolukbasi and colleagues describe a broader procedure with subspace identification, neutralization and an equalization stage: the equation above is only one geometric part.

Gonen and Goldberg took 1,000 words selected by original association, 500 from each extreme, and applied two-cluster k-means. For hard-debiased vectors they reported 92.5% agreement with that original partition, versus 99.9% before; for GN-GloVe, 85.6% versus 100%. These are results for those words and that definition, not universal rates or individual diagnoses. They show a reduced projection does not exhaust what can be recovered from geometry.

The next construction checks the algebraic distinction with six synthetic points. The control direction and groups are part of the teaching model, not profession data or a replication of the cited study.

InteractiveRemove a direction
0.7
Maximum absolute projection onto g1.0
Accuracy of threshold on h for these six points100 %

A toy model, not occupation data or a measurement of people: each A point has first coordinate +1 and each B has −1. The second coordinate is group × intensity plus a fixed offset of −0.2, 0, or +0.2. The control classifier assigns A if that coordinate is positive and B otherwise.

A1A2A3B1B2B3gh

Each point is transformed by (x,y) → (x,y). The projection onto g still contains the first coordinate; the threshold on h gets 6 of 6 examples in this constructed model correct.

Removing a coordinate is an algebraic guarantee about that direction, not a guarantee about every classifier or association. The intensity builds cases where the control threshold retains information or ceases to separate it; the result here is not a measurement of bias in a corpus. The work by Gonen and Goldberg cited in the text studies real embeddings using its own protocol.

Project six points and test whether a second coordinate retains separation in this constructed example.

An association test by permutations

For two nonempty disjoint target sets X,YX,Y and two nonempty attribute sets A,BA,B, define for each word with nonzero vector

s(w;A,B)=media⁡a∈Acos⁡(w,a)−media⁡b∈Bcos⁡(w,b),s(w;A,B)=\operatorname{media}_{a\in A}\cos(w,a)-\operatorname{media}_{b\in B}\cos(w,b), T(X,Y;A,B)=∑x∈Xs(x;A,B)−∑y∈Ys(y;A,B).T(X,Y;A,B)=\sum_{x\in X}s(x;A,B)-\sum_{y\in Y}s(y;A,B).

This is the construction of the WEAT test by Caliskan and colleagues. A permutation test can retain sizes of XX and YY and reassign their labels across X∪YX\cup Y to calculate a statistic for each partition. Specify tail, tie handling and whether all partitions are enumerated or sampled in advance. For a conservative one-sided variant, count partitions with Tperm≥TobsT_{\mathrm{perm}}\geq T_{\mathrm{obs}}; the paper’s strict formulation uses >>. These conventions differ when there are ties.

With MM random permutations, an estimate corrected as (1+#{Tperm≥Tobs})/(M+1)(1+\#\{T_{\mathrm{perm}}\geq T_{\mathrm{obs}}\})/(M+1) avoids reporting zero from finitely many draws. The result depends on included words, coverage and the exchangeability assumption; a p-value is not the probability a person holds a belief. Empty sets, zero norms or zero standard deviation prevent some measurements and must be reported.

One word, multiple uses

In a static representation, every normalized occurrence of “banco” looks up the same row. It can refer to a financial institution, a seat or a school of fish, but the type vector does not itself change with the sentence. A contextual model can produce different representations for different occurrences; that does not guarantee it resolves every ambiguity correctly either.

It is tempting to draw the static vector as an exact average of contexts and move it when sense proportions change. This is a useful simulation if explicitly formulated as a mean model. It does not generally follow that an SGNS- or GloVe-trained embedding is the arithmetic mean of its contexts or necessarily lies between their centroids. Claiming an empirical shift requires training and measuring it, stating the seed and comparing conditions.

InteractiveThree senses and a mean

An explicit geometric experiment using the Spanish word “banco”: replace each financial context by (−0.9; 0.65), each bench context by (0.9; 0.65), and each fish-school context by (0; −0.9). The “banco” point is the weighted mean of these three prototypes. The example words are reminders of senses, not points obtained from a corpus.

financebenchfishbanco
finance: 33.3 % of contexts; credit, account, office.
bench: 33.3 % of contexts; park, sit, wood.
fish: 33.3 % of contexts; sea, school, swim.

Each line joins the mean to a prototype, and its thickness represents the proportion. The averaging rule is a teaching model, not the training rule for SGNS, GloVe, or fastText: a real embedding can move differently. A single static representation does not change when a different context is presented; a contextual representation can.

3
3
3
Total contexts in the model9
Mean coordinates(0.000, 0.133)
Change proportions of three prototypes and observe their weighted mean without attributing it to a trained embedding.

Labs

Evaluation bench

The first lab implements cosine, 3CosAdd, 3CosMul, correlation and a permutation test on explicit data and cell-produced results. It compares exclusion conventions, reports coverage and undefined cases, and keeps evaluations of SGNS, PPMI-SVD and GloVe vectors separate. A small sample checks implementation, not establishes a general method ranking.

The cell reproduces previous-lesson training functions and applies them to Don Quixote excerpts from Project Gutenberg. Two analogies and four similarity pairs are published samples, insufficient for a benchmark; OOV terms are counted and correlation without coverage is undefined. WEAT with Spanish words is only a mathematical demonstration without social categories. The cell also includes complete career and family sets published by Caliskan and colleagues: it reports missing terms and calculates the test only if all are available. The test is one-sided and treats statistics differing by up to 10⁻¹² as equal; interpretation requires exchangeability. The result describes vector associations, not properties of people.

[ ]Embedding evaluation benchBrowser
"""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.')

# Evaluación autocontenida sobre modelos generados por las funciones de l07.
from itertools import combinations

# Cuatro ejemplos de la tabla 2 de Hill et al. (SimLex-999):
# https://aclanthology.org/J15-4004.pdf; son una muestra, no el benchmark.
SIMILARITY = [('dirty', 'narrow', .30), ('student', 'pupil', 9.40),
              ('smart', 'dumb', .60), ('attention', 'awareness', 8.73)]
# Dos preguntas de https://github.com/tmikolov/word2vec/blob/
# 20c129af10659f7c50e86e3be406df663beff438/questions-words.txt
ANALOGIES = [('athens', 'greece', 'baghdad', 'iraq'),
             ('berlin', 'germany', 'paris', 'france')]
# Estímulos publicados en el experimento carrera/familia de Caliskan et al.,
# borrador https://arxiv.org/pdf/1608.07187 ; no inventar etiquetas sociales.
WEAT_MALE = ['john', 'paul', 'mike', 'kevin', 'steve', 'greg', 'jeff', 'bill']
WEAT_FEMALE = ['amy', 'joan', 'lisa', 'sarah', 'diana', 'kate', 'ann', 'donna']
WEAT_CAREER = ['executive', 'management', 'professional', 'corporation',
               'salary', 'office', 'business', 'career']
WEAT_FAMILY = ['home', 'parents', 'children', 'family', 'cousins', 'marriage', 'wedding', 'relatives']


def normalized_rows(vectors):
    vectors = np.asarray(vectors, dtype=float)
    norms = np.linalg.norm(vectors, axis=1)
    valid = np.isfinite(norms) & (norms > 1e-12)
    unit = np.zeros_like(vectors)
    unit[valid] = vectors[valid] / norms[valid, None]
    return unit, valid


def rankdata_average(values):
    values = np.asarray(values)
    order = np.argsort(values, kind='stable')
    ranks = np.empty(len(values), dtype=float)
    start = 0
    while start < len(values):
        end = start + 1
        while end < len(values) and values[order[end]] == values[order[start]]:
            end += 1
        ranks[order[start:end]] = (start + 1 + end) / 2
        start = end
    return ranks


def spearman(predicted, human):
    if len(predicted) < 2:
        return None
    x, y = rankdata_average(predicted), rankdata_average(human)
    if np.std(x) <= 1e-12 or np.std(y) <= 1e-12:
        return None
    return float(np.corrcoef(x, y)[0, 1])


def similarity(words, vectors):
    index = {w: i for i, w in enumerate(words)}
    unit, valid = normalized_rows(vectors)
    predicted, human, oov, invalid = [], [], 0, 0
    for a, b, score in SIMILARITY:
        if a not in index or b not in index:
            oov += 1
        elif not valid[index[a]] or not valid[index[b]]:
            invalid += 1
        else:
            predicted.append(float(unit[index[a]] @ unit[index[b]]))
            human.append(score)
    return {'total': len(SIMILARITY), 'covered': len(predicted), 'oov': oov,
            'invalid': invalid, 'spearman': spearman(predicted, human)}


def analogy(words, vectors, items, method='add', exclude=True):
    index = {w: i for i, w in enumerate(words)}
    unit, valid = normalized_rows(vectors)
    total, evaluated, correct, oov, invalid = len(items), 0, 0, 0, 0
    for a, b, c, expected in items:
        if any(w not in index for w in (a, b, c, expected)):
            oov += 1
            continue
        ia, ib, ic, ie = [index[w] for w in (a, b, c, expected)]
        if not all(valid[i] for i in (ia, ib, ic, ie)):
            invalid += 1
            continue
        if method == 'add':
            query = unit[ib] - unit[ia] + unit[ic]
            if np.linalg.norm(query) <= 1e-12:
                invalid += 1
                continue
            scores = unit @ query
        elif method == 'mul':
            # Coseno desplazado a [0,1], epsilon explícito del denominador.
            ca = np.clip((unit @ unit[ia] + 1.) / 2., 0., 1.)
            cb = np.clip((unit @ unit[ib] + 1.) / 2., 0., 1.)
            cc = np.clip((unit @ unit[ic] + 1.) / 2., 0., 1.)
            scores = cb * cc / (ca + 1e-3)
        else:
            raise ValueError('Método no reconocido')
        scores[~valid] = -np.inf
        if exclude:
            scores[[ia, ib, ic]] = -np.inf
        if not np.isfinite(scores).any():
            invalid += 1
            continue
        guess = int(np.argmax(scores))
        evaluated += 1
        correct += int(guess == ie)
    return {'method': method, 'exclude_inputs': exclude, 'total': total,
            'evaluated': evaluated, 'correct': correct, 'oov': oov, 'invalid': invalid,
            'accuracy': correct / evaluated if evaluated else None}


def weat(words, vectors, X, Y, A, B):
    # Prueba exhaustiva, unilateral, de una asociación en conjuntos pequeños.
    index = {w: i for i, w in enumerate(words)}
    if not X or len(X) != len(Y) or not A or not B:
        raise ValueError('Conjuntos vacíos o objetivos de diferente tamaño')
    targets = X + Y
    if (len(set(targets)) != len(targets) or len(set(A)) != len(A) or
            len(set(B)) != len(B) or set(A) & set(B)):
        raise ValueError('Los conjuntos comparados deben ser disjuntos')
    required = targets + A + B
    missing = sorted({w for w in required if w not in index})
    if missing:
        return {'status': 'oov', 'missing': missing}
    unit, valid = normalized_rows(vectors)
    if any(not valid[index[w]] for w in required):
        return {'status': 'zero_norm'}
    def association(word):
        v = unit[index[word]]
        return float(np.mean(unit[[index[a] for a in A]] @ v) -
                     np.mean(unit[[index[b] for b in B]] @ v))
    scores = np.array([association(word) for word in targets])
    size = len(X)
    observed = float(scores[:size].sum() - scores[size:].sum())
    std = float(np.std(scores))
    effect = float((scores[:size].mean() - scores[size:].mean()) / std) if std > 1e-12 else None
    stats = []
    for chosen in combinations(range(len(targets)), size):
        selected = np.zeros(len(targets), dtype=bool)
        selected[list(chosen)] = True
        stats.append(float(scores[selected].sum() - scores[~selected].sum()))
    p = sum(value >= observed - 1e-12 for value in stats) / len(stats)
    return {'status': 'ok', 'statistic': observed, 'effect': effect, 'p_one_sided': p,
            'permutations': len(stats), 'tie_tolerance': 1e-12,
            'direction': 'X más asociado a A que Y'}


def run_checks():
    assert np.allclose(rankdata_average([4., 1., 1., 3.]), [4., 1.5, 1.5, 3.])
    assert spearman([1., 2., 3.], [3., 2., 1.]) < -.999999
    names = ['a', 'b', 'c', 'd']
    vectors = np.array([[1., 0.], [0., 1.], [-1., 0.], [0., -1.]])
    for method in ('add', 'mul'):
        assert analogy(names, vectors, [('a', 'b', 'c', 'd')], method)['evaluated'] == 1
    assert weat(names, vectors, ['a', 'b'], ['c', 'd'], ['a'], ['c'])['permutations'] == 6


def main_evaluation():
    train = tokenize(TRAIN)
    words, index, counts = vocabulary([train])
    rows, cols, values = cooccurrences([train], index, radius=2)
    params, _ = train_glove(rows, cols, values, len(words), dim=12,
                            epochs=15, rate=.04, seed=GLOVE_SEED)
    E, _, _ = fit_sgns([train], words, index, counts, epochs=15, dim=12, window=2,
                       k=2, rate=.04, seed=GLOVE_SEED, subsample=0., batch_size=32)
    X = np.zeros((len(words), len(words)))
    X[rows, cols] = values
    marginal = X.sum(axis=0) ** .75
    q = marginal / marginal.sum()
    rowmass = X.sum(axis=1)
    nonzero = X > 0
    ppmi = np.zeros_like(X)
    ratio = np.zeros_like(X)
    denominator = rowmass[:, None] * q[None, :]
    ratio[nonzero] = X[nonzero] / denominator[nonzero]
    ppmi[nonzero] = np.maximum(np.log(ratio[nonzero]), 0.)
    U, s, _ = np.linalg.svd(ppmi, full_matrices=False)
    svd = U[:, :min(4, len(s))] * s[:min(4, len(s))]
    models = {'SGNS entrada': E, 'GloVe entrada+contexto': params[0] + params[1], 'PPMI UΣ': svd}
    run_checks()
    print('Muestra real Gutenberg, entrenamiento:', TRAIN)
    print('Grupos WEAT de demostración sin categoría social; no se interpreta como sesgo social.')
    for name, vectors in models.items():
        print(name, '| similitud (solo 4 ejemplos ingleses):', similarity(words, vectors))
        for method in ('add', 'mul'):
            print(name, '| analogías (solo 2 ejemplos ingleses):', analogy(words, vectors, ANALOGIES, method))
        print(name, '| WEAT matemático no social:',
              weat(words, vectors, ['lugar', 'mancha'], ['nombre', 'quiero'],
                   ['acordarme', 'un'], ['de', 'cuyo']))
        print(name, '| WEAT carrera/familia publicado, solo si hay cobertura completa:',
              weat(words, vectors, WEAT_MALE, WEAT_FEMALE, WEAT_CAREER, WEAT_FAMILY))
    print('Cobertura cero significa que una métrica está indefinida, no que valga cero.')
    print('El test de permutación exhaustiva solo es válido bajo intercambiabilidad; '
          'esta muestra y sus asociaciones no establecen propiedades del mundo.')


if __name__ == '__main__':
    main_evaluation()

fastText and review classification

The second lab trains fastText and word2vec with recorded corpus and parameters, compares OOV queries and evaluates a classifier with frozen and tunable embeddings. Both conditions must use the same splits and metrics; if multiple test results are consulted, label them exploratory. The short version checks the pipeline and does not replace the reader’s full training. Download and usage terms must be checked for the specific text edition.

The local cell requires NumPy, SciPy, Gensim, PyArrow, scikit-learn, PyTorch and huggingface_hub. It uses text8 under the previous lesson’s protocol and source and IMDb reviews at a pinned revision, with published train and test SHA-256 hashes. The IMDb card says other and does not clarify license: review terms before redistribution, as with text8. Deduplication uses only train labels to clean train and removes test texts appearing in original train. Contradictions are resolved within each split; partial duplicates are not detected. Stratified validation is separated from train and only its training texts form the classifier vocabulary.

With ORYON_VERIFY_SHORT=1, data, sequence length and epochs are reduced to verify the pipeline, but complete files needed for deduplication are downloaded and examined. FastText analogy evaluation uses known words and excludes OOV. SimLex evaluation, available if you supply the original TSV via ORYON_SIMLEX_PATH, permits OOV composition and counts it separately: coverage is not equivalent. WEAT uses the complete published stimuli, reports which terms are composed from subwords and uses 10⁻¹² tie tolerance. Without the TSV the cell reports it was not supplied; calculated SHA identifies bytes and is not independent authentication.

In a short check on 128 test reviews, accuracy was 46.9% with frozen table and 55.5% with the word table fine-tuned. These are exploratory results of that small test and two systems consulted on the same test; they do not establish which strategy wins with more data or another task. The typo langauge was outside Word2Vec vocabulary, while FastText could compose it; obtaining neighbors does not guarantee semantic quality.

Both classifier strategies start from the same FastText vectors and splits; the tuned condition modifies the classifier’s word table, not the subword model’s buckets. Epoch is chosen on validation and test inspected for both strategies, so test is exploratory. This lab has not been run and no quality advantage demonstrated.

[ ]FastText and review classificationLocal GPU
"""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.')

# El bloque previo procede de la celda de m17-l06 y no depende de archivos externos.
from collections import Counter
from itertools import combinations
from gensim.models import FastText
from huggingface_hub import hf_hub_download
from scipy.stats import spearmanr
from sklearn.metrics import accuracy_score, f1_score
from sklearn.model_selection import train_test_split
import csv
import pyarrow.parquet as pq
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset

IMDB_REPO = 'stanfordnlp/imdb'
IMDB_REV = 'e6281661ce1c48d982bc483cf8a173c1bbeb5d31'
IMDB_FILES = {
    'train': ('plain_text/train-00000-of-00001.parquet',
              'db47d16b5c297cc0dd625e519c81319c24c9149e70e8496de5475f6fa928342c'),
    'test': ('plain_text/test-00000-of-00001.parquet',
             'b52e26e2f872d282ffac460bf9770b25ac6f102cda0e6ca7158df98c94e8b3da'),
}
# Fuente de los estímulos: Caliskan et al. https://arxiv.org/pdf/1608.07187
WEAT_MALE = ['john', 'paul', 'mike', 'kevin', 'steve', 'greg', 'jeff', 'bill']
WEAT_FEMALE = ['amy', 'joan', 'lisa', 'sarah', 'diana', 'kate', 'ann', 'donna']
WEAT_CAREER = ['executive', 'management', 'professional', 'corporation',
               'salary', 'office', 'business', 'career']
WEAT_FAMILY = ['home', 'parents', 'children', 'family', 'cousins', 'marriage', 'wedding', 'relatives']
torch.set_num_threads(1)
DIM = 50
SEQUENCE = 64 if SHORT else 256
CLASSIFIER_EPOCHS = 2 if SHORT else 5


def imdb_split(name):
    filename, expected = IMDB_FILES[name]
    path = hf_hub_download(repo_id=IMDB_REPO, repo_type='dataset', revision=IMDB_REV, filename=filename)
    digest = hashlib.sha256()
    with open(path, 'rb') as source:
        for block in iter(lambda: source.read(1024 * 1024), b''):
            digest.update(block)
    if digest.hexdigest() != expected:
        raise ValueError('Hash inesperado de IMDb: ' + name)
    table = pq.read_table(path, columns=['text', 'label'])
    texts = table.column('text').to_pylist()
    labels = table.column('label').to_pylist()
    if len(texts) != 25000 or len(labels) != 25000:
        raise ValueError('Número inesperado de reseñas IMDb')
    return [(i, text, int(label)) for i, (text, label) in enumerate(zip(texts, labels))]


def unique_splits(train, test):
    # Deduplicación exacta tras NFC, minúsculas y espacios; no detecta paráfrasis.
    canonical_by_digest, removed = {}, Counter()
    def identity(text):
        canonical = ' '.join(unicodedata.normalize('NFC', text).lower().split())
        digest = hashlib.sha256(canonical.encode('utf-8')).hexdigest()
        if digest in canonical_by_digest and canonical_by_digest[digest] != canonical:
            raise ValueError('Colisión SHA-256')
        canonical_by_digest[digest] = canonical
        return digest
    def label_sets(items):
        groups = {}
        for _, text, label in items:
            groups.setdefault(identity(text), set()).add(label)
        return groups
    train_groups = label_sets(train)
    test_groups = label_sets(test)
    def unique(items, groups, name, forbidden):
        output = []
        seen = set()
        for source_id, text, label in items:
            digest = identity(text)
            if digest in forbidden:
                removed[name + '_in_train'] += 1
                continue
            if len(groups[digest]) > 1:
                removed[name + '_conflicting_labels'] += 1
                continue
            if digest in seen:
                removed[name + '_duplicate'] += 1
                continue
            seen.add(digest)
            output.append((source_id, text, label))
        return output
    # Nunca usar las etiquetas de test para decidir qué conservar en train.
    clean_train = unique(train, train_groups, 'train', set())
    clean_test = unique(test, test_groups, 'test', set(train_groups))
    return clean_train, clean_test, dict(removed)


def make_splits():
    original_train, original_test = imdb_split('train'), imdb_split('test')
    original_train, test, removed = unique_splits(original_train, original_test)
    train, valid = train_test_split(original_train, test_size=.2, random_state=SEED,
                                    stratify=[r[2] for r in original_train])
    if SHORT:
        train, _ = train_test_split(train, train_size=256, random_state=SEED,
                                    stratify=[r[2] for r in train])
        valid, _ = train_test_split(valid, train_size=128, random_state=SEED + 1,
                                    stratify=[r[2] for r in valid])
        test, _ = train_test_split(test, train_size=128, random_state=SEED + 2,
                                   stratify=[r[2] for r in test])
    return train, valid, test, removed


def text_tokens(text):
    text = re.sub(r'<br\s*/?>', ' ', text.lower())
    return re.findall(r"[a-z]+(?:'[a-z]+)?", text)


def build_review_vocab(records, max_words):
    counts = Counter(token for _, text, _ in records for token in text_tokens(text))
    ordered = sorted(counts, key=lambda w: (-counts[w], w))[:max_words - 2]
    return ['<pad>', '<unk>', *ordered]


def encode_reviews(records, index):
    x = np.zeros((len(records), SEQUENCE), dtype=np.int64)
    labels = np.empty(len(records), dtype=np.int64)
    total, unknown = 0, 0
    for row, (_, text, label) in enumerate(records):
        tokens = text_tokens(text)[:SEQUENCE]
        total += len(tokens)
        unknown += sum(token not in index for token in tokens)
        x[row, :len(tokens)] = [index.get(token, 1) for token in tokens]
        labels[row] = label
    return torch.from_numpy(x), torch.from_numpy(labels), {'tokens': total, 'unknown': unknown}


class MeanClassifier(nn.Module):
    def __init__(self, initial, freeze):
        super().__init__()
        self.embedding = nn.Embedding.from_pretrained(initial.clone(), freeze=freeze, padding_idx=0)
        self.linear = nn.Linear(initial.shape[1], 2)

    def forward(self, tokens):
        mask = (tokens != 0).unsqueeze(-1)
        pooled = (self.embedding(tokens) * mask).sum(dim=1) / mask.sum(dim=1).clamp(min=1)
        return self.linear(pooled)


def evaluate_classifier(model, tensors):
    model.eval()
    with torch.inference_mode():
        predictions = []
        for tokens, _ in DataLoader(TensorDataset(*tensors), batch_size=64, shuffle=False):
            predictions.extend(model(tokens).argmax(dim=1).tolist())
    truth = tensors[1].tolist()
    return {'n': len(truth), 'accuracy': float(accuracy_score(truth, predictions)),
            'f1_binary': float(f1_score(truth, predictions, zero_division=0))}


def train_classifier(initial, data, freeze):
    torch.manual_seed(SEED)
    model = MeanClassifier(initial, freeze)
    optimizer = torch.optim.Adam([p for p in model.parameters() if p.requires_grad], lr=.003)
    generator = torch.Generator().manual_seed(SEED)
    loader = DataLoader(TensorDataset(*data['train']), batch_size=32, shuffle=True, generator=generator)
    best, best_score, history = None, -1., []
    for epoch in range(CLASSIFIER_EPOCHS):
        model.train()
        for x, y in loader:
            optimizer.zero_grad(set_to_none=True)
            loss = nn.functional.cross_entropy(model(x), y)
            if not torch.isfinite(loss):
                raise ValueError('Pérdida no finita')
            loss.backward()
            if any(p.grad is not None and not torch.isfinite(p.grad).all() for p in model.parameters()):
                raise ValueError('Gradiente no finito')
            optimizer.step()
        metrics = evaluate_classifier(model, data['validation'])
        history.append({'epoch': epoch + 1, 'validation': metrics})
        if metrics['accuracy'] > best_score:
            best_score = metrics['accuracy']
            best = {name: p.detach().clone() for name, p in model.state_dict().items()}
    if best is None:
        raise ValueError('No hay checkpoint válido')
    model.load_state_dict(best)
    return {'history': history, 'test': evaluate_classifier(model, data['test'])}


def weat_evaluation(wv, allow_composed):
    targets, attrs = WEAT_MALE + WEAT_FEMALE, WEAT_CAREER + WEAT_FAMILY
    vocabulary = wv.key_to_index
    missing = [w for w in targets + attrs if w not in vocabulary]
    if missing and not allow_composed:
        return {'status': 'oov', 'missing': missing, 'total': len(targets + attrs)}
    vectors = {}
    for word in targets + attrs:
        try:
            vector = np.asarray(wv.get_vector(word), dtype=float)
        except KeyError:
            return {'status': 'oov_uncomposable', 'word': word, 'missing_in_vocabulary': missing}
        norm = np.linalg.norm(vector)
        if not np.isfinite(norm) or norm <= 1e-12:
            return {'status': 'invalid_norm', 'word': word, 'missing_in_vocabulary': missing}
        vectors[word] = vector / norm
    def association(word):
        v = vectors[word]
        return (np.mean([v @ vectors[a] for a in WEAT_CAREER]) -
                np.mean([v @ vectors[b] for b in WEAT_FAMILY]))
    values = np.asarray([association(w) for w in targets])
    size = len(WEAT_MALE)
    observed = float(values[:size].sum() - values[size:].sum())
    std = float(values.std())
    effect = float((values[:size].mean() - values[size:].mean()) / std) if std > 1e-12 else None
    stats = [float(2 * values[list(indices)].sum() - values.sum())
             for indices in combinations(range(len(targets)), size)]
    return {'status': 'ok', 'statistic': observed, 'effect': effect,
            'p_one_sided': sum(s >= observed - 1e-12 for s in stats) / len(stats),
            'permutations': len(stats), 'tie_tolerance': 1e-12, 'missing_in_vocabulary': missing,
            'composed_oov': allow_composed,
            'interpretation': 'Asociación en estos vectores, estímulos y corpus; no describe individuos.'}


def simlex_evaluation(wv, allow_composed):
    # El lector aporta el TSV original después de revisar sus condiciones:
    # https://fh295.github.io/simlex.html . No se asume licencia no documentada.
    supplied = os.environ.get('ORYON_SIMLEX_PATH')
    if not supplied:
        return {'status': 'not_supplied', 'source': 'https://fh295.github.io/simlex.html'}
    path = Path(supplied)
    with path.open('rb') as stream:
        raw = stream.read(1_000_001)
    if len(raw) > 1_000_000:
        raise ValueError('TSV de SimLex demasiado grande')
    rows = list(csv.DictReader(raw.decode('utf-8-sig').splitlines(), delimiter='\t'))
    if len(rows) != 999 or not {'word1', 'word2', 'SimLex999'}.issubset(rows[0]):
        raise ValueError('Se esperaba el TSV original de 999 pares')
    scores, labels, missing, invalid, composed = [], [], 0, 0, 0
    for row in rows:
        words = [row['word1'].lower(), row['word2'].lower()]
        unseen = any(w not in wv.key_to_index for w in words)
        if unseen and not allow_composed:
            missing += 1
            continue
        try:
            a, b = (np.asarray(wv.get_vector(w), dtype=float) for w in words)
        except KeyError:
            missing += 1
            continue
        norm_a, norm_b = np.linalg.norm(a), np.linalg.norm(b)
        rating = float(row['SimLex999'])
        if (not np.isfinite(norm_a) or not np.isfinite(norm_b) or
                norm_a <= 1e-12 or norm_b <= 1e-12 or not math.isfinite(rating)):
            invalid += 1
            continue
        composed += int(unseen)
        scores.append(float((a / norm_a) @ (b / norm_b)))
        labels.append(rating)
    rho = None
    if len(scores) >= 2 and np.std(scores) > 0 and np.std(labels) > 0:
        rho = float(spearmanr(scores, labels).statistic)
    return {'status': 'evaluated', 'total': len(rows), 'covered': len(scores),
            'oov': missing, 'invalid': invalid, 'pairs_with_composed_oov': composed,
            'spearman': rho, 'sha256_calculated': hashlib.sha256(raw).hexdigest(),
            'source': 'https://fh295.github.io/simlex.html'}


def neighbor_report(model, word):
    present = word in model.wv.key_to_index
    if not present and not isinstance(model, FastText):
        return {'word': word, 'in_vocabulary': False, 'neighbors': None}
    try:
        vec = model.wv.get_vector(word)
        nearest = [(name, float(score)) for name, score in model.wv.similar_by_vector(vec, topn=6)
                   if name != word][:5]
        return {'word': word, 'in_vocabulary': present,
                'neighbors': nearest}
    except KeyError:
        return {'word': word, 'in_vocabulary': present, 'neighbors': None}


def ids_digest(records):
    values = ','.join(str(r[0]) for r in records).encode('ascii')
    return hashlib.sha256(values).hexdigest()


def main_fasttext():
    path, text_hash = get_text8()
    questions, analogy_source = get_analogies()
    text8_train, text8_valid, text8_test = split_sentences(read_sentences(path, MAX_WORDS))
    common = dict(sentences=text8_train, vector_size=DIM, window=WINDOW, min_count=MIN_COUNT,
                  sg=1, negative=NEGATIVE, hs=0, sample=0., shrink_windows=True,
                  workers=1, epochs=EPOCHS, seed=SEED)
    word2vec = Word2Vec(**common)
    fast = FastText(**common, min_n=3, max_n=6, bucket=20000 if SHORT else 100000)
    train, valid, test, removed = make_splits()
    vocab = build_review_vocab(train, max_words=8000 if SHORT else 30000)
    index = {word: i for i, word in enumerate(vocab)}
    encoded = {name: encode_reviews(records, index) for name, records in
               [('train', train), ('validation', valid), ('test', test)]}
    matrix = np.zeros((len(vocab), DIM), dtype=np.float32)
    for i, token in enumerate(vocab[2:], start=2):
        try:
            matrix[i] = fast.wv.get_vector(token)
        except KeyError:
            pass
    if not np.isfinite(matrix).all():
        raise ValueError('Matriz inicial no finita')
    data = {name: (items[0], items[1]) for name, items in encoded.items()}
    initial = torch.from_numpy(matrix)
    frozen = train_classifier(initial, data, freeze=True)
    tuned = train_classifier(initial, data, freeze=False)
    query = 'language'
    typo = 'langauge'
    rare = min(word2vec.wv.index_to_key,
               key=lambda w: (word2vec.wv.get_vecattr(w, 'count'), w))
    source = {'text8_md5_published': MD5, 'text8_sha256_measured': text_hash,
              'analogies': analogy_source,
              'imdb_revision': IMDB_REV, 'imdb_hashes_verified': IMDB_FILES,
              'imdb_license': 'La ficha indica other y deja la licencia sin concretar; verificar derechos.',
              'split': 'IMDb train estratificado 80/20; test oficial filtrado por duplicados exactos. '
                       'Conflictos de etiquetas resueltos dentro de cada partición, sin usar etiquetas '
                       'de test para decidir la composición de train.',
              'split_hashes': {'train': ids_digest(train), 'validation': ids_digest(valid),
                               'test_original_partition': ids_digest(test)},
              'dedup_removed': removed, 'seed': SEED,
              'limitations': 'No detecta duplicados parciales. Test consultado para dos estrategias, '
                             'por tanto exploratorio. Ajuste solo de tabla de palabras del clasificador, '
                             'no actualiza cubetas subpalabra FastText.'}
    result = {'protocol': source, 'short': SHORT, 'gensim': gensim.__version__, 'torch': torch.__version__,
              'vocabulary_classifier': len(vocab), 'sequence_limit': SEQUENCE,
              'coverage': {name: values[2] for name, values in encoded.items()},
              'intrinsic': {
                  'word2vec': report_vectors(list(word2vec.wv.index_to_key), word2vec.wv.vectors,
                                             text8_valid, text8_test, questions),
                  'fasttext': report_vectors(list(fast.wv.index_to_key), fast.wv.vectors,
                                             text8_valid, text8_test, questions),
                  'simlex_word2vec': simlex_evaluation(word2vec.wv, False),
                  'simlex_fasttext': simlex_evaluation(fast.wv, True)},
              'neighbors': {'word2vec_query': neighbor_report(word2vec, query),
                            'fasttext_query': neighbor_report(fast, query),
                            'word2vec_typo': neighbor_report(word2vec, typo),
                            'fasttext_typo': neighbor_report(fast, typo),
                            'rare_word_frequency': int(word2vec.wv.get_vecattr(rare, 'count')),
                            'word2vec_rare': neighbor_report(word2vec, rare),
                            'fasttext_rare': neighbor_report(fast, rare)},
              'weat_career_family': {'word2vec': weat_evaluation(word2vec.wv, False),
                                     'fasttext': weat_evaluation(fast.wv, True)},
              'classification': {'frozen': frozen, 'tuned_word_table': tuned}}
    OUTPUT.mkdir(parents=True, exist_ok=True)
    (OUTPUT / 'fasttext_sentiment.json').write_text(json.dumps(result, ensure_ascii=False, indent=2),
                                                     encoding='utf-8')
    print('Resultados:', result)
    print('Archivo:', OUTPUT / 'fasttext_sentiment.json')
    print('El WEAT usa estímulos publicados y una prueba unilateral; '
          'el resultado describe esta representación, no personas ni causalidad.')
    print('Los modos corto y completo tienen protocolos distintos y no garantizan un ganador.')


if __name__ == '__main__':
    main_fasttext()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Exercises

NumericThree similarities and a sum
In two dimensions use unit vectors a=(1,0), b=(0,1), c=(0,−1) and candidate x=(−1,0). What is cos(x,b)−cos(x,a)+cos(x,c)?
NumericA small denominator
With the previous exercise's vectors, use h=(1+cos)/2 and ε=0.001. What is h(x,b)h(x,c)/(h(x,a)+ε)?
ProofA common factor, with conditions
Prove: Show ranking equivalence between cos(x, b−a+c) and the sum of three cosines under normalization, and state when it fails.
0
Vectors a, b, c and each candidate x are normalized; define r=b−a+c and assume r≠0.

Step 1 of 4. What does the numerator of cos(x,r) express?

NumericA tail with ties
A one-sided test has four association scores [2,0,−2,0]. X contains the first two and Y the other two. Enumerate the six two-element partitions and count those with T at least as large as observed. What is the exact p-value under the ≥ convention?
QuizTwo different metrics
An embedding improves on analogies and worsens on review classification under properly separated evaluation. What conclusion is compatible with the result?
QuizAfter neutralizing
You project several vectors onto the subspace orthogonal to unit direction g and check their products with g are zero. What can you conclude?
CodeAn explicit bucket table
Implement fasttext_vector(word, ngram_table, n_min=3, n_max=6, buckets=7) as a teaching model. Surround word with < and >; extract all contiguous n-grams of lengths between n_min and n_max inclusive, counting repetitions. A fragment's bucket is sum(ord(c) for c in fragment) % buckets. ngram_table is a finite NumPy array of shape (buckets,d). Return the sum of rows for each occurrence without modifying the table. Require a nonempty word, 1≤n_min≤n_max, positive buckets, valid table and at least one n-gram; otherwise raise ValueError. This simple hash does not claim to reproduce fastText FNV.
import numpy as np

def fasttext_vector(word, ngram_table, n_min=3, n_max=6, buckets=7):
  pass
Shift+Enter to run

Further connections

fastText subwords share vectors through a composition function; tokenization in later models organizes units and probabilities differently. Projections and probes connect with Orthogonal projection and representation evaluation: whenever a figure reduces many dimensions to two or three, also calculate metrics in the original space and distinguish visual distortion from measured results.