Home > Net >  pytorch gives me an error when I don't run it in ~/ directory
pytorch gives me an error when I don't run it in ~/ directory

Time:06-29

When I run the following python script in an subdirectory, for example ~/test_dir, python results in an error :

import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 1 input image channel, 6 output channels, 5x5 square convolution
        # kernel
        self.conv1 = nn.Conv2d(1, 6, 5)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx   b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)  # 5*5 from image dimension
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # Max pooling over a (2, 2) window
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # If the size is a square, you can specify with a single number
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = torch.flatten(x, 1) # flatten all dimensions except the batch dimension
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x


net = Net()
print(net)
 

Error msg:

Traceback (most recent call last):
  File "/Users/xxxxxxx/torch/torch.py", line 1, in <module>
    import torch
  File "/Users/xxxxxxx/torch/torch.py", line 2, in <module>
    import torch.nn as nn
ModuleNotFoundError: No module named 'torch.nn'; 'torch' is not a package 

If I run the same file in the home directory ~/ it does not result in the error message shown above.

➜  ~ python3 test.py
Net(
  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))
  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
  (fc1): Linear(in_features=400, out_features=120, bias=True)
  (fc2): Linear(in_features=120, out_features=84, bias=True)
  (fc3): Linear(in_features=84, out_features=10, bias=True)
)
➜  ~ which python3
/Library/Frameworks/Python.framework/Versions/3.9/bin/python3

I did not encounter any similar errors with other packages, so I assume it is caused by pytorch.

I would appreciate any help or hint on how to solve this.

CodePudding user response:

It seems that you named your working directory and a script torch. It causes a conflict with the installed Pytorch library, therefore you're calling your torch, not the installed one.

Try it after changing the names of your directory and script.

  • Related