Installation
- Download Anaconda or Miniconda.
- After installation, open a terminal.
- Create a dedicated virtual environment.
- Install PyTorch according to your system and CUDA version.
# create a new environment
(base) $ conda create -n pytorch python=3.11
(base) $ conda activate pytorch
# install PyTorch (example with CUDA 12.6)
pip install torch==2.7.1 torchvision==0.22.1 torchaudio==2.7.1 --index-url https://download.pytorch.org/whl/cu126
Tensors and variables
A tensor is the main data structure in PyTorch. It can hold numeric values, be moved to CPU or GPU, and support automatic differentiation.
import torch
X = torch.randn(4, 5)
print(X.shape)
print(X.dtype)
print(X.device)
Common tensor creation APIs
torch.eye(4)
torch.zeros((4, 5))
torch.ones((4, 5))
torch.rand((4, 5))
torch.tensor([[1, 2], [3, 4]])
Tensor attributes
X.dtypeX.shapeX.deviceX.numpy()
Summary
PyTorch is a strong deep learning framework with an intuitive API, efficient tensor operations, and automatic differentiation for training neural networks.