Can't import torch in jupyter notebook

42,610

Solution 1

You have to install jupyter in addition to pytorch inside your activated conda env. Here is installation steps:

1. Create conda env

for example: pytorch_p37 with python 3.7:

user@pc:~$ conda create -n pytorch_p37 python=3.7

2. Activate it

user@pc:~$ conda activate pytorch_p37

Or with (for older conda versions):

user@pc:~$ source activate pytorch_p37

Now you should see (pytorch_p37) before your shell prompt:

(pytorch_p37) user@pc:~$ 

3. Go to PyTorch website and choose appropriate installation command via conda. Run it in your shell, for example

(pytorch_p37) user@pc:~$ conda install pytorch torchvision -c pytorch

4. Install jupyter inside your activated env as well

(pytorch_p37) user@pc:~$ conda install jupyter

5. Verify the installation

(pytorch_p37) user@pc:~$ conda list

# packages in environment at /home/user/anaconda3/envs/pytorch_p37:
#
# Name
...
jupyter                   1.0.0  
jupyter_client            5.3.1  
jupyter_console           6.0.0 
jupyter_core              4.5.0
...
python                    3.7.4
pytorch                   1.2.0
...

6. Run jupyter

(pytorch_p37) user@pc:~$ jupyter notebook

Solution 2

I had the same problem where the jupyter lab couldn't import torch after successful installation in my virtual environment. But when I checked the list of installed packages using conda list, PyTorch was present but not jupyterlab. After installing jupyterlab, it is working fine!.

Share:
42,610
Shin Yu Wu
Author by

Shin Yu Wu

Updated on February 10, 2022

Comments

  • Shin Yu Wu
    Shin Yu Wu about 2 years

    System: macOS 10.13.6 Python: 3.7 Anaconda3

    I have trouble when import torch in jupyter notebook.

    ModuleNotFoundError: No module named 'torch'
    

    Here is how I install pytorch:

    conda install pytorch torchvision -c pytorch
    

    I've checked PyTorch is installed in my anaconda environment:

    enter image description here

    When I command python3 in my terminal and import torch, it works. But not work in jupyter notebook

    I've tried:

    conda update conda
    conda install mkl=2018
    

    But still the same error.

    Can anyone help me with this? Thanks!!