Bug when loading model

I have the following piece of code :
import torch
import torchvision
import cv2
import argparse
from PIL import Image
from utils import draw_segmentation_map, get_outputs
from torchvision.transforms import transforms

initialize the model

model = torch.load(“model_folioles.pth”,map_location=torch.device(‘cpu’))

set the computation device

device = torch.device(‘cpu’)

load the modle on to the computation device and set to eval mode


and I have the following error :
Traceback (most recent call last):
File “demo.py”, line 14, in
AttributeError: ‘dict’ object has no attribute ‘to’

could you help me please ?
thank you
best regards

This doesn’t return the model but returns a dict which will contain a key like model_state_dict that contains the state_dict of your model. You’ll need to re-init your model and then load the state_model via something like,

model = ModelClass() 
state_dict = torch.load("file.pth")

This is why you get dict has no to attribute because you’re expecting model to be a nn.Module object which it’s not, it’s currently a dict.

ok thank you I had find that earlier, but my model is maskrcnn 101 but I don’t find a torchvision.models.detection.maskrcnn_resnet101_fpn, it is not exists ?

From the documentation, you need access to the base nn.Module object in order to restore a given model from a pathfile. To quote the documentation,

“Notice that the load_state_dict() function takes a dictionary object, NOT a path to a saved object. This means that you must deserialize the saved state_dict before you pass it to the load_state_dict() function. For example, you CANNOT load using model.load_state_dict(PATH) .”

Wherever you got the .pt file from, you’ll need to find the corresponding model nn.Module object in order to restore the model using that .pt file. I don’t believe you can restore a model directly from a .pt file as stated in the documentation.