Elamur Research

Bayesian Neural Word Embedding

Paper · 2017 · Oren Barkan

Summary

A word embedding compresses a word’s patterns of use into a position in a space. Comparing positions can help answer questions about meaning or grammatical relationships. But a position alone gives no account of how tightly the training evidence constrains it. Bayesian Neural Word Embedding takes up that problem through Skip-Gram with negative sampling, the approach associated with word2vec. Its Bayesian version, Bayesian Skip-Gram, represents a word with a Gaussian distribution. The mean supplies a position, while the covariance describes how the inferred representation can vary around it. The paper asks whether these richer word embeddings can be learned at scale and remain competitive on familiar vocabulary tests.

The training signal is the same kind of evidence ordinary Skip-Gram uses. Words that occur near each other supply positive examples. Sampled alternatives supply negative examples. The Bayesian version starts with prior distributions for the word vectors and uses both kinds of examples to update them. The exact posterior is difficult to compute, so the paper derives a variational approximation. A quadratic bound on the training likelihood makes it possible to update Gaussian distributions in alternating passes. The algorithm keeps separate distributions for a word when it is the focus of a prediction and when it appears as another word’s context.

The comparison uses a shared training sample of 66M words and a vocabulary restricted to the 30K most frequent words. On the retained word analogy questions, Bayesian Skip-Gram achieves 45.1% accuracy against 42.5% for the word2vec baseline. It also has the higher average rank correlation on WordSim353, Rare Words, MEN and SimLex999. On SCWS, ordinary Skip-Gram scores 59.4 against 59.3 for the Bayesian version, with the correlations reported on the paper’s x100 scale. The analogy results vary by category. Ordinary Skip-Gram leads on family relationships, for example, while Bayesian Skip-Gram leads on past-tense relationships.

Those comparisons use the means of the Bayesian distributions as ordinary vectors. The paper also develops ways to use the covariances at scoring time, either to express confidence in a dot product or to compare entire distributions. The tested distribution-aware similarity scores bring no significant improvement over cosine similarity in the reported experiments. The main result is therefore about learning useful word positions while keeping an estimate of their uncertainty. How well that uncertainty reflects the reliability of particular answers remains an open question.

Deep dive: Bayesian Neural Word Embedding

Bayesian Neural Word Embedding explains how Skip-Gram can learn distributions for words and tests those representations on similarity and analogy tasks. · about 38 minutes to read

The problem and its context

What a position can tell us about a word

A corpus records words in use. An embedding tries to preserve some regularities in those uses while giving each word a representation with comparatively few coordinates. Within distributional semantics, a word’s neighbors in text provide evidence about what kind of word it is and how it relates to other words. An embedding can preserve some of that evidence by arranging words with comparable usage patterns nearby, or by arranging pairs so that similar relationships correspond to similar changes of position. The paper’s similarity and analogy tests examine those two properties separately. Both belong to the broader study of lexical semantics.

The method learns separate representations for the same word in different roles. In Skip-Gram, a word used as the focus of a prediction has a target vector. The very same word can also be one of the surrounding words being predicted, in which case it has a context vector. A training pair compares one representation of each kind. The target and context vectors can capture different information because each is used on a different side of the prediction. Once training is complete, a word comparison needs a decision about which representation to use. The paper uses the target side for its main evaluations and mentions context vectors, sums and concatenation as other possibilities.

For a point estimate, the result of learning each vector is a single set of coordinates. Those coordinates can be used to rank candidate neighbors. The representation gives the same kind of answer whether many observations have constrained a word’s position or relatively few observations have done so. The Bayesian question is how much variation in a word’s vector the training evidence leaves plausible under the assumptions of the method. A distribution can express that variation and still provide a central position for tasks that require a vector. This changes what is stored about a word while allowing some existing comparisons to work in the usual way.

There is a related distinction between uncertainty about a representation and the different meanings a word can have. A Gaussian places a single center in the embedding space and describes variation around that center. A word’s occurrences can contribute evidence from different contexts to that distribution. The paper’s target is uncertainty in an inferred representation. A Gaussian around one center does not assign distinct meanings or predictions to individual occurrences, and the experimental questions ask about the vocabulary entries learned across the corpus.

Why Skip-Gram is the starting point

The paper situates Skip-Gram among neural approaches that learn compact representations intended to capture relationships involving usage, meaning and grammar. It describes Skip-Gram with negative sampling as a particularly successful prior approach and notes applications of its training principle outside text, in computer vision and collaborative filtering. For this paper, the attraction is the combination of a useful prediction task and a way of generating training examples from sequences. The starting point already has a way to make learning practical with a large vocabulary. The new derivation has to preserve that practical advantage while fitting distributions.

Given a word and its surroundings, the original prediction objective can use a softmax, which normalizes the scores of every possible context word so that they form a probability distribution. That normalization has a cost. Even a training example with a single observed context involves the whole vocabulary in its denominator. The paper gives the usual vocabulary size relevant to this cost as 10⁵−10⁶ entries. Negative sampling makes each update depend on the observed context and a small draw of alternative words. It changes the task into deciding which of the supplied pairs came from an observed neighborhood.

The paper also recognizes hierarchical softmax as an option for Skip-Gram in earlier work. Here the name Skip-Gram refers to the version with negative sampling unless the full softmax is being discussed in the explanation of the objective. This convention matters because the proposed inference procedure is built around the logistic likelihood for a positive or negative pair. It does not derive a Bayesian update for the full vocabulary denominator or for the hierarchical alternative.

Frequency affects the supply of positive and negative examples differently. Very frequent words appear in many context windows simply because they appear so often. The earlier Skip-Gram procedure described in the paper can discard some occurrences before building those windows, a practice called sub-sampling. Frequency also enters the draw of negative words, where the sampling probabilities are based on corpus counts raised to a power. The two choices have different jobs. Sub-sampling changes the observations that become positive examples. The negative distribution governs which unobserved alternatives the algorithm uses to learn a distinction.

What the Bayesian proposal adds

The paper identifies earlier work on Gaussian embeddings and Bayesian probabilistic tensor factorization as related approaches to word representation. Its own contribution is more specific. It derives a variational Bayesian treatment of the Skip-Gram objective with negative sampling. A prior states how vectors are distributed before observing the training labels. The labels then change the distribution over possible vectors. In principle, this produces a way to retain uncertainty about both sides of the prediction.

The important computational problem lies between writing down a posterior and finding a usable approximation to it. The same word can enter many pairs. A target vector’s likely values depend on the context vectors beside which it has been observed, and the likely context vectors depend on the targets. A direct Bayesian computation must account for those links. The paper chooses to approximate the posterior by separate factors for the vocabulary’s targets and contexts. The updates communicate between the two sides through expectations, quantities such as mean vectors and expected products. This is how the algorithm can preserve a measure of uncertainty while working with operations tied to individual words and sampled pairs.

This design gives the paper two empirical questions. The first is whether the centers learned by Bayesian inference make good embeddings when used the same way as ordinary Skip-Gram vectors. The second is whether distributional information is useful directly in comparisons. Those questions call for different evidence. A higher analogy score from the means concerns where the training algorithm puts words. A stronger result from a covariance-aware similarity would concern what the extra information contributes at evaluation time. The paper addresses both questions, although the detailed numerical comparison concentrates on the first.

The method, step by step

From a sentence to a training decision

Think of a training sentence as a series of chances to choose a focus word and inspect its neighbors. Each occurrence selected as a focus contributes examples pairing that word with words on either side. Repeated co-occurrences matter. If a context word turns up repeatedly near a target, the training procedure has repeatedly observed evidence for that pairing. A positive example records one such event. A negative example shares the target but pairs it with a word drawn as an alternative. In the Bayesian procedure, the sampled negative must be outside the positive-pair multiset for the current sampled data.

The prediction for an example begins with a dot product. A target vector contributes one coordinate at a time, multiplied by the corresponding coordinate of the context vector. The sum gives a score that can be positive or negative. A sigmoid turns the score into a number between the endpoints of a probability scale. A positive label rewards a large dot product, and a negative label rewards a small one. Ordinary Skip-Gram adjusts its vectors directly. Bayesian Skip-Gram treats the vectors as uncertain and asks what distributions of their values can explain the labels.

The Bayesian answer has two parts for each word role. The mean supplies the current central estimate. The covariance supplies the variation around it. When updating a target, the procedure uses both the centers and the second moments of the contexts paired with it. When updating a context, it uses the analogous information about targets. A second moment here describes the expected product of coordinates, so it contains information about dispersion as well as average position. A round of updates therefore carries forward more about a word’s partner vectors than their means alone.

How Bayesian Skip-Gram learns word distributions

The steps in order.

How Bayesian Skip-Gram learns word distributionsStep 1: Retain the most frequent vocabulary words1. Retain the most frequent vocabulary wordsStep 2: Initialize target and context distributions2. Initialize target and context distributionsStep 3: Subsample sentences and draw context windows3. Subsample sentences and draw context windowsStep 4: Collect positive pairs and sample negative alternatives4. Collect positive pairs and sample negative alternativesStep 5: Compute expected scores and logistic bound parameters5. Compute expected scores and logistic bound parametersStep 6: Update target distributions, then context distributions6. Update target distributions, then context distributionsStep 7: Repeat sampling and updates until stopping7. Repeat sampling and updates until stopping

The Skip-Gram objective

The full Skip-Gram objective starts by maximizing the log probability of observed neighboring words given their respective focus words. In a sequence this can be written as follows, with the sum restricted to available neighbors.

J = (1/L) ∑ᵢ₌₁ᴸ ∑_{−c ≤ h ≤ c, h ≠ 0} log p(wᵢ₊ₕ | wᵢ)

Here J is the objective and L is the sequence length. The index i locates the focus occurrence wᵢ. The offset h identifies a candidate context position relative to that occurrence, and c sets the window radius. The condition with 0 excludes the focus position itself. The inner and outer ∑ signs add context contributions and then contributions across focus occurrences. p(wᵢ₊ₕ | wᵢ) is the conditional probability of the word at the context position, and log denotes the natural logarithm. The factor 1/L averages the sum over focus positions.

In the full softmax, the context score is normalized across the retained vocabulary. Here the indices refer to vocabulary entries, even when the same letters also serve as position indices in the sequence objective.

p(wⱼ | wᵢ) = exp(uᵢᵀvⱼ) / ∑_{k ∈ I_W} exp(uᵢᵀvₖ)

wᵢ and wⱼ are the target and observed context words. Their respective vectors are uᵢ and vⱼ. The superscript ᵀ denotes transposition, so uᵢᵀvⱼ is their dot product. The function exp exponentiates a score, and ∑ sums those exponentiated scores over candidate context index k. The set I_W consists of all indices of words in vocabulary W. Its size is l, and both kinds of vectors have m coordinates. Each candidate changes the denominator even when only one of them is the observed word.

The negative-sampling version uses the sigmoid to turn each supplied score into a contribution from a labeled example.

σ(x) = 1 / (1 + exp(−x))

σ is the sigmoid, x is its input score and exp is the exponential function. The negative sign reverses the sign of the input inside the exponential. Large positive inputs yield probabilities towards 1, and inputs in the other direction yield probabilities toward 0.

σ(uᵢᵀvⱼ) ∏ₙ₌₁ᴺ σ(−uᵢᵀv_zₙ)

The first factor is the contribution from target i paired with observed context j. The symbol ∏ multiplies the contributions from the N negative examples, indexed by n. The index zₙ is the negative context drawn for example n, and v_zₙ is its context vector. Each negative score enters σ with its sign reversed. The product is the likelihood of the labels assigned to this collection of pairs. For a fixed target it does not give a normalized probability across all words that might occur next to it. Ordinary Skip-Gram uses stochastic gradient ascent to increase the objective obtained from such contributions.

The draw of a negative word uses the unigram distribution, meaning the empirical frequency of each individual word regardless of its surroundings. The exponent changes the relative mass of frequent and infrequent words before the probabilities are normalized for the draw.

p_neg(w) ∝ p_uni(w)^(3/4)

p_neg denotes the negative-draw probability, and p_uni(w) is the count of word w divided by the word count used to build the unigram distribution. The symbol ∝ means proportional to, with the same normalizing divisor for every retained word. The exponent is 3/4. It flattens the distribution compared with raw frequency while still giving more frequent words more mass than less frequent words. The paper attributes the choice to the original Skip-Gram work, which reported better results for it than for uniform draws or draws using the unmodified unigram distribution.

