White atrium of a multi-story library, shelves and staircases
Jolimoi Tech · Long read

Multi-label Classification Problems with Large Language Models

Sorting a text into several categories at once used to take masses of annotated data and a model to train. An LLM and a few examples shorten the road. They do not spare you from measuring.

By Alexis Blandin and Martin Labenne · 10 min read

Scroll down

In a library, a book takes up only one spot on the shelf. In the catalog, it can take up several: an essay on public debt files under politics and under economics. And some books fit none of the planned boxes.

Text data poses the same problem. A customer review, a support ticket, a news story rarely deal with a single topic. Labeling them is multi-label classification: assigning each text zero, one or several labels. The problem shows up everywhere, from social media tagging to medical diagnosis, through news article categorization and product recommendation.

We took another road than training a model: handing the sorting to a large language model. The shortcut is real. It has a price, and it moves rigor more than it removes it.

News story

“Election debate highlights key economic policies.”

Politics
Economy
Sports
Entertainment

Take this news story. Four shelves are open: politics, economy, sports and entertainment. Where does it go?
A first reader files it under politics: it is an election debate.
A second files it under economy: the debate is about economic policy. Both are right. The story goes on two shelves.
Another story, another case. None of the four shelves fits. Empty is an answer, and a classifier must know how to give it.
That is the whole difference between multi-class and multi-label. In multi-class, each text gets exactly one label. In multi-label, it gets zero, one or several, and their number varies from one text to the next.

Labels are not independent. A text filed under politics is more likely to also be filed under economy than under entertainment: the presence of one label changes the probability of the others. A good model learns these links on top of each label.

These labels are written in two ways: a list per text, or one binary column per label, set to 1 when the label applies. The second form is the one measurement tools expect.

TextListPol.Eco.SportsEnt.
Government passes new healthcare reform.politics1000
Stock market hits new highs amid economic boom.economy0100
Celebrity singer releases new music video.entertainment0001
Local sports team wins championship game.sports0010
Election debate highlights key economic policies.politics economy1100
AI will take on the world.[ ]0000
The same dataset, written as lists and as binary columns.

The difficulty lies in the arithmetic.

4labels
16
possible combinations
Share covered by 500 examples, at best
100%
If every example fell into a different combination.
With 4 labels, a text can get 16 combinations, from the empty set to all four at once. With 500 annotated examples, each one can be seen several times.
Each added label doubles that number. At 8 labels, there are 256 combinations.
At 12, it goes up to 4,096. Even in the best case, 500 examples cover only one in eight.
At 20 labels, more than a million. The label matrix empties out: most combinations have no example, and rare labels have too few for a model to learn them.

Training a model then takes a large amount of annotated data. The practical question becomes: what do you do when you have neither that data nor the means to produce it?

Wooden drawers of an old library card catalog
Shelf 1

The old road

What a hand-trained classifier costs.

The classic answer goes through a natural language processing project, NLP, in three steps.

Preprocessing

Lowercasing, removing punctuation and digits, stemming or lemmatization.

→

Features

Bag of words, n-grams.

→

Model

Model choice, hyperparameter tuning, validation.

Each step takes expertise, and multi-label adds two difficulties.

Imbalance. Some labels show up everywhere, others almost never. The wider the gap, the harder training gets.

Correlation. Labels depend on one another, and the model has to learn those dependencies on top of the labels themselves.

From preprocessing to validation, the road eats time and resources before the first useful prediction.

A ladder leaning against tall shelves, between two columns
Shelf 2

The shortcut

An already trained model, an API, a few examples.

Large language models change the equation. Trained on huge volumes of text, they summarize, translate and analyze sentiment in most languages. Classifying a text is within their skills, for three reasons.

Simple. Providers expose an API you can call from any language. No machine learning expertise needed, and the text does not even need preprocessing.

Cheaper. The best language models are neural networks, which run fast on GPUs. Setting up an equipped instance, in the cloud or on premises, weighs down deployment and operations. For short texts, paying a provider for inference by the token, a fragment of a word, often comes out cheaper.

Tunable. One or two examples slipped into the instructions are enough to raise the quality of predictions.

That leaves the usual objection: an LLM would never answer the same thing twice. True in general, and rare on a simple classification task. The OpenAI API also lets you pin down the randomness.

# pin down randomness as far as the API allows
temperature=0,
seed=424242,

The result becomes almost deterministic. For classification, almost is enough.

No training set.A test set, always.

The LLM spares you from training a model. It does not spare you from checking that it classifies your own texts well. For multi-label, a good test set:

Refreshing it with fresh data lets you track quality under real conditions, on texts the prompt has never seen.

Engraving of readers absorbed under library lamps
Shelf 3

The price of a thought

Every word the model writes is paid for, in money and in time.

Since LLMs arrived, prompting techniques keep multiplying: few-shot, chain of thought, tree of thoughts, and a new one every month. They do not use the same number of tokens, and that number decides cost and latency.

