Pytorch BCELoss 不接受列表

Pytorch BCELoss not accepting lists

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

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()

我原以为会出现大小不匹配错误,但结果却出现了这个错误。我该如何解决这个问题?

target 需要是张量,而不是张量列表。

例子

    >>> m = nn.Sigmoid()
    >>> loss = nn.BCELoss()
    >>> input = torch.randn(3, requires_grad=True)
    >>> target = torch.empty(3).random_(2) #This is a tensor, not a list
    >>> output = loss(m(input), target)
    >>> output.backward()

看看 torch.nn.modules.loss or torch.nn

中的 BCELoss

您好,我使用 torch.stack 解决了这个问题。本来可以使用 torch.cat 但想要一个带有张量列表的张量传递给损失函数以匹配目标格式所以使用 torch.stack