How to import a class from another file?

I don’t want to have my net structure in the main/training file. Therefore I created a new file in the same folder. In that files I created the net class AlexNet.

Thats my Net file:

import torch.nn as nn

class AlexNet(nn.Module):

    def __init__(self, num_classes=3):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.MaxPool2d(kernel_size=3, stride=2),
        self.classifier = nn.Sequential(
            nn.Linear(256 * 7 * 7, 4096),
            nn.Linear(4096, 4096),
            nn.Linear(4096, num_classes),

    def forward(self, x):
        x = self.features(x)
        x = x.view(x.size(0), 256 * 7 * 7)
        x = self.classifier(x)
        return x

And thats how I want to import the class in the main file:

from .Net import AlexNet

Net is the name of the file with the AlexNet class in. When I want to run this I get the following error:

ModuleNotFoundError: No module named '__main__.Net'; '__main__' is not a package

I already tried it with a empty file in the same folder but it changed nothing.

Try to remove the dot in front of Net:

from Net import AlexNet

It works like that but then I get red underlings under Net and AlexNet of the statement from Net import AlexNet. With the message unresolved reference ‘AlexNet’

Does your IDE give you any hints on why it’s complaining?
If it’s working, I would just ignore it.

I use pycharme as IDE and the hint is Unresolved reference ‘AlexNet’. Yeah I know I can ignore that but its marked like an error. And I would like to know the reason for that.

Sorry, I’m not using Pycharm, but maybe this could help?

1 Like

Ty for your help again.