Home > Software design >  Using more than 1 metric in pytorch
Using more than 1 metric in pytorch

Time:03-09

I have some experience in Tenserflow but I'm new to pytorch. Sometimes I need more than 1 metric to check the accuracy of training. In Tenserflow, I used to do as shown below. But I wonder how could list more than 1 metric in pytorch.

LR = 0.0001
optim = keras.optimizers.Adam(LR)

dice_loss_se2 = sm.losses.DiceLoss()
mae = tf.keras.losses.MeanAbsoluteError( )
metrics = [ mae,sm.metrics.IOUScore(threshold=0.5), sm.metrics.FScore(threshold=0.5) , dice_loss_se2]

model.compile(optimizer=optim,loss= dice_loss_se2,metrics= metrics)

CodePudding user response:

In pytorch training is done mostly through loops so you have define via each step, there are packages like torchmetrics which you can run each metric heres an example:

import torchmetrics

for step, (test_image, test_labels) in tqdm(enumerate(test_dataloader), total=len(test_dataloader)):
        test_batch_image = test_image.to('cuda')
        test_batch_label = test_labels.to('cuda')
        targets.append(test_labels)
        
        with torch.no_grad():
            logits = model(test_batch_image)
        
        loss = criterion(logits, test_batch_label)
        test_loss  = loss.item()
        
        preds.append(logits.detach().cpu().numpy().argmax(axis=1))
    
    preds = torch.tensor(np.concatenate(preds))
    targets = torch.tensor(np.concatenate(targets))
    print('[Epoch %d] Test loss: %.3f' %(epoch   1, test_loss/ len(test_dataloader)))
    print('Accuracy: {}%'.format(round(torchmetrics.functional.accuracy(target=targets, preds=preds).item() * 100), 2))
  • Related