Home > Enterprise >  Python ModuleNotFoundError - No module named 'pytorch_net'
Python ModuleNotFoundError - No module named 'pytorch_net'

Time:12-30

I am trying to import a file from a folder named pytorch_net from a folder named AI_physicist into a script named models.py. I have tried to change the folder locations of the files, get an init.py file into the main AI_physicist folder, and change the sys.path.append command to get only the folder with the files inside of it. I have also looked at other posts and have tried their solutions but to no avail.

Here are the posts that I have found and have tried: What does os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)) mean? python

import python module using sys.path.append

file structure:

C:-----
  Users----
     trevo----
        Desktop----
          AI_physicist----
            pytorch_net----
            theory_learning----

Here is the error in its entirety:

No module named 'pytorch_net'
File "C:\Users\trevo\OneDrive\Desktop\AI_physicist\theory_learning\models.py", line 13, in <module>
    from pytorch_net.net import MLP
  File "C:\Users\trevo\OneDrive\Desktop\AI_physicist\theory_learning\theory_model.py", line 24, in <module>
    from AI_physicist.theory_learning.models import Loss_Fun_Cumu, get_Lagrangian_loss

And lastly here is the code that I am using:

models.py:

# coding: utf-8

# In[ ]:


import numpy as np
import torch
import torch.nn as nn
from torch.autograd import grad
import sys, os
sys.path.append(os.path.join(os.path.dirname("__file__"), '..', '..'))
from AI_physicist.pytorch_net.net import MLP
from AI_physicist.pytorch_net.util import get_criterion, MAELoss, to_np_array, to_Variable, Loss_Fun
from AI_physicist.settings.global_param import PrecisionFloorLoss, Dt
from AI_physicist.theory_learning.util_theory import logplus

Any help on what I would be missing would be very appreciated, thank you!

CodePudding user response:

Try to put __init__.py not init.py in that folder.

Alternatively: sys.path.append(f'{os.path.dirname(__file__)}\\folder_name') Please look on the difference between my and yours sys.append. That should always work. Bare in mind these will work only if your script is in a subfolder of your main folder with main.py in.

  • Related