mylightningai
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 (13.1%) to scientific vocabulary
Repository
Basic Info
- Host: GitHub
- Owner: cgpeanut
- License: apache-2.0
- Language: Python
- Default Branch: main
- Size: 1.15 MB
Statistics
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
- 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
Other installations
Install using conda ```bash conda install -c conda-forge torchmetrics ``` Pip from source ```bash # with git pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stable ``` Pip from archive ```bash pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zip ``` Extra dependencies for specialized metrics: ```bash 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 ```bash 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:
```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: cgpeanut
- Kind: user
- Location: Spring Hill, TN
- Repositories: 3
- Profile: https://github.com/cgpeanut
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
Last Year
Dependencies
- nvidia/cuda ${CUDA_VERSION}-runtime-ubuntu${UBUNTU_VERSION} build
- docutils ==0.19
- lightning >=1.8.0,<2.3.0
- lightning-utilities ==0.11.2
- myst-parser ==1.0.0
- pandoc ==2.3
- pydantic >1.0.0,<3.0.0
- scikit-image *
- sphinx ==5.3.0
- sphinx-autodoc-typehints ==1.23.0
- sphinx-copybutton ==0.5.2
- sphinx-gallery ==0.16.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.3 test
- pytest-rerunfailures >=13.0,<15.0 test
- pytorch-lightning >=1.9.0,<2.1.0
- cachier ==3.0.0 test
- cloudpickle >1.3,<=3.0.0 test
- coverage ==7.5.1 test
- fire <=0.6.0 test
- phmdoctest ==1.4.0 test
- psutil <5.10.0 test
- pyGithub ==2.3.0 test
- pytest ==8.1.1 test
- pytest-cov ==5.0.0 test
- pytest-doctestplus ==1.2.1 test
- pytest-rerunfailures ==14.0 test
- pytest-timeout ==2.3.1 test
- pytest-xdist ==3.6.1 test
- scikit-learn >=1.1.1,<1.3.0 test
- scikit-learn >=1.4.0,<1.5.0 test
- pystoi >=0.3.0,<0.5.0
- torchaudio >=0.10.0,<2.4.0
- fast-bss-eval >=0.1.0,<0.1.5 test
- mir-eval >=0.6,<=0.7 test
- torch_complex <=0.4.3 test
- lightning-utilities >=0.8.0,<0.12.0
- numpy >1.20.0
- packaging >17.1
- torch >=1.10.0,<2.4.0
- typing-extensions *
- fairlearn * test
- netcal >1.0.0,<=1.3.5 test
- numpy <1.27.0 test
- pandas >=1.4.0,<=2.0.3 test
- pretty-errors >=1.2.0,<1.3.0
- pycocotools >2.0.0,<=2.0.7
- torchvision >=0.8,<0.19.0
- faster-coco-eval >=1.3.3 test
- scipy >1.0.0,<1.11.0
- torch-fidelity <=0.4.0
- torchvision >=0.8,<0.19.0
- kornia >=0.6.7,<0.8.0 test
- lpips <=0.1.4 test
- numpy <1.27.0 test
- pytorch-msssim ==1.0.0 test
- scikit-image >=0.19.0,<=0.23.2 test
- sewar >=0.4.4,<=0.4.6 test
- piq <=0.8.0
- transformers >=4.10.0,<4.41.0
- dython <=0.7.5 test
- pandas >1.0.0,<=2.0.3 test
- scipy >1.0.0,<1.11.0 test
- statsmodels >0.13.5,<0.15.0 test
- monai ==1.3.0 test
- scipy >1.0.0,<1.11.0 test
- ipadic >=1.0.0,<1.1.0
- mecab-python3 >=1.0.6,<1.1.0
- nltk >=3.6,<=3.8.1
- regex >=2021.9.24,<=2024.5.10
- sentencepiece >=0.2.0,<0.3.0
- tqdm >=4.41.0,<4.67.0
- transformers >4.4.0,<4.41.0
- bert_score ==0.3.13 test
- huggingface-hub <0.23 test
- jiwer >=2.3.0,<3.1.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.5.0 test
- mypy ==1.9.0
- torch ==2.3.0
- types-PyYAML *
- types-emoji *
- types-protobuf *
- types-requests *
- types-setuptools *
- types-six *
- types-tabulate *
- SciencePlots >=2.0.0,<2.2.0
- matplotlib >=3.3.0,<3.9.0