修改代码后,有时会出现“ TypeError:张量不是割炬图像”,并且在我再次运行代码后消失

时间:2019-04-14 06:01:49

标签: python pycharm pytorch

我正在按照官方教程https://pytorch.org/tutorials/beginner/blitz/cifar10_tutorial.html

学习如何使用Pytorch。

一切顺利,直到我运行CIFAR10分类示例。(我根本没有修改代码)

错误消息:

Traceback (most recent call last):
  File "/tmp/pycharm_project_331/main.py", line 90, in <module>
    for i, data in enumerate(trainloader, 0):
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 286, in __next__
    return self._process_next_batch(batch)
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 307, in _process_next_batch
    raise batch.exc_type(batch.exc_msg)
TypeError: Traceback (most recent call last):
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 57, in _worker_loop
    samples = collate_fn([dataset[i] for i in batch_indices])
  File "/usr/local/lib/python3.5/dist-packages/torch/utils/data/dataloader.py", line 57, in <listcomp>
    samples = collate_fn([dataset[i] for i in batch_indices])
  File "/usr/local/lib/python3.5/dist-packages/torchvision/datasets/cifar.py", line 121, in __getitem__
    img = self.transform(img)
  File "/usr/local/lib/python3.5/dist-packages/torchvision/transforms/transforms.py", line 49, in __call__
    img = t(img)
  File "/usr/local/lib/python3.5/dist-packages/torchvision/transforms/transforms.py", line 143, in __call__
    return F.normalize(tensor, self.mean, self.std)
  File "/usr/local/lib/python3.5/dist-packages/torchvision/transforms/functional.py", line 165, in normalize
    raise TypeError('tensor is not a torch image.')
TypeError: tensor is not a torch image.

我想也许我错过了一些代码,但是代码很好。所以我再次运行了几次代码。错误消息以某种方式消失,并且培训进行得很顺利。

我找不到任何模式来复制错误。每当我更改代码时,它就会弹出,并且无需进行任何代码修改即可自行修复。

我将PyCharm配置为通过SSH(Ubuntu服务器)连接到远程解释器,但是当我使用本地解释器并通过python控制台运行代码时,也会发生同样的事情。

这真令人沮丧,因为我不知道我的代码是错误的还是同一件事。

1 个答案:

答案 0 :(得分:0)

您肯定已经修改了代码,这就是发生错误的原因。

问题出在wagtail start $APPNAME的{​​{1}}转换中,这个片段具体是:

ToTensor

您需要将torchvision图像转换为transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]) 对象以对其进行规范化。如果删除PIL,则会出现上述错误。