Lensa ML

Text Classification

Step 1 of 6: Bag of Words

From text to feature vectors

Vocabulary size6
Input sentence:thismoviewasgreatandamazing↓Bag-of-Words vector (vocab=6):great1terrible0love0hate0good0bad0Non-vocabulary words ("this", "movie", "was", "and", "amazing") are ignored
Vocab size
6
Non-zero
1
Sparsity
83%

"amazing" is not among the first 6 vocabulary words, so it is dropped too and the vector misses it. With a 6-word vocabulary, the sentence becomes a 6-dimensional vector. Most entries are 0 (83% sparse). Word order is ignored: "great and amazing" = "amazing and great".

Drag Vocabulary size from 4 to 12 and watch the vector for "this movie was great and amazing" grow. This vocabulary holds only sentiment words, so "this", "movie", and "was" get no column at all, and "amazing" appears only once the vocabulary reaches 7 words. Choosing the vocabulary is a modeling decision. A spam filter needs words like "free" and "winner", and a sentiment model needs negations like "not", which many default stop-word lists remove. Most pipelines let the data decide by keeping the most frequent few thousand words or n-grams.

Step 2 of 6: Feature Space

Documents as data points

Sentence (1/8)0
thismoviewasgreatandamazing
1122330positive word count →negative word count →+×3(2, 0)−×3−+PositiveNegative
Pos words
2
Neg words
0
True label
Positive
Separable?
Yes ✓

This sentence has 2 positive words and no negative words, so it maps to the bottom-right, where most of the positive reviews land.

Drag Sentence from 1 to 8 to step through the reviews and find each one on the plot. Sentences 4 and 7 mix positive and negative words, so they sit between the two clusters. The two axes are hand-built counts of positive and negative words, so 12 vocabulary dimensions collapse to 2. Hand-built signals like these powered early sentiment systems. Learned models take the opposite route: they keep every word as its own dimension and let training decide which ones matter. That works because classes that overlap in two dimensions often become linearly separable in thousands.

Step 3 of 6: Training a Classifier

Finding a decision boundary

Decision boundary angle (°)120
positivewordsnegative words+×3−×3−+✗
Angle
120°
Accuracy
88%
Correct
7/8

88% accuracy. The boundary misclassifies 1 point(s), marked with ✗. Keep rotating to find a better angle.

Drag Decision boundary angle (°) from 0 to 360 and watch the accuracy change. At the default 120°, the mixed review "great work despite a bad start" falls on the negative side, and only angles from about 136° to 153° get all 8 right. The rule is ŷ = 1 if w · x > 0, where w is a weight vector perpendicular to the line. Only the angle moves here, but a trained model also learns the length of w and a bias b that shifts the line away from the origin. Training does not search angles one by one. Logistic regression follows the gradient of the cross-entropy loss, and a linear SVM maximizes the margin between the classes. On clean data their lines end up close.

Step 4 of 6: Softmax & Confidence

From scores to probabilities

Temperature1.00
softmax(z_i / T) — T = 1.0Raw logits:2.1Positive-1.5Negative÷T, exp, normProbabilities:97.3%2.7%Confidence meter97.3%0.112.55argmax (one-hot)standarduniform
Temperature
1.0
P(positive)
97.3%
P(negative)
2.7%
Confidence
97.3%

Temperature 1.0: the model assigns 97% to Positive and 3% to Negative. At T=1 (standard softmax), they follow directly from the raw logit gap.

Drag Temperature from 0.1 to 5.0 and watch confidence fall from near 100% toward 50%. The logits are fixed at 2.1 for Positive and −1.5 for Negative. With two classes, softmax reduces to a sigmoid of the gap: P(positive) = σ((2.1 − (−1.5)) / T), which is σ(3.6) ≈ 0.973 at T = 1. Modern neural classifiers tend to be overconfident. Guo et al. (2017) showed that fitting one temperature on a validation set after training, called temperature scaling, fixes most of this miscalibration without changing any prediction.

Step 5 of 6: Sentiment Polarity

Positive, negative, and neutral

