Distributional semantics: co-occurrence, PMI and LSA
Study distributional semantics, co-occurrence, TF-IDF, PPMI and latent semantic analysis with reproducible corpora.
After this lesson you can
- Build word-context and term-document matrices under explicit conventions.
- Calculate TF-IDF, PMI and PPMI and interpret their limitations.
- Apply truncated SVD and compare latent vector geometries.
- Evaluate neighbors and retrieval with documented data and coverage.
Before you start
Searching for what was not written
A query containing “automóvil” can be relevant to a document about “coche” without using the first word; both mean “car.” Literal matching need not find the relationship. Can we get clues from documents without introducing a synonym dictionary?
The distributional hypothesis, associated with Harris and Firth’s tradition, proposes studying a word through surrounding units. Sharing context does not prove synonymy: “cold” and “hot” can occur in similar constructions despite being antonyms. Vectors capture corpus regularities and biases; they do not directly access meaning or guarantee understanding.
A local representation assigns each type a distinct one-hot vector: every component is zero except the one for that type. Two distinct words have zero dot product, whether “car” and “automobile” or “car” and “algorithm.” A distributed representation spreads description over shared components, such as observed contexts. A linear classifier receiving those vectors directly can exploit a shared component even in a word unseen during its training. This is a possibility, not a guarantee: given one-hot vectors, a subsequently learned parameter matrix can also share information between words. Compare complete systems and data, not just representation names.
Building the evidence
Choose tokenization, normalization and document boundaries before counting. With documents and vocabulary , the term-document matrix has , the number of occurrences of term in document . Columns are documents and rows words; some libraries use the transpose. A frequent row may be large in many documents without distinguishing them, while a very specific word can separate a few.
The word-context matrix answers another question. For each focal occurrence, count tokens 1 to positions away without crossing document boundaries. With uniform weight each pair contributes one; with weight , a nearby pair weighs more. Exclude the focal position, but another occurrence of the same type can be context. If both axes contain the same vocabulary and use the same symmetric window and weight in both directions, . This need not hold if left and right are distinguished or vocabularies differ.
A small window can highlight substitutions compatible with a construction, while a wide window can capture topical relationships. These are hypotheses to test, not guaranteed neighbor properties. In Levy, Goldberg and Dagan, using August 2013 English Wikipedia and two-fold cross-validation to select hyperparameters, PPMI obtained Spearman correlations 0.457, 0.442 and 0.235 on Rare Words with windows of 2, 5 and 10 on each side. Each figure averages two evaluations: each selects a configuration on one half and evaluates on the other. The comparison does not isolate window effect alone or predict another corpus.
To obtain neighbors, compare rows of the same matrix. If and are nonzero, cosine similarity is
An unnormalized dot product can favor high-norm rows, a property often related to frequency. Cosine discards magnitude but does not remove all frequency biases or turn association into synonymy. A zero vector has undefined cosine: exclude it and report coverage. If scoring human-rated pairs, report how many are excluded for vocabulary and how ties are handled; SimLex-999 specifically distinguishes similarity from association.
TF-IDF: distinguishing documents
Inverse document frequency reduces the weight of terms appearing in many documents. For and a term present in , one unsmoothed convention is
We use natural logarithms. If a term appears in every document, its IDF is zero; an absent term has and is excluded from training vocabulary. IDF is surprisal of the event “a uniformly chosen document contains the term” under empirical frequency, not surprisal of a token occurrence. Multiplying by TF values both repeated presence in a document and specificity within the collection. A document with zero norm after weighting has undefined cosine.
The formula is not universal. By default, TfidfVectorizer uses and L2-normalizes each document. Even with smooth_idf=False it retains the added one. Figures also change with tokenization, lowercasing, vocabulary or treatment of single-character words. Comparing implementations requires matching all those options and matrix orientation, not just the name TF-IDF.
PMI: association, not popularity
With , total and positive marginals and , the empirical pair distribution is . For an observed pair, pointwise mutual information is
PMI measures in nats the logarithm of the ratio between joint frequency and that resulting from multiplying independent marginals. A negative value indicates observed association below that reference, not a negative probability. If the pair is unobserved, its empirical PMI is when both marginals are positive and its PPMI is zero. A row or column without mass is outside the support; if , the distribution is undefined. If weights are fractional, contains weighted mass, not necessarily integer occurrence counts.
Mutual information is expected PMI under the joint, not each pair’s value. By Gibbs’ inequality, ; this does not prevent negative PMI. The relationship between both concepts and KL also appears in Mutual information. PPMI clipping changes the matrix and no longer preserves that expectation identity.
A pair seen once can obtain a high ratio if its marginals are tiny. Such a sparse estimate can be unstable; show its counts and compare thresholds or uncertainty, without concluding all rare pairs are spurious. Levy and colleagues consider smoothing only the context marginal:
With we recover empirical PMI. With (0.75), the context distribution flattens: some rare contexts receive higher base probability and their score falls, while frequent ones can rise. The exact difference is ; normalization prevents claiming all pairs decrease. This procedure does not change joint counts or add observations. Expected smoothed PMI is , not the original mutual information.
Now compare those calculations with real text. The next interactive uses chapter I of part one of Don Quixote, Project Gutenberg edition 2000, with each paragraph as a document and this lesson’s cell tokenization. Extraction follows the previous lesson’s program; the full file’s SHA-256 is 392270e534c66988d6e949ba0f9a64117969fde0f2aebbc6efef3314e23e4385. Change the window from 1 to 10 or use the whole paragraph and compare counts, observed PMI and PPMI. The text is limited and neighborhood does not prove two terms are synonyms.
To avoid a dense matrix of size , traverse positive sparse entries, calculate marginals and eliminate values the maximum turns to zero. First sum any duplicate coordinates. Memory depends on stored entries and marginal vectors, not just nominal dimension; even a large sparse matrix can exceed available budget.
LSA: sharing factors
Latent semantic analysis applies SVD to a weighted matrix, for example term-document. For , write and retain the largest singular values:
By Eckart-Young-Mirsky theorem, minimizes Frobenius-norm reconstruction error among matrices of rank at most . This does not directly optimize search accuracy or demonstrate linguistic similarity. Low rank can connect terms that never co-occur if their document profiles share factors; it can also erase useful differences. Greater rank reduces or retains optimal reconstruction error, but task quality may rise or fall.
Deerwester and colleagues presented nine titles, five on interfaces and four on graphs, and 12 terms in a two-dimensional representation. They note the example was chosen for clarity. Their CISI experiment used 1,460 documents, 35 queries, 5,135 terms and rank 100; reported mean precision was approximately 0.11 for both LSI and term matching and 0.14 for SMART with another term selection. This does not prove 100 is always the right rank or independently attribute the difference to factorization.
A useful family assigns words and documents , for . Their cross-products reconstruct . But word cosines from , and generally differ: each power changes factor weights. Choose convention and rank using task validation, without presenting one power as universally best. Queries must be projected with a rule compatible with the chosen representation; for asymmetric document search derive that rule before comparing cosines.
If you calculate one SVD and plot its first two coordinates, changing from 2 to 3 does not move those axes, except for sign or degenerate-subspace ambiguities. However cosine in dimensions can change. A recalculated 2D projection can help exploration if its method is stated and on-screen distances do not replace the full calculation.
A dense SVD is costly. For sparse matrices, scipy.sparse.linalg.svds approximates some singular values, but does not guarantee sorted output: reorder their vectors too. With the default ARPACK solver, must be smaller than the smallest dimension. Each vector pair’s sign is arbitrary and a basis in a repeated singular subspace is not unique either: compare reconstructions or subspaces, not isolated signs. Each word retains one static vector, so meanings in different contexts are mixed. Factorization can compress output, but constructing the matrix and SVD also costs time and memory.
Labs
PPMI and SVD from counts
The lab builds a sparse word-context matrix from an identified corpus and measures neighbors and similarities with several windows, smoothing settings and powers of . The small example checks implementation; a few documents do not support general conclusions or 100 components if dimensions are too small. The extended version must state source, license, split, hash and cost. A cell taking more than five seconds cannot be presented as a valid Pyodide run without adjusting size.
The cell counts co-occurrences without crossing document boundaries, calculates sparse context-smoothed PPMI and compares neighbors under three and weightings. It sorts singular values and excludes numerically zero dimensions and vectors with insufficient norm for cosine. Default rank is 3; you can change RANK to 100 if you provide a sufficiently large matrix. Time and memory for millions of tokens and 100 dimensions are not measured here.
The four initial documents are excerpts from chapters I and II of part one of Don Quixote, Project Gutenberg edition 2000, prepared by an anonymous volunteer and Joaquín Cuenca Abela. Its listing indicates US public-domain status; consult terms of use and applicable law. The sample only checks the pipeline. To evaluate the illustrative selection of four English pairs with scores published in Table 2 of SimLex-999, replace DOCS with real English documents and record provenance. The cell shows covered pairs, OOV and insufficient-norm vectors; if coverage is zero it calculates no correlation. Four pairs do not justify general conclusions.
"""Coocurrencias dispersas, PPMI y SVD truncada; muestra pequeña Pyodide.
Fragmentos de Miguel de Cervantes, Don Quijote, primera parte, capítulos I y II,
Project Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Edición preparada por un voluntario anónimo y Joaquín Cuenca Abela; la ficha
declara dominio público en EE. UU. Consulta la política de marca y la ley local
antes de redistribuir: https://www.gutenberg.org/policy/license.html .
Estos fragmentos son insuficientes para generalizar. DOCS puede sustituirse por
documentos de un corpus inglés real y de procedencia documentada para medir los
pares SimLex; no se necesita ningún archivo de informes.
"""
import re
import unicodedata
from collections import Counter
import numpy as np
import scipy
from scipy import sparse
from scipy.sparse.linalg import svds
from scipy.special import logsumexp
from scipy.stats import spearmanr
DOCS = [
'En un lugar de la Mancha,',
'de cuyo nombre no quiero acordarme',
'Hechas, pues, estas prevenciones,',
'no quiso aguardar más tiempo',
]
PATTERN = re.compile(r"\w+(?:['’]\w+)*|[^\w\s]", re.UNICODE)
WINDOW = 2
ALPHA = .75
RANK = 3 # Para un corpus mayor prueba 100; debe ser menor que ambas dimensiones.
SEED = 17040
# Cuatro pares de la tabla 2 de Hill, Reichart y Korhonen, SimLex-999:
# https://aclanthology.org/J15-4004.pdf . Son ingleses y la muestra española
# puede no cubrir ninguno; se reporta cobertura, nunca se inventa una nota.
GOLD = [('dirty', 'narrow', .30), ('student', 'pupil', 9.40),
('smart', 'dumb', .60), ('attention', 'awareness', 8.73)]
def tokenize(text):
return PATTERN.findall(unicodedata.normalize('NFC', text).lower())
def cooccurrences(documents, window, inverse_distance=False):
if window < 1:
raise ValueError('La ventana debe ser al menos 1')
tokenized = [tokenize(doc) for doc in documents]
vocabulary = sorted({word for doc in tokenized for word in doc})
if not vocabulary:
raise ValueError('Corpus sin tokens')
ids = {word: i for i, word in enumerate(vocabulary)}
pairs = Counter()
for doc in tokenized:
for i, word in enumerate(doc):
for j in range(max(0, i - window), min(len(doc), i + window + 1)):
if i != j:
pairs[(ids[word], ids[doc[j]])] += 1 / abs(i - j) if inverse_distance else 1.
shape = (len(vocabulary), len(vocabulary))
rows = np.fromiter((pair[0] for pair in pairs), dtype=np.int64, count=len(pairs))
cols = np.fromiter((pair[1] for pair in pairs), dtype=np.int64, count=len(pairs))
data = np.fromiter(pairs.values(), dtype=np.float64, count=len(pairs))
matrix = sparse.coo_matrix((data, (rows, cols)), shape=shape, dtype=np.float64).tocsr()
matrix.sum_duplicates()
matrix.eliminate_zeros()
return vocabulary, tokenized, matrix
def ppmi(counts, alpha=1.):
if not sparse.issparse(counts) or not np.isfinite(alpha) or alpha <= 0:
raise ValueError('Se necesita una matriz dispersa y alpha finito positivo')
# COO permite validar también DOK y LIL antes de agregar duplicados.
entries = counts.tocoo(copy=True)
if np.iscomplexobj(entries.data) or not np.isfinite(entries.data).all() or np.any(entries.data < 0):
raise ValueError('Los recuentos deben ser finitos y no negativos')
matrix = entries.tocsr().astype(np.float64, copy=False)
matrix.sum_duplicates()
if not np.isfinite(matrix.data).all():
raise ValueError('La suma de duplicados excede el rango numérico')
matrix.eliminate_zeros()
total = float(matrix.sum())
if not np.isfinite(total) or total <= 0:
raise ValueError('La masa total debe ser positiva y finita')
row_sum = np.asarray(matrix.sum(axis=1)).ravel()
col_sum = np.asarray(matrix.sum(axis=0)).ravel()
active = col_sum > 0
logits = np.log(col_sum[active])
logits = alpha * (logits - logits.max())
if not np.isfinite(logits).all():
raise ValueError('El exponente excede el rango numérico de las marginales')
log_q = np.full(col_sum.shape, -np.inf)
log_q[active] = logits - logsumexp(logits)
coo = matrix.tocoo()
values = np.maximum(np.log(coo.data) - np.log(row_sum[coo.row]) - log_q[coo.col], 0.)
result = sparse.coo_matrix((values, (coo.row, coo.col)), shape=matrix.shape).tocsr()
result.eliminate_zeros()
return result
def embeddings(matrix, dimensions, seed):
if matrix.nnz == 0 or min(matrix.shape) <= 1:
raise ValueError('No hay dimensiones suficientes para SVD dispersa')
k = min(dimensions, min(matrix.shape) - 1)
u, s, vt = svds(matrix, k=k, which='LM', random_state=seed)
order = np.argsort(s)[::-1]
u, s, vt = u[:, order], s[order], vt[order, :]
# U en valores singulares nulos no representa factores identificables.
tolerance = np.finfo(s.dtype).eps * max(matrix.shape) * s[0]
keep = s > tolerance
u, s, vt = u[:, keep], s[keep], vt[keep, :]
if not len(s):
raise ValueError('No hay valores singulares numéricamente positivos')
# Solo se densifican embeddings de tamaño vocabulario × k, no la matriz.
return s, {'U': u, 'U_sqrtSigma': u * np.sqrt(s), 'U_Sigma': u * s}, vt
def normalized_rows(matrix):
norm = np.linalg.norm(matrix, axis=1)
result = np.zeros_like(matrix)
valid = norm > 1e-12
result[valid] = matrix[valid] / norm[valid, None]
return result, valid
def neighbors(word, vocabulary, vectors, limit=10):
ids = {item: i for i, item in enumerate(vocabulary)}
index = ids.get(word)
vectors, valid = normalized_rows(vectors)
if index is None or not valid[index]:
return None
scores = vectors @ vectors[index]
choices = [(vocabulary[i], float(scores[i])) for i in range(len(vocabulary))
if i != index and valid[i]]
return sorted(choices, key=lambda item: (-item[1], item[0]))[:limit]
def benchmark(vocabulary, vectors):
ids = {word: i for i, word in enumerate(vocabulary)}
normalized, valid = normalized_rows(vectors)
covered, oov, near_zero = [], [], []
for a, b, human in GOLD:
if a not in ids or b not in ids:
oov.append((a, b))
elif not valid[ids[a]] or not valid[ids[b]]:
near_zero.append((a, b))
else:
covered.append((a, b, human, float(normalized[ids[a]] @ normalized[ids[b]])))
correlation = None
if len(covered) >= 3:
human, model = [row[2] for row in covered], [row[3] for row in covered]
if len(set(human)) > 1 and len(set(model)) > 1:
correlation = float(spearmanr(human, model).statistic)
return covered, oov, near_zero, correlation
def self_check():
matrix = sparse.csr_matrix([[2., 1., 0.], [0., 1., 3.], [1., 0., 2.]])
result = ppmi(matrix, alpha=1.)
assert np.isclose(result[0, 0], np.log(20 / 9))
assert np.isclose(result[0, 2], 0.)
assert np.isclose(ppmi(matrix, alpha=.75)[0, 0], .7591349139327976)
for fmt in ('dok', 'lil'):
assert np.allclose(ppmi(matrix.asformat(fmt)).toarray(), result.toarray())
# Duplicados se agregan antes de aplicar el logaritmo.
duplicate = sparse.coo_matrix(([1., 1., 1.], ([0, 0, 1], [0, 0, 1])), shape=(2, 2))
assert np.isclose(ppmi(duplicate)[0, 0], np.log(1.5))
invalid = sparse.coo_matrix(([-1., 2.], ([0, 0], [0, 0])), shape=(2, 2))
try:
ppmi(invalid)
except ValueError:
pass
else:
raise AssertionError('Un duplicado negativo no es un recuento válido')
vocab, _, pairs = cooccurrences(['a b', 'b a'], 1)
assert vocab == ['a', 'b'] and pairs[0, 1] == pairs[1, 0] == 2
try:
ppmi(sparse.csr_matrix((2, 2)))
except ValueError:
pass
else:
raise AssertionError('Una matriz vacía no define una distribución')
sample_vocab = ['dirty', 'narrow', 'student', 'pupil']
sample_vectors = np.array([[1., 0.], [0., 1.], [0., 0.], [1., 0.]])
covered, oov, near_zero, rho = benchmark(sample_vocab, sample_vectors)
assert len(covered) == 1 and len(oov) == 2 and len(near_zero) == 1 and rho is None
def main():
self_check()
print('NumPy', np.__version__, '| SciPy', scipy.__version__)
vocabulary, documents, counts = cooccurrences(DOCS, WINDOW)
print('Documentos:', len(documents), '| tokens:', sum(map(len, documents)),
'| vocabulario:', len(vocabulary), '| pares no nulos:', counts.nnz)
print('Ventana simétrica:', WINDOW, '| peso: uno | las ventanas no cruzan documentos')
print('SimLex: cuatro pares ilustrativos de la tabla 2, no una muestra representativa del conjunto.')
for alpha in (1., ALPHA):
matrix = ppmi(counts, alpha=alpha)
print('alpha:', alpha, '| PPMI no nula:', matrix.nnz)
if not matrix.nnz:
print('No hay PPMI positiva: no se ajusta la SVD')
continue
# El corpus mínimo no permite 100 dimensiones. Al usar un corpus mayor,
# el lector puede cambiar RANK a 100 y medir el coste por separado.
k = min(RANK, min(matrix.shape) - 1)
s, variants, _ = embeddings(matrix, k, SEED)
energy = float(np.sum(s ** 2) / matrix.multiply(matrix).sum())
print('Rango solicitado:', k, '| rango numérico retenido:', len(s),
'| valores singulares:', s.tolist(), '| energía retenida:', energy)
for name, vectors in variants.items():
word = 'lugar'
print(name, '| vecinos de', word, ':', neighbors(word, vocabulary, vectors))
covered, oov, near_zero, rho = benchmark(vocabulary, vectors)
print('SimLex tabla 2: cobertura', len(covered), '/', len(GOLD),
'| cubiertos', covered, '| OOV', oov,
'| norma ≤ 1e-12', near_zero, '| Spearman', rho)
if not covered:
print('Cobertura cero: correlación indefinida; prueba un corpus inglés real documentado en DOCS.')
print('La muestra de fragmentos no demuestra relaciones semánticas generales.')
main()+### Larger corpus and 100 dimensions, locally
To study a larger matrix without blocking Pyodide, run this variant locally in Python with NumPy and SciPy. It downloads English Project Gutenberg texts in fixed order, takes up to two million tokens, treats each paragraph as a document and saves URLs and SHA-256 hashes of files actually used. Hashes are pinned in the cell: if a source changes, check the new edition before updating the hash. Local tokenization retains words and internal apostrophes and excludes punctuation and digits, unlike the previous sample. Gutenberg listings describe these editions as public domain in the US; consult applicable law and its terms. Cutoff, minimum frequency and vocabulary limit are part of the experiment, not properties of language.
The calculation uses window 2, PPMI with α equal to 1 and 0.75 and up to 100 components; it compares U, U√Σ and UΣ. The four SimLex-999 pairs are only an illustrative check: coverage is reported and correlation is not calculated without enough pairs. A short run with ORYON_VERIFY_SHORT=1 reduces corpus and rank to check the pipeline; it is not a measurement of the full configuration. The cell writes its report to ORYON_OUTPUT and downloads into ORYON_CORPUS_DIR, without relying on platform files.
"""PPMI y SVD de rango 100 en un corpus reproducible de Project Gutenberg.
Instala NumPy y SciPy en el entorno local. La opción ORYON_VERIFY_SHORT=1
reduce datos, vocabulario y rango para una comprobación funcional. Los libros
son de dominio público en EE. UU. según sus fichas; consulta la normativa
aplicable y https://www.gutenberg.org/policy/license.html antes de redistribuir.
"""
import hashlib
import json
import os
import re
import unicodedata
import urllib.request
from collections import Counter
from pathlib import Path
import numpy as np
from scipy import sparse
from scipy.sparse.linalg import svds
from scipy.special import logsumexp
from scipy.stats import spearmanr
SHORT = os.environ.get('ORYON_VERIFY_SHORT') == '1'
BOOKS = [2600, 1184, 2701, 28054, 2554, 1342, 4300, 76, 98]
EXPECTED_SHA256 = {
2600: 'e4bcf9042609b62c7de72a6f1b311f54c412943a9d641b7efcf79a464b5f31c8',
1184: '649dc5b18efc095035fd29216bdcdfca6744ed3dccacd7bfc11859451004e327',
2701: 'f12eb530502755ef2b8f535e2ecef3e95802eab584e60ac7992ccf856256fdbe',
28054: '5c82b5038b7759b306a31b580d9407b12ee1890694c422d33c72cca76be8e3b2',
2554: '440dae3c3b6a4f749623ab5cc05ba492cc27f6e705fa9675e0b87568e21586dd',
1342: '81300b79e8a8d65ac530a97578417d06137e3bbc90622a10a65e5036183d2500',
4300: '3b79da676aad421c019dafe2645a7d6b38a094a356e07d1ee90ca9e5659e5499',
76: '871bff91213ee10c95a7e05a84ca5de423ff7cd0a4dd4aafc8bea992acd6d1da',
98: 'e3dfeb67feb904ac0f73a35204a175c58248422c2be8556802cb8820d958d67c',
}
if SHORT:
BOOKS = BOOKS[:1]
MAX_TOKENS = 12000 if SHORT else 2_000_000
MAX_VOCAB = 500 if SHORT else 10_000
MIN_COUNT = 3 if SHORT else 5
RANK = 8 if SHORT else 100
WINDOW = 2
SEED = 17040
CORPUS_DIR = Path(os.environ.get('ORYON_CORPUS_DIR', 'corpus_gutenberg_lsa'))
OUTPUT = Path(os.environ.get('ORYON_OUTPUT', 'resultados_lsa'))
TOKEN = re.compile(r"[^\W\d_]+(?:['’][^\W\d_]+)*", re.UNICODE)
GOLD = [('dirty', 'narrow', .30), ('student', 'pupil', 9.40),
('smart', 'dumb', .60), ('attention', 'awareness', 8.73)]
def download(book):
url = f'https://www.gutenberg.org/files/{book}/{book}-0.txt'
CORPUS_DIR.mkdir(parents=True, exist_ok=True)
path = CORPUS_DIR / f'{book}-0.txt'
if not path.exists():
partial = path.with_suffix('.part')
try:
with urllib.request.urlopen(url, timeout=90) as response, partial.open('wb') as out:
size = 0
while block := response.read(1 << 20):
size += len(block)
if size > 20 * 1024 * 1024:
raise ValueError('El libro supera el límite de descarga')
out.write(block)
partial.replace(path)
finally:
partial.unlink(missing_ok=True)
raw = path.read_bytes()
if len(raw) > 20 * 1024 * 1024:
raise ValueError('El libro local supera el límite de tamaño')
sha = hashlib.sha256(raw).hexdigest()
if sha != EXPECTED_SHA256[book]:
raise ValueError(f'Cambió la huella del libro {book}; verifica la fuente antes de actualizarla')
text = raw.decode('utf-8-sig').replace('\r\n', '\n')
start = re.search(r'(?im)^\*{3}\s*START OF (?:THE |THIS )?PROJECT GUTENBERG EBOOK[^\n]*', text)
end = re.search(r'(?im)^\*{3}\s*END OF (?:THE |THIS )?PROJECT GUTENBERG EBOOK[^\n]*', text)
if start is None or end is None or start.end() >= end.start():
raise ValueError(f'No se reconocen los límites del libro {book}')
return text[start.end():end.start()], {'id': book, 'url': url,
'sha256': sha, 'bytes': len(raw)}
def corpus():
documents, manifest, remaining = [], [], MAX_TOKENS
for book in BOOKS:
text, info = download(book)
manifest.append(info)
for paragraph in re.split(r'\n\s*\n', text):
tokens = TOKEN.findall(unicodedata.normalize('NFC', paragraph).lower())
if not tokens:
continue
tokens = tokens[:remaining]
documents.append(tokens)
remaining -= len(tokens)
if not remaining:
return documents, manifest
return documents, manifest
def build_counts(documents):
frequency = Counter(token for doc in documents for token in doc)
words = sorted((item for item in frequency.items() if item[1] >= MIN_COUNT),
key=lambda item: (-item[1], item[0]))[:MAX_VOCAB]
vocab = [word for word, _ in words]
ids = {word: i for i, word in enumerate(vocab)}
pairs = Counter()
for doc in documents:
encoded = [ids.get(word, -1) for word in doc]
for i, word in enumerate(encoded):
if word < 0:
continue
for j in range(max(0, i - WINDOW), min(len(encoded), i + WINDOW + 1)):
if i != j and encoded[j] >= 0:
pairs[(word, encoded[j])] += 1
if len(vocab) < 3 or not pairs:
raise ValueError('El corpus seleccionado no tiene suficientes pares')
row = np.fromiter((pair[0] for pair in pairs), dtype=np.int32, count=len(pairs))
col = np.fromiter((pair[1] for pair in pairs), dtype=np.int32, count=len(pairs))
data = np.fromiter(pairs.values(), dtype=np.float64, count=len(pairs))
matrix = sparse.coo_matrix((data, (row, col)), shape=(len(vocab), len(vocab))).tocsr()
return vocab, matrix
def ppmi(counts, alpha):
row = np.asarray(counts.sum(axis=1)).ravel()
col = np.asarray(counts.sum(axis=0)).ravel()
active = col > 0
if not active.any() or not np.isfinite(alpha) or alpha <= 0:
raise ValueError('Distribución de contexto inválida')
logs = alpha * (np.log(col[active]) - np.log(col[active]).max())
log_q = np.full(col.shape, -np.inf)
log_q[active] = logs - logsumexp(logs)
source = counts.tocoo()
value = np.maximum(np.log(source.data) - np.log(row[source.row]) - log_q[source.col], 0.)
result = sparse.coo_matrix((value, (source.row, source.col)), shape=counts.shape).tocsr()
result.eliminate_zeros()
return result
def representation(matrix):
k = min(RANK, min(matrix.shape) - 1)
u, singular, vt = svds(matrix, k=k, which='LM', random_state=SEED)
order = np.argsort(singular)[::-1]
u, singular = u[:, order], singular[order]
tolerance = np.finfo(singular.dtype).eps * max(matrix.shape) * singular[0]
keep = singular > tolerance
u, singular = u[:, keep], singular[keep]
if not len(singular):
raise ValueError('La matriz no tiene valores singulares positivos')
return singular, {'U': u, 'U_sqrtSigma': u * np.sqrt(singular), 'U_Sigma': u * singular}
def inspect(vocab, vectors):
norms = np.linalg.norm(vectors, axis=1)
unit = np.zeros_like(vectors)
valid = norms > 1e-12
unit[valid] = vectors[valid] / norms[valid, None]
ids = {word: i for i, word in enumerate(vocab)}
fallback = next((vocab[i] for i in range(len(vocab)) if valid[i]), None)
if fallback is None:
raise ValueError('Ningún vector tiene norma suficiente')
neighbors = {}
for word in dict.fromkeys(('student', 'human', 'love', 'war', fallback)):
if word not in ids or not valid[ids[word]]:
neighbors[word] = None
continue
index = ids[word]
scores = unit @ unit[index]
options = [(vocab[i], float(scores[i])) for i in range(len(vocab)) if i != index and valid[i]]
neighbors[word] = sorted(options, key=lambda pair: (-pair[1], pair[0]))[:10]
covered, oov, zero = [], [], []
for a, b, rating in GOLD:
if a not in ids or b not in ids:
oov.append((a, b))
elif not valid[ids[a]] or not valid[ids[b]]:
zero.append((a, b))
else:
covered.append((a, b, rating, float(unit[ids[a]] @ unit[ids[b]])))
rho = None
if len(covered) >= 3:
human = [pair[2] for pair in covered]
predicted = [pair[3] for pair in covered]
if len(set(human)) > 1 and len(set(predicted)) > 1:
rho = float(spearmanr(human, predicted).statistic)
return {'neighbors': neighbors, 'fallback_word': fallback, 'covered': covered,
'oov': oov, 'zero_norm': zero, 'spearman': rho}
def main():
reference = sparse.csr_matrix([[2., 1., 0.], [0., 1., 3.], [1., 0., 2.]])
assert np.isclose(ppmi(reference, .75)[0, 0], .7591349139327976)
documents, manifest = corpus()
vocab, counts = build_counts(documents)
assert (counts != counts.T).nnz == 0
result = {'short': SHORT, 'seed': SEED, 'window': WINDOW, 'token_limit': MAX_TOKENS,
'tokens': sum(map(len, documents)), 'documents': len(documents),
'vocabulary': len(vocab), 'count_nnz': int(counts.nnz), 'sources': manifest,
'gold_source': 'https://aclanthology.org/J15-4004.pdf tabla 2', 'runs': {}}
for alpha in (1., .75):
weighted = ppmi(counts, alpha)
if weighted.nnz == 0:
raise ValueError('Sin PPMI positiva para calcular la SVD')
singular, variants = representation(weighted)
result['runs'][str(alpha)] = {'ppmi_nnz': int(weighted.nnz),
'rank': len(singular), 'singular_values': singular.tolist(),
'variants': {name: inspect(vocab, vectors) for name, vectors in variants.items()}}
print('alpha', alpha, 'rango retenido', len(singular), 'PPMI no nula', weighted.nnz)
for name in variants:
entry = result['runs'][str(alpha)]['variants'][name]
print(name, 'vecinos de', entry['fallback_word'], ':', entry['neighbors'][entry['fallback_word']],
'| cobertura SimLex:', len(entry['covered']), '/', len(GOLD),
'| Spearman:', entry['spearman'])
OUTPUT.mkdir(parents=True, exist_ok=True)
(OUTPUT / 'resumen.json').write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding='utf-8')
print('Tokens:', result['tokens'], '| párrafos:', result['documents'], '| vocabulario:', result['vocabulary'])
print('Fuentes, hashes, vecinos y cobertura:', OUTPUT / 'resumen.json')
print('Cuatro pares ilustrativos no prueban calidad general; compara con un conjunto mayor separado.')
if __name__ == '__main__':
main()npm run lab and open the connection link.TF-IDF and LSA with scikit-learn
The second lab compares counts and weights with explicit options, fits an SVD on training and searches documents using a query transformed with the same vocabulary. Its check must compare complete aligned matrices and document that scikit-learn’s default formula includes smoothing, offset and normalization.
The second cell builds a sparse document-by-term matrix and compares its TF-IDF with TfidfVectorizer, fixing tokenization, vocabulary, the smoothed formula with offset and L2 norm. It then checks projection of the same documents with TruncatedSVD and transforms a query with learned vocabulary and IDF. A query with zero latent vector is declared undefined.
It uses the same short excerpts; you can replace DOCS and QUERY with documents and a query of documented provenance. Do not interpret this sample’s ranking as a general search evaluation.
"""TF-IDF propio y scikit-learn con LSA y consulta, muestra Pyodide.
Fragmentos de Miguel de Cervantes, Don Quijote, primera parte, capítulos I y
II, Project Gutenberg 2000: https://www.gutenberg.org/files/2000/2000-0.txt .
Edición preparada por un voluntario anónimo y Joaquín Cuenca Abela; la ficha
declara dominio público en EE. UU. Consulta la política de marca y la ley local
antes de redistribuir: https://www.gutenberg.org/policy/license.html .
Se pueden sustituir DOCS y QUERY por datos propios de procedencia documentada.
"""
import re
import unicodedata
from collections import Counter
import numpy as np
import scipy
from scipy import sparse
import sklearn
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction.text import TfidfVectorizer
DOCS = [
'En un lugar de la Mancha,',
'de cuyo nombre no quiero acordarme',
'Hechas, pues, estas prevenciones,',
'no quiso aguardar más tiempo',
]
QUERY = 'la Mancha'
PATTERN = r"\w+(?:['’]\w+)*|[^\w\s]"
REGEX = re.compile(PATTERN, re.UNICODE)
SEED = 17040
RANK = 2
def normalize(text):
return unicodedata.normalize('NFC', text).lower()
def counts(documents, vocabulary=None):
tokenized = [REGEX.findall(normalize(text)) for text in documents]
if vocabulary is None:
vocabulary = sorted({token for doc in tokenized for token in doc})
if not vocabulary or len(set(vocabulary)) != len(vocabulary):
raise ValueError('El vocabulario debe ser no vacío y sin duplicados')
ids = {token: index for index, token in enumerate(vocabulary)}
rows, cols, data = [], [], []
for row, tokens in enumerate(tokenized):
for token, count in Counter(tokens).items():
if token in ids:
rows.append(row)
cols.append(ids[token])
data.append(count)
return vocabulary, sparse.csr_matrix((np.asarray(data, dtype=float), (rows, cols)),
shape=(len(documents), len(vocabulary)))
def own_tfidf(train_counts):
if not sparse.issparse(train_counts) or train_counts.shape[0] == 0:
raise ValueError('Recuentos inválidos o ausencia de documentos')
entries = train_counts.tocoo(copy=True)
if np.iscomplexobj(entries.data) or np.any(entries.data < 0) or not np.isfinite(entries.data).all():
raise ValueError('Recuentos inválidos o ausencia de documentos')
matrix = entries.tocsr().astype(float, copy=False)
matrix.sum_duplicates()
if not np.isfinite(matrix.data).all():
raise ValueError('La suma de duplicados excede el rango numérico')
matrix.eliminate_zeros()
indicators = matrix.copy()
indicators.data[:] = 1.
df = np.asarray(indicators.sum(axis=0)).ravel()
# Convención de TfidfVectorizer: suavizado + 1 y norma L2 por documento.
idf = np.log((1 + matrix.shape[0]) / (1 + df)) + 1
return idf, apply_idf(matrix, idf)
def apply_idf(matrix, idf):
weighted = matrix.multiply(idf).tocsr()
norms = np.sqrt(np.asarray(weighted.multiply(weighted).sum(axis=1)).ravel())
inverse = np.zeros_like(norms)
inverse[norms > 0] = 1 / norms[norms > 0]
return sparse.diags(inverse) @ weighted
def sparse_max_difference(a, b):
difference = (a - b).tocsr()
difference.eliminate_zeros()
return float(np.max(np.abs(difference.data))) if difference.nnz else 0.
def cosine_ranking(vectors, query):
qnorm = np.linalg.norm(query)
if qnorm <= 1e-12:
return None
norms = np.linalg.norm(vectors, axis=1)
scores = [(index, float(row @ query / (norms[index] * qnorm)))
for index, row in enumerate(vectors) if norms[index] > 1e-12]
return sorted(scores, key=lambda item: (-item[1], item[0]))
def main():
print('NumPy', np.__version__, '| SciPy', scipy.__version__, '| scikit-learn', sklearn.__version__)
invalid = sparse.coo_matrix(([-1., 2.], ([0, 0], [0, 0])), shape=(1, 1))
try:
own_tfidf(invalid)
except ValueError:
pass
else:
raise AssertionError('Un duplicado negativo no es un recuento válido')
normalized_docs = [normalize(doc) for doc in DOCS]
vocabulary, matrix = counts(normalized_docs)
idf, own = own_tfidf(matrix)
vectorizer = TfidfVectorizer(token_pattern=PATTERN, lowercase=False,
norm='l2', use_idf=True, smooth_idf=True,
sublinear_tf=False, dtype=np.float64,
vocabulary={term: i for i, term in enumerate(vocabulary)})
reference = vectorizer.fit_transform(normalized_docs)
error = sparse_max_difference(own, reference)
assert error < 1e-12 and np.allclose(idf, vectorizer.idf_, atol=1e-12, rtol=1e-12)
print('Documentos:', len(DOCS), '| vocabulario:', len(vocabulary), '| entradas no nulas:', own.nnz)
print('Diferencia máxima de TF-IDF propio frente a sklearn:', error)
print('Convención idf = ln((1+D)/(1+df))+1, tf por recuento y norma L2.')
# ARPACK requiere k estrictamente menor que las dos dimensiones.
k = min(RANK, min(own.shape) - 1)
if k < 1:
raise ValueError('La matriz es demasiado pequeña para SVD truncada')
lsa = TruncatedSVD(n_components=k, algorithm='arpack', random_state=SEED)
doc_vectors = lsa.fit_transform(reference)
projected_own = own @ lsa.components_.T
assert np.allclose(doc_vectors, projected_own, atol=1e-10, rtol=1e-10)
print('Rango:', k, '| valores singulares:', lsa.singular_values_.tolist())
print('Error máximo entre proyecciones propias y sklearn:', float(np.max(np.abs(doc_vectors - projected_own))))
# Comparación propia de valores y error óptimo solo en la matriz pequeña;
# no convertir arbitrariamente una matriz grande a densa.
if own.shape[0] * own.shape[1] <= 4096:
singular = np.linalg.svd(own.toarray(), compute_uv=False)
assert np.allclose(singular[:k], lsa.singular_values_, rtol=1e-7, atol=1e-9)
print('Valores singulares por NumPy:', singular[:k].tolist())
_, query_counts = counts([QUERY], vocabulary)
query_tfidf = apply_idf(query_counts, idf)
query_ref = vectorizer.transform([normalize(QUERY)])
assert sparse_max_difference(query_tfidf, query_ref) < 1e-12
query_vector = np.asarray(query_tfidf @ lsa.components_.T).ravel()
ranking = cosine_ranking(doc_vectors, query_vector)
if ranking is None:
print('Consulta sin vector latente no nulo: coseno indefinido.')
else:
print('Consulta:', QUERY, '| ranking por coseno latente:', ranking)
for index, score in ranking:
print(' Documento', index, '|', score, '|', DOCS[index])
print('Muestra de cuatro fragmentos: las posiciones no prueban calidad de búsqueda general.')
main()Exercises
Step 1 of 3. What expression results from averaging PMI under the joint?
def ppmi(C, alpha):
passFurther connections
Low-rank approximation connects with Low-rank approximation and structure choice with Sparse matrix formats. Nonnegative factorization imposes other constraints on document matrices; modern vector search combines dense representations with lexical methods. The next lessons introduce representations with trained parameters, without assuming that abandoning counts alone resolves polysemy or corpus biases.