The paper also gives a version of the likelihood with additive biases. Each pair gets the sum of a target bias and a context bias added to its dot product, with the sign of the whole score reversed for a negative pair. Such terms can absorb effects associated with general frequency or popularity. The Bayesian procedure used in the experiments leaves them out following preliminary trials. The reported comparison therefore concerns embeddings learned without separate bias terms in the objective.

What the probability distribution is over

Bayesian Skip-Gram introduces a prior for each target and context vector. Before observing the labeled pairs, these vectors are taken to be independent. They have zero-centered normal priors with the same scalar precision.

p(uᵢ) = 𝒩(uᵢ; 0, τ⁻¹I),   p(vᵢ) = 𝒩(vᵢ; 0, τ⁻¹I)

Here p(uᵢ) and p(vᵢ) are prior densities for the target and context vectors of word i. The notation 𝒩 gives a normal density at its first argument, with its mean and covariance after the punctuation. The symbol 0 denotes the zero vector, I is the identity matrix of the embedding dimension, and τ is the prior precision. Its reciprocal τ⁻¹ gives the prior variance along each coordinate. There are no prior covariances between different coordinates. The same τ is fixed for both word roles in the implementation, even though the paper discusses using separate values or learning them from data.

The positive collection, denoted I_P, is a multiset. A multiset retains repetitions, so a recurring neighbor counts once for each observed occurrence contributing that pair. The sampled negative collection is I_N. Its exhaustive counterpart could be very large because many ordered word pairs are absent. The training procedure instead draws negatives for the observed positive examples. The data index collection I_D combines the two multisets, with repetitions carried through into the likelihood. D is the corresponding collection of signed labels attached to those pairs.

p(dᵢⱼ | uᵢ, vⱼ) = σ(dᵢⱼuᵢᵀvⱼ)

dᵢⱼ is the observed label for the indexed pair. It takes the value 1 for a positive occurrence and −1 for a negative occurrence. The function p gives the conditional probability of that label given the target vector uᵢ and the context vector vⱼ. The multiplication by the label sends the dot product to the sigmoid with the sign appropriate to the observed decision. This single expression covers both kinds of examples.

p(U, V, D) = ∏_{(i,j) ∈ I_D} σ(dᵢⱼuᵢᵀvⱼ) ∏_{i ∈ I_W} p(uᵢ) ∏_{i ∈ I_W} p(vᵢ)

U is the collection of target vectors and V the collection of context vectors. Their joint density with the data D is p(U, V, D). The first product runs over occurrences in I_D, so the same dot product can contribute repeatedly. The other products multiply the target and context prior densities over the vocabulary index set I_W. The pair labels are conditionally independent given the vectors for the purpose of this likelihood. The posterior after observing the labels is linked across word roles because each example constrains two vectors jointly.

From a posterior to separate Gaussian factors

A posterior assigns plausibility to configurations of all the word vectors after the examples are observed. In this case the configurations cannot be handled simply by updating each prior in isolation. A target and context could compensate for one another in their dot product, and the same vectors enter different observations. The paper mentions sampling-based posterior approximation as a possible route. It chooses variational Bayes, which turns the approximation into an optimization over a simpler family of distributions.

q(θ) = ∏_{i ∈ I_W} q(uᵢ) q(vᵢ)

θ collects all vectors in U and V. The density q(θ) is the variational approximation, and q(uᵢ) and q(vᵢ) are its factors for each word’s target and context. The product over I_W expresses independence across these factors. This factorization is a restriction on the approximation. The likelihood still links pairs of words through the objective used to choose the factors. As one side changes its mean or covariance, the other side receives different expectations at its next update.

The desired approximation minimizes Kullback–Leibler divergence from q to the posterior. This divergence measures a discrepancy using the log ratio of the two densities, weighted by the probability that q gives to each configuration.

D_KL(q ∥ p(· | D)) = ∫ q(θ) log[q(θ) / p(θ | D)] dθ

D_KL denotes Kullback–Leibler divergence, and ∥ separates its ordered arguments. The dot in p(· | D) stands for the vector configuration supplied as an argument to the posterior density. Inside the integral, that configuration is θ. The measure dθ indicates integration over all coordinates of the target and context vectors. Because q(θ) weights the log density ratio, exchanging the distributions generally changes the quantity.

ℒ(q) = ∫ q(θ) log[p(θ, D) / q(θ)] dθ = log p(D) − D_KL(q ∥ p(· | D))

ℒ(q) is the variational objective, also called the evidence lower bound. The term p(θ, D) is the joint density, and p(D) is the evidence for the labels after the vectors have been integrated out. Its logarithm is constant with respect to the choice of q. Maximizing ℒ(q) thus performs the desired minimization without needing the value of the evidence. The objective trades off the expected log joint density and the spread of the approximation through the term involving log q(θ).

For a factorized approximation, the exact coordinate update has a compact expression even before specifying a practical calculation for it.

q*(uᵢ) ∝ exp(𝔼_{q(θ \ uᵢ)}[log p(θ, D)])

q*(uᵢ) denotes the updated factor for target vector uᵢ. The symbol 𝔼 denotes expectation, and q(θ \ uᵢ) is the product of the current factors for every vector except uᵢ. The expectation averages the log joint over those other vectors, treating uᵢ as the free argument. Exponentiation and normalization produce a density, as the ∝ sign indicates. For a context update, the excluded factor is the context vector being updated.

The obstacle is the sigmoid in the likelihood. The prior gives a quadratic term in the log density of the vector being updated. A quadratic log density would yield a Gaussian directly, but the expected log sigmoid does not have that form. The paper introduces an additional variational parameter for each pair so that a different, tractable objective can be optimized. The auxiliary parameter controls a bound on the sigmoid contribution and does not become part of the final word representation.

The logistic bound and its scale

The bound replaces the log sigmoid from each labeled pair with a function quadratic in the pair score. Its linear term retains the sign of the example. Its squared term is insensitive to the sign, which is useful when computing the second moment of a score.

log σ(a) ≥ (a − ξ)/2 − λ(ξ)(a² − ξ²) + log σ(ξ)

