No module named ‘torchvision.models.utils‘

created at 12-12-2021 views: 147

Problem Description

When I use the environment of pytorch=1.10.0, torchvision=0.11.1 to run the code, I run to the statement from torchvision.models.utils import load_state_dict_from_url. The following error will appear when:

>>> from torchvision.models.utils import load_state_dict_from_url
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'torchvision.models.utils'

And this statement can run under pytorch=1.2.0, torchvision=0.4.0 and pytorch=1.6.0, torchvision=0.7.0.

Cause exploration

Related blog 1 stated:

The reason for the error is that the version 0.2 of torchvision is too low, just install a 0.4

Therefore, installing the corresponding version of torchvision can indeed solve this problem, and this syntax is not supported in the lower version and the latest version.

Refer to the source code analysis of different versions of torchvision.models, you can see the difference in code between the old and new versions when importing pre-trained models.


method 1

Install the corresponding torchvision version. The currently tested versions of 0.4.0~0.7.0 support this type of statement.

Method 2

To change the sentence to import the pre-trained model, you can learn from the import method 2 of the ResNet source code, use

import torch.utils.model_zoo as model_zoo


Import the pre-trained model.

Method 3

By consulting torchvision's code repository, there is another solution:

The original code from .utils import load_state_dict_from_url is not applicable.
you connot import load_state_dict_from_url from .utils.
change .utils to torch.hub can fix the problem.

About to change from torchvision.models.utils import load_state_dict_from_url to from torch.hub import load_state_dict_from_url
Note that this syntax is only for higher versions of pytorch.

created at:12-12-2021
edited at: 12-12-2021: