Howwise RSS
AI & Automation8 min read

Sum vs Mean of Word Embeddings: Does It Matter?

Short answer

Sum vs mean of word embeddings makes no difference for cosine similarity, because the mean is the sum divided by the word count, so both vectors point the same way. It does matter for dot product, Euclidean distance and classifier features.

Key takeaways
  • Mean equals sum divided by n, so cosine similarity between sentence vectors is identical for sum and mean.
  • Dot product, Euclidean distance and neural-net inputs do change, because the sum's magnitude grows with sentence length.
  • L2-normalising sum, mean or any pooled vector makes dot product equal to cosine, and Euclidean distance then ranks the same as cosine.
  • Both pooling methods ignore word order, and frequent words dominate; SIF weighting with first-principal-component removal fixes the second problem.
  • When quality matters, use a sentence-transformers model, which applies attention-mask-aware mean pooling over contextual token embeddings.

Does sum vs mean of word embeddings change cosine similarity?

No. For a sentence with n words, mean = sum / n. Dividing a vector by a positive scalar changes its length but not its direction, and cosine similarity only looks at direction. So sum pooling and mean pooling give exactly the same cosine scores, up to floating point error.

The proof is one line: cos(a/n, b/m) = (a·b)/(nm) / (|a|/n · |b|/m) = (a·b)/(|a||b|). The scale factors cancel. The check below shows it with random stand-in vectors.

import numpy as np

rng = np.random.default_rng(0)
s1 = rng.normal(size=(3, 300))   # 3 word vectors
s2 = rng.normal(size=(9, 300))   # 9 word vectors

def cos(a, b):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b))

print(cos(s1.sum(0), s2.sum(0)))
print(cos(s1.mean(0), s2.mean(0)))
print(np.isclose(cos(s1.sum(0), s2.sum(0)), cos(s1.mean(0), s2.mean(0))))  # True

When do sum and mean give different results?

Anything that uses vector length, not only direction, will see a difference. The sum of n word vectors has a norm that grows with n: roughly linearly when the vectors point the same way, and roughly with the square root of n when they are random. Long sentences therefore get large vectors. The mean keeps the norm on the scale of a single word vector.

This is why the choice matters in these cases:

UseSum vs meanWhat happens
Cosine similarityIdenticalLength cancels out
Dot product (raw)DifferentSum favours long sentences, which win every ranking
Euclidean distance (raw)DifferentSum makes long and short sentences look far apart even when similar in meaning
Dot or Euclidean after L2 normalisationIdenticalNormalising removes the scale, so sum, mean and any other scaling agree
Classifier or neural net inputDifferentSum exposes a length signal; mean hides it and gives stable input scales
k-means on raw vectorsDifferentSum clusters partly by sentence length; mean clusters more by content
Tip: Mean normalises for length, sum keeps a length signal. If length is a real feature for your task (for example, short queries versus long documents), sum can help a classifier. If you did not intend that, it is a bias, and mean is the safer default.

What does a worked example look like?

Use a toy 2D vocabulary: dog = [1, 0], bites = [0, 1], man = [1, 1]. Take three sentences: A = "dog bites man", B = "man bites dog", C = "dog dog dog".

A has sum [2, 2] and mean [0.667, 0.667]. B contains the same words, so it has the same sum and mean as A. C has sum [3, 0] and mean [1, 0].

Cosine matches in both columns, as expected. Dot product and Euclidean distance differ: the dot product scales by n×m (9 for A vs C, going from 6.00 to 0.667). Note also that A vs B scores a perfect 1.0, so "dog bites man" and "man bites dog" are indistinguishable.

If you double sentence A to "dog bites man dog bites man", its mean stays [0.667, 0.667] but its sum becomes [4, 4]. Its dot product with C doubles under sum pooling and is unchanged under mean pooling.

PairCosine (sum)Cosine (mean)Dot (sum)Dot (mean)Euclidean (sum)Euclidean (mean)
A vs B1.0001.0008.000.88900
A vs C0.7070.7076.000.6672.2360.745

Why do both lose word order, and why does averaging drift toward one direction?

Addition is commutative, so any sum or mean of word vectors is a bag of words. "Dog bites man" equals "man bites dog", and "the food was good, not bad" can look much like "the food was bad, not good". Negation is just another vector added to the pile.

Averaging has a second weakness. Word embeddings share a large common component, and frequent words like "the", "of" and "is" have high weight in the average because they appear often. As you add more words, sentence vectors drift toward a shared average direction, so unrelated sentences get cosine scores that are all high, for example 0.7 to 0.9. Ranking still works to some degree, but the scores are compressed and hard to threshold.

Fixes, from cheapest to best:

  1. Remove stop words before pooling. This is fast, but it can delete meaningful words like "not" and "no", so keep negations if your task needs them.
  2. Weight words by TF-IDF, so common words contribute less and rare, informative words contribute more.
  3. Use SIF (smooth inverse frequency, Arora et al. 2017): weight each word by a / (a + p(w)), where p(w) is its corpus frequency and a is about 1e-3, average, then subtract the projection onto the first principal component of all sentence vectors.

How do I implement SIF weighting and handle OOV words and empty sentences?

Mean pooling fails when a sentence has no usable words. If every token is out of vocabulary (OOV) and you divide by the count, you get 0/0, which gives NaN in numpy (with a RuntimeWarning) or ZeroDivisionError in pure Python. NaN then silently poisons cosine scores, nearest-neighbour indexes and k-means.

