Home > OS >  Pytorch model function gives Error :'NoneType' object has no attribute 'size'
Pytorch model function gives Error :'NoneType' object has no attribute 'size'

Time:08-18

I trying to run below code in my image segmentation problem without CUDA as I don't have GPU. I have trained my model on CPU using pytorch but on prediction level I'm getting

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

Here's the code:

idx = 20
model.load_state_dict(torch.load('/content/best_model.pt'))

image, mask = validset[idx]
image = image.unsqueeze_(0)
print(type(image))
# logits_mask = model(image.to(DEVICE).unsqueeze(0)) # (c,h,w) -> (1,c,h,w)
logits_mask = model(image) # (c,h,w) py-> (1,c,h,w)

The resulting error, from the output, is at line number 8:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-56-edf3f0fae49c> in <module>
      6 print(type(image))
      7 # logits_mask = model(image.to(DEVICE).unsqueeze(0)) # (c,h,w) -> (1,c,h,w)
----> 8 logits_mask = model(image) # (c,h,w) py-> (1,c,h,w)
      9 
     10 pred_mask = torch.sigmoid(logits_mask)

3 frames
/usr/local/lib/python3.7/dist-packages/segmentation_models_pytorch/losses/dice.py in forward(self, y_pred, y_true)
     57     def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
     58 
---> 59         assert y_true.size(0) == y_pred.size(0)
     60 
     61         if self.from_logits:

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

CodePudding user response:

assert y_true.size(0) == y_pred.size(0) erroring signifies that either y_true or y_pred are None, so you can try checking the types of image, model(image), & mask respectively.

IMO, this might be the root cause: image = image.unsqueeze_(0)

unsqueze_ is an inplace operator, which means it will return nothing and change the tensor image inplace.

CodePudding user response:

What is the output of print(type(image))?

Since the error is nonetype for model(image) presumably the issues is with the model load or when you index the image in the following lines:

model.load_state_dict(torch.load('/content/best_model.pt'))

image, mask = validset[idx]

EDIT: What's the output of print(image.size()) and print(image)?

t.size()

  • Related