
مقاييس التعلم الآلي لتطبيقات pytorch الموزعة والقابلة للتطوير.
ما هو Torchmetrics • تنفيذ مقياس • مقاييس مدمجة • مستندات • المجتمع • الترخيص

تثبيت بسيط من PYPI
pip install torchmetricsتثبيت باستخدام كوندا
conda install -c conda-forge torchmetricsPIP من المصدر
# with git
pip install git+https://github.com/Lightning-AI/torchmetrics.git@release/stablePIP من الأرشيف
pip install https://github.com/Lightning-AI/torchmetrics/archive/refs/heads/release/stable.zipتبعيات إضافية للمقاييس المتخصصة:
pip install torchmetrics[audio]
pip install torchmetrics[image]
pip install torchmetrics[text]
pip install torchmetrics[all] # install all of the aboveقم بتثبيت أحدث إصدار من المطورين
pip install https://github.com/Lightning-AI/torchmetrics/archive/master.zipTorchMetrics عبارة عن مجموعة من تطبيقات 100+ من مقاييس Pytorch و API سهلة الاستخدام لإنشاء مقاييس مخصصة. يقدم:
يمكنك استخدام Torchmetrics مع أي طراز Pytorch أو مع Lightning Pytorch للاستمتاع بميزات إضافية مثل:
تحتوي المقاييس المستندة إلى الوحدة على حالات مترية داخلية (على غرار معلمات وحدة Pytorch) التي تتم أتمتة التراكم والمزامنة عبر الأجهزة!
يمكن تشغيل ذلك على وحدة المعالجة المركزية أو وحدة معالجة الرسومات المفردة أو GPUs متعددة!
لحالة GPU/وحدة المعالجة المركزية المفردة:
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 } " )يظل استخدام مقياس الوحدة هو نفسه عند استخدام وحدات معالجة الرسومات المتعددة أو العقد المتعددة.
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 ) إن تنفيذ مقياسك الخاص سهلاً مثل تصنيف torch.nn.Module . ببساطة ، torchmetrics.Metric من الدرجة الفرعية وتنفيذ طرق update 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 )) على غرار torch.nn ، فإن معظم المقاييس لها نسخة قائمة على الوحدة النمطية والوظيفية. الإصدارات الوظيفية هي وظائف Python بسيطة تكون عند الإدخال تأخذ torch.tensors وإرجاع المقياس المقابل كحرف 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 . classification . multiclass_accuracy (
preds , target , num_classes = 5
)في إجمالي Torchmetrics يحتوي على 100+ مقاييس ، والتي تغطي المجالات التالية:
قد يتطلب كل مجال بعض التبعيات الإضافية التي يمكن تثبيتها باستخدام pip install torchmetrics[audio] ، pip install torchmetrics['image'] وما إلى ذلك.
يمكن أن يكون تصور المقاييس أمرًا مهمًا للمساعدة في فهم ما يجري مع خوارزميات التعلم الآلي. لدى TorchMetrics دعمًا مدمجًا للتخطيط (تثبيت تبعيات مع pip install torchmetrics[visual] ) لجميع المقاييس المعيارية تقريبًا من خلال طريقة .plot . ما عليك سوى استدعاء طريقة الحصول على تصور بسيط لأي مقياس!
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 )
للحصول على أمثلة للتخطيط لمقاييس مختلفة ، حاول تشغيل ملف المثال هذا.
يعمل فريق Lightning + Torchmetrics بجد إلى إضافة المزيد من المقاييس. لكننا نبحث عن مساهمين لا يصدقون مثلك لتقديم مقاييس جديدة وتحسين المقاييس الحالية!
انضم إلى Discord للحصول على المساعدة في أن تصبح مساهمًا!
للحصول على المساعدة أو الأسئلة ، انضم إلى مجتمعنا الضخم على Discord!
نحن متحمسون لمواصلة الإرث القوي للبرامج المفتوحة المصدر وتم إلهامنا على مر السنين من قبل Caffe و Theano و Keras و Pytorch و Torchbearer و Ignite و Sklearn و Fast.ai.
إذا كنت ترغب في الاستشهاد بهذا الإطار ، فلا تتردد في استخدام خيار الاستشهاد المدمج لـ Github لإنشاء اقتباس من طراز Bibtex أو APA استنادًا إلى هذا الملف (ولكن فقط إذا أحببت ذلك؟).
يرجى مراقبة ترخيص Apache 2.0 المدرج في هذا المستودع. بالإضافة إلى ذلك ، فإن إطار البرق هو براءة اختراع معلقة.