Aller au contenu

Leçon 107 · Projects

Final project: Library Hold Pickup Model

Finish the Data Scientist path: frame a prediction question, clean data, split by time, beat a baseline, evaluate honestly and report what your model cannot do.

Fernhollow Library is an invented town library. When a reader reserves a book, staff set it aside on a hold shelf. Some holds are never collected, so the book sits there while other readers wait. The library asks: "Can we tell, when a book reaches the shelf, which holds are likely to go uncollected, so we can send one extra reminder?"

You will finish with a written problem definition, a repeatable cleaning step, a time-based split, baselines, a model, an honest evaluation and a one-page model report. All data here is invented. The site cannot grade the whole project; checkpoints only compare what your functions print with what a reference solution prints.

What you need first

This is the last step of the Data Scientist path. It draws on Python, SQL, NumPy, pandas, Statistics and Probability, Data Visualization, scikit-learn and Machine Learning. Review baselines, train and test splits, classification metrics and nested validation and leakage if any feel unfamiliar.

The checkpoints use only the Python standard library. The modeling example uses scikit-learn in your browser. For your full project, work on your own computer in a notebook or scripts that you can rerun from start to finish.

The brief

  1. State the decision, the prediction time, the target and who is affected.
  2. List the features that exist at prediction time, and reject those that do not.
  3. Clean the data with explicit rules and report how many rows each rule changes.
  4. Train on older holds and evaluate on newer ones.
  5. Compare a model with at least two simple baselines.
  6. Choose a threshold using validation data and a stated reminder capacity or cost.
  7. Evaluate the test set once, inspect errors and subgroups, and write a model report.

Milestones

1. Define the question

The target is missed: 1 if the hold expired without pickup and 0 if the reader collected it. The prediction happens when the book is placed on the shelf. Each invented record has an id, a day number, wait_days (time spent in the queue), past_holds, past_missed and missed.

Why: a feature recorded later, such as the number of reminders actually sent before expiry, would leak the future. History features must also count only holds that had finished before this prediction.

Hint: finish this sentence: "At the moment of ... we predict ... so that staff can ...". Also decide what the score must not be used for. A reminder is helpful; blocking someone from reserving books would be a very different and harmful use.

Done when: your definition and a feature table with "known when?" for each column fit on one page.

2. Clean without guessing

Raw exports contain repeats and gaps. A missing target cannot be used for supervised training. A hold that is still open is not a pickup, so never turn its blank target into 0.

Python Checkpoint 1: clean the records

Your task: Write clean(rows). Each row is a dict with id, day, wait_days and missed. Keep only rows whose missed is 0 or 1. Among those, keep the first row for each id. If wait_days is negative, replace it with None (None stays None; 0 is valid). Return new dicts sorted by day, then id. Do not change the input rows.

Hint

Check the target before you mark an id as seen, and copy each row before editing it.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def clean(rows):
    seen = set()
    result = []
    for row in rows:
        if row["missed"] not in (0, 1) or row["id"] in seen:
            continue
        seen.add(row["id"])
        copy = dict(row)
        if copy["wait_days"] is not None and copy["wait_days"] < 0:
            copy["wait_days"] = None
        result.append(copy)
    return sorted(result, key=lambda r: (r["day"], r["id"]))

Done when: you can state how many rows were removed or changed by each rule and why.

3. Split by time and impute from training only

The library will use the model on future holds, so test it on later ones. Split into three consecutive periods: training, validation and test. Every value learned from data, including the median used to fill gaps, comes from the training period only.

Python Checkpoint 2: leakage-safe preparation

Your task: Write prepare(rows, cutoff). Training rows have day less than cutoff; later rows are all others. Compute the median of the non-None wait_days in the training rows. Return a tuple (train, later, fill) where both lists contain new dicts, in input order, with every None wait_days replaced by fill. If no training value is known, fill is 0. Do not change the input.

Hint

Calculate the median before filling anything, using only rows before the cutoff.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

from statistics import median

def prepare(rows, cutoff):
    known = [r["wait_days"] for r in rows if r["day"] < cutoff and r["wait_days"] is not None]
    fill = median(known) if known else 0
    train, later = [], []
    for row in rows:
        copy = dict(row)
        if copy["wait_days"] is None:
            copy["wait_days"] = fill
        (train if row["day"] < cutoff else later).append(copy)
    return train, later, fill

Done when: changing a value in a later period cannot change anything learned during training. Test that claim.

4. Set baselines

Measure what you get without machine learning. Try "never flag anyone" and a simple rule such as "flag readers with at least one earlier missed hold".

Python Checkpoint 3: honest metrics

Your task: Write evaluate(actual, flagged) for two equal-length lists of 0 and 1. Return the tuple (tp, fp, fn, tn, accuracy, precision, recall). Round the last three to 3 decimals. A ratio with a zero denominator must be None. For lists of different length, raise ValueError.

