RuntimeError: weight tensor should be defined either for all or no classes

今天在添加网络中添加深监督的时候遇到了这个错误,先看出现错误的位置,是在计算交叉熵的时候:

    def forward(self, inputs_scales, targets_scales):
        losses = []
        for inputs, targets in zip(inputs_scales, targets_scales):
            # mask = targets > 0
            targets_m = targets.clone() #深拷贝
            targets_m -= 1 #减去
            loss_all = self.ce_loss(inputs, targets_m.long())

在网上冲浪一个小时,发现了各路大神解决方案:参考方案

1:检查输出预测图与标签的尺寸是否一样

 2:没有区分背景及边缘:

 3:分割类别与分割标签种类不一样: 

我想在深监督中,使用多尺度标签进行监督,在decoder中输出经过self.side_output,得到了一个通道为37的语义分割图。

self.side_output = nn.Conv2d(in_channels//2,
                                     out_channels=37,
                                     kernel_size=1)

在图像的预处理中,我们对标签进行缩放,使标签的大小和decoder输出的大小一样,这样才可以进行损失计算。

# 
class MultiScaleLabel:
    def __init__(self, downsampling_rates=None):
        if downsampling_rates is None:
            self.downsampling_rates = [8, 4, 2]
        else:
            self.downsampling_rates = downsampling_rates

    def __call__(self, sample):
        label = sample['label']

        h, w = label.shape

        sample['label_down'] = dict()

        # Nearest neighbor interpolation
        for rate in self.downsampling_rates:
            label_down = cv2.resize(label.numpy(), (w // rate, h // rate),
                                    interpolation=cv2.INTER_NEAREST)
            sample['label_down'][rate] = torch.from_numpy(label_down)

        return sample

而在NYUDepth-v2中,标签的类别为40,我的分割类别只有37,因此问题就出现了。即上面的解决办法3。

 所以我们将输出的分割类别调整37为标签类别40就可以了。

self.side_output = nn.Conv2d(in_channels//2,
                                     out_channels=40,
                                     kernel_size=1)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值