Per-Slice Precision and Recall Evaluator

Quick Overview

Implement a pandas function that computes precision and recall for every slice of a dataset, compares each slice with the overall metrics and flags the slices that fall short. It tests groupby logic, handling of undefined metrics, strict threshold rules and exact output dtypes.

Per-Slice Precision and Recall Evaluator

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement `evaluate_slices(df, slice_col, y_true_col="y_true", y_pred_col="y_pred", positive_label=1, min_support=1, tolerance=0.0)`. Compute precision and recall for every subgroup of `slice_col`, compare each to the overall metrics, and return a `pd.DataFrame` flagging underperforming slices. The returned table must follow these rules: - Columns in order: `slice_col`, `n`, `n_positive`, `n_predicted_positive`, `precision`, `recall`, `precision_gap`, `recall_gap`, `underperforming` (counts `int64`, metrics `float64`, flag `bool`, slice column keeps its input name and dtype). - One row per distinct non-missing slice value, sorted ascending, with a fresh `RangeIndex`. - A label is positive when it equals `positive_label`. Precision (recall) is `NaN` when there are no predicted (actual) positives. - Overall metrics use all rows of `df`. Gaps are slice minus overall (`NaN` propagates). - Flag when `n >= min_support` and precision or recall is strictly below `overall - tolerance`. A `NaN` metric never triggers a flag. Example: ```python df = pd.DataFrame({ "region": ["east","east","east","west","west","west","north","north"], "y_true": [1, 0, 1, 1, 1, 0, 0, 0], "y_pred": [1, 1, 0, 1, 1, 0, 1, 0], }) evaluate_slices(df, "region") # overall precision 0.6, recall 0.75 ``` Expected result: ```text region n n_positive n_predicted_positive precision recall precision_gap recall_gap underperforming 0 east 3 2 2 0.5 0.5 -0.1 -0.25 True 1 north 2 0 1 0.0 NaN -0.6 NaN True 2 west 3 2 2 1.0 1.0 0.4 0.25 False ``` ```hint Start from the baseline Compute overall precision and recall once, before grouping. Ask which rows belong in that baseline when some slice values are missing. ``` ```hint Undefined values and dtypes Decide what a zero denominator returns before you write the flag logic. Then check what dtype each output column has when the result has zero rows or the slice column is categorical. ``` ### What a Strong Answer Covers - How the overall metrics are computed: pooled over every row of `df`, including rows whose slice value is missing. - How zero denominators become `NaN`, and how `NaN` propagates into the gaps without ever triggering a flag. - Grouping that gives one row per non-missing slice in ascending order, with the required column order, dtypes and a fresh index, including the empty result. - The flag rule: the support threshold, the strict comparison against overall minus tolerance, and either metric being enough to flag. - Time and space complexity, and how the approach scales to many slices. ### Follow-up Questions - How would you extend this to intersections of several slice columns? - A small slice is flagged by a tiny gap. How do you know it is significant? - How would you make the metric set pluggable (for example F1 or false positive rate)?

Overview: Implement a pandas function that computes precision and recall for every slice of a dataset, compares each slice with the overall metrics and flags the slices that fall short. It tests groupby logic, handling of undefined metrics, strict threshold rules and exact output dtypes.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement evaluate_slices(df, slice_col, y_true_col="y_true", y_pred_col="y_pred", positive_label=1, min_support=1, tolerance=0.0). Compute precision and recall for every subgroup of slice_col, compare each to the overall metrics, and return a pd.DataFrame flagging underperforming slices.

The returned table must follow these rules:

  • Columns in order: slice_col , n , n_positive , n_predicted_positive , precision , recall , precision_gap , recall_gap , underperforming (counts int64 , metrics float64 , flag bool , slice column keeps its input name and dtype).
  • One row per distinct non-missing slice value, sorted ascending, with a fresh RangeIndex .
  • A label is positive when it equals positive_label . Precision (recall) is NaN when there are no predicted (actual) positives.
  • Overall metrics use all rows of df . Gaps are slice minus overall ( NaN propagates).
  • Flag when n >= min_support and precision or recall is strictly below overall - tolerance . A NaN metric never triggers a flag.

Example:

df = pd.DataFrame({
    "region": ["east","east","east","west","west","west","north","north"],
    "y_true": [1, 0, 1, 1, 1, 0, 0, 0],
    "y_pred": [1, 1, 0, 1, 1, 0, 1, 0],
})
evaluate_slices(df, "region")   # overall precision 0.6, recall 0.75

Expected result:

  region  n  n_positive  n_predicted_positive  precision  recall  precision_gap  recall_gap  underperforming
0   east  3           2                     2        0.5     0.5           -0.1       -0.25             True
1  north  2           0                     1        0.0     NaN           -0.6         NaN             True
2   west  3           2                     2        1.0     1.0            0.4        0.25            False

What a Strong Answer Covers Guidance

  • How the overall metrics are computed: pooled over every row of df , including rows whose slice value is missing.
  • How zero denominators become NaN , and how NaN propagates into the gaps without ever triggering a flag.
  • Grouping that gives one row per non-missing slice in ascending order, with the required column order, dtypes and a fresh index, including the empty result.
  • The flag rule: the support threshold, the strict comparison against overall minus tolerance, and either metric being enough to flag.
  • Time and space complexity, and how the approach scales to many slices.

Follow-up Questions Guidance

  • How would you extend this to intersections of several slice columns?
  • A small slice is flagged by a tiny gap. How do you know it is significant?
  • How would you make the metric set pluggable (for example F1 or false positive rate)?