Hamming Distance¶
Module Interface¶
- class torchmetrics.HammingDistance(threshold=0.5, compute_on_step=None, **kwargs)[source]
Computes the average Hamming distance (also known as Hamming loss) between targets and predictions:

Where
is a tensor of target values,
is a tensor of predictions,
and
refers to the
-th label of the
-th sample of that
tensor.This is the same as
1-accuracyfor binary data, while for all other types of inputs it treats each possible label separately - meaning that, for example, multi-class data is treated as if it were multi-label.Accepts all input types listed in Input types.
- Parameters
threshold¶ (
float) – Threshold for transforming probability or logit predictions to binary(0,1)predictions, in the case of binary or multi-label inputs. Default value of0.5corresponds to input being probabilities.compute_on_step¶ (
Optional[bool]) –Forward only calls
update()and returns None if this is set to False.Deprecated since version v0.8: Argument has no use anymore and will be removed v0.9.
kwargs¶ (
Dict[str,Any]) – Additional keyword arguments, see Advanced metric settings for more info.
- Raises
ValueError – If
thresholdis not between0and1.
Example
>>> from torchmetrics import HammingDistance >>> target = torch.tensor([[0, 1], [1, 1]]) >>> preds = torch.tensor([[0, 1], [0, 1]]) >>> hamming_distance = HammingDistance() >>> hamming_distance(preds, target) tensor(0.2500)
Initializes internal Module state, shared by both nn.Module and ScriptModule.
- compute()[source]
Computes hamming distance based on inputs passed in to
updatepreviously.- Return type
Functional Interface¶
- torchmetrics.functional.hamming_distance(preds, target, threshold=0.5)[source]
Computes the average Hamming distance (also known as Hamming loss) between targets and predictions:

Where
is a tensor of target values,
is a tensor of predictions,
and
refers to the
-th label of the
-th sample of that
tensor.This is the same as
1-accuracyfor binary data, while for all other types of inputs it treats each possible label separately - meaning that, for example, multi-class data is treated as if it were multi-label.Accepts all input types listed in Input types.
- Parameters
Example
>>> from torchmetrics.functional import hamming_distance >>> target = torch.tensor([[0, 1], [1, 1]]) >>> preds = torch.tensor([[0, 1], [0, 1]]) >>> hamming_distance(preds, target) tensor(0.2500)
- Return type