= 4 tokens read cost as much as 1 token written
Chain of thoughtreasons step by step
Tree of thoughtsseveral experts debate
Few-shotexamples, short answer
inputoutputa diagram, not a measurement
One rule first. Providers bill roughly a quarter of the cost to input tokens and three quarters to output tokens. Four words read cost as much as one word written, and every word written takes time.
Chain of thought asks the model to reason step by step (“Let's think step by step”). It writes out its reasoning before answering: lots of output.
Tree of thoughts has several imaginary experts debate. Each writes a step, shares it, and leaves the discussion if wrong. The output grows longer still.
Few-shot works the other way around: short instructions, a few question-answer pairs as examples, then the text to process. The input grows, the output shrinks to a list of labels.
For classification, few-shot wins: you pay for the examples at the input rate and save on output. Chain of thought and tree of thoughts remain an option when neither budget nor latency matters.
An aisle of shelves with neatly arranged books
Shelf 4

The classifier

A few dozen lines of Python.

The classifier relies on the OpenAI API. It picks between zero and four labels: sports, politics, economy and entertainment. It all comes down to the message stack sent to the model.

messages = [  {"role": "system", "content":    "You are a multi-label classifier. Return the tags as a "    "list separated by commas. If no tags apply, return nothing. "    "Available tags: sports, politics, economy, entertainment."},   # example 1: two labels  {"role": "user",   "content": "Text: 'Election debate highlights key economic policies.'"},  {"role": "assistant", "content": "Tags:politics,economy"},   # example 2: no label  {"role": "user", "content": "Text: 'AI will take on the world.'"},  {"role": "assistant", "content": "Tags:"},   # the text to classify  {"role": "user", "content": f"Text: '{content_txt}'"},]
The system prompt describes the task, the output format and the allowed labels. It also says what to do when nothing applies: answer nothing.
The first example shows a story with two labels, and the exact shape of the expected answer: a prefix, then a comma-separated list.
The second shows the empty case. An answer with no label is allowed, and the model sees it written in black and white.
The text to classify comes last. Choosing the examples remains the hard part: they are what teach the model the structure of the task and the output format.

The model's answer is still free text. It has to be cleaned: strip the prefix, split, trim the spaces. Then filtered, because the model can invent a label. Intersecting with the allowed list erases it.

ALLOWED = ["sports", "politics", "economy", "entertainment"] def parse_labels(completion) -> list[str]:    text = completion.choices[0].message.content    text = text.replace("Tags:", "").strip()    if not text:        return []    labels = [label.strip() for label in text.split(",")]    return sorted(set(labels) & set(ALLOWED))   # the guardrail
Condensed excerpt. The sorted list compares directly with the test set.

Few-shot has a limit: the more labels, the more the model hesitates, and precision drops. When labels form a hierarchy, a cascade gets around the problem. A first call picks the floor, a second, specialized one, picks the shelf.

Text

→

Broad categories

first call, generalist

→

Specialist A

fine-grained labels

Specialist B

fine-grained labels

Otherwise, you have to test costlier techniques that are less sensitive to the number of labels.

One last plumbing detail. Classifying a backlog of thousands of texts quickly hits the provider's rate limit. The ratelimit package settles it with two decorators: beyond 50 calls a minute, extra calls wait for the next window instead of failing.

from ratelimit import limits, sleep_and_retry @sleep_and_retry               # beyond that: wait, then retry@limits(calls=50, period=60)   # 50 calls per minutedef get_chat_completion(messages):    return client.chat.completions.create(        model=MODEL_NAME, messages=messages,        temperature=0, seed=424242,    )
Large reading room full of readers, seen from above
Shelf 5

In production

Trace, measure, compare.

In production, every call must leave a trace: the input, the output, the number of tokens and the duration. These traces show good and bad predictions, the real cost and the latency. A longer sequence takes longer to generate. Tools like LangSmith or Phoenix make these traces readable.

Quality is measured continuously, on fresh data, through human review or through a second LLM tasked with judging the first: LLM as a judge. Each prompt version is kept with its classification report, to compare versions on the same metrics.

That leaves choosing those metrics. In multi-label, the same prediction gets very different scores depending on the rule applied.

Expectedpoliticseconomy Predictedpolitics

Exact match

0

All or nothing.

Hamming loss

0.25

1 wrong label out of 4.

Jaccard

0.5

1 in common out of 2 in total.

Precision · Recall

1 · 0.5

Nothing wrong, one miss.

Back to the story from the start. We expected politics and economy. The model predicts only politics.
Exact match, or subset accuracy, counts all or nothing: the predicted set must be identical to the expected set. Here, 0. It is the strictest metric.
Hamming loss counts mispredicted labels, one by one. Out of four possible labels, only one is wrong: 0.25. The lower, the better.
The Jaccard score divides the intersection by the union: one label in common, two in total. 0.5.
Precision looks at what was predicted: all of it is right, 1. Recall looks at what was expected: half of it was found, 0.5. F1, their harmonic mean, comes to 0.67.

The choice depends on the error you fear. Precision avoids false positives, recall avoids misses, F1 balances the two. To aggregate over several labels, scikit-learn offers four averages.

micro
a global count of true and false positives, across all labels;
macro
the simple average per label, where a rare label weighs as much as a frequent one;
weighted
the average per label, weighted by its frequency, which accounts for imbalance;
samples
the computation text by text, then the average: it tells whether the model finds the right labels for each text.

A single call to classification_report gives precision, recall, F1 and support, per label and for each average.

mlb = MultiLabelBinarizer().fit([ALLOWED])y_true = mlb.transform(labels_true)y_pred = mlb.transform(labels_pred) accuracy_score(y_true, y_pred)       # exact matchhamming_loss(y_true, y_pred)jaccard_score(y_true, y_pred, average="samples")classification_report(y_true, y_pred, target_names=mlb.classes_)

An LLM does not get rid of the dataset.It moves it from training to testing.

The shortcut is real: an API, a few examples, no preprocessing pipeline and no model to train. But rigor moves elsewhere. It settles in the test set, in the traces, in the metrics and in the prompt history. That is where you find out whether the book is on the right shelf.