AI Wiki中文/EN

GloVe: fit the counts, then inspect the geometry

GloVe

Build weighted co-occurrences, derive the log-count regression and gradients, and test why matching scores do not fix cosine geometry.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Count shared contexts before fitting a vector

The invented sentence a b a contains two occurrences of a. With a symmetric window of radius two and inverse-distance weights, the two neighboring a–b pairs contribute a total of 2 to each direction. The two a positions are two places apart, contributing 1/2 in each direction to the same type pair (a,a). Its diagonal count is therefore 1, even though a position is never paired with itself.

That small example exposes a choice hidden by the phrase “co-occurrence matrix”: what counts as a context, where windows stop, whether directions are merged and how distances are weighted. GloVe learns vectors by fitting a weighted function of such corpus-wide counts. It uses distinct word and context vectors plus bias terms. Original GloVe paper

Word2vec constructs local prediction events; GloVe can aggregate repeated pairs before optimizing its count-based objective. A smaller training objective means a better fit to that declared matrix. Whether the resulting vectors help a language task needs a separate evaluation.

Computed cooccurrences and weighted fitting, followed by a score-preserving transformation that changes word angles. Teaching xmax is 3, not the paper default.
Computed cooccurrences and weighted fitting, followed by a score-preserving transformation that changes word angles. Teaching xmax is 3, not the paper default.

From context ratios to a weighted regression

Define X before taking its logarithm

Let a sentence contain tokens w_1,…,w_T. For window radius R, our symmetric inverse-distance count sums over ordered positions in the same sentence:

Xij=∑sentences d ∑s,t∈d0<∣s−t∣≤R1[ws=i, wt=j]∣s−t∣.X_{ij}=\sum_{\text{sentences }d}\ \sum_{\substack{s,t\in d\\0<|s-t|\le R}} \frac{\mathbf 1[w_s=i,\ w_t=j]}{|s-t|}.

The sum is over occurrences, so repeated word types can produce diagonal entries. It never crosses sentence boundaries. Fractional counts arise naturally from distance weights; X is not necessarily an integer matrix. A radius-one window gives every included occurrence pair weight one.

The original author counting code supports inverse-distance weighting and a symmetric option. It also skips out-of-vocabulary tokens and resets history at line boundaries. Our Python starts from supplied sentence lists with an unpruned vocabulary, so its counting policy is explicit rather than a claim of full file-format equivalence. Pinned co-occurrence code, lines 305–350

For a b a, the default radius-two matrix in vocabulary order [a,b] is [[1,2],[2,0]]. Disabling distance weighting changes the diagonal from 1 to 2. Disabling symmetry while retaining distance weights gives [[0.5,1],[1,0]] under our convention: current-word type is the row, earlier context type is the column.

Why compare ratios?

Let X_i be the sum of row i. When X_i>0, normalized co-occurrences define an empirical context distribution. For two rows i and j and a probe context k with positive relevant entries:

P(k∣i)=XikXi,Rijk=P(k∣i)P(k∣j).P(k\mid i)=\frac{X_{ik}}{X_i},\qquad R_{ijk}=\frac{P(k\mid i)}{P(k\mid j)}.

A ratio above one means k is relatively more frequent in i’s context distribution; below one favors j. The original paper uses such ratios to motivate encoding distinctions between target words. This is a design motivation based on counts, not a guarantee that every semantic distinction appears in those ratios. GloVe, co-occurrence-ratio discussion

Taking logs separates pair-specific and row-specific quantities:

log⁡Rijk=log⁡Xik−log⁡Xjk−log⁡Xi+log⁡Xj.\log R_{ijk}=\log X_{ik}-\log X_{jk}-\log X_i+\log X_j.

The last two terms depend on the target rows, not on the probe k. That suggests giving each row a bias while using dot products for interactions. Ratios involving a zero denominator are not finite evidence to insert into this equation; the derivation above explicitly requires positive values.

The score, biases and residual

Let u_i and v_j be D-dimensional word and context vectors, and b_i and c_j their scalar biases. Define the fitted score and residual on an observed pair:

