torchmetrics


Nametorchmetrics JSON
Version 1.6.0 PyPI version JSON
download
home_pagehttps://github.com/Lightning-AI/torchmetrics
SummaryPyTorch native Metrics
upload_time2024-11-12 19:35:40
maintainerNone
docs_urlNone
authorLightning-AI et al.
requires_python>=3.9
licenseApache-2.0
keywords deep learning machine learning pytorch metrics ai
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            <div align="center">

<img src="https://github.com/Lightning-AI/torchmetrics/raw/v1.6.0/docs/source/_static/images/logo.png" width="400px">

**Machine learning metrics for distributed, scalable PyTorch applications.**

______________________________________________________________________

<p align="center">
  <a href="#what-is-torchmetrics">What is Torchmetrics</a> •
  <a href="#implementing-your-own-module-metric">Implementing a metric</a> •
  <a href="#build-in-metrics">Built-in metrics</a> •
  <a href="https://lightning.ai/docs/torchmetrics/stable/">Docs</a> •
  <a href="#community">Community</a> •
  <a href="#license">License</a>
</p>

______________________________________________________________________

[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/torchmetrics)](https://pypi.org/project/torchmetrics/)
[![PyPI Status](https://badge.fury.io/py/torchmetrics.svg)](https://badge.fury.io/py/torchmetrics)
[![PyPI - Downloads](https://img.shields.io/pypi/dm/torchmetrics)
](https://pepy.tech/project/torchmetrics)
[![Conda](https://img.shields.io/conda/v/conda-forge/torchmetrics?label=conda&color=success)](https://anaconda.org/conda-forge/torchmetrics)
[![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/Lightning-AI/torchmetrics/blob/master/LICENSE)

[![CI testing | CPU](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml/badge.svg?event=push)](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml)
[![Build Status](https://dev.azure.com/Lightning-AI/Metrics/_apis/build/status%2FTM.unittests?branchName=refs%2Ftags%2Fv1.6.0)](https://dev.azure.com/Lightning-AI/Metrics/_build/latest?definitionId=2&branchName=refs%2Ftags%2Fv1.6.0)
[![codecov](https://codecov.io/gh/Lightning-AI/torchmetrics/release/v1.6.0/graph/badge.svg?token=NER6LPI3HS)](https://codecov.io/gh/Lightning-AI/torchmetrics)
[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/Lightning-AI/torchmetrics/master.svg)](https://results.pre-commit.ci/latest/github/Lightning-AI/torchmetrics/master)

[![Documentation Status](https://readthedocs.org/projects/torchmetrics/badge/?version=latest)](https://torchmetrics.readthedocs.io/en/latest/?badge=latest)
[![Discord](https://img.shields.io/discord/1077906959069626439?style=plastic)](https://discord.gg/VptPCZkGNa)
[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5844769.svg)](https://doi.org/10.5281/zenodo.5844769)
[![JOSS status](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43/status.svg)](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43)

______________________________________________________________________

</div>

## Installation

Simple installation from PyPI

```bash
pip install torchmetrics
```

<details>
  <summary>Other installations</summary>

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
```

</details>

______________________________________________________________________

## 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](https://lightning.ai/docs/pytorch/stable/) 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](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) 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)

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.

<details>
  <summary>Example using DDP</summary>

<!--phmdoctest-mark.skip-->

```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)
```

</details>

### Implementing your own Module metric

Implementing your own metric is as easy as subclassing an [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). 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_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`](https://pytorch.org/docs/stable/nn.html), most metrics have both a [module-based](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) and functional version.
The functional versions are simple python functions that as input take [torch.tensors](https://pytorch.org/docs/stable/tensors.html) and return the corresponding metric as a [torch.tensor](https://pytorch.org/docs/stable/tensors.html).

```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.multiclass_accuracy(
    preds, target, num_classes=5
)
```

### Covered domains and example metrics

In total TorchMetrics contains [100+ metrics](https://lightning.ai/docs/torchmetrics/stable/all-metrics.html), 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(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)
```

<p align="center">
  <img src="https://github.com/Lightning-AI/torchmetrics/raw/v1.6.0/docs/source/_static/images/plot_example.png" width="1000">
</p>

For examples of plotting different metrics try running [this example file](_samples/plotting.py).

## 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](https://discord.com/invite/tfXFetEZxv) to get help with becoming a contributor!

## Community

For help or questions, join our huge community on [Discord](https://discord.com/invite/tfXFetEZxv)!

## 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](https://github.com/Lightning-AI/torchmetrics/blob/master/CITATION.cff) (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.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/Lightning-AI/torchmetrics",
    "name": "torchmetrics",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.9",
    "maintainer_email": null,
    "keywords": "deep learning, machine learning, pytorch, metrics, AI",
    "author": "Lightning-AI et al.",
    "author_email": "name@pytorchlightning.ai",
    "download_url": "https://files.pythonhosted.org/packages/18/88/9b0c5542ce845d153eaa7a7eb8e4fad34347b13b5997bf1d744d64410072/torchmetrics-1.6.0.tar.gz",
    "platform": null,
    "description": "<div align=\"center\">\n\n<img src=\"https://github.com/Lightning-AI/torchmetrics/raw/v1.6.0/docs/source/_static/images/logo.png\" width=\"400px\">\n\n**Machine learning metrics for distributed, scalable PyTorch applications.**\n\n______________________________________________________________________\n\n<p align=\"center\">\n  <a href=\"#what-is-torchmetrics\">What is Torchmetrics</a> \u2022\n  <a href=\"#implementing-your-own-module-metric\">Implementing a metric</a> \u2022\n  <a href=\"#build-in-metrics\">Built-in metrics</a> \u2022\n  <a href=\"https://lightning.ai/docs/torchmetrics/stable/\">Docs</a> \u2022\n  <a href=\"#community\">Community</a> \u2022\n  <a href=\"#license\">License</a>\n</p>\n\n______________________________________________________________________\n\n[![PyPI - Python Version](https://img.shields.io/pypi/pyversions/torchmetrics)](https://pypi.org/project/torchmetrics/)\n[![PyPI Status](https://badge.fury.io/py/torchmetrics.svg)](https://badge.fury.io/py/torchmetrics)\n[![PyPI - Downloads](https://img.shields.io/pypi/dm/torchmetrics)\n](https://pepy.tech/project/torchmetrics)\n[![Conda](https://img.shields.io/conda/v/conda-forge/torchmetrics?label=conda&color=success)](https://anaconda.org/conda-forge/torchmetrics)\n[![license](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://github.com/Lightning-AI/torchmetrics/blob/master/LICENSE)\n\n[![CI testing | CPU](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml/badge.svg?event=push)](https://github.com/Lightning-AI/torchmetrics/actions/workflows/ci-tests.yml)\n[![Build Status](https://dev.azure.com/Lightning-AI/Metrics/_apis/build/status%2FTM.unittests?branchName=refs%2Ftags%2Fv1.6.0)](https://dev.azure.com/Lightning-AI/Metrics/_build/latest?definitionId=2&branchName=refs%2Ftags%2Fv1.6.0)\n[![codecov](https://codecov.io/gh/Lightning-AI/torchmetrics/release/v1.6.0/graph/badge.svg?token=NER6LPI3HS)](https://codecov.io/gh/Lightning-AI/torchmetrics)\n[![pre-commit.ci status](https://results.pre-commit.ci/badge/github/Lightning-AI/torchmetrics/master.svg)](https://results.pre-commit.ci/latest/github/Lightning-AI/torchmetrics/master)\n\n[![Documentation Status](https://readthedocs.org/projects/torchmetrics/badge/?version=latest)](https://torchmetrics.readthedocs.io/en/latest/?badge=latest)\n[![Discord](https://img.shields.io/discord/1077906959069626439?style=plastic)](https://discord.gg/VptPCZkGNa)\n[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.5844769.svg)](https://doi.org/10.5281/zenodo.5844769)\n[![JOSS status](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43/status.svg)](https://joss.theoj.org/papers/561d9bb59b400158bc8204e2639dca43)\n\n______________________________________________________________________\n\n</div>\n\n## Installation\n\nSimple installation from PyPI\n\n```bash\npip install torchmetrics\n```\n\n<details>\n  <summary>Other installations</summary>\n\nInstall using conda\n\n```bash\nconda install -c conda-forge torchmetrics\n```\n\nPip from source\n\n```bash\n# with git\npip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stable\n```\n\nPip from archive\n\n```bash\npip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zip\n```\n\nExtra dependencies for specialized metrics:\n\n```bash\npip install torchmetrics[audio]\npip install torchmetrics[image]\npip install torchmetrics[text]\npip install torchmetrics[all]  # install all of the above\n```\n\nInstall latest developer version\n\n```bash\npip install https://github.com/Lightning-AI/torchmetrics/archive/master.zip\n```\n\n</details>\n\n______________________________________________________________________\n\n## What is TorchMetrics\n\nTorchMetrics is a collection of 100+ PyTorch metrics implementations and an easy-to-use API to create custom metrics. It offers:\n\n- A standardized interface to increase reproducibility\n- Reduces boilerplate\n- Automatic accumulation over batches\n- Metrics optimized for distributed-training\n- Automatic synchronization between multiple devices\n\nYou can use TorchMetrics with any PyTorch model or with [PyTorch Lightning](https://lightning.ai/docs/pytorch/stable/) to enjoy additional features such as:\n\n- Module metrics are automatically placed on the correct device.\n- Native support for logging metrics in Lightning to reduce even more boilerplate.\n\n## Using TorchMetrics\n\n### Module metrics\n\nThe [module-based metrics](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) contain internal metric states (similar to the parameters of the PyTorch module) that automate accumulation and synchronization across devices!\n\n- Automatic accumulation over multiple batches\n- Automatic synchronization between multiple devices\n- Metric arithmetic\n\n**This can be run on CPU, single GPU or multi-GPUs!**\n\nFor the single GPU/CPU case:\n\n```python\nimport torch\n\n# import our library\nimport torchmetrics\n\n# initialize metric\nmetric = torchmetrics.classification.Accuracy(task=\"multiclass\", num_classes=5)\n\n# move the metric to device you want computations to take place\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmetric.to(device)\n\nn_batches = 10\nfor i in range(n_batches):\n    # simulate a classification problem\n    preds = torch.randn(10, 5).softmax(dim=-1).to(device)\n    target = torch.randint(5, (10,)).to(device)\n\n    # metric on current batch\n    acc = metric(preds, target)\n    print(f\"Accuracy on batch {i}: {acc}\")\n\n# metric on all batches using custom accumulation\nacc = metric.compute()\nprint(f\"Accuracy on all data: {acc}\")\n```\n\nModule metric usage remains the same when using multiple GPUs or multiple nodes.\n\n<details>\n  <summary>Example using DDP</summary>\n\n<!--phmdoctest-mark.skip-->\n\n```python\nimport os\nimport torch\nimport torch.distributed as dist\nimport torch.multiprocessing as mp\nfrom torch import nn\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torchmetrics\n\n\ndef metric_ddp(rank, world_size):\n    os.environ[\"MASTER_ADDR\"] = \"localhost\"\n    os.environ[\"MASTER_PORT\"] = \"12355\"\n\n    # create default process group\n    dist.init_process_group(\"gloo\", rank=rank, world_size=world_size)\n\n    # initialize model\n    metric = torchmetrics.classification.Accuracy(task=\"multiclass\", num_classes=5)\n\n    # define a model and append your metric to it\n    # this allows metric states to be placed on correct accelerators when\n    # .to(device) is called on the model\n    model = nn.Linear(10, 10)\n    model.metric = metric\n    model = model.to(rank)\n\n    # initialize DDP\n    model = DDP(model, device_ids=[rank])\n\n    n_epochs = 5\n    # this shows iteration over multiple training epochs\n    for n in range(n_epochs):\n        # this will be replaced by a DataLoader with a DistributedSampler\n        n_batches = 10\n        for i in range(n_batches):\n            # simulate a classification problem\n            preds = torch.randn(10, 5).softmax(dim=-1)\n            target = torch.randint(5, (10,))\n\n            # metric on current batch\n            acc = metric(preds, target)\n            if rank == 0:  # print only for rank 0\n                print(f\"Accuracy on batch {i}: {acc}\")\n\n        # metric on all batches and all accelerators using custom accumulation\n        # accuracy is same across both accelerators\n        acc = metric.compute()\n        print(f\"Accuracy on all data: {acc}, accelerator rank: {rank}\")\n\n        # Resetting internal state such that metric ready for new data\n        metric.reset()\n\n    # cleanup\n    dist.destroy_process_group()\n\n\nif __name__ == \"__main__\":\n    world_size = 2  # number of gpus to parallelize over\n    mp.spawn(metric_ddp, args=(world_size,), nprocs=world_size, join=True)\n```\n\n</details>\n\n### Implementing your own Module metric\n\nImplementing your own metric is as easy as subclassing an [`torch.nn.Module`](https://pytorch.org/docs/stable/generated/torch.nn.Module.html). Simply, subclass `torchmetrics.Metric`\nand just implement the `update` and `compute` methods:\n\n```python\nimport torch\nfrom torchmetrics import Metric\n\n\nclass MyAccuracy(Metric):\n    def __init__(self):\n        # remember to call super\n        super().__init__()\n        # call `self.add_state`for every internal state that is needed for the metrics computations\n        # dist_reduce_fx indicates the function that should be used to reduce\n        # state from multiple processes\n        self.add_state(\"correct\", default=torch.tensor(0), dist_reduce_fx=\"sum\")\n        self.add_state(\"total\", default=torch.tensor(0), dist_reduce_fx=\"sum\")\n\n    def update(self, preds: torch.Tensor, target: torch.Tensor) -> None:\n        # extract predicted class index for computing accuracy\n        preds = preds.argmax(dim=-1)\n        assert preds.shape == target.shape\n        # update metric states\n        self.correct += torch.sum(preds == target)\n        self.total += target.numel()\n\n    def compute(self) -> torch.Tensor:\n        # compute final result\n        return self.correct.float() / self.total\n\n\nmy_metric = MyAccuracy()\npreds = torch.randn(10, 5).softmax(dim=-1)\ntarget = torch.randint(5, (10,))\n\nprint(my_metric(preds, target))\n```\n\n### Functional metrics\n\nSimilar to [`torch.nn`](https://pytorch.org/docs/stable/nn.html), most metrics have both a [module-based](https://lightning.ai/docs/torchmetrics/stable/references/metric.html) and functional version.\nThe functional versions are simple python functions that as input take [torch.tensors](https://pytorch.org/docs/stable/tensors.html) and return the corresponding metric as a [torch.tensor](https://pytorch.org/docs/stable/tensors.html).\n\n```python\nimport torch\n\n# import our library\nimport torchmetrics\n\n# simulate a classification problem\npreds = torch.randn(10, 5).softmax(dim=-1)\ntarget = torch.randint(5, (10,))\n\nacc = torchmetrics.functional.classification.multiclass_accuracy(\n    preds, target, num_classes=5\n)\n```\n\n### Covered domains and example metrics\n\nIn total TorchMetrics contains [100+ metrics](https://lightning.ai/docs/torchmetrics/stable/all-metrics.html), which\ncovers the following domains:\n\n- Audio\n- Classification\n- Detection\n- Information Retrieval\n- Image\n- Multimodal (Image-Text)\n- Nominal\n- Regression\n- Segmentation\n- Text\n\nEach domain may require some additional dependencies which can be installed with `pip install torchmetrics[audio]`,\n`pip install torchmetrics['image']` etc.\n\n### Additional features\n\n#### Plotting\n\nVisualization of metrics can be important to help understand what is going on with your machine learning algorithms.\nTorchmetrics have built-in plotting support (install dependencies with `pip install torchmetrics[visual]`) for nearly\nall modular metrics through the `.plot` method. Simply call the method to get a simple visualization of any metric!\n\n```python\nimport torch\nfrom torchmetrics.classification import MulticlassAccuracy, MulticlassConfusionMatrix\n\nnum_classes = 3\n\n# this will generate two distributions that comes more similar as iterations increase\nw = torch.randn(num_classes)\ntarget = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)\npreds = lambda it: torch.multinomial((it * w).softmax(dim=-1), 100, replacement=True)\n\nacc = MulticlassAccuracy(num_classes=num_classes, average=\"micro\")\nacc_per_class = MulticlassAccuracy(num_classes=num_classes, average=None)\nconfmat = MulticlassConfusionMatrix(num_classes=num_classes)\n\n# plot single value\nfor i in range(5):\n    acc_per_class.update(preds(i), target(i))\n    confmat.update(preds(i), target(i))\nfig1, ax1 = acc_per_class.plot()\nfig2, ax2 = confmat.plot()\n\n# plot multiple values\nvalues = []\nfor i in range(10):\n    values.append(acc(preds(i), target(i)))\nfig3, ax3 = acc.plot(values)\n```\n\n<p align=\"center\">\n  <img src=\"https://github.com/Lightning-AI/torchmetrics/raw/v1.6.0/docs/source/_static/images/plot_example.png\" width=\"1000\">\n</p>\n\nFor examples of plotting different metrics try running [this example file](_samples/plotting.py).\n\n## Contribute!\n\nThe lightning + TorchMetrics team is hard at work adding even more metrics.\nBut we're looking for incredible contributors like you to submit new metrics\nand improve existing ones!\n\nJoin our [Discord](https://discord.com/invite/tfXFetEZxv) to get help with becoming a contributor!\n\n## Community\n\nFor help or questions, join our huge community on [Discord](https://discord.com/invite/tfXFetEZxv)!\n\n## Citation\n\nWe\u2019re excited to continue the strong legacy of open source software and have been inspired\nover the years by Caffe, Theano, Keras, PyTorch, torchbearer, ignite, sklearn and fast.ai.\n\nIf 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](https://github.com/Lightning-AI/torchmetrics/blob/master/CITATION.cff) (but only if you loved it \ud83d\ude0a).\n\n## License\n\nPlease observe the Apache 2.0 license that is listed in this repository.\nIn addition, the Lightning framework is Patent Pending.\n",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "PyTorch native Metrics",
    "version": "1.6.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/Lightning-AI/torchmetrics/issues",
        "Documentation": "https://torchmetrics.rtfd.io/en/latest/",
        "Download": "https://github.com/Lightning-AI/torchmetrics/archive/master.zip",
        "Homepage": "https://github.com/Lightning-AI/torchmetrics",
        "Source Code": "https://github.com/Lightning-AI/torchmetrics"
    },
    "split_keywords": [
        "deep learning",
        " machine learning",
        " pytorch",
        " metrics",
        " ai"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "461a9728a502f377ab8cff1fd15c625aa2919a183fa113ebcefa2cd38edff28b",
                "md5": "08ba5bd35e1032c8f17017123e4e6856",
                "sha256": "a508cdd87766cedaaf55a419812bf9f493aff8fffc02cc19df5a8e2e7ccb942a"
            },
            "downloads": -1,
            "filename": "torchmetrics-1.6.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "08ba5bd35e1032c8f17017123e4e6856",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.9",
            "size": 926379,
            "upload_time": "2024-11-12T19:35:38",
            "upload_time_iso_8601": "2024-11-12T19:35:38.247117Z",
            "url": "https://files.pythonhosted.org/packages/46/1a/9728a502f377ab8cff1fd15c625aa2919a183fa113ebcefa2cd38edff28b/torchmetrics-1.6.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "18889b0c5542ce845d153eaa7a7eb8e4fad34347b13b5997bf1d744d64410072",
                "md5": "7b576b22490cbfb6136e55483db9096c",
                "sha256": "aebba248708fb90def20cccba6f55bddd134a58de43fb22b0c5ca0f3a89fa984"
            },
            "downloads": -1,
            "filename": "torchmetrics-1.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "7b576b22490cbfb6136e55483db9096c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.9",
            "size": 538824,
            "upload_time": "2024-11-12T19:35:40",
            "upload_time_iso_8601": "2024-11-12T19:35:40.599305Z",
            "url": "https://files.pythonhosted.org/packages/18/88/9b0c5542ce845d153eaa7a7eb8e4fad34347b13b5997bf1d744d64410072/torchmetrics-1.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-12 19:35:40",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "Lightning-AI",
    "github_project": "torchmetrics",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "requirements": [],
    "lcname": "torchmetrics"
}
        
Elapsed time: 0.94451s