Skip to content

Unit 9 · Text Classification and Embeddings

3 h contact · 8 h self study Prerequisites: Units 7 & 8 CLO 6

1. Setting the scene

Scenario: 50,000 messages, three inboxes

CityDocs' search works. Now the Citizen Services lead has a different problem. Every day ~50,000 app messages arrive, and three people spend their mornings forwarding them:

  • "Bike lane on Warschauer Str. blocked again" → Traffic
  • "Loud construction noise after 22:00 in Neukölln" → Public Order
  • "Dead trees along the canal, nobody waters them" → Environment

At the same time, planners complain that searching urban climate data misses a report titled "Heat islands and green roofs in Berlin", because it shares no words with the query.

Two new needs: assign labels automatically, and search by meaning, not by words.

Guiding questions

  1. What changes when the task is deciding rather than finding?
  2. Can the TF·IDF vectors we already have be reused for labelling?
  3. How can two texts with no shared words be recognised as similar?

2. Intended learning outcomes

# Outcome Bloom CLO
ILO 9.1 Distinguish retrieval from classification and binary, multiclass and multilabel tasks. UNDERSTAND 6
ILO 9.2 Contrast sparse (TF / TF·IDF) and dense (embedding) representations. ANALYSE 6
ILO 9.3 Design storage and semantic search for embeddings, including chunking and metadata filters. CREATE 6
ILO 9.4 Train a Multinomial Naive Bayes classifier by hand, including Laplace smoothing. APPLY 6
ILO 9.5 Build and evaluate a supervised text classification pipeline in Python. APPLY 6

3. From ranking to deciding

flowchart TB
    subgraph R1["Units 4 to 7"]
      direction LR
      B["Boolean retrieval"] --> I["Inverted index"] --> V["TF·IDF · VSM"]
    end
    subgraph R2["Units 8 and 9"]
      direction LR
      BM["BM25 ranking"] --> C["<b>Text classification</b>"]
    end
    R1 --> R2

The transition is not a new topic: it is a change of task on the same representation.

flowchart LR
    D["Document<br/><i>Government approves new climate<br/>data platform for smart cities</i>"]
    D --> IRQ["IR question<br/>Is it relevant to<br/>'smart city data'?"]
    D --> CLQ["Classification question<br/>Which category?<br/>Politics · Technology · Sports"]
Dimension Information Retrieval Classification
Input Query + document collection Document + set of labels
Main question Which documents match this query? Which label belongs to this document?
Output Ranked list Predicted label(s)
Learning signal Relevance judgements, clicks Labelled training examples
Typical score \(\text{score}(q, d)\) \(P(y \mid d)\) or a decision score
Example Search results Spam / not spam

IR is about finding. Classification is about deciding.

4. What is text classification?

Definition

Text classification assigns one or more predefined labels to a document based on its content: we learn a function \(f: d \mapsto y\) from labelled examples.

Task Input Labels
Spam detection Email spam / not spam
Sentiment analysis Product review positive / negative
News categorisation Article politics, sports, tech
Ticket routing Customer / citizen request billing, technical, account · traffic, environment, order
Query intent Search query informational, navigational, transactional
Relevance classification Query, document pair relevant / not relevant
Type Labels per document Example
Binary one of two spam / not spam
Multiclass exactly one of many sports or tech or politics
Multilabel any subset AI and ethics and policy

5. Representations: the bridge between IR and classification

flowchart LR
    R["Raw text"] --> T["Tokens"] --> V["Vector"]
    V --> IR["IR: compare with query vector"]
    V --> ML["Classification: input to a learner"]

Document term matrix \(X\) with labels \(y\):

Document goal team server data Label
d1 2 3 0 0 Sports
d2 0 0 2 3 Tech
d3 1 2 0 0 Sports
d4 0 0 1 2 Tech

In IR, \(X\) lets us compute similarity; in classification, \((X, y)\) is the training data.

Sparse vs. dense vectors

Vocabulary [team, goal, election, government, computer, music]; the text team goal → [1, 1, 0, 0, 0, 0].

  • one dimension per vocabulary word: interpretable;
  • with a real vocabulary (10⁵, 10⁶ terms) almost all entries are zero;
  • synonyms share nothing: car and automobile are orthogonal.

An embedding model maps team goal to, e.g., [0.21, −0.34, 0.67, 0.18, …] (384 to 3,072 dimensions).

  • values are learned by a neural model;
  • no single dimension has a human readable meaning; meaning is distributed across the vector;
  • texts with similar meaning get nearby vectors, even with no shared words.

