All Projects → PyTorchLightning → Metrics

PyTorchLightning / Metrics

Licence: apache-2.0
Machine learning metrics for distributed, scalable PyTorch applications.

Programming Languages

python
139335 projects - #7 most used programming language

Projects that are alternatives of or similar to Metrics

Artificial Adversary
🗣️ Tool to generate adversarial text examples and test machine learning models against them
Stars: ✭ 348 (+114.81%)
Mutual labels:  data-science, metrics
Kd lib
A Pytorch Knowledge Distillation library for benchmarking and extending works in the domains of Knowledge Distillation, Pruning, and Quantization.
Stars: ✭ 173 (+6.79%)
Mutual labels:  data-science
Data Science Toolkit
Collection of stats, modeling, and data science tools in Python and R.
Stars: ✭ 169 (+4.32%)
Mutual labels:  data-science
Anndata
Annotated data.
Stars: ✭ 171 (+5.56%)
Mutual labels:  data-science
Covid19 Severity Prediction
Extensive and accessible COVID-19 data + forecasting for counties and hospitals. 📈
Stars: ✭ 170 (+4.94%)
Mutual labels:  data-science
Express Prom Bundle
express middleware with standard prometheus metrics in one bundle
Stars: ✭ 172 (+6.17%)
Mutual labels:  metrics
Airbyte
Airbyte is an open-source EL(T) platform that helps you replicate your data in your warehouses, lakes and databases.
Stars: ✭ 4,919 (+2936.42%)
Mutual labels:  data-science
Book list
Python, Machine Learning, Deep Learning and Data Science Books
Stars: ✭ 176 (+8.64%)
Mutual labels:  data-science
Datasets For Good
List of datasets to apply stats/machine learning/technology to the world of social good.
Stars: ✭ 174 (+7.41%)
Mutual labels:  data-science
100 Days Of Ml Code
A day to day plan for this challenge. Covers both theoritical and practical aspects
Stars: ✭ 172 (+6.17%)
Mutual labels:  data-science
Ostent
Ostent is a server tool to collect, display and report system metrics.
Stars: ✭ 171 (+5.56%)
Mutual labels:  metrics
Logi Kafkamanager
一站式Apache Kafka集群指标监控与运维管控平台
Stars: ✭ 3,280 (+1924.69%)
Mutual labels:  metrics
Apache exporter
Prometheus exporter for Apache.
Stars: ✭ 172 (+6.17%)
Mutual labels:  metrics
Node Statsd Client
Node.js client for statsd
Stars: ✭ 170 (+4.94%)
Mutual labels:  metrics
Web Database Analytics
Web scrapping and related analytics using Python tools
Stars: ✭ 175 (+8.02%)
Mutual labels:  data-science
Matplotplusplus
Matplot++: A C++ Graphics Library for Data Visualization 📊🗾
Stars: ✭ 2,433 (+1401.85%)
Mutual labels:  data-science
Data Science Resources
👨🏽‍🏫You can learn about what data science is and why it's important in today's modern world. Are you interested in data science?🔋
Stars: ✭ 171 (+5.56%)
Mutual labels:  data-science
Deep Spying
Spying using Smartwatch and Deep Learning
Stars: ✭ 172 (+6.17%)
Mutual labels:  data-science
Chefboost
A Lightweight Decision Tree Framework supporting regular algorithms: ID3, C4,5, CART, CHAID and Regression Trees; some advanced techniques: Gradient Boosting (GBDT, GBRT, GBM), Random Forest and Adaboost w/categorical features support for Python
Stars: ✭ 176 (+8.64%)
Mutual labels:  data-science
Scikit Plot
An intuitive library to add plotting functionality to scikit-learn objects.
Stars: ✭ 2,162 (+1234.57%)
Mutual labels:  data-science

Machine learning metrics for distributed, scalable PyTorch applications.


What is TorchmetricsImplementing a metricBuilt-in metricsDocsCommunityLicense


PyPI - Python Version PyPI Status PyPI Status Conda Slack license

CI testing - base Build Status codecov Documentation Status


Installation

Simple installation from PyPI

pip install torchmetrics
Other installations

Install using conda

conda install torchmetrics

Pip from source

# with git
pip install git+https://github.com/PytorchLightning/[email protected]

Pip from archive

pip install https://github.com/PyTorchLightning/metrics/archive/master.zip

What is Torchmetrics

TorchMetrics is a collection of 25+ 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.Accuracy()

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)
    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
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.Accuracy()

# 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}")

    # Reseting internal state such that metric ready for new data
    metric.reset()

Implementing your own Module metric

Implementing your own metric is as easy as subclassing an torch.nn.Module. Simply, subclass torchmetrics.Metric and implement the following methods:

class MyAccuracy(Metric):
    def __init__(self, dist_sync_on_step=False):
        # 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
	super().__init__(dist_sync_on_step=dist_sync_on_step)

        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):
        # update metric states
        preds, target = self._input_format(preds, target)
        assert preds.shape == target.shape

        self.correct += torch.sum(preds == target)
        self.total += target.numel()

    def compute(self):
        # compute final result
        return self.correct.float() / self.total

Functional metrics

Similar to torch.nn, most metrics have both a module-based and a 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.accuracy(preds, target)

Implemented metrics

And many more!

Contribute!

The lightning + torchmetric 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 Slack to get help becoming a contributor!

Community

For help or questions, join our huge community on Slack!

Citations

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. When/if a paper is written about this, we’ll be happy to cite these frameworks and the corresponding authors.

License

Please observe the Apache 2.0 license that is listed in this repository. In addition the Lightning framework is Patent Pending.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].