AI and machine learning · Intermediate · 25 min
Classify text cheaply with embeddings and logistic regression
By Padding · Updated 18 Nov 2026
Python 3.15 · sentence-transformers 6.3 · scikit-learn 1.9 · PyTorch 2.15 (CPU)
You will train a small intent classifier on embeddings of 1,200 labelled support messages, report its precision and recall on held-out data, send low-confidence messages to a person, and work out what the same job would cost through an LLM API.
On this page
A support inbox, a feedback form or a chat widget often needs one small decision per message: which queue does this go to? Sending every message to a large language model works, but you pay per call, wait for a network round trip each time and send customer text to a third party. For a fixed set of labels there is a cheaper first line: turn each message into an embedding with a small local model, then train a plain logistic regression on those vectors.
In this tutorial you build that for a mobile wallet's support inbox with five intents: checking a balance, sending money, a failed transfer, buying airtime or data, and resetting a PIN. You generate 1,200 labelled messages, embed them on your CPU, train the classifier, read its precision and recall per intent on messages held out from training, and add a confidence threshold that hands unsure messages to a person. Last, you put the cost and time of this approach next to an LLM API call for the same 1,000 messages.
Everything runs offline after the first download. No API key is needed.
Step 1 · Create the project and install the libraries
Make a throwaway folder and a virtual environment:
mkdir -p ~/intent-demo
cd ~/intent-demo
python3 -m venv .venv
source .venv/bin/activateInstall PyTorch from its CPU-only index first, so pip does not pull the much larger GPU build, then the embedding library and scikit-learn:
pip install --quiet torch==2.15.0 --index-url https://download.pytorch.org/whl/cpu
pip install --quiet sentence-transformers==6.3.0 scikit-learn==1.9.1PyTorch is a few hundred megabytes. On prepaid mobile data, run this step on Wi-Fi; it is a one-off.
Check it worked
python -c "import torch, sentence_transformers, sklearn; print(torch.__version__, sentence_transformers.__version__, sklearn.__version__)"The output starts with 2.15.0 (with +cpu on Linux) and ends with 6.3.0 1.9.1.
Step 2 · Generate 1,200 labelled messages
Real labelled data is the slow part of any classifier. Here you generate it, so the tutorial is repeatable: templates for each intent, filled with names and amounts, with greetings and sign-offs added at random. Up to about 8% of messages are deliberately vague, such as "my money is not showing", and get one of two plausible labels at random. Real inboxes are full of those, and they are what the confidence threshold later has to catch.
cat > make_data.py <<'PY'
import csv
import random
random.seed(7)
INTENTS = {
"check_balance": [
"what is my balance",
"how much money is left in my wallet",
"show me my account balance",
"can I see how much I have",
"check my wallet balance",
"I want to know my current balance",
"how much is remaining on my account",
],
"send_money": [
"I want to send {amount} to {name}",
"how do I transfer money to {name}",
"send {amount} to my brother",
"please move {amount} to {name}'s wallet",
"can I pay {name} from my phone",
"transfer {amount} to another number",
"I need to send cash to {name} today",
],
"failed_transfer": [
"I sent {amount} to {name} but it did not arrive",
"my transfer failed but the money left my account",
"{name} has not received the {amount} I sent",
"the payment shows pending since yesterday",
"I was debited twice for one transfer",
"transaction failed and no refund yet",
"money was deducted but {name} got nothing",
],
"buy_airtime": [
"buy {amount} airtime for my line",
"I want to top up my phone",
"how do I buy a data bundle",
"recharge {amount} credit for {name}",
"get me a 2GB data plan",
"top up airtime on my number",
"I need more mobile data",
],
"reset_pin": [
"I forgot my PIN",
"how do I reset my PIN",
"my account is locked after wrong PIN",
"I want to change my password",
"I can't log in to the app",
"my PIN is blocked please help",
"reset my login details",
],
}
# Vague messages that a person could file under either of two intents.
# Each one gets one of its two labels at random, as happens in real inboxes.
VAGUE = [
("my money is not showing", ["check_balance", "failed_transfer"]),
("something is wrong with my account", ["reset_pin", "check_balance"]),
("I need help with a transfer", ["send_money", "failed_transfer"]),
("the app is not working for payments", ["send_money", "reset_pin"]),
("why was I charged", ["failed_transfer", "buy_airtime"]),
("my data money is gone", ["buy_airtime", "check_balance"]),
]
NAMES = ["Ada", "Kofi", "Amina", "Tunde", "Wanjiru", "Sipho", "Maria", "Chen", "Fatima", "Joseph"]
AMOUNTS = ["500", "1,000", "2,500", "5,000", "10,000", "20 dollars", "50 cedis", "3,000 naira"]
OPENERS = ["", "", "hi ", "hello, ", "good morning ", "please ", "pls "]
CLOSERS = ["", "", " thanks", " asap", " please help", "?", " thank you"]
PER_INTENT = 240
VAGUE_SHARE = 0.08
def fill(template):
text = template.format(name=random.choice(NAMES), amount=random.choice(AMOUNTS))
text = random.choice(OPENERS) + text + random.choice(CLOSERS)
return text.lower() if random.random() < 0.3 else text
rows = []
seen = set() # every text appears once, so no test message is a copy of a training one
for intent, templates in INTENTS.items():
count = 0
while count < PER_INTENT:
if random.random() < VAGUE_SHARE:
options = [v for v in VAGUE if intent in v[1]]
text = fill(random.choice(options)[0])
else:
text = fill(random.choice(templates))
if text in seen:
continue
seen.add(text)
rows.append((text, intent))
count += 1
random.shuffle(rows)
with open("messages.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["text", "label"])
writer.writerows(rows)
print(f"wrote {len(rows)} messages")
PY
python make_data.py
head -6 messages.csvThe fixed seed (random.seed(7)) means you get the same 1,200 messages every time you run it. The seen set skips any text that has already been generated. Without it, about a fifth of the rows would be word-for-word copies, and the split below would put the same message in both the training and the test set, which makes the scores look better than they are.
Check it worked
The script prints wrote 1200 messages, and head shows the text,label header followed by mixed messages such as good morning the payment shows pending since yesterday?,failed_transfer. Count the labels to confirm the classes are balanced, and that no text appears twice:
python -c "import csv, collections; rows = list(csv.DictReader(open('messages.csv'))); print(collections.Counter(r['label'] for r in rows)); print('unique texts:', len({r['text'] for r in rows}))"The Counter shows 240 for each of the five intents, and the next line reads unique texts: 1200. If your own data is lopsided, say 90% balance questions, keep that in mind when you read the results: a classifier can look accurate by mostly guessing the common class.
Step 3 · Embed every message once
The embedding model is the same small open model as in the embeddings tutorial, pinned to an exact revision so your vectors stay the same. Keep the loader in its own file, because the classifier script reuses it:
cat > common.py <<'PY'
from sentence_transformers import SentenceTransformer
MODEL_ID = "sentence-transformers/all-MiniLM-L6-v2"
REVISION = "1110a243fdf4706b3f48f1d95db1a4f5529b4d41"
def load_model():
return SentenceTransformer(MODEL_ID, revision=REVISION, device="cpu")
PYEmbed all 1,200 messages in one batched call and save the vectors and labels as NumPy files:
cat > embed.py <<'PY'
import csv
import time
import numpy as np
from common import load_model
with open("messages.csv", newline="") as f:
rows = list(csv.DictReader(f))
texts = [row["text"] for row in rows]
labels = np.array([row["label"] for row in rows])
model = load_model()
start = time.perf_counter()
vectors = model.encode(texts, batch_size=64, normalize_embeddings=True)
seconds = time.perf_counter() - start
np.save("vectors.npy", vectors)
np.save("labels.npy", labels)
print(f"embedded {len(texts)} messages in {seconds:.1f} s")
print(f"about {1000 * seconds / len(texts):.1f} s per 1,000 messages")
print("vectors:", vectors.shape, vectors.dtype)
assert vectors.shape == (1200, 384)
PY
python embed.pyThe first run downloads the model, about 91 MB, into ~/.cache/huggingface. Vectors are normalised (normalize_embeddings=True), so every row has length 1 and no message counts for more just because its vector is longer.
Check it worked
The output ends with vectors: (1200, 384) float32: one row of 384 numbers per message. The timing line is your CPU's speed, something like 2 to 10 seconds per 1,000 short messages on a laptop. You only pay this once; training below reads the saved file.
Step 4 · Train logistic regression and read precision and recall
Logistic regression learns one weight per vector dimension for each intent, then turns the weighted sums into probabilities that add up to 1. With 384 inputs and 960 training rows it trains in well under a second.
Hold back 20% of the messages for testing. stratify=labels keeps the five intents in the same proportions in both halves, and the fixed random_state makes the split repeatable:
cat > train.py <<'PY'
import csv
import joblib
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
vectors = np.load("vectors.npy")
labels = np.load("labels.npy")
with open("messages.csv", newline="") as f:
texts = np.array([row["text"] for row in csv.DictReader(f)])
X_train, X_test, y_train, y_test, t_train, t_test = train_test_split(
vectors, labels, texts, test_size=0.2, stratify=labels, random_state=42
)
clf = LogisticRegression(C=10.0, max_iter=2000)
clf.fit(X_train, y_train)
predicted = clf.predict(X_test)
print(f"train: {len(y_train)} test: {len(y_test)}")
print(classification_report(y_test, predicted, digits=3))
joblib.dump(clf, "intent_clf.joblib")
np.savez("test_set.npz", X=X_test, y=y_test, texts=t_test)
accuracy = float((predicted == y_test).mean())
assert len(y_test) == 240
assert accuracy > 0.85, accuracy
PY
python train.pyC=10.0 weakens the default regularisation (C=1.0) tenfold, which suits a small set of clean vectors; try 1.0 and compare. The trained model is saved with joblib, which comes with scikit-learn.
Check it worked
You see train: 960 test: 240 and a table with one row per intent. Read it like this:
- Precision for
send_moneyanswers: of the messages the model calledsend_money, how many really were? Low precision means other intents are leaking into this queue. - Recall answers: of the real
send_moneymessages, how many did the model find? Low recall means this intent's messages end up in other queues. - Support is the number of test messages with that label,
48for each intent here.
Your table shows precision and recall between about 0.92 and 1.00 for every intent, and an accuracy around 0.95. The third decimal place can differ on another CPU. Most errors come from the vague messages, which have no single right answer. Because every text in the file is unique, no test message is a word-for-word copy of a training one, but the test messages still come from the same templates, so they are closer to the training data than real customers would be. A score of 1.000 on generated data would not mean much: templates are easier than real customers, so expect lower numbers on your own messages and always measure on a held-out set you labelled yourself.
Step 5 · Send low-confidence messages to a person
predict_proba gives the model's probability for each intent. The highest one is its confidence. If you act only on messages above a threshold and route the rest to a person (or to an LLM), you trade coverage for accuracy. See how that trade looks on the test set:
cat > route.py <<'PY'
import joblib
import numpy as np
clf = joblib.load("intent_clf.joblib")
test = np.load("test_set.npz")
X, y, texts = test["X"], test["y"], test["texts"]
proba = clf.predict_proba(X)
confidence = proba.max(axis=1)
predicted = clf.classes_[proba.argmax(axis=1)]
correct = predicted == y
print("threshold handled accuracy_handled sent_to_person")
for threshold in [0.0, 0.5, 0.6, 0.7, 0.8, 0.9]:
handled = confidence >= threshold
acc = correct[handled].mean() if handled.any() else float("nan")
print(f"{threshold:>9.1f} {handled.mean():>7.1%} {acc:>16.1%} {(~handled).sum():>14}")
THRESHOLD = 0.7
routed = confidence < THRESHOLD
print(f"\nwrong answers overall: {(~correct).sum()}")
print(f"wrong answers caught by routing at {THRESHOLD}: {(~correct & routed).sum()}")
print("\nlowest-confidence messages:")
for i in np.argsort(confidence)[:5]:
print(f" {confidence[i]:.2f} guess={predicted[i]:<16} label={y[i]:<16} {texts[i]}")
assert correct[confidence >= THRESHOLD].mean() >= correct.mean()
PY
python route.pyCheck it worked
The table has one row per threshold. At 0.0 the model handles every message, with the accuracy you saw above. As the threshold rises, the handled share falls and the accuracy on handled messages climbs towards 100%. At 0.7, the model handles about 94% of messages, and most of the wrong answers are among the 6% sent to a person: the summary lines show something like wrong answers overall: 12 and wrong answers caught by routing at 0.7: 9.
The five lowest-confidence messages are the vague ones, such as the app is not working for payments and something is wrong with my account, with confidence near 0.5. That is the behaviour you want: the model is unsure exactly where a person would be.
Choose the threshold from your own data and costs. If a wrong queue costs a customer a day, route more; if people are scarce, route less. These probabilities are a guide, not a guarantee. Have a person review a random sample of the auto-handled messages every week as well, because a confident model can still be confidently wrong on a new kind of message.
Step 6 · Classify new messages
Put it together: embed incoming messages, predict, and route by the threshold. The script also times 1,000 messages and saves the figure for the cost comparison:
cat > classify.py <<'PY'
import time
import joblib
from common import load_model
THRESHOLD = 0.7
clf = joblib.load("intent_clf.joblib")
model = load_model()
def classify(messages):
vectors = model.encode(messages, batch_size=64, normalize_embeddings=True)
proba = clf.predict_proba(vectors)
results = []
for message, row in zip(messages, proba):
best = row.argmax()
label, confidence = str(clf.classes_[best]), float(row[best])
route = "auto" if confidence >= THRESHOLD else "person"
results.append((message, label, confidence, route))
return results
new_messages = [
"Please send 4,000 to Ngozi",
"how do I recover my PIN",
"I bought data but my balance did not change",
"hello",
]
results = classify(new_messages)
for message, label, confidence, route in results:
print(f"{route:<7} {label:<16} {confidence:.2f} {message}")
batch = new_messages * 250
start = time.perf_counter()
classify(batch)
seconds = time.perf_counter() - start
print(f"\n{len(batch)} messages in {seconds:.2f} s on this CPU")
with open("local_seconds.txt", "w") as f:
f.write(f"{seconds:.3f}\n")
assert results[0][1] == "send_money" and results[0][3] == "auto"
assert results[1][1] == "reset_pin"
assert results[3][3] == "person"
PY
python classify.pyOnly load joblib files you created yourself. Loading one runs Python's pickle, which can execute code from the file.
Check it worked
Four lines print, one per message:
Please send 4,000 to Ngozigoes tosend_money,auto, with a confidence around 0.95. Ngozi is not among the training names; the embedding carries the meaning.how do I recover my PINgoes toreset_pin,auto. "Recover" never appears in the training data.I bought data but my balance did not changelands oncheck_balance,auto, at about 0.8. A person might call it a failed purchase, and the model is confident anyway. This is why the weekly sample review matters.hellois routed topersonwith low confidence. It fits no intent, and the model says so instead of forcing a guess.
The last line gives the time for 1,000 messages on your CPU, typically a second or a few. If you serve mostly African markets, add your customers' real phrasing to the training data: this model was trained on English, so messages in Pidgin, Hausa, Swahili or a mix score less reliably. Try sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2 and compare its report with this one.
Step 7 · Compare cost and speed with an LLM API call
The alternative is to send each message to an LLM with instructions that list the five intents, and ask for one label back. You do not need to make those calls to estimate the bill. The script below uses published per-token prices (dated in the code) and estimated token counts:
cat > cost.py <<'PY'
# Prices in US dollars per million tokens: standard Claude API rates for prompts
# under 100,000 tokens, copied from https://platform.claude.com/docs/en/about-claude/pricing
# on 26 November 2026. Check that page before you rely on them: prices change.
PRICES = {
"claude-haiku-5-5": (0.10, 0.50),
"claude-sonnet-5-5": (2.00, 10.00),
}
# Estimates for one classification call: instructions that list the five intents,
# plus the message. Count your real prompt with the API's token counting endpoint.
INPUT_TOKENS = 300
# Output: a bare label with no thinking is the lower bound; a few hundred tokens
# is a typical reply when the model thinks first at low effort.
OUTPUT_TOKENS = {"label only, no thinking (lower bound)": 20, "with thinking at low effort": 300}
MESSAGES = 1000
with open("local_seconds.txt") as f:
local_seconds = float(f.read()) # measured by classify.py
print(f"local classifier: {local_seconds:.1f} s per {MESSAGES:,} messages, no per-call fee\n")
print(f"{'model':<19} {'output':<38} {'USD per 1,000':>13}")
costs = []
for model, (price_in, price_out) in PRICES.items():
for label, out_tokens in OUTPUT_TOKENS.items():
cost = MESSAGES * (INPUT_TOKENS * price_in + out_tokens * price_out) / 1_000_000
costs.append(cost)
print(f"{model:<19} {label:<38} {cost:>13.3f}")
ASSUMED_LATENCY = 1.0 # seconds per API call: an assumption, replace it with your own measurement
print(f"\none call at a time, {ASSUMED_LATENCY:.1f} s each: about {MESSAGES * ASSUMED_LATENCY / 60:.0f} minutes per {MESSAGES:,}")
assert round(costs[0], 3) == 0.040
PY
python cost.pyThe estimates in the script: about 300 input tokens per call for the instructions and the message, and between about 20 and about 300 output tokens. Thinking is not a simple switch. Both models use adaptive thinking, which is on by default: the model decides on each request whether to reason first, so a short label may come back with no thinking, which is the 20-token lower bound. Sonnet 5.5 does not support turning thinking off; the control is the effort level, and output_config={"effort": "low"} gets less of it. The 300-token row is a typical reply with thinking at low effort. Thinking tokens are billed as output tokens, so they can multiply the cost of a one-word answer. Count your real prompt with the API's token counting endpoint before you trust any of these numbers.
Check it worked
The first line shows your measured local time for 1,000 messages. The table shows the API cost per 1,000 messages: 0.040 US dollars for Claude Haiku 5.5 at the no-thinking lower bound and 0.180 with thinking at low effort, rising to 3.600 for Claude Sonnet 5.5 with thinking (prices as of 26 November 2026). The last line shows that one call at a time, at an assumed one second each, takes about 17 minutes per 1,000. Replace that assumption with a latency you measure from your own region and network.
What the comparison tells you:
- At small volumes a fast LLM is cheap: Claude Haiku 5.5 costs somewhere between about 4 and 18 cents per thousand messages here, depending on how much it thinks, and a larger model with thinking costs dollars. The local classifier wins on speed, works without a connection, keeps customer text on your server and costs nothing more per message.
- The LLM wins on flexibility. Adding a sixth intent is a prompt change, not a relabelling and retraining job, and it copes better with messages unlike anything in your training data.
- A common design uses both: the local classifier handles the confident majority, and only the messages below the threshold go to an LLM or a person. With the threshold above, that is under 10% of calls.
Step 8 · Run offline and clean up
The model is in your cache, so the classifier runs with no network at all:
HF_HUB_OFFLINE=1 python classify.pyCheck it worked
The same four lines print, with no download. When you have finished, remove the project, the cached model and pip's download cache (which now holds a PyTorch wheel of several hundred megabytes). Keep the cache if you are going straight on to another embeddings tutorial:
pip cache purge
deactivate
cd ~
rm -rf ~/intent-demo ~/.cache/huggingface/hub/models--sentence-transformers--all-MiniLM-L6-v2
ls ~/intent-demo 2>/dev/null || echo "removed"The last command prints removed. pip cache purge clears every package pip has cached, not only these; leave that line out if you want to keep the rest.
Next steps
- Go deeper on the numbers in the report, including ROC curves and choosing thresholds: measure a classifier with precision, recall and ROC.
- Revisit how the vectors behave, including length limits and normalisation: turn text into embeddings with sentence-transformers.
- Make the LLM fallback for unsure messages more accurate: improve LLM answers with few-shot examples.
Part of these paths
Related tutorials
- Turn text into embeddings and compare meaning with sentence-transformersYou will run a small embedding model on your own CPU, turn a dozen sentences into vectors, and check with cosine similarity that paraphrases score high while sentences that only share keywords do not.
- Measure a classifier with precision, recall and ROC curvesYou will score a fraud classifier on rare-class data with a confusion matrix, precision, recall, F1, precision-recall and ROC curves and a reliability curve, then pick its decision threshold from the cost of each mistake.
- Improve LLM answers with few-shot examples and measure the differenceYou will score a small local model on 40 labelled customer messages with zero, three and eight examples in the prompt, and end with a table that shows what the examples changed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials