IndiaIndian Nationals
1800 210 2020
ForiegnForeign Nationals
+918068792934
logologo
Home
About
Director's Message
Blogs
HomeAbout
Director's MessageBlogs
Limited Seats Available

Precision and Recall in Machine Learning: Meaning, Formulas, Differences, and Examples

  1. Home
  2. Blog
  3. Precision and Recall in Machine Learning: Meaning, Formulas, Differences, and Examples

By Rahul Singh

Updated on Nov 25, 2026

Share:

Quick Overview:

  • Precision is the measure of how many predicted positives are really positives, whereas recall is the measure of how many actual positives the model can detect.

  • Precision and recall formulas: Precision = TP / (TP + FP) and Recall = TP / (TP + FN).

  • Both are calculated through a confusion matrix and they are especially helpful in the evaluation of models trained on imbalanced datasets.

  • F1 score balances precision and recall, while the F-beta score puts more emphasis on one of the metrics.

  • The appropriate evaluation metric should be chosen based on the particular problem, data, and cost of the wrong prediction in real life.

  • In this blog you will learn how to calculate precision and recall, understand their differences and trade-offs, explore Python examples, and choose the right evaluation metric for your machine learning model.

In FinTech, metrics like precision and recall help evaluate AI models for fraud detection, credit risk assessment, and financial security. Explore the FinTech in the Age of AI – Professional Certificate Programme from IIT Kharagpur to learn how AI can solve real-world financial challenges.

Understanding Precision and Recall in Machine Learning

So, what is precision and recall? They're two ways of measuring how well a classification model finds the cases you care about, which machine learning people call the positive class. 

  • Precision asks: of everything the model flagged as positive, how much was actually positive? 

  • Recall asks: of everything that was actually positive, how much did the model find?

Take a spam filter. If it marks 100 emails as spam and 80 really are spam, its precision is 80%. If the inbox held 120 real spam emails in total, and the filter caught those 80, its recall is about 67%. Precision tells you how trustworthy the alerts are. Recall tells you how much slips through.

That's the short answer to what is precision and recall in machine learning: precision measures the quality of positive predictions, and recall measures the coverage of actual positives. 

Also Read: Classification vs Regression in Machine Learning

Confusion Matrix: The Foundation of Precision and Recall

Both metrics come from the confusion matrix, a small table that counts a model's right and wrong calls for each class. For a yes-or-no problem it has four cells.

Predicted Positive

Predicted Negative

Actually Positive

True Positive (TP)

False Negative (FN)

Actually Negative

False Positive (FP)

True Negative (TN)

The four terms are easy to mix up, so here's what each means in the spam example.

Term

Meaning

Spam Filter Example

True Positive (TP)

Predicted positive, and it was positive

Spam correctly sent to the spam folder

False Positive (FP)

Predicted positive, but it was negative

A real email wrongly marked as spam

False Negative (FN)

Predicted negative, but it was positive

Spam that reached the inbox

True Negative (TN)

Predicted negative, and it was negative

A real email correctly left in the inbox

An easy way to remember it: the second word is what the model predicted, and the first word says whether that prediction was right. A false positive is a wrong "positive" call. 

Precision is affected by false positives, and recall is affected by false negatives. True negatives affect neither, which is the main reason these two metrics hold up on imbalanced data where true negatives dominate.

Precision and Recall Formulas With Examples

Here is the precision and recall formula, written in terms of the confusion matrix counts:

Precision = TP / (TP + FP)

Recall    = TP / (TP + FN)

  • Precision divides the true positives by everything the model calls positive. 

  • Recall divides them by everything that really was positive. 

Worked Example

Imagine a spam filter is tested on 1,000 emails. The confusion matrix shows 80 true positives, 20 false positives, 40 false negatives, and 860 true negatives.

Metric

Calculation

Result

Precision

80 / (80 + 20)

0.80

Recall

80 / (80 + 40)

0.67

Accuracy

(80 + 860) / 1,000

0.94

F1 score

2 x 0.80 x 0.67 / (0.80 + 0.67)

0.73

Notice that accuracy looks excellent at 94%, while recall shows the filter misses a third of the spam. That's the gap precision and recall are meant to expose.

Reading the Numbers

A common slip when learning the precision and recall formula is to swap the denominators. A quick check: precision always has FP in the denominator, because it's about the model's positive calls, and recall always has FN, because it's about the positives that exist. If you can say in words what the denominator counts, you'll rarely mix them up. 

Another check is that both values sit between 0 and 1 (or 0% and 100% if you prefer percentages), and both reach 1 only when the corresponding error count is zero.

Precision and Recall in ML: Python Example

The code below does two things. First it reproduces the hand calculation above. Then it trains a logistic regression model on a synthetic dataset where only about 10% of samples are positive, and reports precision, recall, and F1 at several decision thresholds. It needs scikit-learn and NumPy.

import numpy as np

from sklearn.datasets import make_classification

from sklearn.linear_model import LogisticRegression

from sklearn.metrics import confusion_matrix, f1_score, precision_score, recall_score

from sklearn.model_selection import train_test_split


# 1. The worked example from the article, done by hand

tp, fp, fn, tn = 80, 20, 40, 860

precision = tp / (tp + fp)

recall = tp / (tp + fn)

f1 = 2 precision recall / (precision + recall)

print(f"By hand -> precision={precision:.3f} recall={recall:.3f} f1={f1:.3f}")


# 2. A real model on imbalanced data (about 10% positives)

X, y = make_classification(

    n_samples=5000, n_features=10, n_informative=5,

    weights=[0.9, 0.1], flip_y=0.02, random_state=42,

)

X_train, X_test, y_train, y_test = train_test_split(

    X, y, test_size=0.3, stratify=y, random_state=42

)

model = LogisticRegression(max_iter=1000).fit(X_train, y_train)

scores = model.predict_proba(X_test)[:, 1]


print("\nThreshold  Precision  Recall   F1     TP   FP   FN")

for threshold in [0.2, 0.3, 0.5, 0.7, 0.9]:

    pred = (scores >= threshold).astype(int)

    tn_, fp_, fn_, tp_ = confusion_matrix(y_test, pred).ravel()

    print(

        f"{threshold:<10} {precision_score(y_test, pred):<10.3f} "

        f"{recall_score(y_test, pred):<8.3f} {f1_score(y_test, pred):<6.3f} {tp_:<4} {fp_:<4} {fn_}"

    )

The first line prints precision 0.800, recall 0.667, and F1 0.727, matching the table. 

The second part prints the results used in the next section. Because the data is synthetic and deliberately hard, the absolute numbers matter less than the pattern they show.

You can also use cross-validation to assess precision and recall across multiple data splits.

The Trade-Off Between Precision and Recall

Most classifiers don't output a hard yes or no. They output a probability, and you pick a threshold above which a case counts as positive. That threshold is the dial that trades precision against recall.

Lower the threshold and the model flags more cases. It catches more real positives, so recall rises, but it also flags more false alarms, so precision falls. Raise the threshold and the opposite happens. Here is what the script printed for the test set of 1,500 samples, of which 163 were positive.

Threshold

Precision

Recall

F1

True Positives

False Positives

False Negatives

0.2

0.386

0.626

0.478

102

162

61

0.3

0.490

0.472

0.481

77

80

86

0.5

0.657

0.282

0.395

46

24

117

0.7

0.708

0.104

0.182

17

7

146

0.9

1.000

0.031

0.060

5

0

158

At a threshold of 0.9, the model is never wrong when it speaks up, with perfect precision, but it finds only 5 of 163 positives. 

At 0.2 it finds most of them, but about 60% of its alerts are false. No setting wins on both. The default threshold of 0.5 is rarely the right one, and choosing it deliberately is often the cheapest improvement available.

Precision and Recall Difference at a Glance

The difference between precision and recall is easiest to keep straight in a side-by-side view.

Factor

Precision

Recall

Question it answers

Of the cases flagged positive, how many were right?

Of the real positives, how many were found?

Formula

TP / (TP + FP)

TP / (TP + FN)

Error it punishes

False positives (false alarms)

False negatives (missed cases)

Other names

Positive predictive value

Sensitivity, true positive rate, hit rate

High value means

Few false alarms

Few missed positives

Easy way to inflate

Flag only the most certain cases

Flag everything

Matters most when

A false alarm is expensive

A miss is expensive

If you remember one line about the difference between precision and recall, make it this one: precision is about being right when you say yes, and recall is about not missing the yeses that exist.

Visualizing the Trade-Off With a Precision-Recall Curve

Instead of testing thresholds one by one, you can plot precision against recall across every threshold. That plot is called a precision-recall curve. A model whose curve sits higher and further right is better overall. 

Alt text: Precision-recall curve infographic comparing Model A (PR-AUC = 0.89) and Model B (PR-AUC = 0.72), illustrating the trade-off between precision and recall across classification thresholds, its usefulness for imbalanced datasets, and relevant scikAlt text: Precision-recall curve infographic comparing Model A (PR-AUC = 0.89) and Model B (PR-AUC = 0.72), illustrating the trade-off between precision and recall across classification thresholds, its usefulness for imbalanced datasets, and relevant scik

F1 Score and Other Metrics Related to Precision and Recall

Comparing two models is awkward when one has higher precision and the other has higher recall. 