Hint

Count the four pairs first. Every metric comes from those counts.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def evaluate(actual, flagged):
    if len(actual) != len(flagged):
        raise ValueError("lengths differ")
    pairs = list(zip(actual, flagged))
    tp = pairs.count((1, 1))
    fp = pairs.count((0, 1))
    fn = pairs.count((1, 0))
    tn = pairs.count((0, 0))
    def ratio(a, b):
        return round(a / b, 3) if b else None
    return (tp, fp, fn, tn, ratio(tp + tn, len(pairs)), ratio(tp, tp + fp), ratio(tp, tp + fn))

Why: if few holds are missed, a rule that flags nobody can have high accuracy while finding nothing. Recall tells you how many missed holds you found; precision tells you how many flagged holds really were missed.

Done when: you have a table of both baselines on the validation period.

5. Train, tune and choose a threshold

The program below creates synthetic records with a weak, known signal, then compares a prior-only baseline with logistic regression. It uses the first period to fit and the second to compare. It deliberately leaves the final period untouched.

Python Baseline and model on validation data

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The baseline gives everyone the same score, so its "top 45" is just the first 45 rows. Treat that number as an arbitrary slice; the overall missed rate is what you should expect from random selection. Add your rule-based baseline to the comparison too.

Why: staff capacity makes the threshold concrete: "flag the highest 15 percent" is easier to explain than 0.5. A capacity rule ranks a batch. If holds arrive one at a time, choose a score cutoff on validation data instead, and monitor how many it flags.

Hint: try a few settings or one more model family, choosing with validation data. With more data, use several rolling time windows to see how much results vary.

Done when: one model and one threshold are written down, and a simpler option wins if the difference is too small to matter.

6. Test once and report

Freeze every choice, then score the test period. Report the counts behind each metric. A bootstrap interval gives a rough sense of sampling uncertainty, although it does not cover future changes in behavior. See calibration and uncertainty.

Inspect false positives and false negatives. Compare error rates across relevant groups where you may lawfully and appropriately do so, and show group sizes. Invented fields such as home branch can illustrate the method. Plot a calibration curve and one chart comparing model and baseline.

Your report should cover: intended use, forbidden uses, data and cleaning, split dates, baselines, test results with uncertainty, known failures, who checks the system and when to switch it off. It should also say that a model predicting missed pickups does not show that a reminder prevents them. To learn that, the library would need a fair experiment that compares outcomes with and without the reminder.

Done when: someone else can rerun your work from raw data to report and get the same numbers.

Check your work

Criterion What good looks like
Question Decision, prediction time, target and acceptable use are explicit
Features Each one is available at prediction time and has a reason to be collected
Preparation Rules are reproducible; learned values come from training data only
Baselines At least two, scored on the same rows as the model
Evaluation Time-based, with counts, suitable metrics and uncertainty; test used once
Responsibility Errors, group sizes, privacy and human oversight are discussed
Report States clearly what the model cannot do, including that it does not show cause

Common mistakes

Do not shuffle future holds into training when the real task is predicting forward. Do not keep changing the model after you see the test result: that turns the test set into validation data, and you need new unseen data for a fair estimate. Do not present results on synthetic data as evidence that the method works for real library members. Use only data you have permission to use, and remove names and contact details that the task does not need.

Take it further

  • Store the invented records in SQLite and build history features with a query that looks only backward.
  • Add a monitoring plan that tracks the missed rate, score distribution and missing values each month.
  • Design the reminder experiment, including what outcome you would measure and how you would assign reminders fairly.
  • Repeat the project with a public dataset whose license permits your use, and document its limits.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Which feature leaks information if you predict when a book reaches the shelf?

    The pickup date is only known after the prediction, and it reveals the outcome.
  2. 2. From which rows should you compute the median that fills missing values?

    Anything learned from later data lets information flow backward into the model.
  3. 3. A model has 90 percent accuracy and 10 percent of holds are missed. What can you conclude?

    Compare with a baseline and look at precision, recall and the counts.
  4. 4. You change the model after seeing the test score. What is the consequence?

    Choices based on test results can fit that particular sample.
  5. 5. The model ranks missed holds well. Does that show reminders will reduce them?

    Predicting an outcome and changing it are different questions.

Summary

  • Define the decision and prediction time before choosing a model.
  • Clean with explicit rules, split by time and learn preparation values from training data only.
  • Compare against simple baselines on the same rows.
  • Choose with validation data, then test once.
  • Report uncertainty, errors, limits and what the model does not prove.

Back to the path: Data Scientist learning path

Suivez votre progression

Créez un compte gratuit pour cocher vos leçons et reprendre où vous vous étiez arrêté, sur n'importe quel appareil.