How to Install PyTorch: Easy Steps for Beginners
To install
PyTorch, use the command pip install torch torchvision torchaudio for CPU-only version or visit the official site to get the right command for your system and GPU support. Alternatively, use conda install pytorch torchvision torchaudio -c pytorch if you prefer conda environments.Syntax
Use pip or conda commands to install PyTorch. The basic syntax includes the package names torch, torchvision, and torchaudio. You can add options for CUDA support if you have an NVIDIA GPU.
bash
pip install torch torchvision torchaudio # or using conda conda install pytorch torchvision torchaudio -c pytorch
Example
This example shows how to install the CPU-only version of PyTorch using pip and verify the installation by printing the PyTorch version.
bash
pip install torch torchvision torchaudio
python -c "import torch; print(torch.__version__)"Output
2.0.1
Common Pitfalls
- Trying to install PyTorch without specifying the right CUDA version for your GPU can cause errors or fallback to CPU-only.
- Using outdated pip or conda versions may fail the installation.
- Not activating your virtual environment before installing can lead to package conflicts.
Always check your Python version and update pip with pip install --upgrade pip before installing PyTorch.
bash
## Wrong way: Installing without upgrading pip pip install torch torchvision torchaudio ## Right way: Upgrade pip first pip install --upgrade pip pip install torch torchvision torchaudio
Quick Reference
Here is a quick summary of commands to install PyTorch:
| Method | Command | Notes |
|---|---|---|
| pip (CPU only) | pip install torch torchvision torchaudio | Simple, no GPU support |
| pip (with CUDA) | Use command from https://pytorch.org/get-started/locally/ | Select CUDA version for GPU |
| conda (CPU only) | conda install pytorch torchvision torchaudio -c pytorch | Works well in conda envs |
| conda (with CUDA) | conda install pytorch torchvision torchaudio pytorch-cuda=11.8 -c pytorch -c nvidia | For NVIDIA GPU support |
Key Takeaways
Use pip or conda commands to install PyTorch depending on your environment.
Check your system's CUDA version if you want GPU support and get the right install command from the official site.
Always upgrade pip before installing to avoid errors.
Activate your virtual environment before installing to keep packages organized.
Verify installation by importing torch and printing its version.