a is the signed score of a training example, and ξ is its auxiliary parameter. The function λ supplies the coefficient of the quadratic term. The symbol ≥ indicates that the right side lower-bounds the log sigmoid at the left. The squared symbols apply to their respective scalar arguments. When the method applies this bound to a pair, it uses a equal to the label times the target–context dot product.

λ(ξ) = [σ(ξ) − 1/2] / (2ξ)

λ(ξ) is the coefficient in the bound at auxiliary value ξ, and σ(ξ) is the usual sigmoid of that value. The constants 1/2 and 2 respectively center the sigmoid value before division and scale the denominator. This expression serves as a weight on expected products when updating the Gaussian precision.

Using the bound across the sampled data reduces the likelihood contribution to a sum of tractable terms. Denote the exponentiated bounded likelihood by p_ξ(D | θ). The complete variational objective then has another lower bound.

ℒ(q) ≥ ℒ_ξ(q) = ∫ q(θ) log[p_ξ(D | θ)p(θ) / q(θ)] dθ

ℒ_ξ(q) is the objective built with the bounded log likelihood, and ξ in its subscript refers to the collection of auxiliary parameters. p_ξ(D | θ) is the likelihood surrogate for data D given vectors θ. p(θ) is the joint prior, which remains in the objective, and q(θ) is the current approximation. The integral averages over the same vector configurations as the evidence lower bound. In the factor update, the log of the product p_ξ(D | θ)p(θ) takes the place of the exact log joint. This makes the coordinate calculation Gaussian while preserving a lower-bound objective.

The auxiliary scale for an example is updated to match the expected square of its dot product. Squaring removes the distinction between the positive and negative signs, so the same calculation applies to both labels.

ξᵢⱼ² = 𝔼_q[(uᵢᵀvⱼ)²] = Var_q(uᵢᵀvⱼ) + (μ_uᵢᵀμ_vⱼ)²

ξᵢⱼ is the auxiliary parameter for the pair with target index i and context index j. The subscript q on 𝔼 and Var indicates that expectation and variance use the current variational distributions. μ_uᵢ and μ_vⱼ are their mean vectors. Their dot product equals the expected dot product because the two factors are independent under q. The right side distinguishes the expected score’s magnitude from the dispersion of scores around that expectation.

The implementation uses diagonal covariances in calculating this expectation. In that representation, cross-coordinate covariances vanish, so the expected square can be expressed using coordinate means and variances.

ξᵢⱼ² = ∑ₐ₌₁ᵐ (σ²_uᵢₐ + μ²_uᵢₐ)(σ²_vⱼₐ + μ²_vⱼₐ)

a is the coordinate index and m the number of coordinates. σ²_uᵢₐ and σ²_vⱼₐ are the variances in the specified target and context coordinates, with σ² here denoting variance instead of the sigmoid. μ²_uᵢₐ and μ²_vⱼₐ are the corresponding squared means. Each parenthesis is the expected square of one coordinate. The sum across coordinates gives the square of the auxiliary parameter. The parameter used in λ is obtained from its non-negative square root.

Updating a word distribution

For a target update, the context distributions act as the current evidence about the vectors on the other side of the training pairs. The quadratic term in the bounded log likelihood requires the expected outer product of each context vector.

𝔼_q[vⱼvⱼᵀ] = Σ_vⱼ + μ_vⱼμ_vⱼᵀ

vⱼvⱼᵀ is the outer product of context vector vⱼ with itself, a matrix indexed by pairs of coordinates. Its expectation under q is the sum of Σ_vⱼ, the context covariance matrix, and the outer product of μ_vⱼ, the context mean. Diagonal covariance leaves the mean outer product intact. The resulting second-moment matrix can therefore have entries away from the diagonal.

The target update has a precision matrix and a linear coefficient vector. The precision collects the squared-score terms from the data together with the prior precision.

P_uᵢ = τI + ∑_{j ∈ I_uᵢ} 2λ(ξᵢⱼ)𝔼_q[vⱼvⱼᵀ]

P_uᵢ is the candidate precision matrix for target uᵢ, and τI is the precision supplied by its prior. I_uᵢ is the multiset of context indices attached to target i in the sampled labeled data. For each occurrence, 2λ(ξᵢⱼ) scales the expected outer product of vⱼ. The repeated contributions are kept when an index occurs more than once. Positive and negative examples both contribute to this matrix, since their labels disappear when the dot product is squared.

r_uᵢ = (1/2) ∑_{j ∈ I_uᵢ} dᵢⱼ μ_vⱼ

r_uᵢ is the candidate linear coefficient vector for target uᵢ. The constant 1/2 comes from the linear term of the logistic bound. The context mean μ_vⱼ enters with its observed label dᵢⱼ, so positive and negative occurrences supply signed contributions. I_uᵢ is the same context multiset as in the precision update. Through this term the two classes of examples pull the center of the updated target in different directions.

log q*(uᵢ) = uᵢᵀr_uᵢ − (1/2)uᵢᵀP_uᵢuᵢ + const

q*(uᵢ) is the bounded-objective update of the target density evaluated at uᵢ. The term with r_uᵢ is linear in the vector, and the term with P_uᵢ is quadratic. const collects terms independent of uᵢ and gives the log density the required normalization. This is the log density of a Gaussian when the precision is positive definite. A positive prior precision adds curvature in every coordinate, including for a target with little information in the current sample.

Σ_uᵢ = P_uᵢ⁻¹,   μ_uᵢ = Σ_uᵢr_uᵢ

Σ_uᵢ is the Gaussian covariance obtained by taking the matrix inverse, denoted ⁻¹, of P_uᵢ. The mean μ_uᵢ is that covariance multiplied by the linear coefficient vector r_uᵢ. Equivalently, r_uᵢ is the mean multiplied by the precision matrix. These are the conversions for the Gaussian before the implementation imposes its diagonal covariance restriction. The context update interchanges the roles of target and context, using the target distributions attached to each context’s examples.

The order of matrix operations matters. The paper uses Cholesky decomposition to handle the full precision matrix when obtaining its inverse. It then computes the mean using that inverse. Only afterward does it set the off-diagonal covariance entries to zero, while retaining the full precision matrix for subsequent stochastic updates. Inverting the diagonal entries of the precision alone would be a different operation. It would discard coordinate interactions before computing the mean, and the resulting mean and marginal variances would generally differ.

Alternating updates on resampled data

With the context distributions fixed, every target factor can be updated from its own group of observations. The targets can therefore be updated in parallel. A pass over context factors uses the freshly updated target distributions and can also proceed in parallel within that pass. The fixed-data argument in the paper is a local optimization argument. It describes alternating improvement of a variational objective when the examples are held constant. The implemented training loop refreshes the examples, which changes the objective contributions from one iteration to the next.

To carry information across the changing samples, the paper blends new estimates with stored natural parameters. These are the precision matrix and the precision-weighted mean vector. They collect data contributions additively in the Gaussian log density, which is the form in which the stochastic update operates.

P_uᵢ^(k) = β^(k) P_uᵢ,new + (1 − β^(k))P_uᵢ^(k−1)

k indexes iterations on the stochastic schedule. P_uᵢ^(k) is the stored target precision after the update, P_uᵢ,new is the candidate precision calculated from the current examples, and P_uᵢ^(k−1) is the previous stored precision. The coefficient β^(k) controls the weight of the current estimate. Its complement 1 − β^(k) controls the weight of the earlier one.

r_uᵢ^(k) = β^(k) r_uᵢ,new + (1 − β^(k))r_uᵢ^(k−1)

The meanings of k and β^(k) are the same as in the precision update. r_uᵢ,new is the linear coefficient estimated from the current data, and the superscripts on r_uᵢ distinguish the stored value after the update and the one before it. The method blends these parameters before converting them to a covariance and mean. A context factor uses the same rule with the natural parameters of its context distribution.

∑ₖ₌₀^∞ β^(k) = ∞,   ∑ₖ₌₀^∞ (β^(k))² < ∞

The two sums in the paper state conditions on a stochastic approximation schedule. The index k runs over iterations and ∞ represents the unbounded continuation of the schedule. The left sum says the total update weight must keep growing, while the right says the sum of squared weights must stay finite. The first condition lets later observations keep influencing the result. The second limits the continuing influence of noise from any particular sample. The paper presents these as conditions from the stochastic approximation argument, alongside its separate discussion of fixed-data coordinate updates.

β^(k) = k^(−γ),   0.5 < γ ≤ 1

γ is the decay parameter and k in this expression runs over the positive indices of the decay schedule. Higher values within the stated range make the current-sample weight fall faster. The implementation first performs 10 iterations with full weight on the new parameters, before beginning the stochastic averaging. The early passes give the distributions time to move away from their random initialization before the update weights start shrinking.

Constructing and refreshing the training data

The inputs include the text as a collection of sentences and the dimension and vocabulary size to use. The procedure can in principle select a vocabulary by a minimum count, but the paper’s implementation takes a fixed number of the most frequent words and removes all others. It initializes target and context means with draws from the standard multivariate normal and sets their covariance matrices to the identity. Those are starting values for inference. The prior remains the zero-centered distribution with precision τ. Following vocabulary selection, the procedure computes the corpus frequencies for negative sampling.

At the start of each iteration, sub-sampling discards some word occurrences. This is the inherited Skip-Gram step aimed at reducing the dominance of words that occur frequently. The paper gives the discard expression in terms of word frequency and a threshold.

p(discard | w) = 1 − ρ/f(w)

p(discard | w) denotes the chance of dropping an occurrence of w, ρ is the prescribed sub-sampling threshold and f(w) is the frequency of that word. For frequencies above the threshold, the expression increases as the word becomes more frequent. Taken literally at frequencies below the threshold, the expression falls outside the probability range. The paper’s description does not specify a separate rule for that case.

For every surviving occurrence chosen as a target, the procedure draws a window radius uniformly from the positive integers up to c_max, the maximum radius. It records the words within that radius to either side of the occurrence in the resulting sentence. A new radius is drawn for each focus occurrence. This creates the positive multiset. Different occurrences of a target can have different window radii, and their contributions are all assigned to the same target distribution.

For each positive example, the procedure draws N negative contexts from the powered unigram distribution, excluding contexts that would duplicate a positive pairing for that target in the sampled data. It records the negative label and adds the example to the lists needed to update both ends of the pair. The paper suggests an alternative storage scheme in which dictionaries retain positive and negative counts for each pair. The summands for repeated copies can then be weighted by their counts. This changes how the examples are stored while retaining their multiplicity in the calculation.

The implementation saves the previous natural parameters, computes the new target pass, and then computes the context pass. It repeats data sampling and parameter updates until a stopping threshold is reached or the iteration budget is exhausted. The threshold is denoted by ε, and the maximum number of iterations by K. The final output contains means and covariances for both word roles. For applications to item similarity, the paper proposes replacing each sentence with an item sequence. If only sets of items are available, it proposes a window spanning the sequence so that the representation can use whole-set co-occurrences, giving a Bayesian version of item2vec.

Comparing words after training

The scoring choices start with the target distributions. The simplest uses their means as vectors. With the ordinary Skip-Gram baseline, the same comparison uses the learned target vectors directly.

sim(wᵢ, wⱼ) = xᵢᵀxⱼ / (‖xᵢ‖‖xⱼ‖)

sim is the cosine semantic similarity score for words wᵢ and wⱼ. The vectors xᵢ and xⱼ are the Bayesian target means or the ordinary target vectors, according to the method being evaluated. The norm marks ‖ ‖ give their Euclidean lengths. Dividing the dot product by their lengths makes the score depend on the angle between the vectors. This is the score used for the main comparison.

The paper also asks what can be learned about the dot product itself when each word has a distribution over vectors. Its proposal treats the dot product of independent target draws as a scalar random quantity, then approximates its distribution by a Gaussian matched to the first two moments.

yᵢⱼ = uᵢᵀuⱼ

yᵢⱼ is the random dot product for target vectors uᵢ and uⱼ. For distinct words, the representation factors used for these vectors are independent under q. This score uses both words in the target role. The likelihood during training used a target and a context. Reusing the scoring form with two targets is a choice about how to compare the final word representations.

μ_yᵢⱼ = μ_uᵢᵀμ_uⱼ

μ_yᵢⱼ is the expected dot product, and μ_uᵢ and μ_uⱼ are the target means. Independence permits taking the expected product by pairing coordinates of the means. This expectation is an unnormalized dot product. The cosine calculation divides by the two vector lengths.

σ²_yᵢⱼ = tr(Σ_uᵢΣ_uⱼ) + μ_uᵢᵀΣ_uⱼμ_uᵢ + μ_uⱼᵀΣ_uᵢμ_uⱼ

σ²_yᵢⱼ is the variance of the random dot product. The matrices Σ_uᵢ and Σ_uⱼ are the target covariances, and tr denotes the sum of diagonal entries of a matrix. The trace term accounts for variation in both vectors together. In each of the other terms, one vector’s mean determines how variation in the other vector contributes to the dot product. These are the cross-covariance placements obtained from the independent-vector second-moment calculation used earlier in the paper. The displayed similarity variance in the paper pairs each mean with its own covariance instead, which is inconsistent with that calculation.

The paper proposes the negative of the variance as a confidence score. A pair with a more dispersed dot product receives a lower confidence value. This is uncertainty about the dot product under the fitted distributions. It is distinct from the magnitude of that dot product and can also diverge from the ordering given by cosine. The paper gives a further approximation that averages a sigmoid score over the distribution of the dot product.

p(dᵢⱼ = 1 | D) ≈ σ(μ_yᵢⱼ / √(1 + σ²_yᵢⱼπ/8))

dᵢⱼ = 1 is the positive-label event in the proposed target–target score, and D denotes the observed training labels. The sign ≈ indicates approximation. Inside the sigmoid, μ_yᵢⱼ is the dot product mean and σ²_yᵢⱼ its variance. The square root in the denominator contains the constants 1, π and 8. The proposal first replaces the joint uncertainty by the fitted factors, then substitutes a normal density with the dot product’s moments, then approximates the integral of the sigmoid against that density. As the variance grows with the mean held fixed, the expression moves the sigmoid argument towards zero. This makes the score less decisive for both strongly positive and strongly negative means.

Another proposal uses the shapes of the distributions directly. It adds the Kullback–Leibler divergence in each direction and reverses the sign so that closer distributions receive a higher similarity.

sim_symKL(q_uᵢ, q_uⱼ) = −D_KL(q_uᵢ ∥ q_uⱼ) − D_KL(q_uⱼ ∥ q_uᵢ)

sim_symKL is the symmetric score, and q_uᵢ and q_uⱼ denote the target Gaussian densities of the two words. The ordered arguments of D_KL exchange places in the two terms. The negative signs turn increased divergence into decreased similarity. This makes it possible to give different scores to pairs whose mean positions are equally far apart but whose covariances differ.

D_KL(q_uᵢ ∥ q_uⱼ) = (1/2)[log det Σ_uⱼ − log det Σ_uᵢ + (μ_uⱼ − μ_uᵢ)ᵀΣ_uⱼ⁻¹(μ_uⱼ − μ_uᵢ) + tr(Σ_uⱼ⁻¹Σ_uᵢ) − m]

Here det is the determinant, log is the natural logarithm and m is the embedding dimension. The two Σ matrices belong to target words i and j, whose means are μ_uᵢ and μ_uⱼ. The difference of the means is weighted by the inverse covariance of the second distribution, Σ_uⱼ⁻¹. The trace term combines the first covariance with that inverse, while the determinant terms compare their volumes in the Gaussian divergence. The factor 1/2 scales the sum. The asymmetric placement of the second distribution’s inverse explains why reversing the arguments can change the divergence.

Experiments and results

Shared training data and settings

The experiments compare Bayesian Skip-Gram, abbreviated BSG, with ordinary Skip-Gram, abbreviated SG. The baseline is the word2vec implementation. Both learn from the corpus cited as the One Billion Word Benchmark, with an additional restriction imposed for this comparison. Only the 30K most frequent corpus words are retained. After the removal of other words, the training sample consists of 2.8M randomly selected sentence units and contains 66M words. These are the sizes of the vocabulary, sampled sentence collection and resulting text, respectively. The evaluation uses external word similarity datasets and an analogy question bank.

The shared settings fix the dimension at 40, the maximum context window at 4, the sub-sampling parameter at 10⁻⁵, the vocabulary size at 30000 and the number of negatives per positive at 1. For the Bayesian method, the prior precision is 1, the number of initial iterations before stochastic averaging is 10 and the decay parameter is 0.7. The training budget is 40 iterations for both methods. The authors report verifying convergence after ~30 iterations. For each method they train 10 instances and report average performance, reducing the role of any single run in the comparison.

Using the same dimension and the same window and sampling settings gives the comparison a clear interpretation. Both methods have the same coordinate budget when their target vectors or target means are scored. The Bayesian procedure maintains additional training quantities and returns additional covariance information. Equal dimension therefore controls the size of the vectors used in the final comparison. It does not equate the cost of fitting them or the amount of information returned by training.

Agreement with human similarity rankings

The word similarity task supplies a human score for each word pair. The paper uses Spearman rank correlation to compare the ordering induced by the embeddings with the ordering induced by those scores. Rank correlation measures whether stronger and weaker relationships tend to appear in the same order. A method can agree with the ordering while using a completely different range of numerical scores. This is appropriate for comparing the cosine values to human judgments without interpreting cosine as a rating on the same scale. The results are reported as Spearman correlation multiplied by 100, which the paper labels x100.

Cosine similarity on WordSim353 by Spearman rank correlation

Bayesian Skip-Gram ranks the word pairs closer to the human ordering.

Cosine similarity on WordSim353 by Spearman rank correlationSkip-Gram: 58.6Skip-Gram58.6Bayesian Skip-Gram (this paper): 61.1Bayesian Skip-Gram (this paper)61.1
The numbers
System or settingSpearman x100
Skip-Gram58.6
Bayesian Skip-Gram (this paper)61.1

The WordSim353 result favors the Bayesian target means, and other datasets offer a check on how far that result carries. On Rare Words, BSG reaches 52.5 on the Spearman x100 scale and SG reaches 51.2. On SimLex999, the corresponding scores are 27.3 and 26.4. The methods stay close on MEN, where BSG scores 61.1 and SG scores 60.9. SCWS is the exception to the direction of these results. There, BSG scores 59.3 and SG scores 59.4. Each comparison is between average scores for the two methods on the same set of judgments. The numerical level on one dataset gives no direct measure of how hard a different dataset is for humans or for either method.

