Skip to main content
v2026.11,986 entries · CC-BY 4.0

sklearn precision_recall_curve: Syntax, Plotting and Reading the Output

How to use sklearn precision_recall_curve: arguments, plotting with PrecisionRecallDisplay, the n+1 array rule, AP versus trapezoid area and common errors.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In scikit-learn, sklearn.metrics.precision_recall_curve(y_true, y_score) takes binary labels and non-thresholded scores (probabilities or decision values) and returns three arrays: precision, recall and the thresholds at which they were computed. Plot them with PrecisionRecallDisplay, and summarise the curve with average_precision_score. This guide covers the call, the array-length rule that trips up most first-time users, how to plot, how to read the output, and the errors you are most likely to meet.

What it is used for in research

A precision-recall (PR) curve shows how precision (tp / (tp + fp)) trades against recall (tp / (tp + fn)) as the decision threshold on a classifier’s score moves. The scikit-learn user guide describes the metrics this way and notes that average precision (AP) summarises the curve as a weighted mean of precisions, with the increase in recall from the previous threshold as the weight. Researchers use PR curves when the positive class is rare, because precision responds directly to false positives and recall to missed positives, and neither uses the true negatives. For a side-by-side with the ROC curve see AUROC vs AUPRC; for the underlying definitions see the precision and recall formula.

The function is restricted to the binary case. For multiclass or multilabel problems, the documentation points to average_precision_score, which handles them one-vs-rest through its average parameter.

How to install or access it

The function ships in scikit-learn. The official installation page (read 2026-11-15, showing 1.9.1 as the latest release) recommends installing into a virtual environment:

python3 -m venv sklearn-envsource sklearn-env/bin/activate   # Windows: sklearn-envScriptsactivatepip3 install -U scikit-learn

With conda the documented route is conda create -n sklearn-env -c conda-forge scikit-learn. Check the installation with python -c "import sklearn; sklearn.show_versions()". The plotting classes need Matplotlib (3.6.1 or later according to the installation page); the metric function itself does not plot anything.

Step-by-step task: compute and plot a precision-recall curve

Step 1. Get scores, not hard predictions

Pass y_score as probability estimates or non-thresholded decision values. For a fitted classifier that means predict_proba(X)[:, 1] or decision_function(X), not predict(X). For decision values, the documentation states that a value of 0 or above means the positive class.

Step 2. Call precision_recall_curve

from sklearn.metrics import precision_recall_curveprecision, recall, thresholds = precision_recall_curve(y_true, y_score)

The full signature is precision_recall_curve(y_true, y_score, *, pos_label=None, sample_weight=None, drop_intermediate=False). pos_label is the label treated as positive. When it is None and the labels are in {0, 1} or {-1, 1}, the positive class is 1; for any other labels the call raises an error until you set pos_label. drop_intermediate (added in version 1.3) drops suboptimal thresholds to give a lighter curve.

Step 3. Plot with PrecisionRecallDisplay

The documented pattern builds a classifier on simulated data and plots straight from the estimator:

from sklearn.datasets import make_classificationfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import PrecisionRecallDisplayfrom sklearn.model_selection import train_test_splitX, y = make_classification(random_state=0)X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)clf = LogisticRegression().fit(X_train, y_train)PrecisionRecallDisplay.from_estimator(clf, X_test, y_test)

If you already hold scores, use PrecisionRecallDisplay.from_predictions(y_test, clf.predict_proba(X_test)[:, 1]). With from_estimator, response_method='auto' tries predict_proba first and then decision_function. Setting plot_chance_level=True (added in 1.3) draws the no-skill line, and the returned display exposes line_, chance_level_, ax_ and figure_ for further styling.

Step 4. Summarise with average precision

from sklearn.metrics import average_precision_scoreap = average_precision_score(y_test, clf.predict_proba(X_test)[:, 1])

AP is sum_n (R_n - R_{n-1}) P_n, between 0 and 1, higher is better; the documentation notes that random predictions give an AP equal to the fraction of positives.

Output and how to read it

The array-length rule

The two curve arrays are one element longer than the thresholds array. Per the documentation, precision and recall each have n_thresholds + 1 elements, thresholds has n_thresholds elements, and n_thresholds = len(np.unique(y_score)). Recall is decreasing and thresholds are increasing. The last precision and recall values are 1.0 and 0.0 and have no matching threshold; they make the curve start on the y axis. The first values correspond to the lowest threshold, where every sample is called positive: recall is 1.0 and precision equals the class balance.

A four-point example, row by row

The documentation’s example uses y_true = [0, 0, 1, 1] and y_scores = [0.1, 0.4, 0.35, 0.8] and returns precision [0.5, 0.66666667, 0.5, 1, 1], recall [1, 1, 0.5, 0.5, 0] and thresholds [0.1, 0.35, 0.4, 0.8]. The data table below sets these out point by point. You can reproduce each row by hand by calling every sample with a score at or above the threshold positive:

  • At threshold 0.1 all four samples are positive calls: 2 true positives, 2 false positives, so precision 2/4 = 0.5 and recall 2/2 = 1.
  • At 0.35 the calls are the samples scoring 0.35, 0.4 and 0.8: 2 true positives, 1 false positive, so precision 2/3 and recall 1.
  • At 0.4 the calls are 0.4 and 0.8: 1 true positive, 1 false positive, so precision 0.5 and recall 1/2.
  • At 0.8 only the top sample is called: 1 true positive, 0 false positives, so precision 1 and recall 0.5.
  • The final point (precision 1, recall 0) has no threshold; it is the sentinel that anchors the curve.

