RuntimeError:断言`THIndexTensor_(size)(target,0)== batch_size'失败。 at ... ClassNLLCriterion.c:79

时间:2018-04-10 15:53:18

标签: conv-neural-network pytorch assertion

我正在研究机器学习项目。我的任务是对卫星图像进行分类。我有5个班级作为我的标签。整个数据采用Matlab格式。 发布整个代码太多了,所以我决定发布它的重要部分。

以下是代码段:

...

from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 5)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()


import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

for epoch in range(2):  # loop over the dataset multiple times

    running_loss = 0.0
    for i in range(1):
        print(i)
        # get the inputs
        #inputs, labels = data
        inputs=in_data
        labels=in_labels
        print("A:",labels.shape)
        print("B:",inputs.shape)


        # wrap them in Variable
        inputs, labels = Variable(inputs), Variable(labels)
        print("A_2:",inputs.size())
        print("A_3:",labels.size())

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        labels = labels.squeeze_()
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

...

你可以很容易地看到,这是一个CNN(卷积神经网络)。如果我运行我的代码,将显示以下错误:

0
A: torch.Size([100])
B: torch.Size([100, 3, 64, 64])
A_2: torch.Size([100, 3, 64, 64])
A_3: torch.Size([100])
Traceback (most recent call last):
  File "datasetAnalyser.py", line 283, in <module>
    main(args)
  File "datasetAnalyser.py", line 139, in main
    run(torchImage,torchLabel)
  File "datasetAnalyser.py", line 114, in run
    loss = criterion(outputs, labels)
  File "/home/qais/anaconda2/envs/Python3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 325, in __call__
    result = self.forward(*input, **kwargs)
  File "/home/qais/anaconda2/envs/Python3/lib/python3.6/site-packages/torch/nn/modules/loss.py", line 601, in forward
    self.ignore_index, self.reduce)
  File "/home/qais/anaconda2/envs/Python3/lib/python3.6/site-packages/torch/nn/functional.py", line 1140, in cross_entropy
    return nll_loss(log_softmax(input, 1), target, weight, size_average, ignore_index, reduce)
  File "/home/qais/anaconda2/envs/Python3/lib/python3.6/site-packages/torch/nn/functional.py", line 1049, in nll_loss
    return torch._C._nn.nll_loss(input, target, weight, size_average, ignore_index, reduce)
RuntimeError: Assertion `THIndexTensor_(size)(target, 0) == batch_size' failed.  at /opt/conda/conda-bld/pytorch_1513368888240/work/torch/lib/THNN/generic/ClassNLLCriterion.c:79

好吧,我已经google了一下,发现了很多关于这个问题的线索。不知何故,他们都没有解决我的问题。这就是我再次问你的原因。

我该怎么办?我想我必须改变

中的整数值
class Net(nn.Module)

但我不确切知道应该更改哪些值。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

错误肯定是由labelsoutputs之间不兼容的大小引起的。我很好奇你为什么要使用label = label.squeeze_()。我认为没必要。

尝试删除label = label.squeeze_()并调整labels的大小以匹配outputs。这是关于图像分类的good tutorial。你可以了解他们是如何做到的。