【问题标题】:Change expectation to multi dimensional rather than 1D in nn.crossentropyloss在 nn.crossentropyloss 中将期望更改为多维而不是 1D
【发布时间】:2020-10-21 22:16:01
【问题描述】:

我的目标是使用 EMNIST 数据集在 Pytorch 中进行多类图像分类。 作为损失函数,我想使用 Multi-Class Cross-Entropy Loss。

目前,我将损失函数定义如下:

criterion = nn.CrossEntropyLoss()

我按如下方式训练我的模型:

iter = 0
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        
        # Add a single channel dimension
        # From: [batch_size, height, width]
        # To: [batch_size, 1, height, width]
        images = images.unsqueeze(1)

        # Forward pass to get output/logits
        outputs = model(images)
        
        # Clear gradients w.r.t. parameters
        optimizer.zero_grad()
        
        # Forward pass to get output/logits
        outputs = model(images)

        # Calculate Loss: softmax --> cross entropy loss
        loss = criterion(outputs, labels)
        
        # Getting gradients w.r.t. parameters
        loss.backward()
        
        # Updating parameters
        optimizer.step()
        
        iter += 1
        
        if iter % 500 == 0:
            # Calculate Accuracy         
            correct = 0
            total = 0
            # Iterate through test dataset
            for images, labels in test_loader:
               
                images = images.unsqueeze(1)
                
                # Forward pass only to get logits/output
                outputs = model(images)
                
                # Get predictions from the maximum value
                _, predicted = torch.max(outputs.data, 1)
                
                # Total number of labels
                total += labels.size(0)
                
                correct += (predicted == labels).sum()
            
            accuracy = 100 * correct / total
            
            # Print Loss
            print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))

但是,我得到的错误是:

RuntimeError                              Traceback (most recent call last)
<ipython-input-15-c26c43bbc32e> in <module>()
     21 
     22         # Calculate Loss: softmax --> cross entropy loss
---> 23         loss = criterion(outputs, labels)
     24 
     25         # Getting gradients w.r.t. parameters

3 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
   2113                          .format(input.size(0), target.size(0)))
   2114     if dim == 2:
-> 2115         ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
   2116     elif dim == 4:
   2117         ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)

RuntimeError: 1D target tensor expected, multi-target not supported

我的CNN输出26个变量,我的目标变量也是26D。

如何更改我的代码以使 nn.crossentropyloss() 需要 26D 输入而不是 1D?

【问题讨论】:

    标签: python-3.x pytorch conv-neural-network


    【解决方案1】:

    nn.CrossEntropy()(input, target) 期望 input 是大小为 batchsize X num_classes 的 one-hot 向量,而 target 是大小为 batchsize 的真实类的 id。

    简而言之,您可以使用target = torch.argmax(target, dim=1) 更改您的目标,使其适合nn.CrossEntropy()

    【讨论】:

      【解决方案2】:

      除了@Flicic Suo的答案,你应该使用predicted = torch.argmax(output, dim=1)来预测labels。现在你正在获得最大值,你所追求的是具有最大值的类。

      这样你会得到0.0的准确度,所以argmax是正确的。

      【讨论】:

        猜你喜欢
        • 2015-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-26
        • 1970-01-01
        • 1970-01-01
        • 2022-01-18
        相关资源
        最近更新 更多