Learning from data
We teach a model to sort support messages, and find out how easily a good score can be a false one: splits, leakage, precision, recall and the threshold the fraud desk can staff.
This pathway follows one system from its first line of code to production: a support assistant for a stock-broking app. Customers ask it why an order was rejected, when a withdrawal will reach their bank, what a charge on their contract note means. It answers from the help centre and the product docs, it can look up the status of a specific order, and when it cannot help it raises a ticket for a human. By the end it will be a language model with retrieval, tools and evaluations around it. It does not start there.
It starts with a triage desk. The support team receives about 30,000 messages a day, most of them between the market opening at 9:15 and a little after the close. Three people read each incoming message and drop it into a queue: order status, funds and withdrawals, account and KYC, charges, app or login trouble, and one queue that matters more than the rest, which the team calls “urgent: possible unauthorised activity”. A customer who writes “someone sold my shares, I did not do this” needs a human on the fraud desk within minutes, not in the afternoon batch.
The team has two years of messages that agents already sorted by hand. This chapter uses them to build a model that does the sorting, and spends most of its length on the harder question: how we know whether that model is any good. Every later chapter, including the ones about language models, leans on the habits we form here.
Why rules stop working, and what replaces them
The obvious first attempt is a set of keyword rules. A message containing “withdraw” goes to funds. A message containing “not me” or “did not place” goes to the fraud queue. This works for a week. Then a customer writes “my order did not place, please check”, which is an order status question, and it lands on the fraud desk. Another writes “there is a sell order in my history I don’t recognise”, which contains none of the trigger phrases and goes to order status, where it waits four hours. Each fix adds a rule, each rule interacts with the others, and after a month nobody can say why a given message went where it did.
Machine learning replaces the rules with examples. We give the computer messages (the features, here the words in each message) together with the queue an agent chose (the label), and ask it to find weights that reproduce those choices. For one yes-or-no question, “is this possible fraud?”, the simplest useful model is logistic regression. It gives each word a weight, adds up the weights of the words present, adds a constant called the bias, and squashes the total into a probability between 0 and 1 with the sigmoid function, σ(z) = 1 / (1 + e−z).
Take the message “someone sold my shares without my permission”. Suppose training has settled on weights of +0.4 for “sold”, +0.9 for “without”, +1.6 for “permission”, about zero for “my” and “shares”, and a bias of −2.5. The score is 0.4 + 0.9 + 1.6 − 2.5 = 0.4, and σ(0.4) is about 0.60. The model thinks this is more likely fraud than not. Notice that the bias is strongly negative: before reading any words, the model assumes a message is not fraud, which matches the fact that almost none are.
Training is the search for those weights. We need a number that says how wrong the current weights are, called the loss. For probabilities the standard choice is log loss: if the true label is fraud, the loss is −ln(p); if not, −ln(1 − p). With p = 0.60 and a true label of fraud, the loss is 0.51. Had the agent labelled it “order status”, the loss would be −ln(0.40) = 0.92. Training nudges every weight in the direction that lowers the average loss across all labelled messages, thousands of times over. The deep learning chapter works through that nudge with numbers. For now, the important point is what the loss rewards: agreement with the labels on the messages it is shown. Nothing in it asks the model to be right about messages it has not seen.
A model is judged on messages it has never seen
That gap is the central problem of the field. A model with enough freedom can drive its training loss close to zero by memorising. Give logistic regression every token in the corpus as a feature, including account numbers and order ids, and it will learn that “ORD-88213” means fraud because the one message containing it was fraud. Training accuracy reaches 99%. On fresh messages that id never appears again, and the weight is useless or worse.
So we hold data back. Of the 60,000 labelled messages we use, 42,000 go into the training set the weights are fitted on, 9,000 into a validation set we use to compare choices (which features, how much regularisation, which threshold), and 9,000 into a test set we look at once, at the end, to estimate how the model will do in production. The test set loses its value the moment we start making decisions based on it. If we try five feature sets and keep the one with the best test score, the test score is now a selected maximum, biased upward, and we have no honest estimate left.
The two ways to fail have names. A model that does well on training data and noticeably worse on validation is overfitting: it learned details of the training messages that do not carry over. A model that does poorly on both is underfitting: it is too simple, or its features do not contain the signal. The cure for one makes the other worse. Adding features and freedom reduces underfitting and invites overfitting; removing them does the reverse. Plotting training and validation scores as we add more labelled data tells us which side we are on. If the two curves have already met and flattened, more data will not help and we need better features. If there is still a wide gap that is narrowing, more labels are worth paying for.
The team splits its 60,000 messages at random and the intent model scores 94% accuracy on the test portion. A colleague re-runs the experiment training on January to August and testing on September, and gets 88%. Which number belongs in the launch document, and where did six points go?
Show the worked answer
The September number. Production will always be predicting next month from last month, which is exactly what the time-based split simulates.
The random split flattered the model in two ways. Customers who are upset write more than once: the same complaint arrives three times, lightly edited, and a random split puts one copy in training and another in test, so the model gets credit for recognising a message it has effectively seen. And topics drift. In September the app changed how margin from pledged shares is shown, and a new kind of question appeared that no training message covered. A random split mixes September messages into training and hides that drift. The fix is to split by time, and to keep all messages from one customer thread on the same side of the split.
The feature that arrives after the answer
A month into the project, a new version of the fraud model scores 98% recall on validation, up from 80%. The team is pleased for about a day. Here is what happened, step by step, because this failure is common enough that every team meets it eventually.
The training data came from an export of the support tool. Someone added a feature to make the export richer: the text of the first agent reply, joined onto each customer message. For fraud cases that reply almost always contains a phrase like “I have escalated this to our risk team” or “we have temporarily blocked your account”. The model found that phrase and leaned on it. On validation data, drawn from the same export, the reply was present, and the model looked brilliant.
In production the model runs the moment a message arrives. No agent has replied yet. The feature is empty for every message, and the model, which had shifted weight from the customer’s words to the agent’s, now does worse than the old version. This is called leakage: the training data contains information that will not exist, or will not mean the same thing, at the moment the prediction is made. The tell is a jump in score that is too large for the change that caused it.
The fix is a rule applied to every feature: write down when that value becomes known, and drop anything that becomes known after the prediction time. For the triage model the prediction time is “message received”, so the allowed features are the message text, the customer’s account state as of that moment, and their history before it. Doing this properly costs something. The team had to rebuild the export from event logs so that account state was taken as of the message timestamp rather than as of today, which took a week, and the honest recall went back to 80%. That 80% is the number production will see. The 98% was never available.
Leakage has quieter forms. Computing the average message length over the whole dataset and using it to normalise every message lets test statistics into training, a small effect. Labelling messages with the queue they finally ended up in, rather than the queue the triage agent first chose, leaks the outcome of an investigation into the input. Each one follows the same pattern and yields to the same question.
Why accuracy is the wrong number for fraud
With leakage removed, we need a number that says whether the fraud model is useful. Accuracy, the share of messages labelled correctly, is the first one people reach for. In our 9,000 test messages, 90 are genuine reports of unauthorised activity: 1%. A model that answers “not fraud” for every message is right 8,910 times out of 9,000. Its accuracy is 99.0%, and it never catches a single case.
Now take the real model at a threshold of 0.5: it flags any message it scores above 0.5. It flags 150 messages, of which 72 are real fraud reports. It misses 18 real ones and raises 78 false alarms. That is 96 errors, so its accuracy is 8,904 / 9,000 = 98.9%, lower than the model that does nothing. Accuracy ranks the useless model above the useful one, because with a rare class it is dominated by the easy majority.
Two numbers describe the useful model properly. Precision asks: of the messages we flagged, how many were real? Here 72 / 150 = 48%. Recall asks: of the real cases, how many did we flag? Here 72 / 90 = 80%. Precision is what the fraud desk feels, since every false alarm costs an analyst a few minutes. Recall is what customers feel, since every miss is a compromised account that stays open while its holdings are sold. The do-nothing model has a recall of zero, and that one number exposes it.
The threshold is a staffing decision
The model does not output “fraud” or “not fraud”. It outputs a score, and we choose where to draw the line. Moving the line changes precision and recall in opposite directions, and the right place for it depends on things outside the model. Scaling the test-set counts up to the real daily volume (30,000 messages, so multiply by 3.3) gives the following.
| Threshold | Flagged per day | Real cases caught | Precision | Recall | Missed per day |
|---|---|---|---|---|---|
| 0.8 | ≈200 | ≈170 of 300 | 85% | 57% | ≈130 |
| 0.5 | ≈500 | ≈240 of 300 | 48% | 80% | ≈60 |
| 0.2 | ≈1,330 | ≈287 of 300 | 21% | 96% | ≈13 |
The fraud desk has four analysts. A careful review of a flagged message, which includes checking the account’s recent logins and orders, takes about three minutes, so each analyst can clear roughly 150 a day and the desk about 600. At 0.2 the desk receives more than twice what it can review, and a queue that never empties is worse than a smaller one, because real cases wait behind false alarms. At 0.8 the desk is comfortable and 130 genuine reports a day go to the ordinary queues. At 0.5 the desk is busy but keeps up.
The team chose 0.5 and added a second tier: messages scoring between 0.2 and 0.5 go to the front of the general queue rather than to the fraud desk, so they are read within the hour. That decision can be written as a sentence another engineer can challenge: “We flag at 0.5 because the desk can review 600 messages a day, and we route 0.2 to 0.5 to priority general support because a miss costs more than a fast read.” If the desk grows, or if the business decides an unreviewed fraud report is unacceptable at any volume, the threshold moves. The model stays the same.
This only works if the scores mean something. A model is calibrated if, among messages it scores around 0.6, roughly 60% turn out to be fraud. Logistic regression tends to be reasonably calibrated out of the box; many other models are not, and their scores are only good for ranking. When a score feeds a decision directly, such as “freeze the account above 0.9”, check calibration on validation data by grouping messages by score and comparing each group’s average score with its actual fraud rate.
The number to beat comes first
Before training anything we should know what a trivial approach achieves, because a model is only worth its upkeep if it beats that by a margin. For the intent classifier the baselines are cheap to compute. Predicting the most common queue for every message (order status, 34% of traffic) is right 34% of the time. The old keyword rules, run over the September test month, are right 71% of the time. Logistic regression on word counts reaches 88%. That 17-point gain over the rules is what pays for building, monitoring and retraining a model. Had it been two points, the honest recommendation would have been to tidy the rules.
Baselines also catch bugs. If a sophisticated model scores below the keyword rules, the likeliest explanation is a mistake in the pipeline (labels shifted by one row, a feature computed on the wrong date) rather than a property of the model.
When a trained classifier is the wrong tool
Everything above assumes a stable set of categories and enough labelled examples. Both can fail. If the support team reorganises its queues every quarter, every reorganisation invalidates the labels, and a model that needs 40,000 fresh examples to retrain will always be behind. If a new category appears with only 200 examples, such as questions about a newly launched product, a classifier will do poorly on it for months.
In those situations the later chapters offer alternatives: a language model can classify a message from a written description of each queue and a handful of examples, with no training at all. It costs more per message and is slower, and it must still be measured with the same split, metrics and thresholds as this chapter. A useful way to decide is to ask how often the categories change, how many labelled examples each category has, and what one prediction may cost. Stable categories, plenty of labels and a tight per-message budget point to a trained classifier. Shifting categories and thin labels point to a prompted model.
What does not change is the discipline. Whatever produces the prediction, we split by time, check every input for leakage, choose metrics from the cost of each kind of error, and set thresholds from the capacity of the people downstream.
The next chapter, The classical toolbox, stays with structured data. The team wants to predict, at the start of a conversation, whether it will end up needing a human agent. The inputs there are account fields rather than words, and the choice between a linear model and a tree ensemble starts to matter.