torchmetrics1.6.0
Published
PyTorch native Metrics
pip install torchmetrics
Package Downloads
Authors
Project URLs
Requires Python
>=3.9
Dependencies
- numpy
>1.20.0
- packaging
>17.1
- torch
>=2.0.0
- lightning-utilities
>=0.8.0
- typing-extensions
; python_version < "3.9"
- numpy
<2.0; extra == "all"
- onnxruntime
>=1.12.0; extra == "all"
- pesq
>=0.0.4; extra == "all"
- librosa
>=0.10.0; extra == "all"
- gammatone
>=1.0.0; extra == "all"
- pystoi
>=0.4.0; extra == "all"
- torchaudio
>=2.0.1; extra == "all"
- requests
>=2.19.0; extra == "all"
- pycocotools
>2.0.0; extra == "all"
- torchvision
>=0.15.1; extra == "all"
- torch-fidelity
<=0.4.0; extra == "all"
- scipy
>1.0.0; extra == "all"
- transformers
>=4.42.3; extra == "all"
- piq
<=0.8.0; extra == "all"
- nltk
>3.8.1; extra == "all"
- tqdm
<4.68.0; extra == "all"
- sentencepiece
>=0.2.0; extra == "all"
- mecab-python3
>=1.0.6; extra == "all"
- regex
>=2021.9.24; extra == "all"
- ipadic
>=1.0.0; extra == "all"
- transformers
>4.4.0; extra == "all"
- mypy
==1.13.0; extra == "all"
- types-PyYAML
; extra == "all"
- types-tabulate
; extra == "all"
- types-protobuf
; extra == "all"
- types-emoji
; extra == "all"
- types-setuptools
; extra == "all"
- torch
==2.5.1; extra == "all"
- types-requests
; extra == "all"
- types-six
; extra == "all"
- SciencePlots
>=2.0.0; extra == "all"
- matplotlib
>=3.6.0; extra == "all"
- numpy
<2.0; extra == "audio"
- onnxruntime
>=1.12.0; extra == "audio"
- pesq
>=0.0.4; extra == "audio"
- librosa
>=0.10.0; extra == "audio"
- gammatone
>=1.0.0; extra == "audio"
- pystoi
>=0.4.0; extra == "audio"
- torchaudio
>=2.0.1; extra == "audio"
- requests
>=2.19.0; extra == "audio"
- pycocotools
>2.0.0; extra == "detection"
- torchvision
>=0.15.1; extra == "detection"
- numpy
<2.0; extra == "dev"
- onnxruntime
>=1.12.0; extra == "dev"
- pesq
>=0.0.4; extra == "dev"
- librosa
>=0.10.0; extra == "dev"
- gammatone
>=1.0.0; extra == "dev"
- pystoi
>=0.4.0; extra == "dev"
- torchaudio
>=2.0.1; extra == "dev"
- requests
>=2.19.0; extra == "dev"
- pycocotools
>2.0.0; extra == "dev"
- torchvision
>=0.15.1; extra == "dev"
- torch-fidelity
<=0.4.0; extra == "dev"
- scipy
>1.0.0; extra == "dev"
- transformers
>=4.42.3; extra == "dev"
- piq
<=0.8.0; extra == "dev"
- nltk
>3.8.1; extra == "dev"
- tqdm
<4.68.0; extra == "dev"
- sentencepiece
>=0.2.0; extra == "dev"
- mecab-python3
>=1.0.6; extra == "dev"
- regex
>=2021.9.24; extra == "dev"
- ipadic
>=1.0.0; extra == "dev"
- transformers
>4.4.0; extra == "dev"
- mypy
==1.13.0; extra == "dev"
- types-PyYAML
; extra == "dev"
- types-tabulate
; extra == "dev"
- types-protobuf
; extra == "dev"
- types-emoji
; extra == "dev"
- types-setuptools
; extra == "dev"
- torch
==2.5.1; extra == "dev"
- types-requests
; extra == "dev"
- types-six
; extra == "dev"
- SciencePlots
>=2.0.0; extra == "dev"
- matplotlib
>=3.6.0; extra == "dev"
- scikit-image
>=0.19.0; extra == "dev"
- pytorch-msssim
==1.0.0; extra == "dev"
- rouge-score
>0.1.0; extra == "dev"
- statsmodels
>0.13.5; extra == "dev"
- fast-bss-eval
>=0.1.0; extra == "dev"
- huggingface-hub
<0.27; extra == "dev"
- pandas
>1.4.0; extra == "dev"
- fairlearn
; extra == "dev"
- sacrebleu
>=2.3.0; extra == "dev"
- numpy
<2.2.0; extra == "dev"
- faster-coco-eval
>=1.6.3; extra == "dev"
- kornia
>=0.6.7; extra == "dev"
- jiwer
>=2.3.0; extra == "dev"
- netcal
>1.0.0; extra == "dev"
- mir-eval
>=0.6; extra == "dev"
- permetrics
==2.0.0; extra == "dev"
- torch-complex
<0.5.0; extra == "dev"
- lpips
<=0.1.4; extra == "dev"
- bert-score
==0.3.13; extra == "dev"
- sewar
>=0.4.4; extra == "dev"
- mecab-ko
<1.1.0,>=1.0.0; python_version < "3.12" and extra == "dev"
- mecab-ko-dic
>=1.0.0; python_version < "3.12" and extra == "dev"
- PyTDC
==0.4.1; python_version < "3.12" and extra == "dev"
- dython
==0.7.6; python_version < "3.9" and extra == "dev"
- monai
==1.3.2; python_version < "3.9" and extra == "dev"
- dython
~=0.7.8; python_version > "3.8" and extra == "dev"
- monai
==1.4.0; python_version > "3.8" and extra == "dev"
- torch-fidelity
<=0.4.0; extra == "image"
- torchvision
>=0.15.1; extra == "image"
- scipy
>1.0.0; extra == "image"
- transformers
>=4.42.3; extra == "multimodal"
- piq
<=0.8.0; extra == "multimodal"
- nltk
>3.8.1; extra == "text"
- tqdm
<4.68.0; extra == "text"
- sentencepiece
>=0.2.0; extra == "text"
- mecab-python3
>=1.0.6; extra == "text"
- regex
>=2021.9.24; extra == "text"
- ipadic
>=1.0.0; extra == "text"
- transformers
>4.4.0; extra == "text"
- mypy
==1.13.0; extra == "typing"
- types-PyYAML
; extra == "typing"
- types-tabulate
; extra == "typing"
- types-protobuf
; extra == "typing"
- types-emoji
; extra == "typing"
- types-setuptools
; extra == "typing"
- torch
==2.5.1; extra == "typing"
- types-requests
; extra == "typing"
- types-six
; extra == "typing"
- SciencePlots
>=2.0.0; extra == "visual"
- matplotlib
>=3.6.0; extra == "visual"
Machine learning metrics for distributed, scalable PyTorch applications.
What is Torchmetrics • Implementing a metric • Built-in metrics • Docs • Community • License
Installation
Simple installation from PyPI
pip install torchmetrics
Other installations
Install using conda
conda install -c conda-forge torchmetrics
Pip from source
# with git
pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stable
Pip from archive
pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zip
Extra dependencies for specialized metrics:
pip install torchmetrics[audio]
pip install torchmetrics[image]
pip install torchmetrics[text]
pip install torchmetrics[all] # install all of the above
Install latest developer version
pip install https://github.com/Lightning-AI/torchmetrics/archive/master.zip
What is TorchMetrics
TorchMetrics is a collection of 100+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers:
- A standardized interface to increase reproducibility
- Reduces boilerplate
- Automatic accumulation over batches
- Metrics optimized for distributed-training
- Automatic synchronization between multiple devices
You can use TorchMetrics with any PyTorch model or with PyTorch Lightning to enjoy additional features such as:
- Module metrics are automatically placed on the correct device.
- Native support for logging metrics in Lightning to reduce even more boilerplate.
Using TorchMetrics
Module metrics
The module-based metrics contain internal metric states (similar to the parameters of the PyTorch module) that automate accumulation and synchronization across devices!
- Automatic accumulation over multiple batches
- Automatic synchronization between multiple devices
- Metric arithmetic
This can be run on CPU, single GPU or multi-GPUs!
For the single GPU/CPU case:
import torch
# import our library
import torchmetrics
# initialize metric
metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5)
# move the metric to device you want computations to take place
device = "cuda" if torch.cuda.is_available() else "cpu"
metric.to(device)
n_batches = 10
for i in range(n_batches):
# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1).to(device)
target = torch.randint(5, (10,)).to(device)
# metric on current batch
acc = metric(preds, target)
print(f"Accuracy on batch {i}: {acc}")
# metric on all batches using custom accumulation
acc = metric.compute()
print(f"Accuracy on all data: {acc}")
Module metric usage remains the same when using multiple GPUs or multiple nodes.
Example using DDP
import os
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from torch import nn
from torch.nn.parallel import DistributedDataParallel as DDP
import torchmetrics
def metric_ddp(rank, world_size):
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = "12355"
# create default process group
dist.init_process_group("gloo", rank=rank, world_size=world_size)
# initialize model
metric = torchmetrics.classification.Accuracy(task="multiclass", num_classes=5)
# define a model and append your metric to it
# this allows metric states to be placed on correct accelerators when
# .to(device) is called on the model
model = nn.Linear(10, 10)
model.metric = metric
model = model.to(rank)
# initialize DDP
model = DDP(model, device_ids=[rank])
n_epochs = 5
# this shows iteration over multiple training epochs
for n in range(n_epochs):
# this will be replaced by a DataLoader with a DistributedSampler
n_batches = 10
for i in range(n_batches):
# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))
# metric on current batch
acc = metric(preds, target)
if rank == 0: # print only for rank 0
print(f"Accuracy on batch {i}: {acc}")
# metric on all batches and all accelerators using custom accumulation
# accuracy is same across both accelerators
acc = metric.compute()
print(f"Accuracy on all data: {acc}, accelerator rank: {rank}")
# Resetting internal state such that metric ready for new data
metric.reset()
# cleanup
dist.destroy_process_group()
if __name__ == "__main__":
world_size = 2 # number of gpus to parallelize over
mp.spawn(metric_ddp, args=(world_size,), nprocs=world_size, join=True)
Implementing your own Module metric
Implementing your own metric is as easy as subclassing an torch.nn.Module
. Simply, subclass torchmetrics.Metric
and just implement the update
and compute
methods:
import torch
from torchmetrics import Metric
class MyAccuracy(Metric):
def __init__(self):
# remember to call super
super().__init__()
# call `self.add_state`for every internal state that is needed for the metrics computations
# dist_reduce_fx indicates the function that should be used to reduce
# state from multiple processes
self.add_state("correct", default=torch.tensor(0), dist_reduce_fx="sum")
self.add_state("total", default=torch.tensor(0), dist_reduce_fx="sum")
def update(self, preds: torch.Tensor, target: torch.Tensor) -> None:
# extract predicted class index for computing accuracy
preds = preds.argmax(dim=-1)
assert preds.shape == target.shape
# update metric states
self.correct += torch.sum(preds == target)
self.total += target.numel()
def compute(self) -> torch.Tensor:
# compute final result
return self.correct.float() / self.total
my_metric = MyAccuracy()
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))
print(my_metric(preds, target))
Functional metrics
Similar to torch.nn
, most metrics have both a module-based and functional version.
The functional versions are simple python functions that as input take torch.tensors and return the corresponding metric as a torch.tensor.
import torch
# import our library
import torchmetrics
# simulate a classification problem
preds = torch.randn(10, 5).softmax(dim=-1)
target = torch.randint(5, (10,))
acc = torchmetrics.functional.classification.multiclass_accuracy(
preds, target, num_classes=5
)
Covered domains and example metrics
In total TorchMetrics contains 100+ metrics, which covers the following domains:
- Audio
- Classification
- Detection
- Information Retrieval
- Image
- Multimodal (Image-Text)
- Nominal
- Regression
- Segmentation
- Text
Each domain may require some additional dependencies which can be installed with pip install torchmetrics[audio]
,
pip install torchmetrics['image']
etc.
Additional features
Plotting
Visualization of metrics can be important to help understand what is going on with your machine learning algorithms.
Torchmetrics have built-in plotting support (install dependencies with pip install torchmetrics[visual]
) for nearly
all modular metrics through the .plot
method. Simply call the method to get a simple visualization of any metric!
import torch
from torchmetrics.classification import MulticlassAccuracy, MulticlassConfusionMatrix
num_classes = 3
# this will generate two distributions that comes more similar as iterations increase
w = torch.randn(num_classes)
target = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
preds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)
acc = MulticlassAccuracy(num_classes=num_classes, average="micro")
acc_per_class = MulticlassAccuracy(num_classes=num_classes, average=None)
confmat = MulticlassConfusionMatrix(num_classes=num_classes)
# plot single value
for i in range(5):
acc_per_class.update(preds(i), target(i))
confmat.update(preds(i), target(i))
fig1, ax1 = acc_per_class.plot()
fig2, ax2 = confmat.plot()
# plot multiple values
values = []
for i in range(10):
values.append(acc(preds(i), target(i)))
fig3, ax3 = acc.plot(values)
For examples of plotting different metrics try running this example file.
Contribute!
The lightning + TorchMetrics team is hard at work adding even more metrics. But we're looking for incredible contributors like you to submit new metrics and improve existing ones!
Join our Discord to get help with becoming a contributor!
Community
For help or questions, join our huge community on Discord!
Citation
We’re excited to continue the strong legacy of open source software and have been inspired over the years by Caffe, Theano, Keras, PyTorch, torchbearer, ignite, sklearn and fast.ai.
If you want to cite this framework feel free to use GitHub's built-in citation option to generate a bibtex or APA-Style citation based on this file (but only if you loved it 😊).
License
Please observe the Apache 2.0 license that is listed in this repository. In addition, the Lightning framework is Patent Pending.