Compare predicted class assignments with ground-truth labels.
Multiclass evaluation
Keras · Class
Keras F1Score computes the harmonic mean of precision and recall for multiclass or multilabel classification. Configure average for per-class, micro, macro, or weighted aggregation, and threshold for binary label decisions.
F1Score accumulates precision and recall statistics from true and predicted labels, then returns their harmonic mean. It supports multiclass and multilabel classification; averaging controls whether the result is per class or aggregated.
keras.metrics.F1Score(average=None, threshold=None, name="f1_score", dtype=None)| Name | Type | Description |
|---|---|---|
average | str | None | Averaging mode: None, "micro", "macro", or "weighted"; defaults to None. |
threshold | float | None | Decision cutoff for converting predictions to binary labels. If omitted, predictions use last-axis argmax. |
name | str | Name assigned to the metric; defaults to "f1_score". |
dtype | str | dtype | None | Optional data type for the metric result. |
A float F-1 Score; with average=None, result() returns one score per class.
dtype controls the result data type.average=None produces one score per class rather than a single scalar.import numpy as np
import keras
metric = keras.metrics.F1Score(threshold=0.5)
y_true = np.array([[1, 1, 1], [1, 0, 0], [1, 1, 0]], np.int32)
y_pred = np.array([[0.2, 0.6, 0.7], [0.2, 0.6, 0.6], [0.6, 0.8, 0.0]], np.float32)
metric.update_state(y_true, y_pred)
print(metric.result())Creates a multilabel F1 metric, accumulates one batch, and reads the per-class result.
Multiclass evaluation
Multilabel evaluation
Imbalanced classification
F1Score is the harmonic mean of precision and recall: 2 * (precision * recall) / (precision + recall). Its output is bounded between 0 and 1.
Follow-up: How would you obtain one value across all classes? Set average="micro", which computes statistics globally from total counts.
average options.average=None returns a score for every class. "macro" averages class scores equally, while "weighted" averages them using class support.
Follow-up: When can macro and weighted averages differ substantially? They diverge when class frequencies are imbalanced, because weighted averaging gives more influence to frequent classes.
threshold affect predictions?With threshold=None, Keras selects the class with the largest prediction on the last axis and converts it to one-hot form. A numeric threshold instead converts predictions to binary labels using that cutoff.
Follow-up: Which setting is generally appropriate for multilabel outputs? Use a threshold chosen for the application rather than argmax, because multiple labels may be positive simultaneously.
keras.metrics.FBetaScorekeras.metrics.Precisionkeras.metrics.Recallkeras.metrics.Metric