Evaluate thresholded binary predictions
Binary classification with probability outputs.
TensorFlow · Class
Computes the fraction of predicted positives that are correct. It supports threshold-based binary evaluation, top-k multiclass evaluation, and restricting measurement to one class.
Precision accumulates true-positive and false-positive counts across updates, then returns their ratio. Predictions become positive when they meet the configured threshold; alternatively, top-k selection or a specific class can control which predictions are evaluated.
tf.keras.metrics.Precision(thresholds=None, top_k=None, class_id=None, name=None, dtype=None)| Name | Type | Description |
|---|---|---|
thresholds | float or list/tuple of float | Optional float or list/tuple of floats in [0, 1]; each threshold determines whether a prediction is positive. Defaults to 0.5 when neither thresholds nor top_k is set. |
top_k | int | Optional number of highest-scoring classes used for precision in multiclass predictions. |
class_id | int | Optional class ID for which binary precision is computed; it must be within the prediction class dimension. |
name | str | Optional name for the metric instance. |
dtype | str or tf.dtypes.DType | Optional data type for the metric. |
A scalar or tensor of precision values produced by the metric; multiple configured thresholds produce one value per threshold.
import tensorflow as tf
metric = tf.keras.metrics.Precision()
metric.update_state([1, 1, 0, 0], [0.9, 0.6, 0.8, 0.2])
print(metric.result().numpy()) # 0.6666667Creates the metric, adds one batch of labels and prediction scores, and reads the accumulated precision.
Binary classification with probability outputs.
Multiclass classification where only the highest-scoring candidates matter.
Per-class monitoring in a multiclass model.
The metric tracks true_positives and false_positives. Its result is true positives divided by the sum of true positives and false positives.
Follow-up: How does it decide whether a prediction is positive? It compares prediction values with configured thresholds, or uses top-k selection when top_k is set.
top_k change?With top_k, precision evaluates whether classes among the k highest predicted values are correctly represented in the labels. This is useful for multiclass predictions.
Follow-up: What happens if class_id is also supplied? The calculation focuses on that class, but the documented modes should be configured deliberately because they select a narrower evaluation target.
class_id affect the metric?class_id restricts the calculation to batch entries where that class passes the threshold or is among the top-k predictions. Precision then measures how often that class is a correct label for those entries.
Follow-up: What constraint applies to class_id? It must be an integer from zero through one less than the number of prediction classes.
tf.keras.metrics.Recalltf.keras.metrics.TruePositivestf.keras.metrics.FalsePositivestf.keras.metrics.F1Score