sij=ui⊤vj+bi+cj,rij=sij−log⁡Xij.s_{ij}=u_i^\top v_j+b_i+c_j,\qquad r_{ij}=s_{ij}-\log X_{ij}.

A row bias can absorb effects shared across its contexts; a column bias can absorb effects shared across target words. Without them, vector dot products would have to carry all of that variation. This does not mean a fitted bias is uniquely identifiable or equals a particular frequency statistic exactly.

The paper’s equation 8 sums weighted squared residuals. Our lab uses one half of that sum, making its derivative cleaner; the pinned implementation also records a half-scaled cost:

L=12∑(i,j):Xij>0f(Xij)rij,2.L=\frac12\sum_{(i,j):X_{ij}>0}f(X_{ij})r_{ij}^{,2}.

Multiplying the whole objective by 1/2 preserves its minimizers but changes the gradient scale. Do not compare raw loss values or learning rates without accounting for the convention. GloVe, equation 8 Pinned objective code, lines 186–202

The weighting function is:

f(x)={0x=0,(x/xmax⁡)α0<x<xmax⁡,1x≥xmax⁡,xmax⁡>0,0<α≤1.f(x)=\begin{cases} 0&x=0,\\ (x/x_{\max})^{\alpha}&0<x<x_{\max},\\ 1&x\ge x_{\max}, \end{cases}\qquad x_{\max}>0,\quad 0<\alpha\le1.

It reduces the influence of weakly observed pairs and caps the weight of large counts. The original paper uses α=3/4 and x_max=100 in its reported experiments; this tiny lab chooses x_max=3 to make the weighting visible in a small corpus. That is a teaching parameter, not a new recommended universal default. GloVe, equation 9 and surrounding text

A zero cell is omitted from the regression. The code does not compute log0 and later multiply by zero, nor does it replace the target with log(1+0)=0. Assigning a zero regression target to every absent pair would define a different objective. Thus an unobserved pair can have a nonzero fitted score without contributing any direct loss here.

Gradients follow the weighted residual

Set Δ_ij=f(X_ij)r_ij on positive cells and zero elsewhere. Differentiating each occurrence of a parameter gives:

∇uiL=∑jΔijvj,∇vjL=∑iΔijui,∂L∂bi=∑jΔij,∂L∂cj=∑iΔij.\nabla_{u_i}L=\sum_j\Delta_{ij}v_j,\qquad \nabla_{v_j}L=\sum_i\Delta_{ij}u_i,\qquad \frac{\partial L}{\partial b_i}=\sum_j\Delta_{ij},\qquad \frac{\partial L}{\partial c_j}=\sum_i\Delta_{ij}.

There is no extra factor of two because of our half-scaled objective. In matrix form, let U collect word rows and W collect context rows; the two vector gradients are ΔW and ΔᵀU. An isolated type with no positive row or column receives no direct gradient from this objective. All-zero co-occurrence data therefore has zero loss and zero gradient for every parameter setting; “perfect loss” in that case provides no learned context information.

The objective is not jointly convex in the two vector tables: their dot product couples unknown parameters. The same fitted scores can also be represented in multiple ways. These facts matter when comparing parameter files, even when two optimizers have similar losses.

A good fit does not determine a unique geometry

For any invertible D×D matrix A, transform the row-vector tables as follows while leaving biases unchanged:

U′=UA,W′=WA−⊤,U′W′⊤=UW⊤.U'=UA,\qquad W'=WA^{-\top},\qquad U'W'^{\top}=UW^{\top}.

Every word–context score and the objective stay unchanged. A non-orthogonal A can change cosine similarities within U. For example, the word vectors [1,0] and [1,1] have cosine 1/√2, about 0.707107. With A=diag(2,0.5), they become [2,0] and [2,0.5], whose cosine is 2/√4.25, about 0.970143. Transforming the context table inversely preserves the cross-table scores despite that change.

Biases also admit a simple ambiguity: add a constant to every b_i and subtract it from every c_j. Scores do not change. These are algebraic checks on the model, not claims that training will explore all such transformations or that every exported embedding performs equally well.

The paper reports using the sum of its word and context vectors as the final word representation. Our output includes both tables and their sum, so the export choice is visible. The regression objective alone does not certify cosine neighborhoods for every possible choice. GloVe, §4.2

Fit a small matrix and inspect what was actually fitted

Save the full block as glove.py and run python3 glove.py. The checked environment is Python 3.12.4 with NumPy 1.26.4. The original seven-sentence corpus matches the Word2vec lab so that the counting policies can be compared, but their losses are not the same measurement.

"""Original tiny GloVe objective and co-occurrence laboratory; NumPy 1.26.4.

Uses a half-scaled weighted-square sum over positive counts and deterministic
full-batch descent. It does not reproduce author AdaGrad/Hogwild code, claim
semantic quality, or replace absent co-occurrences by observed zero targets.
"""
from collections import Counter
import json,math
import numpy as np


def positive_integer(value):
    if type(value) is not int or value<1:raise ValueError('Positive integer required')
    return value


def cooccurrences(sentences,window=2,weighted=True,symmetric=True):
    positive_integer(window)
    if type(weighted) is not bool or type(symmetric) is not bool:raise ValueError('Boolean counting policies required')
    if not isinstance(sentences,(list,tuple)) or not sentences:raise ValueError('Tokenized sentence collection required')
    rows=[]
    for row in sentences:
        if not isinstance(row,(list,tuple)) or any(not isinstance(w,str) or not w or any(0xD800<=ord(c)<=0xDFFF for c in w) for w in row):raise ValueError('Nonempty Unicode tokens without surrogates required')
        rows.append(list(row))
    counts=Counter(w for row in rows for w in row);words=tuple(sorted(counts))
    if not words:raise ValueError('No training words')
    index={w:i for i,w in enumerate(words)};x=np.zeros((len(words),len(words)))
    for row in rows:
        for i,w in enumerate(row):
            for j in range(max(0,i-window),i):
                amount=1/(i-j) if weighted else 1.;a,b=index[w],index[row[j]]
                x[a,b]+=amount
                if symmetric:x[b,a]+=amount
    return {'vocabulary':words,'index':index,'matrix':x,'token_counts':dict(counts),'window':window,'weighted':weighted,'symmetric':symmetric}


def initialize(size,dim=3,seed=13):
    positive_integer(size);positive_integer(dim)
    if type(seed) is not int or seed<0:raise ValueError('Nonnegative integer seed required')
    rng=np.random.default_rng(seed)
    return {'word':rng.uniform(-.1,.1,(size,dim)),'context':rng.uniform(-.1,.1,(size,dim)),
            'word_bias':np.zeros(size),'context_bias':np.zeros(size)}


def checked(model,x):
    keys={'word','context','word_bias','context_bias'}
    if not isinstance(model,dict) or set(model)!=keys:raise ValueError('Two matrices and two bias vectors required')
    p={k:np.asarray(v,dtype=float) for k,v in model.items()};a=p['word'];x=np.asarray(x,dtype=float)
    if a.ndim!=2 or not all(a.shape) or p['context'].shape!=a.shape or p['word_bias'].shape!=(len(a),) or p['context_bias'].shape!=(len(a),):raise ValueError('Parameter shapes disagree')
    if x.shape!=(len(a),len(a)) or not np.isfinite(x).all() or np.any(x<0) or any(not np.isfinite(v).all() for v in p.values()):raise ValueError('Finite parameters and nonnegative square counts required')
    return p,x


def weighting(x,xmax=3.,alpha=.75):
    if any(isinstance(v,bool) or not isinstance(v,(int,float)) or not math.isfinite(v) for v in (xmax,alpha)) or xmax<=0 or not 0<alpha<=1:raise ValueError('Positive xmax and alpha in (0,1] required')
    x=np.asarray(x,dtype=float)
    if not np.isfinite(x).all() or np.any(x<0):raise ValueError('Nonnegative finite counts required')
    f=np.zeros_like(x);low=(x>0)&(x<xmax);f[low]=(x[low]/xmax)**alpha;f[x>=xmax]=1.
    return f


def loss_gradient(model,x,xmax=3.,alpha=.75):
    p,x=checked(model,x);mask=x>0;f=weighting(x,xmax,alpha);target=np.zeros_like(x);target[mask]=np.log(x[mask])
    with np.errstate(over='raise',invalid='raise'):
        try:
            prediction=p['word']@p['context'].T+p['word_bias'][:,None]+p['context_bias'][None,:]
            residual=np.zeros_like(x);residual[mask]=prediction[mask]-target[mask]
            delta=f*residual;loss=float(.5*np.sum(delta*residual))
            grad={'word':delta@p['context'],'context':delta.T@p['word'],'word_bias':delta.sum(axis=1),'context_bias':delta.sum(axis=0)}
        except FloatingPointError as error:raise ValueError('Objective arithmetic overflow') from error
    if not math.isfinite(loss) or any(not np.isfinite(g).all() for g in grad.values()):raise ValueError('Nonfinite loss or gradient')
    return loss,grad,{'prediction':prediction,'residual':residual,'weight':f,'observed':mask,'target':target}


def train(initial,x,steps=100,rate=.1,xmax=3.,alpha=.75):
    checked(initial,x)
    if type(steps) is not int or steps<0:raise ValueError('Nonnegative integer step count required')
    if isinstance(rate,bool) or not isinstance(rate,(int,float)) or not math.isfinite(rate) or rate<=0:raise ValueError('Positive finite step required')
    model={k:np.array(v,dtype=float,copy=True) for k,v in initial.items()};value,grad,_=loss_gradient(model,x,xmax,alpha);trace=[value]
    for _ in range(steps):
        norm=sum(float(np.sum(g*g)) for g in grad.values())
        if norm<1e-24:break
        step=rate
        for attempt in range(40):
            candidate={k:model[k]-step*grad[k] for k in model}
            try:new,ng,_=loss_gradient(candidate,x,xmax,alpha)
            except ValueError:new=math.inf
            if new<=value-1e-4*step*norm:break
            step*=.5
        else:raise ValueError('No decreasing step found')
        model,value,grad=candidate,new,ng;trace.append(value)
    return model,trace


def cosine(a,b):
    a=np.asarray(a,dtype=float);b=np.asarray(b,dtype=float)
    if a.ndim!=1 or b.shape!=a.shape or not np.isfinite(a).all() or not np.isfinite(b).all():raise ValueError('Finite vectors with matching dimensions required')
    na=math.hypot(*a);nb=math.hypot(*b)
    if not math.isfinite(na) or not math.isfinite(nb):raise ValueError('Norm overflow')
    return None if not na or not nb else float((a/na)@(b/nb))


def demo():
    sentences=[['blue','bird','flies'],['red','bird','flies'],['blue','fish','swims'],['red','fish','swims']]+[['blue','bird','flies']]*3
    counts=cooccurrences(sentences);x=counts['matrix'];model,trace=train(initialize(len(x)),x)
    _,_,d=loss_gradient(model,x);fits=[]
    for i,j in zip(*np.nonzero(x)):
        fits.append({'word':counts['vocabulary'][i],'context':counts['vocabulary'][j],'count':float(x[i,j]),'weight':float(d['weight'][i,j]),
                     'log_target':float(d['target'][i,j]),'score':float(d['prediction'][i,j]),'residual':float(d['residual'][i,j])})
    a=np.array([[1.,0.],[1.,1.]]);b=np.array([[.2,.5],[-.4,.3]]);transform=np.diag([2.,.5]);aa=a@transform;bb=b@np.linalg.inv(transform).T
    return {'training':sentences,'vocabulary':list(counts['vocabulary']),'cooccurrences':x.tolist(),'weighting':{'xmax':3.,'alpha':.75},
            'loss_trace':trace,'observed_fits':fits,'unobserved_pairs':int(np.count_nonzero(x==0)),
            'word_vectors':model['word'].tolist(),'context_vectors':model['context'].tolist(),'sum_vectors':(model['word']+model['context']).tolist(),
            'word_bias':model['word_bias'].tolist(),'context_bias':model['context_bias'].tolist(),
            'nonidentifiability':{'old_pair_scores':(a@b.T).tolist(),'new_pair_scores':(aa@bb.T).tolist(),
                                 'old_word_cosine':cosine(a[0],a[1]),'new_word_cosine':cosine(aa[0],aa[1])},
            'scope':'Original tiny symmetric inverse-distance counts; sentence boundaries retained. Half-scaled weighted-square sum on positive cells only; xmax3 is a teaching choice, not paper default100. Full-batch backtracking, not author AdaGrad/Hogwild. No semantic-quality benchmark.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The output contains the full co-occurrence matrix, one record per positive pair, the weight, log-count target, fitted score and residual, along with both vector tables and biases. Absent cells are counted separately. The target array inside the computation uses zeros for storage outside the observed mask; those entries are not regression targets and are never added to the loss.

Over 100 accepted full-batch steps, this small half-scaled objective falls from about 5.584310 to 0.002498. The line search evaluates the same fixed count matrix and halves its step until the sufficient-decrease condition holds. The code’s adaptive choice of a global step is distinct from the per-parameter adaptive updates and asynchronous training in the author implementation. Pinned objective/update block

The nonidentifiability output uses a separate two-vector hand example. It prints equal cross-table scores before and after the invertible transform, but different word–word cosines. This example does not rely on the particular optimizer reaching an exact factorization.

Dense teaching code and sparse production work

Let T be the total token count, S the sentence count, V the vocabulary size, R the window radius and D the vector dimension. Under expected hashing cost and bounded-length token comparisons, constructing the vocabulary costs O(T+S+V log V). This implementation then allocates a dense V×V matrix and scans O(TR) occurrence pairs, so its count stage also includes O(V²) initialization and storage. With variable-length strings, validation, hashing and comparison add their own character costs.

Each objective evaluation forms all V² dot-product scores and dense gradient products, taking O(V²D) arithmetic work and O(V²+VD) storage. The loss mask ignores absent cells but does not make this implementation sparse. A sparse positive-pair representation with B nonzero cells can compute the relevant score and gradient contributions in O(BD); it is a separate implementation choice.

A training step may call the objective repeatedly during backtracking, up to 40 proposals. Initial count construction is not repeated. Finite checks reject invalid or overflowing scores and gradients instead of returning a misleading successful loss. The code is for small inspectable matrices, not a corpus-scale memory or throughput benchmark.

Counts reflect both language and the counting policy

An inverse-distance window is one context definition. Directed windows, syntactic contexts, token normalization, vocabulary pruning and sentence segmentation can produce different matrices from the same text. In particular, dropping tokens before counting can change effective distances. Persist the complete policy with a model.

Omitting zero cells avoids undefined log arithmetic and concentrates work on observations. It also means a small observed-cell residual says nothing directly about unseen pairs. Very rare observations may be noisy, while frequent associations may reflect a narrow domain or undesirable correlations. Weighting is a modeling choice, not an automatic correction for those issues.

Truncated SVD can be used with a deliberately chosen transformed matrix; prediction methods such as Word2vec use a different objective; TF-IDF weights document-term features. The input statistics, treatment of zeros, dimensionality and evaluation all need to be matched or explained before claiming one approach is better.

A static vector still combines a word’s different senses. Evaluate similarity, analogy and downstream behavior separately and keep corpus/version information. A falling toy regression loss and visually appealing neighborhoods do not establish semantic reliability. See embedding evaluation.

Check the counts, then the interpretation

1. Understanding: the diagonal is not necessarily empty

Compute X for a b a with symmetric radius two and inverse-distance weights. Why is X_aa positive even though a position is not paired with itself?

Answer: The adjacent a–b occurrences produce X_ab=X_ba=2. The two different a positions are distance two apart; their two ordered directions each add 1/2, giving X_aa=1. Thus X=[[1,2],[2,0]]. “No self position” does not mean “no same word type.”

2. Hand calculation: the factor of one half

Set both vector tables and both biases to zero. Use X=[[0,2],[1,0]], x_max=3 and α=3/4. What are the loss and the first word-bias derivative?

Answer: Only the count-two cell has a nonzero log target. Write f=(2/3)^(3/4). Its residual is −ln2, giving L=(1/2)f(ln2)² and ∂L/∂b_0=−f ln2. The count-one cell has log target zero and residual zero; absent cells are omitted. Adding a factor of two to this gradient would disagree with the declared half-scaled objective.

3. Boundary case: no co-occurrences

Fit a vocabulary on separate one-word sentences [a] and [b]. Can zero objective loss certify that the learned vectors are useful? What happens to gradients if a zero-count cell has a large predicted score?

Answer: There are no within-sentence pairs, so X is all zero. Every parameter setting has loss zero and gradient zero; no context relation was learned. A zero-count cell is outside the loss mask, so its predicted score produces no direct residual penalty. Replacing it with a target of zero would be another model.

4. Transfer: matching scores, changing cosine

Apply A=diag(2,0.5) to word vectors [1,0] and [1,1]. How can the context vectors be changed to retain every cross-table score? Does the word–word cosine stay fixed?

Answer: Transform context rows by A^(-T). Then UA times (WA^(-T))ᵀ equals UWᵀ. The word cosine changes from 1/√2 to 2/√4.25, approximately 0.707107 to 0.970143. Therefore equal regression scores alone do not identify one cosine geometry or prove equal downstream performance; report the actual exported representation and evaluate it.

Tie the formula and the code to their actual versions

The 2014 paper motivates ratios, introduces weighted log-count regression and reports a sum of two vector tables for use afterward. The author repository snapshot reviewed here is commit 52f7dbc from July 27, 2025. Reading it can clarify a current implementation detail, but does not establish that every optimizer line was present in 2014.

The source review covers the ratio discussion, inspected PDF page 4 (printed page 1535), the two-table export paragraph, co-occurrence code lines 305–350 and objective/update lines 186–234. It does not adopt the paper’s numerical benchmark claims or the repository’s newer pretrained-vector statistics. The repository’s Apache-2.0 root license was identified; no upstream implementation or artwork was copied or executed. The numerical corpus, code, algebraic checks and exercises here are original.

Make a prediction, then check

An unobserved pair has X_ij=0. How does the declared GloVe objective in this lab handle it?

Choose one answer

Learning objectives

  • Construct sentence-bounded inverse-distance co-occurrences.
  • Derive the positive-cell weighted-square objective and gradients.
  • Explain how bias terms and two vector tables share the fit.
  • Separate objective fit, exported vectors and semantic evaluation.

Prerequisites & connections

Explore related knowledge →

References

  1. GloVe: Global Vectors for Word Representation
    Jeffrey Pennington; Richard Socher; Christopher Manning · 2014
  2. Author GloVe implementation: objective and update block
    GloVe contributors · 2025
  3. Author GloVe implementation: co-occurrence counting
    GloVe contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: scoped original GloVe method and pinned author counting/objective code; eight paired equations, ordered inverse-distance counts, positive-only half weighted-square objective, teaching xmax3 versus paper100, gradients, nonidentifiability with preserved cross-scores and changed cosine, actual dense complexity and four explained exercises. Original small deterministic batch fitting; not author optimizer or semantic benchmark.

  • Both languages align on eight displayed equations, four explained exercises and three scoped sources. Recounted sentence-bounded symmetric inverse-distance cells, including repeated-token diagonals; derived f-weighted residual gradients and log-ratio example. Zero observations are excluded rather than targets at zero; half scaling and xmax3 are explicit teaching choices.
  • Production suite executes actual MDX:20 original checks,3 article math cases and6 publication checks. Checked all parameter gradients, zero-observation objective, gauge transformations and cosine1/sqrt(2) to4/sqrt(17) with unchanged cross-scores. Loss5.584310 to0.002498 is this toy fit, not a semantic evaluation.
  • Four original SVGs bind the exact MDX results; eight figure tests check data, arithmetic, bars and bilingual references. Isolated18 language/width combinations and four fallback fonts passed after isolating the harness from the Astro development toolbar. Actual desktop/mobile screenshots inspected. Full article browser acceptance recorded separately; no human peer review or upstream code execution.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.