dimanche 18 juillet 2021

Pytorch Custom Loss Function with If Statement

I am trying to create a custom loss function in Pytorch that evaluates each element of a tensor with an if statement and acts accordingly.

def my_loss(outputs,targets,fin_val):
    if (outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach())<0:
        loss=3*(outputs-targets)**2
    else:
        loss=0.3*(outputs-targets)**2
    return loss

I have also tried:

def my_loss(outputs,targets,fin_val):
    if torch.gt((outputs.detach()-fin_val.detach())*(targets.detach()-fin_val.detach()),0):
        loss=0.3*(outputs-targets)**2
    else:
        loss=3*(outputs-targets)**2
    return loss

In both cases, I get the following error:

RuntimeError: Boolean value of Tensor with more than one value is ambiguous

TIA

Aucun commentaire:

Enregistrer un commentaire