Crucially, the similarity comparison in these results uses the same cosine procedure for both methods. The BSG representation supplied to it is a mean vector. The SG representation is the point estimate. If the scores differ on a dataset, that difference reflects where the training methods positioned the words and what the resulting cosine angles capture. It cannot be attributed to the Bayesian score changing its behavior for word pairs with high dot-product uncertainty, since the evaluated cosine has no such adjustment.

Completing word analogies

The analogy task poses a relationship between a first and second word, then asks which word bears the same relationship to a third. A question can involve a grammatical change, as when a plural is related to its singular, or a relation involving meaning, as when countries are paired with their capitals. The scoring rule assumes that the difference between the vectors of the first pair can be applied to the third word. The chosen answer is the candidate whose vector has the highest cosine with the resulting query vector.

x_? = x_b − x_a + x_c

x_a and x_b are the representations of the first and second words. Their difference provides the direction used to transfer the relationship. x_c represents the third word, and x_? is the vector used to search for the answer. Each x is a target mean for BSG or a target vector for SG. Each candidate answer has its own representation, which is compared to x_? by cosine. The percentage of correct answers records how frequently the top-scoring choice matches the recorded word.

The analogy bank consists of 14 groups with uneven numbers of questions. Both methods are evaluated on the same 14122 questions after filtering out any question containing a word outside the training vocabulary. The total is accuracy over retained questions. A group with more retained questions has greater influence on that total than a smaller group. The paper reports percentages for each group as well as the overall result.

Overall accuracy on the retained word analogy questions

Bayesian Skip-Gram answers a larger share of the retained questions correctly.

Overall accuracy on the retained word analogy questionsSkip-Gram: 42.5Skip-Gram42.5Bayesian Skip-Gram (this paper): 45.1Bayesian Skip-Gram (this paper)45.1
The numbers
System or settingaccuracy %
Skip-Gram42.5
Bayesian Skip-Gram (this paper)45.1

The capital and currency categories illustrate differences among the semantic relations. For capitals of common countries, BSG achieves 62.4% and SG 59.5%. In the world-capitals group, BSG achieves 53.2% and SG 50.2%. Currency questions give 7.1% for BSG and 3.6% for SG, so the Bayesian result is higher while correct completions remain uncommon for each approach. The pattern reverses for city-in-state questions, with 14.3% for BSG and 17.9% for SG. It also reverses for family relations, with 55.7% for BSG and 63.3% for SG.

Several groups involving changes in word form favor BSG. It reaches 20.1% on adjective-to-adverb analogies against 15.2% for SG. On present participles the scores are 39% and 36.2%, and on past tense they are 43.7% and 39.2%. The plural category yields 46.9% for BSG and 42.3% for SG. Plural verbs are closer, with 29.4% for BSG and 29.1% for SG. These comparisons concern particular transformations. The higher total accuracy does not imply a uniform improvement in representing grammar.

The nationality-adjective category gives 88.9% for BSG and 82.3% for SG. In the comparative category, labeled “Comparable” in the paper’s table, BSG scores 47.2% and SG 43%. In the superlative category, the scores are 41% for BSG and 48.1% for SG. The opposite category is tied at 6.7%. These results show why the group-level breakdown matters. Performance can improve for one grammatical relationship and fall for a related one, while some categories remain difficult for both approaches.

What the ablations show

The paper gives no systematic component ablation of Bayesian Skip-Gram. Its closest controlled comparisons keep the learned representation fixed while changing the similarity score, or keep the final score fixed while changing the way the vectors are learned. Those comparisons answer different questions. Changing the score tests whether covariance is useful at the point of comparison. Changing the training method tests the combined effect of the prior, variational inference and associated updates on the representation used by that score.

When the covariance enters the score

The scoring comparison places cosine of the target means beside the proposed sigmoid-based and symmetric divergence scores. The paper reports no significant improvement from substituting either of the distribution-aware scores for cosine on the word similarity task. It gives neither a separate set of numerical scores for these variants nor details of a significance test. The reported result supports the choice of cosine for the benchmark comparison. It leaves open which pairs changed rank, whether a different dataset would reward those changes, and whether the uncertainty information might help with a different question.

The variants also use the distribution in different ways. The sigmoid score softens the decision when the dot product has high variance under the fitted factors. The symmetric divergence score examines the Gaussian densities themselves, including how their shapes compare and how each covariance weights the difference of their centers. Cosine examines the angle between centers. A weak outcome from the distribution-aware comparisons could concern the fitted covariances, the scoring definitions, the suitability of human similarity rankings for assessing them, or some combination of those factors. The reported comparison does not isolate those explanations.

The proposed confidence value is yet another use of the variance. A benchmark that evaluates ordering by similarity does not directly ask whether the method knows which of its comparisons are reliable. One can imagine a pair whose similarity is ranked appropriately while the variance of its score is poorly related to how much the evidence constrains it. Conversely, a method might identify uncertain pairs without using the resulting confidence to improve the overall rank correlation. The paper describes the confidence calculation, but the similarity evaluation gives no direct measurement of its quality.

When both methods use the same score

With cosine held fixed, Bayesian Skip-Gram generally gives competitive or better scores. This supports the paper’s claim that the centers produced by its inference procedure can serve as useful word vectors. It also eliminates a simple confound in the main results. The Bayesian procedure did not gain its benchmark advantage by receiving a new comparison rule for the reported scores. Both procedures faced the same tests using the same kind of vector comparison.

The authors suggest that using second moments during training may help explain the gains. There is a clear point in the derivation at which this information could matter. The Bayesian precision update includes each context’s covariance as part of its expected outer product. That update affects the precision matrix whose inverse helps determine the target mean. Even when the final cosine ignores covariances, the estimated centers can therefore reflect covariance information that passed through training. The experiment compares whole procedures, however. It does not hold the Bayesian prior and update schedule fixed while suppressing precisely the covariance contribution, so the proposed explanation is plausible without being isolated.

The category breakdown is diagnostic in a different sense. It shows which types of analogy answer improve more often and which move in the other direction. The published scores are grouped by relation, with no comparison that holds frequency or the number of questions constant across groups. The gain on Rare Words likewise concerns the score on that named dataset after learning the shared restricted vocabulary. The paper does not break that result down by the words’ corpus frequencies or by their posterior variances. It therefore gives a result on a rare-word benchmark without testing a more specific claim that uncertainty handling is especially beneficial at lower observed counts.

