本文介绍了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:

一部分训练循环:

    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不接受列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 02:38