我在colab上运行nn,遇到了在本地系统上运行相同代码时不存在的错误。我也尝试减少批次大小,但错误仍然存在。
Loading dataset
Start training
---------------------------------------------------------------------------
RuntimeError Traceback (most recent call last)
<ipython-input-4-37432f9d142a> in <module>()
70 start_epoch=start_epoch, log=log_interval,
71 checkpoint_path=os.path.join(dataset_dir, "cnn_block_frame_flow"),
---> 72 validate=True, resume=False, flow=True, use_cuda=cuda)
73
74 #model = models.model()
/content/KTH-Action-Recognition/main/train_helper.py in train(model, num_epochs, train_set, dev_set, lr, batch_size, start_epoch, log, checkpoint_path, validate, resume, flow, use_cuda)
107 outputs = get_outputs(model, samples["instance"], flow=flow,
108 use_cuda=use_cuda)
--> 109 loss = criterion(outputs, labels)
110 loss.backward()
111 optimizer.step()
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/module.py in __call__(self, *input, **kwargs)
487 result = self._slow_forward(*input, **kwargs)
488 else:
--> 489 result = self.forward(*input, **kwargs)
490 for hook in self._forward_hooks.values():
491 hook_result = hook(self, input, result)
/usr/local/lib/python3.6/dist-packages/torch/nn/modules/loss.py in forward(self, input, target)
902 def forward(self, input, target):
903 return F.cross_entropy(input, target, weight=self.weight,
--> 904 ignore_index=self.ignore_index, reduction=self.reduction)
905
906
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in cross_entropy(input, target, weight, size_average, ignore_index, reduce, reduction)
1968 if size_average is not None or reduce is not None:
1969 reduction = _Reduction.legacy_get_string(size_average, reduce)
-> 1970 return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
1971
1972
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
1788 .format(input.size(0), target.size(0)))
1789 if dim == 2:
-> 1790 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
1791 elif dim == 4:
1792 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: Expected object of scalar type Long but got scalar type Byte for argument #2 'target'
有人可以告诉我是什么导致此错误吗?谢谢
答案 0 :(得分:1)
您的问题的标题是告诉导致此错误的原因。 target
的类型应为torch.LongTensor
,但类型应为torch.ByteTensor
。致电nll_loss
之前,请执行以下操作:
target = target.type(torch.LongTensor)