Pytorch BCELoss不接受列表 [英] Pytorch BCELoss not accepting lists

查看:52
本文介绍了Pytorch BCELoss不接受列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的convLSTM模型返回一个隐藏状态列表(总共17个,大小(1,3,128,128)),我的目标是17个图像列表(所有张量大小:(3,128,128))调用损失函数时,出现以下错误:

My convLSTM model returns a list of hidden states (17 total, size (1,3,128,128)) and my target is a list of 17 images( all tensors size: (3,128,128) When the loss function is called, I get the following error:

文件"/Users/xyz/opt/anaconda3/envs/matrix/lib/python3.7/site->packages/torch/nn/modules/loss.py",行498,向前返回F.binary_cross_entropy(输入,目标,权重= self.weight,> reduction = self.reduction)文件"/Users/xyz/opt/anaconda3/envs/matrix/lib/python3.7/site->packages/torch/nn/functional.py",第2052行,位于binary_cross_entropy中如果target.size()!= input.size():AttributeError:列表"对象没有属性大小"

File "/Users/xyz/opt/anaconda3/envs/matrix/lib/python3.7/site->packages/torch/nn/modules/loss.py", line 498, in forward return F.binary_cross_entropy(input, target, weight=self.weight, >reduction=self.reduction) File "/Users/xyz/opt/anaconda3/envs/matrix/lib/python3.7/site->packages/torch/nn/functional.py", line 2052, in binary_cross_entropy if target.size() != input.size(): AttributeError: 'list' object has no attribute 'size'

一部分训练循环:

    hc = model.init_hidden(batch_size=1)
    for batch_idx, (data, target) in enumerate(train_loader):
        optimizer.zero_grad()
        # Set target, images 2 to 18
        target = data[1:]
        if gpu:
            data = data.cuda()
            target = target.cuda()
            hc.cuda()
        # Get outputs of LSTM
        output = model(data, hc)
        # Calculate loss
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()

我期待尺寸不匹配错误,但是却得到了它.我该如何解决?

I was expecting a size mismatch error but got this instead. How can I fix this?

推荐答案

我使用 torch.stack 解决了这个问题.可以使用 torch.cat ,但希望将带有张量列表的张量传递给损失函数以匹配目标格式,因此可以使用 torch.stack .

Hi I solved it by using torch.stack. Could have used torch.cat but wanted a tensor with a list of tensors to pass to the loss function to match the target format so used torch.stack.

这篇关于Pytorch BCELoss不接受列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