Pytorch模型函数给出错误:“NoneType”对象没有属性“size”

cuxqih21  于 2022-11-09  发布在  其他
关注(0)|答案(3)|浏览(1122)

我尝试在没有CUDA的情况下运行下面的代码来解决图像分割问题,因为我没有GPU。我已经使用pytorch在CPU上训练了我的模型,但在预测级别上,我得到了

  1. AttributeError: 'NoneType' object has no attribute 'size'

下面是代码:

  1. idx = 20
  2. model.load_state_dict(torch.load('/content/best_model.pt'))
  3. image, mask = validset[idx]
  4. image = image.unsqueeze_(0)
  5. print(type(image))
  6. # logits_mask = model(image.to(DEVICE).unsqueeze(0)) # (c,h,w) -> (1,c,h,w)
  7. logits_mask = model(image) # (c,h,w) py-> (1,c,h,w)

输出中产生的错误位于第8行:

  1. ---------------------------------------------------------------------------
  2. AttributeError Traceback (most recent call last)
  3. <ipython-input-56-edf3f0fae49c> in <module>
  4. 6 print(type(image))
  5. 7 # logits_mask = model(image.to(DEVICE).unsqueeze(0)) # (c,h,w) -> (1,c,h,w)
  6. ----> 8 logits_mask = model(image) # (c,h,w) py-> (1,c,h,w)
  7. 9
  8. 10 pred_mask = torch.sigmoid(logits_mask)
  9. 3 frames
  10. /usr/local/lib/python3.7/dist-packages/segmentation_models_pytorch/losses/dice.py in forward(self, y_pred, y_true)
  11. 57 def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
  12. 58
  13. ---> 59 assert y_true.size(0) == y_pred.size(0)
  14. 60
  15. 61 if self.from_logits:
  16. AttributeError: 'NoneType' object has no attribute 'size'
s71maibg

s71maibg1#

assert y_true.size(0) == y_pred.size(0)错误表示y_truey_pred为None,因此您可以尝试分别检查image, model(image), & mask的类型。
IMO,这可能是根本原因:image = image.unsqueeze_(0)
unsqueze_是一个原地运算符,这意味着它将不返回任何内容,并原地更改Tensorimage

cngwdvgl

cngwdvgl2#

print(type(image))的输出是什么?
由于model(image)的错误为nonetype,因此推测问题与模型加载有关,或者在以下行中对图像进行索引时出现问题:

  1. model.load_state_dict(torch.load('/content/best_model.pt'))
  2. image, mask = validset[idx]

EDIT:print(image.size())和print(image)的输出是什么?
t.大小()

cedebl8k

cedebl8k3#

您需要将掩码作为第二个参数传递以避免NoneType. # logits_mask = model(image.to(DEVICE).unsqueeze(0), mask(DEVICE).unsqueeze(0)) # (c,h,w) -> (1,c,h,w) #or# logits_mask = model(image, mask) # (c,h,w) py-> (1,c,h,w)

相关问题