By Sagi Shaier · 7 November 2026 · 10 min read
Text classification explained: sentiment, topic, and intent
How sentiment, topic and intent classification differ and how to build, train and evaluate a text classifier in PyTorch.
Text classification reads a whole piece of text and returns one or more labels from a fixed list. A support ticket gets a queue such as billing, a review gets negative and a chat message gets reset_password. Many products sort text this way so that a person or another program can act on the label: route the ticket, count the complaints, open the right chatbot flow.
Language models work with tokens, which are whole words or pieces of words. This post says "word" in a few places to keep the examples simple.
What a text classifier returns
The input is one text and the output is a label from a list chosen before any model is built. That list is the label set. A ticket router might use billing, technical, shipping and account. Whatever the model reads, it can only answer with one of those four.

The label set comes from what the product does with the answer. If no part of the product acts on a label, that label usually does not belong in the first version.
Binary, multi-class and multi-label
The next choice is how many labels can apply to one text.
- Binary: one of two labels, such as
spamornot spam. - Multi-class: exactly one label out of several, such as one topic out of 20.
- Multi-label: several labels can be true at once, such as an article tagged both
politicsandeconomy.

A trained binary or multi-class classifier outputs one score per label and turns the scores into probabilities with softmax, which makes them positive and sum to 1. A multi-label classifier gives each label its own yes or no score, usually through a sigmoid, so several labels can pass at once. The multi-class vs multi-label post covers that difference in detail.
Sentiment classification
Sentiment classification returns a label for the opinion in a text. Common label sets are negative and positive, or negative, neutral and positive. Some products use one to five stars instead.

A product manager who wants a complaint queue might only need negative versus not negative. A dashboard of customer mood needs the neutral and positive counts too. Aspect-based sentiment changes the target again. In "the screen is sharp but the battery dies fast" it returns screen: positive and battery: negative instead of one label for the whole review.

Counting positive and negative words is not enough to get sentiment right. "great, another crash" contains a positive word and is a complaint. "not bad" contains a negative word and is mildly positive. Words also shift with the domain, so a model trained on movie reviews can misread support tickets about app crashes.

Topic classification
Topic classification returns a label for what a text is about. A research archive might sort abstracts into five research areas such as machine learning and biology. The fixed list of topics is called the taxonomy, and it comes from the application: the areas of an archive, the departments of a wiki or the folders of a document system.
Topic is often multi-label. A paper on neural networks for protein folding is both machine learning and biology, and forcing one label loses half the answer.
Single keywords are unreliable here. The word "model" can mean a statistical model, an animal model or a climate model. The word "cell" can point to biology, batteries or a spreadsheet.

Intent classification
Intent classification returns a label for what the user wants to do. A support chatbot reads "I forgot my password and cannot sign in" and returns reset_password, which opens the password reset flow. The list of goals the system can recognize is the intent inventory:
1intents = [
2 "reset_password",
3 "track_order",
4 "cancel_subscription",
5 "update_payment",
6 "talk_to_agent",
7 "out_of_scope",
8]Topic and intent can disagree on the same message. "My card was charged twice" is about billing, and the intent is dispute_charge or refund_request depending on what the product can do.

An intent system also needs a plan for messages that fit no intent. Without an out_of_scope label, "What is the weather tomorrow?" gets forced into one of the known flows. For vague messages such as "There is a problem with my card", asking a clarifying question can help the user more than any single label.