Worked example: similar meaning, different words

A: "The team won the match." B: "The players achieved victory in the game."

An embedding model might produce \(e_A = [0.82, 0.15, 0.61]\) and \(e_B = [0.79, 0.18, 0.65]\) (illustrative numbers). Their cosine similarity is ≈ 0.99, although the sentences share only the word the. TF·IDF would score them near zero.

Embedding hygiene

  • Vectors from different models live in different spaces: never compare them, even if the dimensions match.
  • Use the similarity metric the model was trained for: cosine (most text models), dot product, or Euclidean distance.

6. Embeddings in practice

What can be embedded?

Words, sentences, passages and whole documents, but also images, audio, video and source code. For long documents, one vector may blur several topics, so we chunk them:

flowchart TB
    subgraph R1["Split and embed"]
      direction LR
      L["Long document<br/>many pages, many topics"] --> C["Chunks<br/>paragraphs / passages"] --> E["One embedding<br/>per chunk"]
    end
    subgraph R2["Store"]
      direction LR
      S[("Store: id · vector · text ·<br/>document_id · position · metadata")]
    end
    R1 --> R2

Chunks that are too large mix topics; chunks that are too small lose context. A common starting point is a few hundred tokens with small overlaps.

Where to store embeddings

Option Suits
In memory (NumPy, FAISS) experiments, small datasets
Relational DB with vector extension (PostgreSQL + pgvector) teams already on Postgres; vectors + SQL filters in one place
Dedicated vector database very large collections, high query volume
Search engine with vector support (Elasticsearch/OpenSearch) hybrid keyword + vector search

A vector database does not necessarily replace a traditional database: the traditional one is optimised for exact values, joins and transactions; the vector index for nearest neighbour search. Many systems use both.

flowchart TB
    Q["Query<br/>'urban climate data'"] --> EQ["Embed query<br/>same model as documents!"]
    EQ --> VS["Nearest neighbour search<br/>+ metadata filter"]
    F["country = Germany<br/>year ≥ 2024"] --> VS
    VS --> TK["Top k chunks"]
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE document_chunks (
    id          BIGSERIAL PRIMARY KEY,
    document_id BIGINT       NOT NULL,
    content     TEXT         NOT NULL,
    category    VARCHAR(100),
    embedding   VECTOR(384)             -- dimension of the chosen model
);

-- approximate nearest-neighbour index for cosine distance
CREATE INDEX document_chunks_embedding_idx
    ON document_chunks USING hnsw (embedding vector_cosine_ops);
SELECT id, document_id, content, category,
       1 - (embedding <=> :query_embedding) AS similarity   -- <=> = cosine distance
FROM   document_chunks
WHERE  category = 'Technology'                              -- metadata filter
ORDER  BY embedding <=> :query_embedding
LIMIT  5;
from sentence_transformers import SentenceTransformer
import numpy as np

model = SentenceTransformer("all-MiniLM-L6-v2")        # 384-dim, cosine
chunks = ["Heat islands and green roofs in Berlin",
          "Parking permit application guide",
          "Tree watering schedule for canal districts"]
E = model.encode(chunks, normalize_embeddings=True)
q = model.encode(["urban climate data"], normalize_embeddings=True)[0]

scores = E @ q                                          # unit vectors → dot = cosine
for i in np.argsort(-scores):
    print(f"{scores[i]:.2f}  {chunks[i]}")

This is the retrieval half of a RAG (retrieval augmented generation) pipeline, and it answers the planners' complaint from the scenario.

7. Supervised text classification

A vector alone predicts nothing; a classifier learns how vectors relate to labels. Geometrically, each document is a point, and the classifier learns a decision boundary between classes.

flowchart TB
    subgraph TR["Training"]
      direction LR
      L["Labelled<br/>documents"] --> V["Prepare and vectorise<br/>U3 pipeline · TF·IDF or embeddings"] --> T["Train and<br/>evaluate"]
    end
    subgraph PR["Prediction"]
      direction LR
      N["New<br/>document"] --> NV["Vectorise"] --> M(["Trained<br/>model"]) --> Y["Predicted<br/>label"]
    end
    TR -->|"produces the model"| PR
  • Training uses documents with known labels, e.g. 80 % of the data.
  • Testing measures performance on the held out 20 %. A useful classifier must generalise, not memorise.
Model Main idea
Naive Bayes probability of words appearing in each class
Logistic Regression learns how strongly each feature supports each class
Support Vector Machine learns a maximum margin boundary
k nearest Neighbours labels of the most similar document vectors
Neural classifier learns complex relationships (e.g. a layer on top of embeddings)

Naive Bayes, Logistic Regression and linear SVMs are strong, fast baselines for text.

A map of classification methods

mindmap
  root((Text<br/>classification))
    Manual rules
      keyword lists
      regular expressions
    Classic ML
      Naive Bayes
      Logistic regression
      Linear SVM
      k nearest neighbours
    Neural
      fine tuned transformers
      embeddings + classifier
    Zero shot
      LLM prompts

8. Naive Bayes, step by step

For a document with terms \(t_1, \dots, t_n\), choose the class with the highest score:

\[ \hat c = \arg\max_{c}\; P(c) \prod_{i=1}^{n} P(t_i \mid c) \]

It is naive because it assumes words contribute independently given the class. That is false for language, yet it works surprisingly well.

Training data

ID Class Document
S1 Sports goal team win
S2 Sports team goal match
S3 Sports goal score team
T1 Technology data server cloud
T2 Technology server network data
T3 Technology cloud data model

Step 1: vocabulary: {goal, team, win, match, score, data, server, cloud, network, model}, \(\lvert V\rvert = 10\).

Step 2: word counts per class

Word Sports Tech Word Sports Tech
goal 3 0 data 0 3
team 3 0 server 0 2
win 1 0 cloud 0 2
match 1 0 network 0 1
score 1 0 model 0 1

Total words: Sports 9, Technology 9.

Step 3: priors: \(P(\text{Sports}) = P(\text{Tech}) = 3/6 = 0.5\).

Step 4: the zero problem. Without smoothing \(P(\text{goal} \mid \text{Tech}) = 0/9 = 0\), so any document containing goal gets a Technology score of exactly 0: one unseen word vetoes a whole class.

Step 5: Laplace (add one) smoothing

\[ P(t \mid c) = \frac{\mathrm{count}(t, c) + 1}{\mathrm{totalWords}(c) + \lvert V\rvert} = \frac{\mathrm{count}(t,c) + 1}{9 + 10} \]
Word \(P(\cdot \mid \text{Sports})\) \(P(\cdot \mid \text{Tech})\)
goal \(4/19 = 0.211\) \(1/19 = 0.053\)
team \(4/19 = 0.211\) \(1/19 = 0.053\)

Step 6: classify goal team

\[ \text{Score}(\text{Sports}) = 0.5 \times \tfrac{4}{19} \times \tfrac{4}{19} \approx 0.0222 \qquad \text{Score}(\text{Tech}) = 0.5 \times \tfrac{1}{19} \times \tfrac{1}{19} \approx 0.0014 \]

Step 7: decide: Sports, with a score 16× larger. Normalised, \(P(\text{Sports} \mid d) \approx 0.0222 / (0.0222 + 0.0014) \approx 0.94\).

Practical note: use log probabilities

Multiplying hundreds of small probabilities underflows to 0 on a computer. Implementations add logs instead; the argmax is unchanged:

\[ \log \text{Score}(c) = \log P(c) + \sum_{t \in d} \log P(t \mid c) \]
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
from sklearn.pipeline import make_pipeline

X = ["goal team win", "team goal match", "goal score team",
     "data server cloud", "server network data", "cloud data model"]
y = ["Sports"] * 3 + ["Technology"] * 3

clf = make_pipeline(CountVectorizer(), MultinomialNB(alpha=1.0))   # alpha=1 → Laplace
clf.fit(X, y)
print(clf.predict(["goal team"]), clf.predict_proba(["goal team"]).round(3))
# ['Sports'] [[0.941 0.059]]  : matches the hand calculation
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.pipeline import make_pipeline

# texts, labels = load_citizen_messages()   # your data
X_tr, X_te, y_tr, y_te = train_test_split(texts, labels, test_size=0.2,
                                          stratify=labels, random_state=42)
model = make_pipeline(TfidfVectorizer(sublinear_tf=True, ngram_range=(1, 2), min_df=2),
                      LogisticRegression(max_iter=1000))
model.fit(X_tr, y_tr)
print(classification_report(y_te, model.predict(X_te)))   # precision, recall, F1 per class

Evaluating a classifier

For each class, count true/false positives and negatives on the test set:

\[ \text{Precision} = \frac{TP}{TP + FP}, \qquad \text{Recall} = \frac{TP}{TP + FN}, \qquad F_1 = \frac{2 \cdot P \cdot R}{P + R} \]

For CityDocs routing, recall on urgent classes (e.g. safety hazards) matters more than overall accuracy: a missed hazard is costlier than a misforwarded noise complaint. Always report per class metrics when classes are imbalanced.

Beyond accuracy: per class evaluation

The CityDocs inbox is imbalanced: most messages are routine.

pie showData
    title Test set of 1,000 citizen messages
    "Roads" : 600
    "Noise" : 300
    "Safety hazard" : 100

A classifier that always answers Roads reaches 60 % accuracy and never finds a hazard. We therefore evaluate per class, from the counts of true positives (TP), false positives (FP) and false negatives (FN):

\[ P_c = \frac{TP_c}{TP_c + FP_c}, \qquad R_c = \frac{TP_c}{TP_c + FN_c}, \qquad F_{1,c} = \frac{2 P_c R_c}{P_c + R_c} \]

and average in two ways:

\[ F_1^{\text{macro}} = \frac{1}{|C|} \sum_{c} F_{1,c} \qquad\qquad F_1^{\text{micro}} = F_1 \text{ computed from } \textstyle\sum_c TP_c,\; \sum_c FP_c,\; \sum_c FN_c \]

Worked example: the safety class

Of the 100 hazards, the model finds 70 (\(TP = 70\), \(FN = 30\)) and wrongly flags 20 other messages (\(FP = 20\)):

\[ P = \frac{70}{90} \approx 0.78, \qquad R = \frac{70}{100} = 0.70, \qquad F_1 = \frac{2 \cdot 0.78 \cdot 0.70}{1.48} \approx 0.74 \]

Macro averaging gives this small class the same weight as Roads; micro averaging is dominated by the large classes. For CityDocs we report both, and we tune for recall on hazards.

9. Classwork

Route the messages (30 min, pairs)

Using the Naive Bayes model trained above (by hand):

  1. Classify "team data". What happens, and why?
  2. Classify "new stadium network", where new and stadium are not in the vocabulary. What should happen to unknown words?
  3. Would you rather use TF·IDF + Logistic Regression or embeddings + Logistic Regression for CityDocs messages written in German, English and mixed slang? Justify.
Discussion
  1. \(0.5 \cdot \tfrac{4}{19} \cdot \tfrac{1}{19}\) for both classes: a tie; the priors are equal, so a tie breaking rule (or more features) is needed.
  2. Unknown words are usually ignored (they contribute equally to all classes). Only network counts → Technology.
  3. Multilingual embeddings handle synonyms, spelling variants and mixed language better; TF·IDF + LR is faster, more interpretable and a strong baseline. A sound plan: start with the TF·IDF baseline, then compare with embeddings on the same test set.

10. Check your understanding

Why is Laplace smoothing necessary?

Without it, a single word never seen with class \(c\) in training gives \(P(t \mid c) = 0\) and forces the whole product to 0, regardless of all other evidence.

Why might a chunked document be retrieved more accurately than the whole document?

A single embedding of a long, multitopic document averages its topics; chunk embeddings keep each topic's signal sharp, so a specific query can match the right passage.

When would you combine a vector index with metadata filters?

When results must satisfy hard constraints (country, date, department, access rights) and be semantically similar, for example climate adaptation projects in Germany since 2024.

11. Key takeaways

  • IR finds, classification decides, both on the same vector representations.
  • Sparse vectors are interpretable but miss synonyms; dense embeddings capture meaning.
  • Embedding systems need chunking, consistent models, a similarity metric and metadata.
  • Naive Bayes = prior × smoothed word likelihoods, computed in log space; a strong, fast baseline.
  • Always evaluate on held out data with per class precision, recall and F1.

Project options include text classification, clustering, topic tracking and semantic search. If you classify, provide a train/test split, a baseline (e.g. Naive Bayes), at least one stronger model, and per class precision/recall in your README.

Further reading

  • Manning, Raghavan & Schütze, Introduction to IR, ch. 13 to 15.
  • Jurafsky & Martin, Speech and Language Processing (3rd ed. draft), ch. 4 (Naive Bayes) and ch. 6 (vector semantics & embeddings).
  • Mitra & Craswell (2018), An Introduction to Neural Information Retrieval.
  • pgvector documentation: github.com/pgvector/pgvector