The usual policy is to skip OOV words, and if nothing remains, return a zero vector (and handle cosine with a small epsilon, or exclude that row). fastText helps because it builds vectors from character n-gram subwords, so a typo or rare word still gets a sensible vector. The code below covers SIF, OOV skipping and the empty case.

import numpy as np

def sif_embeddings(sentences, wv, freq, a=1e-3, dim=300):
    """sentences: list of token lists; wv: dict-like word->vector;
    freq: dict word->probability p(w) in a large corpus."""
    out = np.zeros((len(sentences), dim))
    for i, toks in enumerate(sentences):
        toks = [t for t in toks if t in wv]          # skip OOV
        if not toks:
            continue                                   # stays a zero vector
        w = np.array([a / (a + freq.get(t, 1e-6)) for t in toks])
        vecs = np.stack([wv[t] for t in toks])
        out[i] = (w[:, None] * vecs).sum(0) / len(toks)
    # remove first principal component of the sentence matrix
    u = np.linalg.svd(out, full_matrices=False)[2][0]
    out -= np.outer(out @ u, u)
    return out

def safe_cosine(a, b, eps=1e-9):
    return a @ b / (np.linalg.norm(a) * np.linalg.norm(b) + eps)
Warning: Fit the principal component on a reasonably large set of sentences (hundreds or more), not on two or three. With very few sentences the SVD removes real signal. Save the component and reuse it for new queries rather than refitting.

Should I use sentence-transformers instead of averaged word vectors?

When quality matters, yes. Sentence-transformers models are trained so that cosine similarity reflects meaning, and they use contextual token embeddings, so word order, negation and word sense are partly captured. Most of them still use mean pooling, but over the transformer's output tokens, with the attention mask so padding is ignored. A few use the CLS token instead.

The first snippet is the library. The second shows what it does inside, including the mask-aware mean.

from sentence_transformers import SentenceTransformer, util

model = SentenceTransformer("all-MiniLM-L6-v2")
emb = model.encode(["dog bites man", "man bites dog", "the cat sat"],
                   normalize_embeddings=True)
print(util.cos_sim(emb, emb))

# What mean pooling does under the hood
import torch
from transformers import AutoTokenizer, AutoModel

tok = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
mdl = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
batch = tok(["short", "a much longer sentence here"], padding=True,
            return_tensors="pt")
with torch.no_grad():
    hidden = mdl(**batch).last_hidden_state          # (B, T, D)
mask = batch["attention_mask"].unsqueeze(-1).float()  # (B, T, 1)
mean = (hidden * mask).sum(1) / mask.sum(1).clamp(min=1e-9)
Warning: Averaging over padded tokens is a common bug: a plain hidden.mean(1) divides by the padded length, so a short sentence's vector depends on what else is in its batch. Always multiply by the attention mask and divide by the mask sum.

How do I pick pooling and normalisation for retrieval, and what mistakes should I avoid?

For nearest-neighbour search, L2-normalise every vector to unit length. Then dot product equals cosine, and squared Euclidean distance equals 2 - 2·cos, so Euclidean ranking is monotonic with cosine ranking. Many vector indexes (inner-product indexes in particular) assume you did this.

The classic mistake is to build a dot-product index from summed, unnormalised vectors. Long documents then top every result list regardless of meaning. Normalise first, or use cosine explicitly.

Decision rule: for cosine similarity, use mean (or SIF if you stay with static word vectors), and the choice between mean and sum is then irrelevant. Use a sentence-transformers model when ranking quality matters. Measure on your own data, or on a public benchmark such as STS-B (Spearman correlation between predicted and human similarity), rather than trusting reputation.

Other pooling choices:

PoolingWhat it keepsTypical use
MeanOverall topic, length-independentDefault for cosine, clustering
SumTopic plus a length signalClassifier features where length matters
MaxStrongest activation per dimension, detects rare key wordsShort texts with distinctive terms
Concat [mean; max]Both overall topic and peak features, doubles the dimensionInputs to a classifier
  1. Avoid mixing sum with unnormalised dot-product retrieval, so long texts do not always win.
  2. Avoid averaging padded tokens, which makes embeddings depend on batch composition.
  3. Never compare vectors from different models or dimensions; each model has its own coordinate system and the cosine between them is meaningless.
  4. Prevent empty or all-OOV sentences from producing NaN vectors that spread through an index.
  5. Do not expect a bag of vectors to handle negation or word order; if "not" matters, use a contextual model.

Common questions

Is mean pooling the same as average pooling?

Yes, they are two names for the same operation: summing the vectors and dividing by the number of items. In transformer libraries it is often called mean pooling, and in Keras or PyTorch layers it is called global average pooling.

Should I use Euclidean distance or cosine similarity for sentence vectors?

Use cosine, or L2-normalise the vectors first. On unit-length vectors Euclidean distance squared equals 2 minus 2 times cosine, so the ranking is identical, and on raw vectors Euclidean distance is distorted by sentence length.

Do GloVe, word2vec and fastText need different pooling?

No, the same pooling applies to all three static embeddings. The practical difference is OOV handling: fastText can build vectors for unseen words from subwords, while word2vec and GloVe need you to skip them or use a zero vector.

Does the order of words matter when averaging embeddings?

No. Addition is commutative, so reordering the words gives the identical vector. If order or negation matters, use a contextual model such as a sentence transformer, or a sequence model that reads tokens in order.

Why are my averaged sentence vectors all very similar to each other?

Frequent words and a shared common direction in the embedding space dominate the average, so unrelated sentences score high. Remove stop words, apply TF-IDF or SIF weights, and subtract the first principal component to spread the scores out.

Related topics:word embeddingssentence similaritycosine similaritysentence transformersnlp