What the paper says about design choices

The paper mentions preliminary experiments with bias terms and characterizes their contribution as marginal. This is evidence about the authors’ reason for omitting the biases. The comparison comes without numbers, a dataset breakdown or an account of the settings under which those trials ran. Its contribution is accordingly narrower than that of the main shared-data experiments. It records a design choice instead of measuring how strongly separate frequency effects interact with the priors or factor updates.

The authors also report that the Bayesian method is fairly robust to the decay parameter within the range they give. The published configuration uses γ = 0.7, and the theoretical discussion gives the range 0.5 < γ ≤ 1 for the schedule. The paper provides no table sweeping γ and no comparable analysis for the prior precision or the initial full-update period. The report identifies a workable configuration and an observed tolerance for that schedule choice. It does not quantify the sensitivity of the learned means and covariances to the other settings.

Limitations

Limits the authors identify

The authors frame the benchmark as a comparison between Bayesian and ordinary Skip-Gram under a shared setup. They observe that both methods score below results in the earlier literature they discuss. They point to two differences in scale. Their training sample has 66M words, while the earlier training corpora they mention range from 1-30B. Their vectors have dimension 40, while the earlier work they discuss uses dimensions in the range 100-600. The paper proposes larger data and larger dimensions as possible ways to improve the absolute scores. The experiments do not separately vary either quantity, so the effect of increasing one while leaving the other fixed is unknown.

The other qualification comes from the distribution-aware similarity tests. The paper derives more than one way to score distributions and explicitly reports that the tried alternatives do not significantly improve over cosine on the evaluated task. Its numerical benchmark evidence is strongest for the usefulness of the posterior means. The confidence proposal and the item-sequence extension show what the representation makes possible in principle. The reported experiments establish word-level results and give no evaluation of the confidence score or item-similarity extension.

The mathematical argument also has a stated condition. The alternating update scheme is described as converging to a local optimum under a constant dataset. The training procedure subsamples words, redraws windows and samples negatives at each iteration. The paper addresses the resulting fluctuation with a decreasing update weight and reports convergence behavior for its experimental runs. That observation is narrower than a guarantee for every corpus and parameter setting. The local optimum description also allows different initializations to settle in different regions of the latent space.

Limits visible in the setup

The inference procedure makes several approximations before a covariance reaches the output. It factorizes the posterior by target and context, replaces the logistic likelihood contribution with a lower bound, and removes the off-diagonal entries from the covariance used by the implementation. A single Gaussian factor therefore describes the uncertainty of each word role within a restricted family. Dependence between estimates for related words, or dependence between the inferred target and context of the same word, cannot appear explicitly in the output. The original training likelihood can create these dependencies even though the variational factors discard them.

The reported metrics offer limited evidence about how faithfully the covariance reflects uncertainty. A rank correlation assesses the ordering of word pairs. Analogy accuracy assesses top answers after vector arithmetic. In the main tables both depend on the means. Neither measures whether a wide distribution signals that additional observations would substantially change the estimate, or whether a narrow distribution corresponds to a more reliable decision. The word-level uncertainty is uncertainty conditional on the priors, likelihood, data selection and approximation used in the paper. It should not be read as a measured probability that a particular human judgment agrees with the embedding.

Coverage is another constraint. The vocabulary retains frequent corpus words, and the analogy test discards questions that involve excluded entries. Its total accuracy applies to the 14122 retained questions. The paper does not measure how either method would answer questions about a word left outside the learned vocabulary. It also supplies no account of how coverage varies across the similarity datasets. This limits what can be concluded about lexical coverage from the reported correlations, including the result for Rare Words.

The results average 10 runs, but the tables do not give the variation across those runs. Averaging helps avoid treating a single random training instance as representative. It does not reveal whether a narrow lead, such as the MEN difference between the reported average correlations of 61.1 and 60.9, persists across initializations or training draws. The analogy group results also come without the number of retained questions in each group, so the reader cannot judge the sampling variability of a category from the reported accuracy alone.

Finally, the algorithm’s scalability claim is supported primarily by how the work is organized. Negative sampling limits the set of observed alternatives per positive pair, and target or context updates can be parallelized within their respective passes. Training nonetheless maintains and processes matrices in addition to vectors, including a full precision matrix even after the stored covariance has been diagonalized. The paper gives no timing comparison with word2vec, no memory measurements and no scaling curve over vocabulary size or dimension. The experiments establish that the procedure can be run on the reported training sample. They leave the cost of increasing that scale unmeasured.

What came after

Understanding Feature Focus in Multitask Settings for Lexico-semantic Relation Identification (2021) cites Bayesian Neural Word Embedding. Its stated subject is feature focus in multitask settings for identifying lexico-semantic relations. This puts the emphasis on which features matter when identifying a relationship between words. Bayesian Neural Word Embedding instead examines how the representations used in such comparisons can be learned from corpus neighborhoods and how uncertainty about those representations can be retained.

The citation establishes a connection between the papers, but it does not specify a technical transfer. It is unclear whether the later work uses the Gaussian factors, the learned means, a covariance-aware score or the paper as background on embedding methods. The distinction is material. Using a Bayesian mean as an input feature would evaluate information in the learned word positions. Using the fitted covariance would additionally put the uncertainty estimate to work. The relationship between the papers can be established at the level of citation and research subject, while the role of Bayesian Skip-Gram in the later experiments remains unspecified.

Cite

Cite as Oren Barkan. 2017. Bayesian Neural Word Embedding. Proceedings of the AAAI Conference on Artificial Intelligence.

The paper itself, not this page. BibTeX from the library's record of the work. DOI 10.1609/aaai.v31i1.10987

@inproceedings{barkan2017bayesian,
  title = {{Bayesian Neural Word Embedding}},
  author = {Oren Barkan},
  booktitle = {Proceedings of the AAAI Conference on Artificial Intelligence},
  year = {2017},
  doi = {10.1609/aaai.v31i1.10987},
  eprint = {1603.06571},
  archivePrefix = {arXiv},
  url = {https://doi.org/10.1609/aaai.v31i1.10987}
}

↑ back to top

This page in Markdown https://md.research.elamur.ai/free/en/papers/barkan-2017-bayesian-neural-word-embedding/