Sentence (1/8)0
1. Look up each word in the sentiment lexicon:this+0.00movie+0.00was+0.00great+0.40and+0.00amazing+0.482. Visualize each word's contribution:0+−3. Sum all scores → polarity:+0.40 +0.48 = +0.884. Map to polarity scale [−1, +1]:−1 (negative)0+1 (positive)POSITIVE (+0.88)
Polarity
+0.88
Scored words
2/6
Raw sum
+0.88
Sentiment
Positive

Positive words (great, amazing) contribute +0.40, +0.48. These sum to +0.88, giving a clear positive polarity. For plainly worded sentences like this, a lexicon is enough.

Drag Sentence from 1 to 8 and watch each word's lexicon score add up. Lexicon methods need no training data, which is why tools like VADER are still used for quick social media analysis. Sentence 5, "not bad but could be better", shows the weakness: the sum is −0.38, a negative label for a mildly positive review. Rule-based systems patch negation by flipping the scores of words that follow "not". Learned models handle it by treating "not bad" as a bigram or by reading the sentence in order.

Step 6 of 6: Beyond Binary

Multi-class text classification

Number of classes2
PositiveNegative
Classes
2
Samples
10
Boundaries
1

Binary classification: positive vs. negative. One decision boundary splits the space into two regions, like a single threshold on a score.

Drag Number of classes from 2 to 5 and watch the regions multiply. A softmax classifier learns one weight vector per class and assigns each input to the class with the highest score, so K classes need K weight vectors, not one per pair. Many tasks are multi-label instead: one news story can be both sports and business. Those use an independent sigmoid per label and a threshold on each. Today the usual approach is to fine-tune a pretrained model such as BERT with a small classification layer on top.

What is text classification?

Text classification is the task of assigning a label to a piece of text, such as positive or negative for a review, or spam or not spam for an email. A classifier turns the text into a vector of numbers, computes a score for each label, and picks the label with the highest score. It learns how to score from examples that people have already labeled.

It is one of the most common uses of machine learning on language. Email providers filter spam with it, support teams route tickets by topic, chatbots detect user intent, platforms flag toxic posts, and companies track sentiment in reviews and social media. The methods range from word counts with logistic regression, which still make strong baselines, to fine-tuned transformers such as BERT and zero-shot prompting of large language models.

Key ideas

  • A text classifier maps a document to a vector and the vector to a label.
  • Bag-of-words and TF-IDF vectors with a linear model make a strong, fast baseline.
  • A linear classifier separates classes with a hyperplane w · x + b = 0.
  • Softmax turns class scores into probabilities, and temperature controls how confident they look.
  • Lexicon scoring needs no training but fails on negation, sarcasm, and context.
  • Multi-class tasks use one softmax over K classes; multi-label tasks use one sigmoid per label.

Common questions

What is the best algorithm for text classification?

It depends on how much labeled data there is. With a few thousand examples, TF-IDF with logistic regression or a linear SVM is fast and hard to beat. With more data, or when context and negation matter, a fine-tuned transformer such as BERT is usually more accurate. With no labeled data at all, a large language model can classify from a prompt.

How do you evaluate a text classifier?

Accuracy works when classes are balanced. When one class is rare, such as spam or toxic posts, precision, recall, and F1 for that class are more informative, because a model that always predicts the majority class can still score high accuracy. A confusion matrix shows which classes get mixed up.

How much labeled data does text classification need?

Simple binary tasks with distinctive words can work with a few hundred labeled examples. Fine-tuning a pretrained model needs far less data than training from scratch, because the model already knows the language. Tasks with many classes or subtle distinctions need more examples per class.

What is the difference between sentiment analysis and text classification?

Sentiment analysis is one kind of text classification, where the labels are opinions such as positive, negative, and neutral. Text classification also covers topic labeling, spam detection, language identification, and intent detection, all of which use the same methods with different labels.

Related explainers

References

  1. Pang, Lee & Vaithyanathan (2002), "Thumbs up? Sentiment Classification using Machine Learning Techniques", EMNLP
  2. Joulin et al. (2016), "Bag of Tricks for Efficient Text Classification"
  3. Guo et al. (2017), "On Calibration of Modern Neural Networks", ICML
  4. Devlin et al. (2019), "BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding", NAACL
  5. Jurafsky & Martin, "Speech and Language Processing" (3rd ed. draft)

Last updated