
Métricas de aprendizaje automático para aplicaciones de Pytorch distribuidas y escalables.
¿Qué es Torchmetrics? • Implementación de una métrica • Métricas incorporadas • Docios • Comunidad • Licencia

Instalación simple de Pypi
pip install torchmetricsInstalar con conda
conda install -c conda-forge torchmetricsPip de la fuente
# with git
pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stablePip del archivo
pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zipDependencias adicionales para métricas especializadas:
pip install torchmetrics[audio]
pip install torchmetrics[image]
pip install torchmetrics[text]
pip install torchmetrics[all] # install all of the aboveInstale la última versión de desarrollador
pip install https://github.com/Lightning-AI/torchmetrics/archive/master.zipTorchmetrics es una colección de más de 100 implementaciones de métricas de Pytorch y una API fácil de usar para crear métricas personalizadas. Ofrece:
Puede usar Torchmetrics con cualquier modelo de Pytorch o con Pytorch Lightning para disfrutar de características adicionales como:
¡Las métricas basadas en el módulo contienen estados métricos internos (similares a los parámetros del módulo Pytorch) que automatizan la acumulación y la sincronización entre los dispositivos!
¡Esto se puede ejecutar en CPU, GPU única o multi-GPU!
Para el caso único de GPU/CPU:
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 } " )El uso de la métrica del módulo sigue siendo el mismo cuando se usa múltiples GPU o múltiples nodos.
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 ) Implementar su propia métrica es tan fácil como subclasificar una torch.nn.Module . Simplemente, subclase torchmetrics.Metric y simplemente implementa los métodos update y compute :
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 )) Similar a torch.nn , la mayoría de las métricas tienen una versión funcional y basada en módulos. Las versiones funcionales son funciones simples de pitón que, a medida que la entrada, toman antorch.tensors y devuelve la métrica correspondiente como antorcha. 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
)En total, Torchmetrics contiene más de 100 métricas, que cubre los siguientes dominios:
Cada dominio puede requerir algunas dependencias adicionales que se pueden instalar con pip install torchmetrics[audio] , pip install torchmetrics['image'] etc.
La visualización de las métricas puede ser importante para ayudar a comprender lo que está sucediendo con sus algoritmos de aprendizaje automático. Torchmetrics tiene soporte de trazado incorporado (Instale Dependencias con pip install torchmetrics[visual] ) para casi todas las métricas modulares a través del método .plot . ¡Simplemente llame al método para obtener una visualización simple de cualquier métrica!
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 )
Para ver ejemplos de trazar diferentes métricas, intente ejecutar este archivo de ejemplo.
El equipo Lightning + Torchmetrics está trabajando duro, agregando aún más métricas. ¡Pero estamos buscando contribuyentes increíbles como usted para enviar nuevas métricas y mejorar las existentes!
¡Únase a nuestra discordia para obtener ayuda para convertirse en un contribuyente!
Para ayuda o preguntas, ¡únase a nuestra gran comunidad en Discord!
Estamos entusiasmados de continuar con el fuerte legado del software de código abierto y hemos sido inspirados a lo largo de los años por Caffe, Theo, Keras, Pytorch, Torchbearer, Ignite, Sklearn y Fast.ai.
Si desea citar este marco, no dude en usar la opción de cita incorporada de GitHub para generar una cita de estilo Bibtex o APA basada en este archivo (pero solo si le encantó?).
Observe la licencia Apache 2.0 que se enumera en este repositorio. Además, el marco Lightning está pendiente de patente.