Learning path: End-to-End ML Use Cases: Fraud, Recommendations, Forecasting and Ticket Routing · Step 13 of 16
Ticket Routing, Part 1: A Safe Split, Keyword Rules and a TF-IDF Baseline
Before training anything big to route support tickets, set a fair test and a cheap score to beat. On 2,400 synthetic tickets, a random split shows 0.927, a customer-and-time split shows 0.669, keyword rules get 0.550, and TF-IDF falls to 0.436 on tickets that use new words.
What you will learn
- See how a random split inflates a ticket classifier from 0.669 to 0.927
- Split by customer and then by day so the test matches real use
- Build two cheap baselines: keyword rules and TF-IDF with logistic regression
- Read the score to beat per slice, with bootstrap ranges
Before you start
- TF-IDF with TfidfVectorizer
- Time Splits and Group Splits: Make the Split Match How the Model Is Used
This is the first part of an end-to-end use case: routing support tickets. A ticket comes in, and it has to reach the right queue: billing, login, shipping or technical. You could jump straight to a clever model. Today we won't train anything big at all. We'll set up a test we can trust, try keyword rules, then TF-IDF, and end with a score that anything bigger has to beat.
The tickets are synthetic. I made them up with a small generator, so read every number as a result on this data, not a promise about yours.
The spare key
You're locked out of your house. You don't call the locksmith straight away. You try the spare key under the flower pot: it costs nothing and takes ten seconds. If the door opens, you're done. If it doesn't, you've still learned something: you know exactly what the locksmith has to do better than. That's a baseline. Try the cheap thing first, and a bigger model has to earn its cost against it.
The tickets
data.py makes 2,400 tickets from 240 customers over 120 days. A few things are built in on purpose:
- Each customer has a favourite queue: 60% of the time a ticket goes to it, otherwise to a random queue.
- Email tickets carry the customer's signature, like
(acme15). Chat tickets are just the body. - From day 80 (
SHIFT_DAY), about half the tickets use new words: package instead of parcel, statement instead of invoice. - About 12% are vague: "please look into this", with no hint of the queue.
The same model, two scores
Before we trust any score, we need a fair test. python compare.py split trains the same TF-IDF model twice:
random split tfidf acc=0.927
safe split tfidf acc=0.669
On a random split, 0.927. You'd be happy with that. On the safe split, it falls to 0.669. Same tickets, same model. Why was the first score so easy? With a random split, 209 customers sit on both sides, so training and test both know their signatures and favourite queues.
One careful note: customers, dates and training size all changed at once between those two runs, and this run doesn't separate them. All I can say is that the 0.927 can't be trusted.
Split by customer, then by day: split_by
def split_by(rows, seed=7):
"""Entity and time safe: customers never cross groups,
and only days before SHIFT_DAY are used for training."""
rng = random.Random(seed)
cust = sorted({r["customer"] for r in rows})
rng.shuffle(cust)
k = len(cust)
tr = set(cust[: int(k * 0.6)])
va = set(cust[int(k * 0.6): int(k * 0.8)])
out = {"train": [], "val": [], "test": []}
for r in rows:
late = r["day"] >= SHIFT_DAY
if r["customer"] in tr and not late:
out["train"].append(r)
elif r["customer"] in va and late:
out["val"].append(r)
elif r["customer"] not in tr | va and late:
out["test"].append(r)
return out
- We shuffle the customers, not the tickets. 60% go to train, 20% to validation, 20% to test, and a customer stays in one group.
- Then the clock. Training keeps only tickets before day 80; validation and test keep only tickets from day 80 onwards.
- Tickets drop out on both counts: 2,400 become 941 for training, 157 for validation and 160 for test.
Since the new words only start after day 80, not one training ticket has them. Three tests check the split (no customer crosses groups, training is earlier than test, and the rules and interval behave), and they pass. Group and time splits are taught in full in Time Splits and Group Splits.
Baseline one: keyword rules
RULES = {q: words for q, words in OLD.items()}
def rule_predict(text):
text = text.lower()
for q in QUEUES:
if any(w in text for w in RULES[q]):
return q
return "technical"
It lowers the text and walks through the queues in order. Take "invoice and refund": billing is checked first, invoice is on its list, so it's billing. Correct.
Now take "consignment and package". Billing, no match. Login, no match. Shipping, no match, because the list says parcel, not package. Technical, no match. So it falls off the end, and the last line sends everything left over to technical. The right answer was shipping.
On the test set, rules score 0.550. I handed them every old word in the data, so that's their best case.
Baseline two: TF-IDF and logistic regression
def fit_tfidf(rows):
model = make_pipeline(
TfidfVectorizer(ngram_range=(1, 2), min_df=2),
LogisticRegression(max_iter=1000, C=5.0))
model.fit([r["text"] for r in rows],
[r["label"] for r in rows])
return model
This one learns its words instead. TF-IDF builds a vocabulary of single words and pairs from the 941 training tickets, and logistic regression gives each one a weight per queue. The top words make sense:
| Queue | Top TF-IDF words |
|---|---|
| billing | refund, invoice, failed, payment, payment failed, charged twice |
| login | verification code, code, verification, out, locked, locked out |
| shipping | parcel, wrong address, address, late, delivery late, delivery |
| technical | app crashes, app, crashes, error, message, error message |
Now send it "stack trace and data not updating". Of those words, only and and not are in the vocabulary; everything else disappears. With so little left, it guesses shipping. The right answer was technical. Overall TF-IDF scores 0.669, about twelve points above the rules, in about two seconds. (The building blocks are in TF-IDF with TfidfVectorizer and Build a Text Classifier with TF-IDF and a Pipeline.)
The score to beat, per slice
python compare.py baseline prints accuracy per slice with a 95% bootstrap range in brackets:
rules
all n= 160 acc=0.550 [0.481, 0.631]
email n= 75 acc=0.467 [0.360, 0.573]
chat n= 85 acc=0.624 [0.518, 0.729]
new words n= 78 acc=0.231 [0.154, 0.321]
vague n= 21 acc=0.048 [0.000, 0.143]
tfidf
all n= 160 acc=0.669 [0.588, 0.738]
email n= 75 acc=0.640 [0.533, 0.747]
chat n= 85 acc=0.694 [0.588, 0.788]
new words n= 78 acc=0.436 [0.333, 0.551]
vague n= 21 acc=0.286 [0.095, 0.476]
- A floor. Always answering billing, the biggest queue, scores 0.325 (52 of 160). Both baselines clear it.
- The brackets. With only 160 tickets, each score has a range, and rules and TF-IDF overlap a little. I wouldn't lean hard on that gap.
- New words, 78 tickets: rules 0.231, TF-IDF 0.436. They can only use words they've already seen, and that's where they're weakest.
- Vague, 21 tickets: rules 0.048, TF-IDF 0.286. "Please look into this" tells you nothing. Remember that row; a ticket like that might not be fixable by any model.
Scoring group by group, with ranges, is the method from Slice Evaluation and Fairness Checks.
Common mistakes
- A random split on tickets. Customers repeat across both sides, and the score jumped from 0.669 to 0.927.
- Skipping the baseline. Without 0.669, a bigger model's score has nothing to be compared with.
- Quoting one number. The overall score hid that new words sit at 0.436.
- Reading a gap without its range. On 160 tickets, the brackets overlap.
Recap
| Check | Result |
|---|---|
| Random split, TF-IDF | 0.927 (not trustworthy) |
| Safe split, TF-IDF | 0.669 |
| Keyword rules | 0.550 |
| Always billing | 0.325 |
| New words: rules / TF-IDF | 0.231 / 0.436 |
So any model now has a clear job: beat 0.669 overall, and do much better than 0.436 on new words.
Try it yourself: remove the (acme) customer signature from the ticket text in data.py (line 50), then run python compare.py split again. Guess first how far the random score will fall. The project files are in the community, free to join.
In Part 2, we fine-tune a small encoder against this baseline.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Demand Forecasting, Part 4: Serving the Forecasts, the Outcome Join and a Retrain Rule
Next →Ticket Routing, Part 2: Fine-Tuning a Small Encoder on a CPU, With a Run Log and Honest Ranges
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Project: Car Price Predictor End to End, from CSV to a FastAPI Price API
The whole ML workflow on 205 cars: clean the brand out of CarName, split first, audition five regressors on the same folds, tune the random forest, test once (RMSE 2,195, R2 0.939), save it and serve prices with FastAPI.
Fraud Scoring, Part 1: The Problem, the Metric and the Baseline
Before training a fraud model, write down what good means. On 6,000 synthetic validation transactions, a rule that never flags is 96.13% accurate and costs 23,200, flagging everyone costs 28,840, and a small contract.py fixes the rules first.
Fraud Scoring, Part 2: Training With Time Splits, Leak-Free Features and a Cost-Picked Threshold
Train the fraud model against its contract: a time split of 30,000 synthetic transactions, a card_n_1h feature that never looks ahead, XGBoost that pays 23,200 at 0.5, and a cost-picked threshold of 0.045 that brings validation to 14,955 and test to 16,765.
Fraud Scoring, Part 3: Serving It With FastAPI, Docker and a 50 ms Budget
A payment is waiting on the fraud score. Time each stage (the model takes 0.43 ms of a 3.3 ms request), then load test: p99 is 6.1 ms with one client and 163.3 ms with 32, against an example 50 ms budget. Then a Dockerfile, built and run once.