TExcelTAD

Text Feature Extraction with Sentence Embeddings

Feature extraction works for text as well as for images. A sentence-embedding model turns a whole sentence into one fixed-length vector so that sentences with similar meaning get nearby vectors, even when they share no words. "The film was a delight" and "I enjoyed this movie a lot" have almost no word in common, so a bag-of-words model sees them as unrelated; a sentence embedding puts them close together. On top of those vectors a logistic regression learns sentiment, topic or intent from a few hundred labels.

How a sentence becomes one vector

A transformer encoder such as BERT produces one vector per token. A sentence embedding model (here all-MiniLM-L6-v2, a 6-layer, 384-dimensional encoder from the sentence-transformers project) adds two steps:

  1. Mean pooling: average the token vectors, ignoring padding, s=1T∑t=1Tht\mathbf{s} = \frac{1}{T} \sum_{t=1}^{T} \mathbf{h}_t.
  2. Normalisation to unit length, e=s/∥s∥\mathbf{e} = \mathbf{s} / \lVert \mathbf{s} \rVert, so that the dot product of two embeddings is their cosine similarity:
cos⁡(ea,eb)=ea⋅eb∥ea∥ ∥eb∥=ea⋅ebwhen ∥ea∥=∥eb∥=1\cos(\mathbf{e}_a, \mathbf{e}_b) = \frac{\mathbf{e}_a \cdot \mathbf{e}_b}{\lVert \mathbf{e}_a \rVert \, \lVert \mathbf{e}_b \rVert} = \mathbf{e}_a \cdot \mathbf{e}_b \quad \text{when } \lVert \mathbf{e}_a \rVert = \lVert \mathbf{e}_b \rVert = 1

The model was trained contrastively (the idea of Contrastive Learning) on hundreds of millions of sentence pairs that mean the same thing, so that their pooled vectors point the same way. The geometry of embeddings and similarity explains why cosine is the natural measure.

From scratch: pooling, normalising, comparing

With made-up 4-dimensional token vectors, the whole pipeline after the encoder is a few lines of NumPy. The padding mask matters: averaging padding vectors into the sentence would pull every short sentence towards the same point.

python · try it yourself
import numpy as np

rng = np.random.default_rng(0)
# pretend encoder output: 3 sentences, padded to 5 tokens, 4 numbers per token
H = rng.normal(size=(3, 5, 4))
mask = np.array([[1, 1, 1, 0, 0],      # sentence 0 has 3 real tokens
                 [1, 1, 1, 1, 1],      # sentence 1 has 5
                 [1, 1, 0, 0, 0]])     # sentence 2 has 2
H[1] = H[0].copy(); H[1, 3:] = H[0, :2]          # sentence 1 repeats sentence 0's content
H[mask == 0] = 9.0                                # padding vectors: garbage that must not count

def mean_pool(H, mask):
    m = mask[:, :, None]
    return (H * m).sum(1) / m.sum(1)

def normalise(S):
    return S / np.linalg.norm(S, axis=1, keepdims=True)

E = normalise(mean_pool(H, mask))
print("unit length:", np.linalg.norm(E, axis=1).round(3))
print("cosine similarity matrix (E @ E.T):")
print((E @ E.T).round(2))
naive = normalise(H.mean(1))                       # wrong: averages the padding too
print("without the mask, sentence 0 vs 2:", round(float(naive[0] @ naive[2]), 2),
      "| with the mask:", round(float(E[0] @ E[2]), 2))
unit length: [1. 1. 1.]
cosine similarity matrix (E @ E.T):
[[1.   0.94 0.68]
 [0.94 1.   0.86]
 [0.68 0.86 1.  ]]
without the mask, sentence 0 vs 2: 1.0 | with the mask: 0.68

After normalising, every row has length 1 and E @ E.T is the cosine matrix with ones on the diagonal. Sentence 1 contains sentence 0's tokens plus two repeats, and their similarity is 0.94. Without the mask, the padding vectors (all 9.0) dominate the averages of the two short sentences and make them look identical (1.0); with the mask their real similarity is 0.68.

With all-MiniLM-L6-v2

The real model on a few sentences. normalize_embeddings=True returns unit vectors, so E @ E.T is the cosine-similarity matrix.

python · try it yourself
from sentence_transformers import SentenceTransformer

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
sentences = ["The film was a delight from start to finish.",
             "I enjoyed this movie a lot.",
             "A dull, lifeless two hours.",
             "The plot drags and the acting is wooden.",
             "The train to Hanoi leaves at nine."]
E = model.encode(sentences, normalize_embeddings=True)
print("embedding shape:", E.shape)
S = E @ E.T
for i, s in enumerate(sentences):
    print(f"{s[:30]:30s}", " ".join(f"{v:5.2f}" for v in S[i]))
embedding shape: (5, 384)
The film was a delight from st  1.00  0.56  0.25  0.41  0.22
I enjoyed this movie a lot.     0.56  1.00  0.21  0.39  0.16
A dull, lifeless two hours.     0.25  0.21  1.00  0.24  0.12
The plot drags and the acting   0.41  0.39  0.24  1.00  0.16
The train to Hanoi leaves at n  0.22  0.16  0.12  0.16  1.00