Choosing an operating threshold

Because the arrays are offset by one, align them before picking a threshold: use precision[:-1] and recall[:-1] against thresholds. Which point to choose is a study decision (for example, a minimum recall you must reach), not something the function decides. If you need the full confusion matrix at the chosen cut-off, see the sklearn confusion matrix guide; for a single number that blends the two measures see the F1 score formula.

Curve versus summary: why AP and a trapezoid area disagree

scikit-learn’s average_precision_score does not implement interpolated variants. Since version 0.19 it weights by the change in recall instead of using linear interpolation, and PrecisionRecallDisplay draws the curve as a step function to stay consistent with it. The user guide cites Davis (2006) and Flach (2015) as describing linear (trapezoidal) interpolation of the PR curve as overly optimistic. Passing the curve arrays to sklearn.metrics.auc gives a different number from AP, so do not label an auc(recall, precision) value as average precision. On the four-point example, AP is about 0.83, while a trapezoid over the same arrays gives about 0.79 (our arithmetic from the arrays above), so the two summaries are not interchangeable. The display’s curve_kwargs={"drawstyle": "default"} option draws straight lines between points, but then the plotted line no longer matches the AP shown in the legend. For the ROC-side summary see ROC curve and AUC.

Reporting a PR curve in a paper

State the positive class (pos_label), the score you used (probability or decision value), the class prevalence in the evaluation set, and the AP alongside the plot. Prevalence matters because it is the PR curve’s baseline: the first precision value equals the class balance, and a random classifier’s AP equals the fraction of positives. Add the chance-level line with plot_chance_level=True so readers can see the baseline, and name the scikit-learn version you ran.

Version notes

The parameters below changed across releases according to the API documentation (read 2026-11-15). Pin the version in your methods section if you rely on any of them.

Version Change
0.19 average_precision_score moved from linear interpolation to recall-change weighting
1.3 drop_intermediate added to precision_recall_curve; plot_chance_level added to the display
1.6 despine added to the display
1.8 from_predictions argument y_pred deprecated and renamed y_score
1.9 curve_kwargs added; passing **kwargs deprecated, with removal in 1.11

Troubleshooting

Error when labels are not 0/1 or -1/1

If y_true holds strings or other integers, the call fails until you pass pos_label, for example pos_label='malignant'. Check the label that ends up in the positive role; a flipped pos_label gives a valid but different curve.

Multiclass labels

The function is binary only. Binarise the problem (one class versus the rest) and call it per class, or use average_precision_score with its average parameter for a one-vs-rest summary.

Hard predictions give a one-point curve

Passing predict(X) output means y_score has only two distinct values, so there are at most two thresholds and the curve has almost no shape. Pass probabilities or decision values instead.

Mismatched array lengths when plotting or indexing

Trying to plot thresholds against precision directly fails because of the extra sentinel point; slice precision[:-1] and recall[:-1] first.

Deprecation warnings from PrecisionRecallDisplay

Rename y_pred to y_score in from_predictions (1.8) and move styling arguments into curve_kwargs (1.9 onward).

Free alternatives

Option What it gives you Basis
PrecisionRecallDisplay Plot directly from an estimator or from scores, with chance level scikit-learn API documentation
average_precision_score Single non-interpolated summary, supports multiclass and multilabel one-vs-rest scikit-learn API documentation
roc_curve ROC counterpart, listed under See Also on the function’s page scikit-learn API documentation
det_curve Detection error tradeoff curve, listed under See Also scikit-learn API documentation

Frequently asked questions

What does sklearn precision_recall_curve return?

It returns precision, recall and thresholds. Precision and recall each have one more element than thresholds because the final point (precision 1, recall 0) has no threshold.

How do I plot a precision-recall curve in sklearn?

Use PrecisionRecallDisplay.from_estimator(clf, X_test, y_test) for a fitted classifier, or PrecisionRecallDisplay.from_predictions(y_true, y_score) when you already have scores.

Does precision_recall_curve work for multiclass problems?

No. The user guide states it is restricted to the binary case. Use a one-vs-rest setup or average_precision_score with average.

Why does my area under the PR curve differ from average precision?

AP is a step-wise, non-interpolated sum. A trapezoidal area from auc uses linear interpolation, which the scikit-learn documentation describes as overly optimistic, so the numbers differ.

What is the sklearn precision-recall curve baseline?

The first precision value equals the class balance, and random predictions give an AP equal to the fraction of positives.

Sources

Data: scikit-learn precision_recall_curve worked example: output arrays for a four-sample input

Precision, recall and threshold values returned by sklearn.metrics.precision_recall_curve for the documentation's example y_true=[0,0,1,1], y_scores=[0.1,0.4,0.35,0.8], listed point by point including the final sentinel point with no threshold.

scikit-learn precision_recall_curve worked example: output arrays for a four-sample input
PointThresholdPrecisionRecall
10.10.51
20.350.666666671
30.40.50.5
40.810.5
5 (sentinel)none10

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about sklearn precision_recall_curve: Syntax, Plotting and Reading the Output

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →