如何解决计算两个张量之间的损耗时,Pytorch错误 TypeError:__init __接受1个位置参数,但给出了3个
当尝试使用以下函数计算两个张量rPPG = (shape(torch.Size([4,128]))
和BVP_label = (shape(torch.Size([4,128])))
之间的损耗时:
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)
我一直收到以下错误:
---------------------------------------------------------------------------
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
我是Pytorch的新手,我不确定这是怎么回事。有什么建议吗?
解决方法
您在那里有错字。而是尝试:
neg_pears_loss = Neg_Pearson()
loss = neg_pears_loss(rPPG,BVP_label)
,
在Neg_Pearson
的{{1}}方法中,您定义一个类实例只有一个参数-对__init__
的引用。但是,当您进入以下代码行时:
self
因此出现错误消息:loss_ecg = Neg_Pearson(rPPG,BVP_label)
# There's a confusion.
# Parser expects this:
loss_ecg = Neg_Pearson(self)
# But instead it got:
loss_ecg = Neg_Pearson(self,rPPG,BVP_label)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。