Metrics
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A metric is a number you watch to judge a model, but that is not differentiated or optimised: accuracy, AUC, F1, mean absolute error. Unlike a loss it is stateful and accumulates over all batches of an epoch. This page covers the built-in keras.metrics classes, how to read and reset them, the classification-metric pitfalls (logits versus probabilities, thresholds, averaging) and custom metrics. The objective that is actually optimised is on Losses; how metrics are reported by fit() is on compile, fit, evaluate & predict and how they reach the logs in Callbacks. The theory of classification and regression metrics (precision, recall, ROC, calibration) is in scikit-learn metrics; this page is only the Keras API.
Targets: Python 3.13, TensorFlow 2.21 with Keras 3.15 (TensorFlow 2.22 is upcoming), checked against keras.io on 2026-10-30. Examples were run on Python 3.13 with TensorFlow 2.21 and Keras 3.15 (CPU) on 2026-10-31. Snippets that continue an earlier example, or use names such as model and x_train defined elsewhere, were run with small synthetic stand-ins.
The metric catalogue
| Family | Classes (keras.metrics) |
|---|---|
Accuracy |
|
Probabilistic |
|
Regression |
|
Confusion-matrix based |
|
Correlation |
|
Segmentation |
|
Hinge |
|
Wrappers and reductions |
|
Source: https://keras.io/api/metrics/
Stateful by design
A metric object holds variables (for example a running total and count) and exposes three operations: update_state(y_true, y_pred, sample_weight=None) folds in a batch, result() returns the current value over everything seen so far, and reset_state() clears it. fit() resets the metrics at the start of every epoch, so the printed value is an average over the whole epoch, not the last batch.
import keras
m = keras.metrics.AUC()
m.update_state([0, 1, 1, 1], [0.0, 1.0, 0.0, 0.0])
print(float(m.result())) # 0.666... (AUC over all samples seen so far)
m.update_state([0, 0], [0.2, 0.1]) # accumulate a second batch
print(float(m.result())) # 0.444...
m.reset_state() # start over
Source: https://keras.io/api/metrics/
The keras.io overview page calls reset_states() (plural) in one standalone example, while custom metrics override reset_state(). In Keras 3 reset_state() is the method to use and override. A call to a metric as a function, m(y_true, y_pred), updates the state and returns the new result in one step. Calling m.result() never changes state; calling update_state twice with the same batch counts it twice.
Passing metrics to compile
import keras
model = keras.Sequential([keras.Input((20,)), keras.layers.Dense(64, activation="relu"), keras.layers.Dense(1)])
model.compile(
optimizer="adam",
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[
keras.metrics.BinaryAccuracy(name="acc", threshold=0.0), # logits: threshold at 0
keras.metrics.AUC(name="auc", from_logits=True),
keras.metrics.Precision(name="precision", thresholds=0.0),
keras.metrics.Recall(name="recall", thresholds=0.0),
],
)
# String identifiers use default arguments
model.compile(optimizer="adam", loss="mse", metrics=["mae", "MeanSquaredError"])
Instances let you set name (the key in the history.history dict and in callback logs), thresholds and averaging. Strings use defaults, so "accuracy" is resolved by Keras to an accuracy metric suited to the loss and output shape (binary, categorical or sparse); it is convenient but easy to misread, so name the class when it matters. With several outputs, metrics can be a dict keyed by output name or a list per output; weighted_metrics=[...] applies sample_weight to the metric as well, whereas plain metrics ignore the weights unless the metric is listed there.
Logits, probabilities and thresholds
Most classification metrics assume that the prediction is a probability in \([0, 1]\) and apply a threshold of 0.5 to turn it into a class. If the model outputs logits, the metric sees values like -3.2 or 4.1 and the 0.5 threshold is wrong.
-
AUChas afrom_logitsargument (apply a sigmoid internally). -
BinaryAccuracy,PrecisionandRecallhavethresholdorthresholdsarguments: on logits use0.0(equivalent to probability 0.5), or put asigmoidactivation on the output layer and keep the default. -
The multi-class accuracies (
CategoricalAccuracy,SparseCategoricalAccuracy, top-k variants) use the argmax or ranking, so they are the same on logits and probabilities. -
PrecisionandRecallaccept a list of thresholds and then return one value per threshold, andtop_korclass_idto focus on part of a multi-class output.
Check the constructor of each class on keras.io for the exact argument list in your version.
import keras
import numpy as np
y_true = np.array([0, 1, 1, 0, 1])
logits = np.array([-2.0, 1.5, 0.3, -1.1, 3.0]) # 0.3 is a positive logit (probability 0.57)
# Wrong: logits compared with the default 0.5 threshold
wrong = keras.metrics.BinaryAccuracy()
wrong.update_state(y_true, logits)
# Right: threshold 0 on logits
right = keras.metrics.BinaryAccuracy(threshold=0.0)
right.update_state(y_true, logits)
print(float(wrong.result()), float(right.result())) # 0.8 1.0
Multi-class and imbalanced problems
Accuracy hides imbalance: a model that always predicts the majority class of a 95/5 problem scores 0.95. Prefer metrics that look at the minority class:
-
Precision,Recall,AUC(withcurve="PR"for precision-recall AUC, better on rare positives) andF1Score. -
F1Score(average=None | "micro" | "macro" | "weighted")andFBetaScore(beta=...)take one-hot or multi-hot targets of shape(batch, C), return per-class values whenaverage=None, and threshold the predictions (default 0.5) unless athresholdis given. -
AUCwithmulti_label=Truecomputes one curve per label;num_thresholdscontrols the resolution of the approximation, which is computed from thresholded confusion counts, not an exact sort. -
TopKCategoricalAccuracy(k=5)orSparseTopKCategoricalAccuracyfor many-class problems such as ImageNet.
import keras
num_classes = 5
model.compile(
optimizer="adam",
loss=keras.losses.CategoricalCrossentropy(from_logits=True),
metrics=[
keras.metrics.CategoricalAccuracy(name="acc"),
keras.metrics.TopKCategoricalAccuracy(k=3, name="top3"),
keras.metrics.F1Score(average="macro", name="f1_macro"),
keras.metrics.AUC(curve="PR", multi_label=False, from_logits=True, name="pr_auc"),
],
)
For a full per-class report after training, predict and use scikit-learn’s classification_report (see scikit-learn metrics); streaming metrics are for monitoring during training. Class imbalance remedies are on Problem Framing & ML Projects.
Regression and segmentation metrics
-
MeanAbsoluteErroris on the target’s scale and robust to outliers;RootMeanSquaredErroris on the target’s scale and penalises large errors. -
R2Score(class_aggregation="uniform_average" | "variance_weighted_average" | None, num_regressors=0)is the coefficient of determination; it can be negative for a model worse than the mean, and withclass_aggregation=Nonereturns one value per output. -
MeanAbsolutePercentageErrorexplodes when targets are near zero. -
PearsonCorrelationandConcordanceCorrelationmeasure agreement between predictions and targets; the concordance version also penalises bias. -
MeanIoU(num_classes=...)expects integer class maps,OneHotMeanIoUtakes one-hot maps, andBinaryIoUthresholds a probability mask.
import keras
model.compile(
optimizer="adam",
loss="mse",
metrics=[
keras.metrics.MeanAbsoluteError(name="mae"),
keras.metrics.RootMeanSquaredError(name="rmse"),
keras.metrics.R2Score(name="r2"),
],
)
Aggregating values with Mean and Sum
keras.metrics.Mean and Sum track a running average or total of arbitrary values, which is how you log a quantity that is not a function of (y_true, y_pred), for example the loss in a custom loop, a gradient norm or a KL term.
import keras
loss_tracker = keras.metrics.Mean(name="loss")
grad_norm = keras.metrics.Mean(name="grad_norm")
loss_tracker.update_state(0.9)
loss_tracker.update_state(0.7)
print(float(loss_tracker.result())) # 0.8
Source: https://keras.io/api/metrics/
In a custom train_step these trackers are returned from the metrics property so that fit() resets them each epoch (see Customizing fit() with train_step and Writing a Training Loop from Scratch).
Custom metrics
A stateless metric is any callable fn(y_true, y_pred) returning per-sample values: pass it to compile() and Keras wraps it in MeanMetricWrapper, so the reported value is the mean of the per-sample values. That is wrong for quantities that are not averages of per-sample values (F1, AUC, correlation). Those need a stateful subclass of keras.metrics.Metric:
import keras
from keras import ops
class BinaryTruePositives(keras.metrics.Metric):
def __init__(self, name="binary_true_positives", **kwargs):
super().__init__(name=name, **kwargs)
self.true_positives = self.add_weight(name="tp", initializer="zeros")
def update_state(self, y_true, y_pred, sample_weight=None):
y_true = ops.cast(y_true, "bool")
y_pred = ops.cast(ops.greater(y_pred, 0.5), "bool")
values = ops.cast(ops.logical_and(y_true, y_pred), self.dtype)
if sample_weight is not None:
values = values * ops.cast(sample_weight, self.dtype)
self.true_positives.assign(self.true_positives + ops.sum(values))
def result(self):
return self.true_positives
def reset_state(self):
self.true_positives.assign(0.0)
# A stateless metric as a plain function: mean of per-sample values
def within_tolerance(y_true, y_pred):
return ops.cast(ops.abs(y_true - y_pred) < 0.1, "float32")
Source: https://keras.io/api/metrics/ (the "Creating custom metrics" section)
Notes:
-
State is created with
self.add_weight(...), which registers the variable so it is tracked; the keras.io example uses the same call. -
Update state with
variable.assign(...)andops, not Python side effects, becauseupdate_stateis traced into the compiled training step. -
Implement
get_config()if the metric has constructor arguments and the model must be reloaded (see Saving Keras Models). -
Metrics should never create gradients; they are applied to the already computed outputs.
Reading the results
model.fit() returns a History whose history dict maps each metric name to a list per epoch, with a val_ prefix for validation. model.evaluate(..., return_dict=True) returns the same names as a dict. model.metrics_names lists the names in order (including loss).
history = model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=5, verbose=0)
print(history.history.keys()) # dict_keys(['auc', 'loss', 'val_auc', 'val_loss'])
scores = model.evaluate(x_val, y_val, return_dict=True, verbose=0)
best_epoch = max(range(5), key=lambda i: history.history["val_auc"][i])
A callback can monitor any of these names, for example EarlyStopping(monitor="val_auc", mode="max"); use mode="max" for metrics where larger is better, because the default "auto" guesses from the name.
Common mistakes
-
Reading training metrics as the final model quality: they are averages over an epoch while the weights changed. Use
evaluateon held-out data. -
Using accuracy on imbalanced data, or
0.5thresholds on logits. -
Reusing a metric instance across several models or
compile()calls: its state carries over; create fresh instances (or callreset_state()). -
Passing integer labels to
CategoricalAccuracy(use the sparse variant) or one-hot labels toSparseCategoricalAccuracy. -
Treating a stateless function metric as a global statistic; it is a mean of batch results.