Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't import torch in jupyter notebook

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.

like image 806
Shin Yu Wu Avatar asked Aug 31 '19 06:08

Shin Yu Wu


2 Answers

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
like image 178
trsvchn Avatar answered Sep 28 '22 16:09

trsvchn


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!.

like image 29
Ankita Jaiswal Avatar answered Sep 28 '22 16:09

Ankita Jaiswal