Compute average precision vs trapezoid AUC-PR with scikit-learn
Role: Data Scientist
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `ap_versus_trapezoid(y_true, y_proba)`. Given ground-truth binary labels and the predicted probabilities of the positive class (for example, from a logistic regression model), return the average precision and the trapezoidal area under the precision-recall curve as a 2-tuple of Python floats.
The function must:
- Return `(average_precision, trapezoid_auc)` in that order, both as Python `float`.
- Compute `average_precision` with `sklearn.metrics.average_precision_score(y_true, y_proba)`.
- Compute `trapezoid_auc` by calling `sklearn.metrics.precision_recall_curve(y_true, y_proba)` and then `sklearn.metrics.auc(recall, precision)`, with recall as the first argument.
For example:
```text
Input: y_true = [1, 0, 1, 0], y_proba = [0.9, 0.8, 0.7, 0.6]
Output: (0.8333..., 0.7916...)
```
Here the average precision is 5/6 and the trapezoid area is 19/24, so the two summaries of the same curve disagree.
```hint Which argument is x
`auc(x, y)` integrates y over x. Decide which of the two arrays is the horizontal axis of a PR curve before you call it.
```
```hint Comparing the two areas
Write both areas as sums over the recall increments and compare the precision value each one multiplies by an increment.
```
### Constraints & Assumptions
- `y_true` holds binary labels in {0, 1} and contains at least one positive.
- `y_proba` is a 1-D array of the same length holding the probability of class 1 (the second column of `predict_proba`).
- Inputs may be Python lists or NumPy arrays.
### What a Strong Answer Covers
- Calls both scikit-learn routines as specified and returns Python floats in the required order.
- Passes recall as the x argument of `auc` and a 1-D positive-class score to both metrics.
- Explains how average precision weights each recall increment by the precision at that step, and how the trapezoid rule averages adjacent precision values instead.
- Says when the trapezoid area falls below average precision, when it can exceed it, and what tied scores do.
- Handles edge cases such as no positive labels or hard 0/1 predictions.
### Follow-up Questions
- The trapezoid area under a PR curve is often called over-optimistic, yet on many inputs it comes out below average precision. When is it lower, when can it be higher, and why?
- When would average precision and `auc(recall, precision)` nearly coincide?
- What happens to each number if you pass hard 0/1 predictions from `predict` instead of probabilities?
- Which of the two would you report when comparing models, and why?
Overview: Implement a function that returns both the average precision and the trapezoidal area under the precision-recall curve for a binary classifier using scikit-learn. It tests correct use of the PR curve APIs and an understanding of why step-wise and interpolated PR areas give different numbers.