torchmetrics
Science Score: 67.0%
This score indicates how likely this project is to be science-related based on various indicators:
-
✓CITATION.cff file
Found CITATION.cff file -
✓codemeta.json file
Found codemeta.json file -
✓.zenodo.json file
Found .zenodo.json file -
✓DOI references
Found 3 DOI reference(s) in README -
✓Academic publication links
Links to: joss.theoj.org, zenodo.org -
○Academic email domains
-
○Institutional organization owner
-
○JOSS paper metadata
-
○Scientific vocabulary similarity
Low similarity (12.6%) to scientific vocabulary
Repository
Basic Info
- Host: GitHub
- Owner: Tecorigin
- License: apache-2.0
- Language: Python
- Default Branch: master
- Size: 11.8 MB
Statistics
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 5
- Releases: 0
Metadata Files
README.md
**Machine learning metrics for distributed, scalable PyTorch applications.**
______________________________________________________________________
What is Torchmetrics • Implementing a metric • Built-in metrics • Docs • Community • License
______________________________________________________________________ [](https://pypi.org/project/torchmetrics/) [](https://badge.fury.io/py/torchmetrics) [ ](https://pepy.tech/project/torchmetrics) [](https://anaconda.org/conda-forge/torchmetrics) [](https://github.com/Lightning-AI/torchmetrics/blob/master/LICENSE) [](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml) [](https://dev.azure.com/Lightning-AI/Metrics/_build/latest?definitionId=54&branchName=master) [](https://codecov.io/gh/Lightning-AI/torchmetrics) [](https://results.pre-commit.ci/latest/github/Lightning-AI/torchmetrics/master) [](https://torchmetrics.readthedocs.io/en/latest/?badge=latest) [](https://discord.gg/VptPCZkGNa) [](https://doi.org/10.5281/zenodo.5844769) [](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43) ______________________________________________________________________Installation
Simple installation from PyPI
bash
pip install torchmetrics-1.8.0.dev0-py3-none-any.whl
Other installations
Pip from source ```bash pip install -e . ```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
To use on SDAA platform: export TORCHSDAAAUTOLOAD=cuda_migrate
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:
```python 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)
nbatches = 10 for i in range(nbatches): # 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
```python 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:
```python import torch from torchmetrics import Metric
class MyAccuracy(Metric):
def init(self):
# remember to call super
super().init()
# call self.add_statefor every internal state that is needed for the metrics computations
# distreducefx indicates the function that should be used to reduce
# state from multiple processes
self.addstate("correct", default=torch.tensor(0), distreducefx="sum")
self.addstate("total", default=torch.tensor(0), distreducefx="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.
```python 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.multiclassaccuracy( preds, target, numclasses=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!
```python 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(numclasses=numclasses, average="micro") accperclass = MulticlassAccuracy(numclasses=numclasses, average=None) confmat = MulticlassConfusionMatrix(numclasses=numclasses)
plot single value
for i in range(5): accperclass.update(preds(i), target(i)) confmat.update(preds(i), target(i)) fig1, ax1 = accperclass.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.
Owner
- Login: Tecorigin
- Kind: user
- Website: http://tecorigin.com/
- Repositories: 1
- Profile: https://github.com/Tecorigin
Where There is Computation, There is Tecorigin.
Citation (CITATION.cff)
cff-version: 1.2.0
message: "If you want to cite the framework, feel free to use this (but only if you loved it 😊)"
title: "TorchMetrics - Measuring Reproducibility in PyTorch"
abstract:
"A main problem with reproducing machine learning publications is the variance of metric implementations across papers.
A lack of standardization leads to different behavior in mech- anisms such as checkpointing, learning rate schedulers or early stopping, that will influence the reported results.
For example, a complex metric such as Fréchet inception distance (FID) for synthetic image quality evaluation will differ based on the specific interpolation method used.
There have been a few attempts at tackling the reproducibility issues.
Papers With Code links research code with its corresponding paper. Similarly, arXiv recently added a code and data section that links both official and community code to papers.
However, these methods rely on the paper code to be made publicly accessible which is not always possible.
Our approach is to provide the de-facto reference implementation for metrics.
This approach enables proprietary work to still be comparable as long as they’ve used our reference implementations.
We introduce TorchMetrics, a general-purpose metrics package that covers a wide variety of tasks and domains used in the machine learning community.
TorchMetrics provides standard classification and regression metrics; and domain-specific metrics for audio, computer vision, natural language processing, and information retrieval.
Our process for adding a new metric is as follows, first we integrate a well-tested and established third-party library.
Once we’ve verified the implementations and written tests for them, we re-implement them in native PyTorch to enable hardware acceleration and remove any bottlenecks in inter-device transfer."
authors:
- name: Nicki Skafte Detlefsen
orcid: "https://orcid.org/0000-0002-8133-682X"
- name: Jiri Borovec
orcid: "https://orcid.org/0000-0001-7437-824X"
- name: Justus Schock
orcid: "https://orcid.org/0000-0003-0512-3053"
- name: Ananya Harsh
- name: Teddy Koker
- name: Luca Di Liello
- name: Daniel Stancl
- name: Changsheng Quan
- name: Maxim Grechkin
- name: William Falcon
doi: 10.21105/joss.04101
license: "Apache-2.0"
url: "https://www.pytorchlightning.ai"
repository-code: "https://github.com/Lightning-AI/torchmetrics"
date-released: 2022-02-11
keywords:
- machine learning
- deep learning
- artificial intelligence
- metrics
- pytorch
GitHub Events
Total
- Issue comment event: 13
- Push event: 1
- Pull request event: 10
- Create event: 5
Last Year
- Issue comment event: 13
- Push event: 1
- Pull request event: 10
- Create event: 5
Issues and Pull Requests
Last synced: 6 months ago
All Time
- Total issues: 0
- Total pull requests: 8
- Average time to close issues: N/A
- Average time to close pull requests: about 1 month
- Total issue authors: 0
- Total pull request authors: 1
- Average comments per issue: 0
- Average comments per pull request: 1.75
- Merged pull requests: 0
- Bot issues: 0
- Bot pull requests: 8
Past Year
- Issues: 0
- Pull requests: 8
- Average time to close issues: N/A
- Average time to close pull requests: about 1 month
- Issue authors: 0
- Pull request authors: 1
- Average comments per issue: 0
- Average comments per pull request: 1.75
- Merged pull requests: 0
- Bot issues: 0
- Bot pull requests: 8
Top Authors
Issue Authors
Pull Request Authors
- dependabot[bot] (8)
Top Labels
Issue Labels
Pull Request Labels
Dependencies
- actions/cache/restore v3 composite
- actions/cache/save v3 composite
- actions/upload-artifact v4 composite
- actions/checkout v4 composite
- actions/setup-python v5 composite
- actions/cache/restore v4 composite
- actions/cache/save v4 composite
- actions/download-artifact v4 composite
- ./.github/actions/pull-caches * composite
- actions/checkout v4 composite
- actions/setup-python v5 composite
- readthedocs/actions/preview v1 composite
- ./.github/actions/pull-caches * composite
- ./.github/actions/push-caches * composite
- actions/checkout v4 composite
- actions/setup-python v5 composite
- codecov/codecov-action v5 composite
- peter-evans/create-or-update-comment v4.0.0 composite
- actions/checkout v4 composite
- peter-evans/create-or-update-comment v4.0.0 composite
- actions/checkout v4 composite
- docker/build-push-action v6 composite
- docker/login-action v3 composite
- ./.github/actions/pull-caches * composite
- ./.github/actions/push-caches * composite
- actions/checkout v4 composite
- actions/download-artifact v4 composite
- actions/setup-python v5 composite
- actions/upload-artifact v4 composite
- google-github-actions/auth v2 composite
- google-github-actions/setup-gcloud v2 composite
- actions/first-interaction v1 composite
- actions/checkout v4 composite
- actions/labeler v5 composite
- AButler/upload-release-assets v3.0 composite
- actions/checkout v4 composite
- actions/download-artifact v4 composite
- actions/setup-python v5 composite
- actions/upload-artifact v4 composite
- juliangruber/sleep-action v2 composite
- pypa/gh-action-pypi-publish v1.12.4 composite
- peter-evans/slash-command-dispatch v4.0.0 composite
- mcr.microsoft.com/vscode/devcontainers/python ${VARIANT} build
- nvidia/cuda ${CUDA_VERSION}-runtime-ubuntu${UBUNTU_VERSION} build
- docutils ==0.19
- lightning >=1.8.0,<2.6.0
- lightning-utilities ==0.14.3
- myst-parser ==1.0.0
- pandoc ==2.4
- pydantic >1.0.0,<3.0.0
- scikit-image *
- sphinx ==5.3.0
- sphinx-autobuild ==2024.10.3
- sphinx-autodoc-typehints ==1.23.0
- sphinx-copybutton ==0.5.2
- sphinx-gallery ==0.19.0
- sphinx-paramlinks ==0.6.0
- sphinx-togglebutton ==0.3.2
- sphinxcontrib-fulltoc >=1.0
- sphinxcontrib-mockautodoc *
- pytest >=8.0,<9.0 test
- pytest-doctestplus >=1.0,<1.5 test
- pytest-rerunfailures >=13.0,<16.0 test
- pytorch-lightning >=1.9.0,<2.6.0
- cachier ==3.1.2 test
- cloudpickle >1.3,<=3.1.1 test
- codecov ==2.1.13 test
- coverage ==7.8. test
- fire ==0.7. test
- phmdoctest ==1.4.0 test
- psutil ==7. test
- pyGithub >2.0.0,<2.7.0 test
- pytest ==8.3. test
- pytest-cov ==6.1.1 test
- pytest-doctestplus ==1.4.0 test
- pytest-rerunfailures ==15.1 test
- pytest-timeout ==2.4.0 test
- pytest-xdist ==3.6.1 test
- scikit-learn >1.5.0 test
- gammatone >=1.0.0,<1.1.0
- librosa >=0.10.0,<0.11.0
- onnxruntime >=1.12.0,<1.23
- pesq >=0.0.4,<0.0.5
- pystoi >=0.4.0,<0.5.0
- requests >=2.19.0,<2.33.0
- torchaudio >=2.0.1,<2.8.0
- fast-bss-eval >=0.1.0,<0.1.5 test
- mir-eval >=0.6,<=0.8.2 test
- torch_complex <0.5.0 test
- lightning-utilities >=0.8.0,<0.15.0
- numpy >1.20.0,<2.3.0
- packaging >17.1
- torch >=2.0.0,<2.8.0
- PyTDC ==0.4.1 test
- fairlearn * test
- netcal >1.0.0,<1.4.0 test
- numpy <2.3.0 test
- pandas >1.4.0,<=2.2.3 test
- torch_linear_assignment >=0.0.2,<0.0.4
- aeon >=1.0.0,<1.2.0 test
- pycocotools >2.0.0,<2.1.0
- torchvision >=0.15.1,<0.23.0
- faster-coco-eval >=1.6.3,<1.7.0 test
- scipy >1.0.0,<1.16.0
- torch-fidelity <=0.4.0
- torchvision >=0.15.1,<0.23.0
- dists-pytorch ==0.1 test
- kornia >=0.6.7,<0.9.0 test
- lpips <=0.1.4 test
- numpy <2.3.0 test
- pytorch-msssim ==1.0.0 test
- scikit-image >=0.19.0,<0.26.0 test
- sewar >=0.4.4,<=0.4.6 test
- einops >=0.7.0,<=0.8.1
- piq <=0.8.0
- timm >=0.9.0,<1.1.0
- transformers >=4.42.3,<4.50.0
- dython ==0.7.9 test
- pandas >1.4.0,<=2.2.3 test
- scipy >1.0.0,<1.16.0 test
- statsmodels >0.13.5,<0.15.0 test
- permetrics ==2.0.0 test
- properscoring ==0.1 test
- monai ==1.4.0 test
- scipy >1.0.0,<1.16.0 test
- ipadic >=1.0.0,<1.1.0
- mecab-python3 >=1.0.6,<1.1.0
- nltk >3.8.1,<=3.9.1
- regex >=2021.9.24,<=2024.11.6
- sentencepiece >=0.2.0,<0.3.0
- tqdm <4.68.0
- transformers >4.4.0,<4.50.0
- bert_score ==0.3.13 test
- huggingface-hub <0.32 test
- jiwer >=2.3.0,<3.2.0 test
- mecab-ko >=1.0.0,<1.1.0 test
- mecab-ko-dic >=1.0.0,<1.1.0 test
- rouge-score >0.1.0,<=0.1.2 test
- sacrebleu >=2.3.0,<2.6.0 test
- mypy ==1.15.0
- torch ==2.7.0
- types-PyYAML *
- types-emoji *
- types-protobuf *
- types-requests *
- types-setuptools *
- types-six *
- types-tabulate *
- SciencePlots >=2.0.0,<2.2.0
- matplotlib >=3.6.0,<3.11.0