Chaeun Lee
Chaeun Lee

Reputation: 61

Unable to import Pytorch module in Jupyter Notebook

I installed pytorch using conda command when the virtual env was activated.

But, there are some problems when I import torch modules in Jupyter Notebook.

I checked the sys.path both in the prompt and in Jupyter Notebook.

Well.. in the prompt, the result of sys.path is

['', '/home/usrname/anaconda3/lib/python36.zip',
     '/home/usrname/anaconda3/lib/python3.6',
     '/home/usrname/anaconda3/lib/python3.6/lib-dynload',
     '/home/usrname/anaconda3/lib/python3.6/site-packages']

and there are no errors when I import torch modules.

But, in the jupyter notebook(executed in chrome), the sys.path is

['',
 '/home/usrname/anaconda3/lib/python36.zip',
 '/home/usrname/anaconda3/lib/python3.6',
 '/home/usrname/anaconda3/lib/python3.6/lib-dynload',
 '/home/usrname/anaconda3/lib/python3.6/site-packages',
 '/home/usrname/anaconda3/lib/python3.6/site-packages/IPython/extensions',
 '/home/usrname/.ipython']

and I see an error: No module named 'torch'

I can't solve this problem...

Upvotes: 6

Views: 30937

Answers (6)

Amit Pathak
Amit Pathak

Reputation: 1367

I had the same issue while I was running the notebook instance in a python virtual environment.

$ python3 -m venv myenv
$ source myenv/bin/activate
$ jupyter notebook

After this, I ran !pip3 install torch. While it got installed successfully, I was getting the error No module named 'torch'. Restarting the kernel did not work for me so I ran the following command and restarted the Jupyter notebook instance.

$ pip3 install ipykernel
$ jupyter notebook

Strangely, I was facing some issue trying to start the notebook instance. However, reinstalling notebook using pip3 install jupyter worked for me and I could import the library successfully.

Upvotes: 0

Anj
Anj

Reputation: 157

Use below command-

conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch

Upvotes: 1

vjc
vjc

Reputation: 11

  1. Go to anaconda.navigator -> environments -> base(root) -> select not installed -> search 'torch' -> install 2.run 'import torch' in your jupyter notebook!

Upvotes: 1

Caíque Coelho
Caíque Coelho

Reputation: 461

This works for me:

1.Create a conda virtual environment:

conda create -n env_pytorch python=3.6

2.Active this environment create above:

source activate env_pytorch

3.Install PyTorch with pip or pip3:

pip install torchvision --user

Upvotes: 1

Fan
Fan

Reputation: 1

You need to create a kernel in the virtual envs and choose that kernel in the jupyter.

Upvotes: 0

MLDev
MLDev

Reputation: 356

I had the same issues with this but managed to solve the problem. I think PyTorch has an 'issue' with the regular Jupyter application in Anaconda, so I urge you to first install the numpy jupyter notebook that supports PyTorch, then you can launch you notebook again. Use (while in your virtual env path):

conda install numpy jupyter notebook

Hope this helps.

Upvotes: 11

Related Questions