PyTorch Introduction I

Installation

  1. Download Anaconda or Miniconda.
  2. After installation, open a terminal.
  3. Create a dedicated virtual environment.
  4. 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.dtype
  • X.shape
  • X.device
  • X.numpy()

Summary

PyTorch is a strong deep learning framework with an intuitive API, efficient tensor operations, and automatic differentiation for training neural networks.

Related articles

PyTorch Introduction II

5. Objective Functions 6. Optimizers 7. Activation Functions 8. Multilayer Perceptron Jupyter Notebook Consider $\mathbf{y}\in \mathbb{R}^m$ to be the actual values we want to predict, and $\mathbf…

Training