No module named "Torch"

I installed pytorch via

conda install pytorch-cpu torchvision-cpu -c pytorch

And I also tried

pip3 install https://download.pytorch.org/whl/cpu/torch-1.0.1-cp36-cp36m-win_amd64.whl

pip3 install torchvision

Both installed successfully!

But, it only works in jupiter notebook. Whenever I try to execute a script from the console, I get the error message: No module named "torch"

How can I fix this?


Solution 1:

Try to install PyTorch using pip:

First create a Conda environment using:

conda create -n env_pytorch python=3.6

Activate the environment using:

conda activate env_pytorch

Now install PyTorch using pip:

pip install torchvision 

Note: This will install both torch and torchvision.

Now go to Python shell and import using the command:

import torch
import torchvision

Solution 2:

I installed on my macos by the official command:

conda install pytorch torchvision -c pytorch

but when I follow the official verification I get the same problem like yours.

Then I create a conda virtual environment:

conda create --name learnpytorch python=3.5

and install pytorch inside the environment:

conda install pytorch torchvision -c pytorch

run the verification, it works.

Hope these could help you.

Solution 3:

You need to add this at the very top of your program

import torch

If this is not a problem execute this program on both Jupiter and command line and pretty much you will understand if you have a mismatch.

import sys
print(sys.executable)

Solution 4:

If you are using Anaconda Prompt, there is a simpler way to solve this.

conda install -c pytorch pytorch

Solution 5:

Welcome to SO,

please create a seperate conda environment

activate this environment conda activate myenv and than install pytorch in it.

Besides you can check which python you are currently using by which python