Cannot import "BasicBlock" from torchvision.models.resnet

Viewed 443

I am trying to import the class BasicBlock from torchvision.models.resnet by doing this

from torchvision.models.resnet import *

It is giving no error but when I am trying to use BasicBlock class in my code (which is supposed to be imported already), I am getting the error that

NameError: name 'BasicBlock' is not defined

even though BasicBlock is present in torchvision.models.resnet

But it gives no error when I import like this

from torchvision.models.resnet import BasicBlock

and then use it in my code

Why am I getting this error?

2 Answers

BasicBlock is indeed defined, however it is not exported by the module: see here the definition of __all__. So torchvision/models/resnet.py only exports these: ResNet, resnet18, resnet34, resnet50, resnet101, resnet152, resnext50_32x4d, resnext101_32x8d, wide_resnet50_2, and wide_resnet101_2.

BasicBlock is imported under torchvision.models however it is not advisable to do import *and importing everything but incase you want to do that then use from torchvision.models import * you will not get the error.

import * imports everything under __all__ variable and this variable in resnet has ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101','resnet152', 'resnext50_32x4d', 'resnext101_32x8d','wide_resnet50_2', 'wide_resnet101_2'] that why it is throwing up error NameError for BasicBlock

Related