在 pytorch 中使用超过 1 个指标

原文标题Using more than 1 metric in pytorch

我在 Tenserflow 方面有一些经验,但我是 pytorch 的新手。有时我需要超过 1 个指标来检查训练的准确性。在 Tenserflow 中,我曾经这样做如下所示。但我想知道如何在 pytorch 中列出超过 1 个指标。

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)

原文链接:https://stackoverflow.com//questions/71404067/using-more-than-1-metric-in-pytorch

回复

我来回复
  • Edwin Cheong的头像
    Edwin Cheong 评论

    在 pytorch 中,训练主要是通过循环完成的,因此您可以通过每个步骤进行定义,有诸如 torchmetrics 之类的包,您可以运行每个指标,这里有一个示例:

    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))
    
    2年前 0条评论