A single number that combines both helps, and the most common one is the F1 score.

F1 Score

F1 is the harmonic mean of precision and recall:

F1 = 2 x (Precision x Recall) / (Precision + Recall)

The harmonic mean punishes imbalance between the two inputs. A model with precision 1.0 and recall 0.03, like the 0.9 threshold row above, gets an F1 of only 0.06, while a plain average would call it 0.52 and hide the problem. F1 is high only when both precision and recall are reasonably high.

F-Beta Score

F1 treats precision and recall as equally important. When they aren't, the F-beta score lets you weight them. 

An F2 score values recall more than precision, which suits cases where misses are costly. An F0.5 score values precision more, which suits cases where false alarms are costly. The general formula adds a beta factor, and beta values above 1 lean toward recall while values below 1 lean toward precision.

Other Metrics You'll Meet

Metric

Formula or Idea

What It Tells You

Watch Out For

Accuracy

(TP + TN) / total

Share of all predictions that were correct

Misleading when classes are imbalanced

Specificity

TN / (TN + FP)

Share of real negatives correctly identified

Ignores positives completely

Sensitivity

Same as recall

Share of real positives found

Ignores false alarms

F1 score

Harmonic mean of precision and recall

Balance between the two

Hides which one is weak

PR-AUC

Area under the precision-recall curve

Performance across all thresholds

Harder to explain to non-technical readers

ROC-AUC

Area under the curve of true positive rate vs false positive rate

Ability to rank positives above negatives

Can look flattering on heavily imbalanced data

Matthews correlation coefficient

Correlation between predicted and actual labels

A balanced single score using all four cells

Less familiar to many teams

Choosing the Right Evaluation Metric for Your ML Model

There's no best metric in the abstract. The right one depends on what a mistake costs. A useful exercise is to ask which error you'd rather explain to a customer or a manager: the false alarm or the miss.

Scenario

Costlier Error

Metric to Favor

Why

Cancer screening

Missing a real case

Recall

A false alarm leads to more tests, a miss can cost a life

Spam filtering

Blocking a real email

Precision

Losing a job offer is worse than seeing some spam

Fraud detection

Missing a fraudulent transaction

Recall, with a limit on false alarms

Fraud losses are large, but too many blocks hurt customers and analyst time

Semantic search results

Showing irrelevant items at the top

Precision, often at the top of the list

Users read only the first few results

Legal document review

Missing a relevant document

Recall

Courts expect thorough discovery

Content moderation

Missing harmful content

Recall, with human review of flags

Missed content causes harm, and review catches false alarms

Product recommendation

Recommending items nobody wants

Precision

Poor suggestions reduce trust in the whole feed

Balanced classes, equal costs

Neither stands out

Accuracy or F1

Both error types matter about equally

Sentiment analysis

Missing negative customer feedback

Recall for the negative class

Helps businesses identify dissatisfied customers.

Costs also change over time. A fraud team might accept a flood of alerts during a known attack wave, then tighten the threshold once the wave passes. Treat the threshold as a setting you review, not a number you choose once.

Conclusion

A high accuracy score doesn't always mean you have a good machine learning model. What really matters is understanding where your model makes mistakes and how those mistakes affect real-world outcomes. This is where precision and recall become more meaningful than accuracy alone.

Rather than chasing perfect scores, focus on balancing both metrics based on the problem you're trying to solve.


Rahul Singh

Rahul Singh

37+ of articles published


Current role in the industry :

Associate - Content Marketing

Education Qualification :

B.Tech in Computer Science & Engineering

Expertise :

Artificial intelligenceMachine Learning (ML)Data ScienceFull-Stack DevelopmentData Structures & Algorithms

Tools & Technologies :

PythonReact.js & Next.jsJavaScript (ES6+)SQLTailwind CSSNode.js & MongoDBGit & GitHubSEO Tools (SEMRush)Google Search ConsoleTableau / Power BIFigma

About

Rahul Singh is an Associate Content Writer, with a strong interest in Generative AI, Agentic AI and AI-Native Software Engineering. He combines technical development skills with data-driven strategies to build scalable applications and optimize digital content. Rahul specializes in simplifying complex concepts across AI, ML and software development into practical, easy-to-understand insights, helping learners understand how AI products, systems and services are built and applied. He focuses on real world applications and explains advanced topics in a clear, step by step manner so you can follow along without confusion. His work connects theory with hands-on examples, covering AI-assisted development, intelligent automation and AI integration in software applications. He aims to help you learn faster, create better projects, and apply your knowledge confidently in real scenarios.

Follow me on :

No blogs published yet.

Frequently Asked Questions

FAQ

Ready to Take the Next Step? Enroll Today!

Ready to Take the Next Step? Enroll Today!