ValueError:没有足够的值在Pytorch中解包(预期为3,得到2)

2024-03-29 09:36:26 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的定义验证函数
当我加载模型并使用这段代码开始预测时,我使用PyTorch收到了错误。在这之后,我通过epoch循环和batch循环进行迭代,我得到了这个错误

def validate_epoch(net, val_loader,loss_type='CE'):
    net.train(False)
    running_loss = 0.0
    sm = nn.Softmax(dim=1)

    truth = []
    preds = []
    bar = tqdm(total=len(val_loader), desc='Processing', ncols=90)
    names_all = []
    n_batches = len(val_loader)
    for i, (batch, targets, names) in enumerate(val_loader):
        if loss_type == 'CE':
                labels = Variable(targets.float())
                inputs = Variable(batch)
        elif loss_type == 'MSE':
                labels = Variable(targets.float())
                inputs = Variable(batch)

        outputs = net(inputs)
        labels = labels.long()
        loss = criterion(outputs, labels)
        if loss_type =='CE':
            probs = sm(outputs).data.cpu().numpy()
        elif loss_type =='MSE':
            probs = outputs
            probs[probs < 0] = 0
            probs[probs > 4] = 4
            probs = probs.view(1,-1).squeeze(0).round().data.cpu().numpy()
        preds.append(probs)
        truth.append(targets.cpu().numpy())
        names_all.extend(names)
        running_loss += loss.item()
        bar.update(1)
        gc.collect()
    gc.collect()
    bar.close()
    if loss_type =='CE':
        preds = np.vstack(preds)
    else:
        preds = np.hstack(preds)
    truth = np.hstack(truth)
    return running_loss / n_batches, preds, truth, names_all

这是我调用validate函数的主要函数,在加载模型时获取错误,并在测试加载程序上开始预测

criterion = nn.CrossEntropyLoss()

model.eval()

test_losses = []
test_mse = []
test_kappa = []
test_acc = []


test_started = time.time()

test_loss, probs, truth, file_names = validate_epoch(model, test_iterator)

正如您在回溯错误中看到的,它给出了一些终端显示错误:

ValueError                                Traceback (most recent call last)
<ipython-input-27-d2b4a1ca3852> in <module>
     12 test_started = time.time()
     13 
---> 14 test_loss, probs, truth, file_names = validate_epoch(model, test_iterator)
     15 preds = probs.argmax(1)
     16 

<ipython-input-25-34e29e0ff6ed> in validate_epoch(net, val_loader, loss_type)
      9     names_all = []
     10     n_batches = len(val_loader)
---> 11     for i, (batch, targets, names) in enumerate(val_loader):
     12         if loss_type == 'CE':
     13                 labels = Variable(targets.float())

ValueError: not enough values to unpack (expected 3, got 2)

Tags: testlabelsnamestype错误batchvalloader
1条回答
网友
1楼 · 发布于 2024-03-29 09:36:26

torchvision.datasets.ImageFolder documentation

返回:(示例,目标),其中目标是目标类的类索引

因此,非常简单,您当前使用的dataset对象返回一个包含2个项的元组。如果试图将此元组存储在3个变量中,则会出现错误。正确的路线是:

for i, (batch, targets) in enumerate(val_loader):

如果您真的需要名称(我假设是每个图像的文件路径),您可以定义一个从ImageFolder数据集继承的新数据集对象,并重载__getitem__函数以同时返回此信息

相关问题 更多 >