The two positive reviews are the most similar pair (0.56) although they share no word, and the sentence about a train is the least similar to everything (0.12 to 0.22). But look at the negative review "The plot drags and the acting is wooden": it is closer to the positive "The film was a delight" (0.41) than to the other negative one (0.24). A general-purpose embedding captures topic (both talk about a film's qualities) more strongly than sentiment. Similarity alone will not classify sentiment; a classifier trained on labelled embeddings has to find the sentiment direction.

Sentiment from frozen embeddings

The rotten_tomatoes data set has 10,662 one-sentence movie reviews labelled positive or negative (8,530 train, 1,066 validation, 1,066 test). To keep the run short the example takes a fixed random 1,000 training and 500 test sentences, embeds them once, and trains logistic regression on the first 50, 200 and 1,000 training embeddings. The baseline is the classic text pipeline, TF-IDF of words and word pairs with logistic regression, trained on the same sentences.

python · try it yourself
import numpy as np
from datasets import load_dataset
from sentence_transformers import SentenceTransformer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline

ds = load_dataset("cornell-movie-review-data/rotten_tomatoes")
train = ds["train"].shuffle(seed=0).select(range(1000))
test = ds["test"].shuffle(seed=0).select(range(500))
X_tr, X_te = list(train["text"]), list(test["text"])
y_tr, y_te = np.array(train["label"]), np.array(test["label"])
print("example:", X_tr[0][:70], "->", "positive" if y_tr[0] else "negative")

model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
E_tr = model.encode(X_tr, batch_size=64, normalize_embeddings=True)   # embed once
E_te = model.encode(X_te, batch_size=64, normalize_embeddings=True)

print("labels | TF-IDF + logistic | MiniLM embeddings + logistic   (test accuracy, 500 sentences)")
for n in [50, 200, 1000]:
    tfidf = make_pipeline(TfidfVectorizer(ngram_range=(1, 2)), LogisticRegression(max_iter=2000, C=10))
    a = tfidf.fit(X_tr[:n], y_tr[:n]).score(X_te, y_te)
    b = LogisticRegression(max_iter=2000).fit(E_tr[:n], y_tr[:n]).score(E_te, y_te)
    print(f"{n:6d} | {a:17.3f} | {b:.3f}")
example: this is pure , exciting moviemaking . you won't exactly know what's ha -> positive
labels | TF-IDF + logistic | MiniLM embeddings + logistic   (test accuracy, 500 sentences)
    50 |             0.562 | 0.588
   200 |             0.612 | 0.698
  1000 |             0.684 | 0.728

With 200 labels the embeddings reach 0.698 against 0.612 for TF-IDF; with 1,000 labels the gap narrows to 0.728 against 0.684. With 50 labels both are close to guessing (0.562 and 0.588; the standard error on 500 test sentences is about 0.02, so that difference is within the noise). The pattern is the one of the transfer lesson: pretrained features matter most when labels are few. A model fine-tuned on all 8,530 training reviews does better than either; the mini project compares the options on equal terms.

Advantages and limits for text

Advantages Limits
Meaning instead of word overlap: synonyms and paraphrases land close Fixed vector size: long documents are squeezed (MiniLM reads at most 256 word pieces; the rest is cut)
One embedding serves classification, search, clustering and deduplication General-purpose: domain jargon (medicine, law, code) may be embedded poorly
CPU-friendly: a small encoder, run once per text Mostly English for this model; other languages need a multilingual one
No training loop: scikit-learn on top Below what a fine-tuned model reaches once labels are plentiful

Pitfalls

  • Comparing unnormalised vectors with a dot product. Long vectors dominate; normalise, or use cosine explicitly.
  • Mixing embedding models. Vectors from two models (or two versions of one) live in different spaces; never compare or concatenate them as if they were one.
  • Silent truncation. Text beyond the model's maximum length is dropped. Check token lengths, and split long documents into chunks.
  • Small test sets. On 500 test sentences one point of accuracy is 5 sentences, and the standard error of an accuracy near 0.7 is about 0.7⋅0.3/500≈0.02\sqrt{0.7 \cdot 0.3 / 500} \approx 0.02.

Practice

  1. Two unit vectors have cosine similarity 0.8. What is their Euclidean distance?
  2. Why does the example embed the 1,000 training sentences once and then slice E_tr[:n], instead of embedding again for each nn?
  3. Your support tickets are in Vietnamese and English. What would you check before using all-MiniLM-L6-v2?
Answers
  1. For unit vectors ∥a−b∥2=2−2cos⁡=0.4\lVert \mathbf{a} - \mathbf{b} \rVert^2 = 2 - 2\cos = 0.4, so the distance is 0.4≈0.63\sqrt{0.4} \approx 0.63. Ranking by cosine and by Euclidean distance gives the same order for unit vectors.
  2. The backbone is frozen, so a sentence's embedding never changes. Embedding once and reusing the vectors is the whole point of feature extraction.
  3. Whether the model was trained on Vietnamese (this one mostly on English); compare it with a multilingual sentence-embedding model on a labelled sample of your own tickets.

Test yourself

Why is mean pooling done with the attention mask?

  1. To make it faster
  2. So that padding tokens, which carry no meaning, do not count in the average
  3. Because the mask normalises the vectors
  4. To remove stop words

When are the dot product and the cosine similarity of two embeddings equal?

  1. Always
  2. When both vectors have length 1
  3. When the vectors are orthogonal
  4. Never

In the experiment, which statement fits the results best?

  1. TF-IDF is better at every label count
  2. Sentence embeddings are ahead at every label count, with the clearest margin at 200 labels
  3. The two are identical
  4. Embeddings only help with 1,000 labels