Cal11 calculator

Calculate True Positive Rate Javascript

Reviewed by Calculator Editorial Team

The true positive rate (TPR) is a key metric in statistics and machine learning that measures the proportion of actual positives correctly identified by a test or model. This guide explains how to calculate the true positive rate in JavaScript, including the formula, practical examples, and common pitfalls.

What is True Positive Rate?

The true positive rate, also known as sensitivity or recall, measures how well a test or model correctly identifies positive cases. It's calculated by dividing the number of true positives by the total number of actual positives.

In medical testing, for example, a high true positive rate means the test accurately identifies people who have a particular condition. In machine learning, it indicates how well a model correctly classifies positive instances.

JavaScript Calculation

To calculate the true positive rate in JavaScript, you'll need the number of true positives and the total number of actual positives. Here's a simple function that performs this calculation:

function calculateTruePositiveRate(truePositives, actualPositives) {
  if (actualPositives === 0) return 0;
  return truePositives / actualPositives;
}

This function first checks if there are any actual positives to avoid division by zero. If there are, it returns the ratio of true positives to actual positives.

Formula

The mathematical formula for true positive rate is:

True Positive Rate (TPR) = True Positives / Actual Positives

Where:

  • True Positives (TP) are cases correctly identified as positive
  • Actual Positives (P) are all cases that are actually positive

The result is typically expressed as a decimal between 0 and 1, where 1 means all actual positives were correctly identified.

Example

Let's say you have a medical test where:

  • 120 people tested positive (True Positives)
  • 150 people actually have the condition (Actual Positives)

The true positive rate would be calculated as:

TPR = 120 / 150 = 0.8 (or 80%)

This means the test correctly identified 80% of people who actually have the condition.

FAQ

What's the difference between true positive rate and precision?
True positive rate measures how well a test identifies actual positives, while precision measures how accurate the positive predictions are. A high true positive rate doesn't necessarily mean high precision.
How do I interpret a true positive rate of 0.7?
A TPR of 0.7 means the test correctly identified 70% of all actual positive cases. This is generally considered good performance, though the acceptable threshold depends on the specific application.
What if I get a division by zero error?
This happens when there are no actual positives in your data. The JavaScript function provided handles this case by returning 0, as you can't have a true positive rate when there are no actual positives.