Skip to content

Instantly share code, notes, and snippets.

@dschaehi
Created November 6, 2021 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dschaehi/1ecdb3e53647d62e7daf106266bfa4bc to your computer and use it in GitHub Desktop.
Save dschaehi/1ecdb3e53647d62e7daf106266bfa4bc to your computer and use it in GitHub Desktop.
The Hamming score in PyTorch
import torch
def hamming_score(pred, answer):
out = ((pred & answer).sum(dim=1) / (pred | answer).sum(dim=1)).mean()
if out.isnan():
out = torch.tensor(1.0)
return out
answer = torch.tensor([[0, 1, 0], [0, 1, 1], [1, 0, 1], [0, 0, 1]])
pred = torch.tensor([[0, 1, 1], [0, 1, 1], [0, 1, 0], [0, 0, 0]])
hamming_score(pred, answer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment