Solve the torch not defined nameerror
Make sure to import the PyTorch machine learning library into your Jupyter or Colab notebook before invoking it from your code.
import torch
tensor_1 = torch.rand (4,4)
How to reproduce the error?
Suppose that you have written the following Python code at the beginning of your script running on PyCharm, VSCode, Jupyter or Colab:
tensor_1 = torch.rand (4,4)
Running the command will cause a NameError exception as shown below:
Why do i get torch is not defined error?
PyTorch is a third party library that is not part of the Python core library and hence it has to be imported to your development environment before calling any of its modules.
In order to fix the NameError torch is not defined exception – make sure to import PyTorch into your environment before using it:
import torch
tensor_1 = torch.rand (4,4)
No Module named Torch in Python
You might encounter a somewhat related error when you try to import PyTorch into your notebook or script. If this is the first time you are using PyTorch in a Python virtual environment or Anaconda environment, you first need to make sure to install the PyTorch package. Otherwise you will receive a module not found error:
ModuleNotFoundError: No module named 'torch'