Modulenotfounderror no module named torch in Python

TL; DR: Fix the no module named pytorch exception

You will get a modulenotfounderror exception when trying to invoke one of the pytorch modules before you have installed the torch package in your Python development environment. You can use the Anaconda prompt to invoke conda; or alternatively invoke the Python Package installer (pip) to install pytorch.

Understand the module not found error for pytorch

Pytorch is a a third party library that is not included in the Python standard library and therefore has to be installed independently. You will receive this error when invoking PyTorch modules such as: torch.cuda, torch_space, serialization, scatter, tensor, random etc’ if you haven’t installed pytorch in your Python development environment.

import torch
my_tensor = torch.rand (3,3)

You’ll receive the following exception (screenshot taken from Jupyter Lab – but you will get the same message in the iPython console of VS Code, PyCharm, Google Colab and Spyder)

Solve no module named pytorch error for CPU only installs

As we mentioned before, you can easily troubleshoot this error by installing pytorch.

If you are using Anaconda or miniconda and the conda Package Manager

  • Call the Anaconda Prompt in Windows or Terminal in macOS or Ubuntu
  • Type the following command to activate your conda environment:
conda activate <os_path_to_your_conda_env> 
  • Then install the pytorch library using the following command. This assumes that you will be using your CPU as the Compute Platform:
conda install pytorch cpuonly torchvision torchaudio  -c pytorch
  • When prompted hit Y and then enter.
  • Pytorch will be collected and installed.
  • Once installation is done close your Anaconda Prompt.
  • Return to your notebook and invoke the pytorch module.

If using the pip Package Manager on standard or virtual environments:

  • Invoke Terminal (for macOS or Ubuntu) or the Windows command prompt
  • Navigate to the install directory of the python.exe file.
  • Invoke pip 3 (Note: PyTorch doesn’t run on Python 2.X!) and type the following command:
pip3 install torch torchvision torchaudio
  • PyTorch will be installed.
  • Close Terminal or the Command Prompt.
  • Now you can invoke pytorch from your Jupyter Notebook or Python IDE.

Follow-up learning

How to verify if a pandas DataFrame column contains a specific value?