Artificial Intelligence Fundamentals / Final Challenge

Final challenge: review and improve a model

Lesson 25 of 26. Open to read. No account needed.

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.

  1. Create the exercise folder. macOS and Linux:

    mkdir -p ~/ai-practice/final-challenge
    cd ~/ai-practice/final-challenge
    

    Windows PowerShell:

    mkdir $HOME\ai-practice\final-challenge
    cd $HOME\ai-practice\final-challenge
    

    Save this as make_tickets.py in 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.py
    

    The first prints Saved 2000 tickets to tickets.csv; the second prints the teammate's Accuracy: 0.996 and their conclusion.

    make_tickets.py generates 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, escalated is set for most urgent tickets after the fact, and 30 message counts are deliberately blanked. rng.choice picks a region for each ticket, about 80% North, and rng.random gives 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.

  2. 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 escalated column is filled in by a manager after reviewing a ticket.
    • Split the data before any choice, stratified by urgent, with random_state=0, and keep the test set for one final measurement.
    • Use a decision tree with random_state=0, and choose its max_depth from 1 to 8 by 5-fold cross-validation on the training data. cross_val_score accepts scoring="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.md with the five sections from the documentation lesson, using your numbers.
  3. Check your result. All of these must hold:

    • escalated is 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.
  4. 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 use train[features] and train["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 seeLikely causeNext step
Your test recall is near 1.00escalated is still a featureRemove it from the feature list
ValueError: Input X contains NaNYou tried a model other than a decision tree before removing the incomplete ticketsRemove them with dropna(), as the support lead asked
Your numbers differ from the solutionA different split, seed, depth range or scoringCompare your settings with the requirements
You want to start againAny reasonRemove ~/ai-practice/final-challenge and save the starting files again
  1. Clean up when you have finished. macOS and Linux:

    cd ~/ai-practice
    ls
    rm -rf final-challenge
    ls
    

    Windows PowerShell:

    cd $HOME\ai-practice
    ls
    Remove-Item -Recurse final-challenge
    ls
    

    This 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-practice on Windows), then run rm -rf ~/ai-practice on macOS and Linux, or Remove-Item -Recurse $HOME\ai-practice in PowerShell. Copy anything you want to keep, such as your model summaries, before removing it.

Check Your Understanding

  1. Name three separate reasons why the teammate's 0.996 was misleading.
  2. Your model's test accuracy, 0.856, is well above the baseline's 0.791. Why is that not enough to call it ready?
  3. 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:

  1. 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.
  2. The leak: escalated is 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.
  3. The split comes before any choice: 1,477 training and 493 test tickets.
  4. Cross-validation on the training tickets compares depths 1 to 8 by recall and chooses depth 5. The test set plays no part.
  5. 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.
  6. 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

  1. 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.
  2. 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.
  3. 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.

Study this course with an account

Course access adds revision notes, the Quick Reference, saved progress, bookmarks and your own notes.

INR 199 plus 18% GST. 90 days of online access. No auto-renewal.

See course access

This website is operated by VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED, operating as Vectametric.

Corporate Identity Number (CIN): U85499KA2026OPC229822. GSTIN: 29AAMCV8281D1ZS. Registered office: RS NO/38/2A/1 BASTAND, ROAD MAHANTESH NAGAR, Ramdurg, Ramdurg, Belgaum- 591123, Karnataka.

Queries and grievances: Prajval Honnungar, Grievance Officer and Data Protection Contact.

Telephone: +91 94800 09310. Support: support@vectametric.com. Grievances: support@vectametric.com.

Copyright 2026 VECTAMETRIC EDTECH (OPC) PRIVATE LIMITED. All rights reserved.

Vectametric home · Roadmaps · Vecta IT Exams · Vecta Government Exams · Vecta Banking & Finance Exams · Vecta Entrance Exams · About us · Contact · Privacy Policy · Terms and Conditions · No-Refund Policy