How a trained classifier makes a prediction
The trained versions of sentiment, topic and intent classifiers can use the same model shape. The text is split into tokens and each token is turned into an id. An embedding layer maps each id to a vector, and an encoder reads the sequence of vectors and returns one vector $h$ for the whole text. The encoder can be a recurrent network (RNN), which reads one token at a time and updates a hidden state, or a transformer.
A classification head is a linear layer that maps $h$ to one score per label:
$$z = Wh + b$$
$W$ is a weight matrix with one row per label and $b$ is a bias vector. The scores in $z$ are called logits. For three sentiment labels $z$ has three numbers, such as $-0.30$ for negative, $0.66$ for neutral and $1.88$ for positive. Softmax turns them into probabilities:
$$p_i = \frac{\exp(z_i)}{\sum_j \exp(z_j)}$$
For these logits that gives 0.08, 0.21 and 0.71. Taking the label with the highest probability, called the argmax, returns positive.
Training with cross-entropy
Training needs labeled examples, such as the review "the app keeps crashing after the update" with the label negative. The label is stored as an index into the label list, so negative is y = 0. The index only says which logit should be high. It does not mean negative is numerically close to neutral.
Cross-entropy is the standard loss for single-label classification. It is the negative log of the probability the model gave the correct label:
$$L = -\log p_y$$
Say the model outputs logits 2.0, 0.4 and 0.1 for this negative review. Softmax gives 0.74 for negative, so the loss is $-\log 0.74 = 0.30$. A model that put 0.99 on negative would get a loss of 0.01, and one that put 0.10 there would get 2.30. Training lowers the loss by raising the probability of the correct label.

PyTorch gives the same numbers:
1import torch
2import torch.nn.functional as F
3
4logits = torch.tensor([[2.0, 0.4, 0.1]]) # negative, neutral, positive
5target = torch.tensor([0]) # the review is negative
6
7probs = logits.softmax(dim=-1)
8print(probs.round(decimals=2))
9print(round(F.cross_entropy(logits, target).item(), 3))1tensor([[0.7400, 0.1500, 0.1100]])
20.301F.cross_entropy takes the raw logits and applies the softmax itself. Passing probabilities into it applies softmax twice and gives a wrong loss.
A small RNN classifier in PyTorch
The code below builds the whole classifier, runs one training step on two reviews and then predicts their labels:
1import torch
2import torch.nn as nn
3import torch.nn.functional as F
4
5torch.manual_seed(0)
6
7class SentimentRNN(nn.Module):
8 def __init__(self, vocab_size, emb_dim, hidden_size, num_classes=3):
9 super().__init__()
10 self.emb = nn.Embedding(vocab_size, emb_dim, padding_idx=0)
11 self.rnn = nn.RNN(emb_dim, hidden_size, batch_first=True)
12 self.head = nn.Linear(hidden_size, num_classes)
13
14 def forward(self, input_ids):
15 x = self.emb(input_ids) # (batch, seq_len, emb_dim)
16 output, hn = self.rnn(x) # hn: (1, batch, hidden_size)
17 h = hn[-1] # (batch, hidden_size)
18 return self.head(h) # (batch, num_classes)
19
20vocab = {"<pad>": 0, "the": 1, "app": 2, "keeps": 3, "crashing": 4,
21 "after": 5, "update": 6, "love": 7, "this": 8}
22id_to_label = ["negative", "neutral", "positive"]
23
24reviews = [["the", "app", "keeps", "crashing", "after", "the", "update"],
25 ["love", "this", "app"]]
26max_len = max(len(r) for r in reviews)
27input_ids = torch.tensor([[vocab[w] for w in r] + [0] * (max_len - len(r))
28 for r in reviews])
29labels = torch.tensor([0, 2]) # negative, positive
30
31model = SentimentRNN(vocab_size=len(vocab), emb_dim=16, hidden_size=32)
32optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)
33
34logits = model(input_ids)
35print(input_ids.shape, logits.shape)
36
37loss = F.cross_entropy(logits, labels)
38optimizer.zero_grad()
39loss.backward()
40optimizer.step()
41print(f"loss before the step: {loss.item():.3f}")
42
43model.eval()
44with torch.no_grad():
45 pred_ids = model(input_ids).softmax(dim=-1).argmax(dim=-1)
46print([id_to_label[i] for i in pred_ids.tolist()])1torch.Size([2, 7]) torch.Size([2, 3])
2loss before the step: 0.986
3['negative', 'positive']The shorter review is padded with id 0 up to 7 tokens, so input_ids has shape (2, 7). The logits have shape (2, 3), one row per review and one column per label, which is the layout F.cross_entropy expects. After one step on these two reviews the model labels both correctly, which says nothing yet about reviews it has not seen. A real classifier trains over many batches and is judged on held-out examples. If the loss does not go down, check first that labels holds class indices of shape (batch,) and not one-hot vectors or label strings.

Here is the same path for the review "the screen is sharp", with the logits from earlier:

Asking a language model instead
A large language model can also act as a classifier. The prompt names the allowed labels and includes the text:
1Return exactly one label: negative, neutral, or positive.
2Review: the app keeps crashing after the updateThe model generates its answer one token at a time, for example neg then ative. The system joins the tokens into a string, normalizes it and checks that it is one of the allowed labels. An answer such as mostly negative fails that check, so the code needs a rule for invalid answers.

A trained classifier can be cheaper, faster and easier to evaluate once it exists, and it needs labeled data that looks like the real inputs. A language model needs no training for the task and can help when the labels depend on long instructions or a few examples. Both paths still need held-out labeled examples to measure how well they work.
Evaluating a classifier
Hold back labeled examples the model never trained on, run them through the full pipeline and compare each predicted label with the true one. Accuracy is the share of correct labels. It can hide a weak label when the classes are uneven. If 1 review in 20 is negative, a model that never predicts negative still scores 0.95.
A confusion matrix shows where the mistakes are. Rows are the true labels, columns are the predicted labels and the diagonal holds the correct predictions. For one label, precision is the share of texts predicted as that label that really have it, and recall is the share of texts with that label that the model found. F1 combines the two, and macro F1 averages F1 over the labels so a rare label counts as much as a common one.
The code below computes all of these from the confusion matrix of 400 held-out reviews:
1import torch
2
3# rows are true labels, columns are predicted labels
4labels = ["negative", "neutral", "positive"]
5cm = torch.tensor([[120, 15, 10],
6 [ 20, 80, 20],
7 [ 10, 15, 110]], dtype=torch.float)
8
9tp = cm.diag()
10precision = tp / cm.sum(dim=0) # column sums: everything predicted as that label
11recall = tp / cm.sum(dim=1) # row sums: everything that truly has that label
12f1 = 2 * precision * recall / (precision + recall)
13
14for name, p, r, f in zip(labels, precision, recall, f1):
15 print(f"{name:9s} precision {p:.2f} recall {r:.2f} F1 {f:.2f}")
16print(f"accuracy {tp.sum() / cm.sum():.2f} macro F1 {f1.mean():.2f}")1negative precision 0.80 recall 0.83 F1 0.81
2neutral precision 0.73 recall 0.67 F1 0.70
3positive precision 0.79 recall 0.81 F1 0.80
4accuracy 0.77 macro F1 0.77neutral is the weakest label here. The model finds 80 of the 120 neutral reviews and labels the other 40 as negative or positive, 20 each.

Which number to watch depends on the product. If a small team reads every flagged complaint, precision on negative decides how much of their time is wasted. If a missed complaint is costly, recall on negative is the one to raise. The precision, recall and F1 post goes through these metrics with more examples.
Common mistakes
- Choosing the label set after collecting data. Labels decide what annotators mark and what the head outputs, so changing them later means relabeling.
- Forcing one label on multi-label text. An article about a trade deal that only gets
politicsloses itseconomytag. - No
out_of_scopeintent. Every unsupported request lands in a real flow, often with a high probability. - Passing probabilities to
F.cross_entropy. It expects raw logits and applies the softmax itself. - Reporting only accuracy on uneven classes. Report per-label precision and recall, or macro F1. The class imbalance post covers ways to handle rare labels during training.
- Trusting a language model's answer as a label. Parse it, check it against the allowed labels and decide what happens when the check fails.
Related concepts
Natural language inference is text classification over a pair of texts, with labels that describe how the two relate. Token classification gives a label to every token instead of one label to the whole text, which is how named entity recognition finds names. The encoder in the classifier above is an RNN, and softmax and cross-entropy each have their own post. NLP tasks explained shows how to decide that a request is a classification task in the first place.
QuiddityML teaches sentiment, topic and intent classification as separate concepts in the NLP tasks unit of its NLP track. The exercises on them include filling in the blanks of the RNN classifier, putting the lines of its prediction step in order and writing the model from scratch (QuiddityML).