Search code examples
pythonjupyter-notebookpytorchanaconda

No module named 'torch' in Jupyter Notebook


I am fairly new to using jupyter notebook, and I've read every forum available for this issue, with no luck.

I am running Windows 11, and I installed Anaconda, then created and activated a virtual environment called pytorchenv. My .yml file includes the following

name: pytorchenv channels:

  • defaults
  • pytorch dependencies:
  • numpy=1.16.2
  • pandas=0.24.2
  • matplotlib=3.0.3
  • pillow=5.4.1
  • pip=19.0
  • plotly=3.7.0
  • scikit-learn=0.20.3
  • seaborn=0.9.0
  • python=3.7.3
  • jupyter=1.0.0
  • pytorch=1.1.0
  • torchvision=0.2.2

If I list all of the included packages in the command prompt, using

conda list -n pytorch

it shows that pytorch is installed as...

Name                    Version                   Build  Channel
pytorch                   1.1.0           py3.7_cuda100_cudnn7_1    pytorch

What's more, if I enable the virtual environment in the Command Prompt, It seems that I am able to import pytorch successfully

C:\\Users\\Xxxx\>conda activate pytorchenv

(pytorchenv) C:\\Users\\Xxxx\>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) \[MSC v.1915 64 bit (AMD64)\] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>import torch
>>>

However, when I try to import pytorch into jupyter notebook, I get the message

import torch
ModuleNotFoundError                       
Traceback (most recent call last)
Input In \[1\], in \<cell line: 1\>()
1 import torch
ModuleNotFoundError: No module named 'torch'

I have been able to import pandas and numpy in jupyter notebook without issue, but I have not figured out a way to import pytorch successfully.

In case this is helpful, jupyter notebook shows that it is running on

Python 3 (ipykernel)

and running the following in jupyter notebook

import sys
print(sys.executable)

results in

C:\\Users\\Nathaniel\\anaconda3\\python.exe

I've tried checking if there were multiple versions of jupyter notebook on my computer (there aren't).

I also checked that pytorch is installed in the same place as my other anaconda packages (it is).

What am I doing wrong?


Solution

  • The notebook is running with your base environment, as indicated by sys.executable.

    Two methods:

    • Start Jupyter from your environment
    • Register your environment to be usable by all jupyter notebooks
      For that you can find the necessary steps here

    Basic step is this

    source activate pytorchenv   # or activate the environment via conda
    python -m ipykernel install --user --name pytorchenv --display-name "Python (pytorchenv)"
    

    Afterwards be sure to restart Juypter, then you should be able to select your pytorchenv kernel.