简体   繁体   English

pytorch 加权 MSE 损失

[英]pytorch weighted MSE loss

I wanted to apply a weighted MSE to my pytorch model, but I ran into some spots where I do not know how to adapt it correctly.我想将加权 MSE 应用于我的 pytorch 模型,但我遇到了一些我不知道如何正确调整它的地方。 The original lines of code are:原始代码行是:

self.mse_criterion = torch.nn.MSELoss(reduction='none')
loss_mot_rec = self.mse_criterion(self.fake_noise, self.real_noise).mean(dim=-1)

def to(self, device):
    if self.opt.is_train:
        self.mse_criterion.to(device)
    self.encoder = self.encoder.to(device)

The function for my weighted MSE loss is:我的加权 MSE 损失函数是:

def weighted_mse_loss(input, target):
    weight=torch.FloatTensor([2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1])
    return (weight * (input - target) ** 2)

So I am confused how to replace the mse_criterion with my function.所以我很困惑如何用我的函数替换 mse_criterion。 Any help would be great.任何帮助都会很棒。 The entire original code can be found here Thanks完整的原始代码可以在这里找到谢谢

I tried what @DerekG suggested and now I am getting this error.我尝试了@DerekG 的建议,现在我收到了这个错误。 File "/content/MotionDiffuse/text2motion/trainers/ddpm_trainer.py",文件“/content/MotionDiffuse/text2motion/trainers/ddpm_trainer.py”,

   line 159, in to self.mse_criterion.to(device)
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 987, in to
   return self._apply(convert)
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 638, in _apply
   for module in self.children():
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1792, in children
   for name, module in self.named_children():
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1811, in named_children
   for name, module in self._modules.items():
File "/usr/local/lib/python3.8/dist-packages/torch/nn/modules/module.py", line 1265, in __getattr__
   raise AttributeError("'{}' object has no attribute '{}'".format(
AttributeError: 'weighted_MSELoss' object has no attribute '_modules'

Your loss criterion looks fine.您的损失标准看起来不错。 Just wrap it in a nn.module and it should be good to use.只需将它包装在一个nn.module中,它应该很好用。

class weighted_MSELoss(nn.Module):
    def __init__(self):
        super().__init__()
    def forward(self,inputs,targets,weights):
        return ((input - target)**2 ) * weight

And then call it as the other loss function more or less (I moved the weights outside as I assume you want to generate the weights as some function of the inputs that I am not aware of:然后或多或少地将其称为另一个损失函数(我将权重移到外面,因为我假设您想生成权重作为我不知道的输入的某些函数:

mse_criterion = weighted_MSELoss()
loss_mot_rec = mse_criterion(self.fake_noise,self.real_noise,weights).mean(dim = -1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM