The Situation
You join a support team that wants to flag urgent tickets automatically, so that staff answer them first. A teammate has trained a model and reports:
Accuracy: 0.996. The model is ready to use.
Your manager asks you to review that claim before anyone relies on it. Missing an urgent ticket is the costly mistake: the customer waits too long. The data is generated for this challenge, and the two regions in it, North and South, are fictional.
This challenge uses skills from across the course: inspecting data, avoiding leakage, baselines, choosing a metric, cross-validation, per-group evaluation and model summaries. Try it without looking back first; the hints and the explained solution are below.
Exercise: Review the Ticket Model
Starting state: the course environment, active in your terminal.
-
Create the exercise folder. macOS and Linux:
mkdir -p ~/ai-practice/final-challenge cd ~/ai-practice/final-challengeWindows PowerShell:
mkdir $HOME\ai-practice\final-challenge cd $HOME\ai-practice\final-challengeSave this as
make_tickets.pyin that folder:"""Generate the support tickets for the final challenge and save them as tickets.csv.""" import numpy as np import pandas as pd rng = np.random.default_rng(31) n = 2000 tickets = pd.DataFrame({ "ticket_id": np.arange(1, n + 1), "region": rng.choice(["North", "South"], size=n, p=[0.8, 0.2]), "wait_days": rng.integers(0, 15, size=n), "messages": rng.integers(1, 9, size=n).astype(float), "account_years": rng.integers(0, 11, size=n), }) need = 0.25 * tickets["wait_days"] + 0.5 * tickets["messages"] - 0.1 * tickets["account_years"] tickets["urgent"] = (need + rng.normal(0, 1.2, size=n) > 5.0).astype(int) # Filled in by a manager after reviewing a ticket, so only after its urgency was known. tickets["escalated"] = ((tickets["urgent"] == 1) & (rng.random(n) < 0.9)).astype(int) tickets.loc[rng.choice(n, size=30, replace=False), "messages"] = np.nan tickets.to_csv("tickets.csv", index=False) print("Saved", len(tickets), "tickets to tickets.csv")Then save the teammate's script. Save this as
teammate_model.py:"""A teammate's evaluation of a ticket-priority model. Something is wrong with it.""" import pandas as pd from sklearn.tree import DecisionTreeClassifier tickets = pd.read_csv("tickets.csv") features = ["wait_days", "messages", "account_years", "escalated"] model = DecisionTreeClassifier(random_state=0).fit(tickets[features], tickets["urgent"]) print(f"Accuracy: {model.score(tickets[features], tickets['urgent']):.3f}") print("The model is ready to use.")Run both:
python make_tickets.py python teammate_model.pyThe first prints
Saved 2000 tickets to tickets.csv; the second prints the teammate'sAccuracy: 0.996and their conclusion.make_tickets.pygenerates the tickets with a seeded random generator, as the regression and fairness lessons did. Each ticket has a region, the days the customer has waited, the number of messages they sent and their years as a customer. Urgency depends on those three numbers plus random variation,escalatedis set for most urgent tickets after the fact, and 30 message counts are deliberately blanked.rng.choicepicks a region for each ticket, about 80% North, andrng.randomgives the random numbers behind the escalation. The teammate's script trains an unlimited decision tree on every ticket and scores it on those same tickets. -
Write your own script,
review_model.py, and a model summary,model_summary.md, that together meet these requirements:- Inspect the data first. The support lead confirms that tickets without a message count were logged wrongly and must be left out.
- Use only features that are known when a ticket arrives. The
escalatedcolumn is filled in by a manager after reviewing a ticket. - Split the data before any choice, stratified by
urgent, withrandom_state=0, and keep the test set for one final measurement. - Use a decision tree with
random_state=0, and choose itsmax_depthfrom 1 to 8 by 5-fold cross-validation on the training data.cross_val_scoreacceptsscoring="recall", which scores each fold by recall instead of accuracy; use it, because missed urgent tickets are the costly mistake. - Report test accuracy beside a baseline, test precision and recall, and recall for each region with its number of test tickets and urgent tickets.
- Write
model_summary.mdwith the five sections from the documentation lesson, using your numbers.
-
Check your result. All of these must hold:
escalatedis not among your features, and the incomplete tickets were removed.- The depth was chosen without the test set, and the test set was used once.
- Your report shows a baseline and recall, not only accuracy.
- Recall is reported for North and South, with their sizes.
- Every number in your summary matches your script's output, and the summary says plainly whether the model is ready for the team's purpose.
-
Write down, in a sentence each, why the teammate's 0.996 was misleading. The Check Your Understanding questions below ask for the same reasoning.
Hints, from gentle to specific. Read one at a time, only if you are stuck:
- Hint 1: Start by printing the number of tickets, the number of urgent tickets and the missing values per column, as in the inspection lesson.
- Hint 2: The teammate scored the model on the same tickets it learned from, and one feature is only known after the outcome. Both inflate the score.
- Hint 3: Split the DataFrame itself, as in the fairness lesson:
train, test = train_test_split(tickets, random_state=0, stratify=tickets["urgent"]). Then usetrain[features]andtrain["urgent"]for cross-validation and training. - Hint 4: Store each depth's mean cross-validation recall in a
dictionary and choose the best with
max, as in the cross-validation lesson; then train that depth on the whole training set and score it once.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
| Your test recall is near 1.00 | escalated is still a feature | Remove it from the feature list |
ValueError: Input X contains NaN | You tried a model other than a decision tree before removing the incomplete tickets | Remove them with dropna(), as the support lead asked |
| Your numbers differ from the solution | A different split, seed, depth range or scoring | Compare your settings with the requirements |
| You want to start again | Any reason | Remove ~/ai-practice/final-challenge and save the starting files again |
-
Clean up when you have finished. macOS and Linux:
cd ~/ai-practice ls rm -rf final-challenge lsWindows PowerShell:
cd $HOME\ai-practice ls Remove-Item -Recurse final-challenge lsThis is the last lesson that uses the course environment. If you have finished the course and do not want to keep it, you can remove the whole practice folder, including the environment and any files you saved. Check the path first with
ls ~/ai-practice(ls $HOME\ai-practiceon Windows), then runrm -rf ~/ai-practiceon macOS and Linux, orRemove-Item -Recurse $HOME\ai-practicein PowerShell. Copy anything you want to keep, such as your model summaries, before removing it.
Check Your Understanding
- Name three separate reasons why the teammate's 0.996 was misleading.
- Your model's test accuracy, 0.856, is well above the baseline's 0.791. Why is that not enough to call it ready?
- South's recall is lower than North's. What can you conclude, and what can you not conclude?
Answer and Reasoning
Solution
Save this as review_model.py:
"""A fair evaluation of the ticket-priority model."""
import pandas as pd
from sklearn.dummy import DummyClassifier
from sklearn.metrics import precision_score, recall_score
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.tree import DecisionTreeClassifier
tickets = pd.read_csv("tickets.csv")
print("Tickets:", len(tickets), "| urgent:", tickets["urgent"].sum())
print(tickets.isna().sum())
tickets = tickets.dropna() # the support lead confirmed these tickets were logged wrongly
features = ["wait_days", "messages", "account_years"] # "escalated" is recorded after the outcome
train, test = train_test_split(tickets, random_state=0, stratify=tickets["urgent"])
mean_scores = {}
for depth in range(1, 9):
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
mean_scores[depth] = cross_val_score(tree, train[features], train["urgent"], scoring="recall").mean()
best = max(mean_scores, key=mean_scores.get)
print("Depth chosen by cross-validation:", best)
model = DecisionTreeClassifier(max_depth=best, random_state=0).fit(train[features], train["urgent"])
baseline = DummyClassifier().fit(train[features], train["urgent"])
predicted = model.predict(test[features])
print(f"Test accuracy: {model.score(test[features], test['urgent']):.3f} (baseline {baseline.score(test[features], test['urgent']):.3f})")
print(f"Test precision: {precision_score(test['urgent'], predicted):.2f}, recall: {recall_score(test['urgent'], predicted):.2f}")
test = test.assign(predicted=predicted)
for region, part in test.groupby("region"):
print(f"{region}: {len(part)} test tickets, {part['urgent'].sum()} urgent, recall {recall_score(part['urgent'], part['predicted']):.2f}")
Its output:
Tickets: 2000 | urgent: 417
ticket_id 0
region 0
wait_days 0
messages 30
account_years 0
urgent 0
escalated 0
dtype: int64
Depth chosen by cross-validation: 5
Test accuracy: 0.856 (baseline 0.791)
Test precision: 0.73, recall: 0.50
North: 382 test tickets, 77 urgent, recall 0.53
South: 111 test tickets, 26 urgent, recall 0.38
Step by step:
- Inspection shows 417 urgent tickets out of 2,000, about one in five,
and 30 missing message counts.
dropna()removes those 30 tickets, as the support lead asked, leaving 1,970. - The leak:
escalatedis excluded. Almost every urgent ticket is escalated and no other ticket is, so it gives the answer away; a model using it would have nothing to use on a new ticket, which has not been reviewed yet. - The split comes before any choice: 1,477 training and 493 test tickets.
- Cross-validation on the training tickets compares depths 1 to 8 by recall and chooses depth 5. The test set plays no part.
- The final measurement: accuracy 0.856 against the baseline's 0.791, precision 0.73 and recall 0.50. The model finds half of the urgent tickets, and about three in four of the tickets it flags are urgent.
- Per region: North 0.53 from 77 urgent test tickets, South 0.38 from 26.
One possible summary, with every number taken from the output:
# Model summary: urgent ticket classifier
## Intended use
Flags support tickets that are likely to be urgent, from waiting days, number of messages and account age, so that staff can look at them first. Built to practise evaluation on generated data.
## Not suitable for
Deciding on its own which tickets are urgent: it misses about half of the urgent tickets.
## Data
2,000 generated tickets from two fictional regions. 30 tickets without a message count were removed on the support lead's instruction, leaving 1,970. The escalated column was excluded because it is filled in after urgency is known. Split into 1,477 training and 493 test tickets, stratified by urgency.
## Evaluation
Depth 5, chosen by 5-fold cross-validation on recall using the training tickets only. On the test tickets: accuracy 0.856 against a baseline of 0.791; precision 0.73 and recall 0.50. Recall by region: North 0.53 (77 urgent test tickets), South 0.38 (26 urgent test tickets).
## Limitations
It misses half of the urgent tickets, so urgent tickets still need another route to staff. South's recall rests on only 26 urgent tickets; the gap from North may be partly chance and needs more data before conclusions. The data is generated, so the results say nothing about real tickets.
Your wording can differ, provided every number matches and the summary is clear that the model is not ready to decide on its own.
Understanding check
- It was measured on the same tickets the model learned from; the model used
escalated, which is only known after urgency is decided; and it reported accuracy alone, with no baseline and no recall, although one in five tickets is urgent and missing them is the costly error. The unlimited tree depth also let the model memorise its training tickets. - Accuracy hides the costly error. Recall shows that the model misses half of the urgent tickets. Whether that is acceptable depends on what else catches them; it is not acceptable as the only route.
- You can conclude that on this test set the model found a smaller share of South's urgent tickets, and that this needs attention. You cannot conclude that the model treats South worse in general: South's figure rests on 26 urgent tickets, so it is rough, and the cause is unknown. More data and an investigation of the cause come before any claim either way.
References
This challenge introduces no new technique beyond the scoring setting
described in its requirements. The sources for each step are listed in the
lessons that teach it.