Search code examples
pythoncompiler-errorspytorchtensorloss

Pytorch error when computing loss between two tensors. TypeError: __init__() takes 1 positional argument but 3 were given


When trying to compute the loss between two tensors rPPG = (shape(torch.Size([4, 128])) and BVP_label = (shape(torch.Size([4, 128]))) using the following function:

class Neg_Pearson(nn.Module):    # Pearson range [-1, 1] so if < 0, abs|loss| ; if >0, 1- loss
    def __init__(self):
        super(Neg_Pearson,self).__init__()
        return
    def forward(self, preds, labels):       # tensor [Batch, Temporal]
        loss = 0
        for i in range(preds.shape[0]):
            sum_x = torch.sum(preds[i])                # x
            sum_y = torch.sum(labels[i])               # y
            sum_xy = torch.sum(preds[i]*labels[i])        # xy
            sum_x2 = torch.sum(torch.pow(preds[i],2))  # x^2
            sum_y2 = torch.sum(torch.pow(labels[i],2)) # y^2
            N = preds.shape[1]
            pearson = (N*sum_xy - sum_x*sum_y)/(torch.sqrt((N*sum_x2 - torch.pow(sum_x,2))*(N*sum_y2 - torch.pow(sum_y,2))))
            
            print(N)
            #if (pearson>=0).data.cpu().numpy():    # torch.cuda.ByteTensor -->  numpy
            #    loss += 1 - pearson
            #else:
            #    loss += 1 - torch.abs(pearson)
            
            loss += 1 - pearson
            
            
        loss = loss/preds.shape[0]
        return loss

#3. Calculate the loss
loss_ecg = Neg_Pearson(rPPG, BVP_label)

I keep getting the following error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-15-f14cbf0fc84b> in <module>
      1 #3. Calculate the loss
----> 2 loss_ecg = Neg_Pearson(rPPG, BVP_label)

TypeError: __init__() takes 1 positional argument but 3 were given

I am new to Pytorch, I am not sure what is going on here. Any suggestions?


Solution

  • You have a typo there. instead try :

    neg_pears_loss = Neg_Pearson()
    loss = neg_pears_loss(rPPG, BVP_label)