PyTorch 2 cheatsheet

PyTorch 2: Tensors

8 common PyTorch 2 tasks.

Install PyTorch

Install the library. Choose your CUDA version at pytorch.org/get-started for GPU builds.

pip install torch torchvision

Import PyTorch

The standard imports for building models.

import torch
import torch.nn as nn

Create tensors

Create tensors from data, zeros, ones or random values.

x = torch.tensor([[1.0, 2.0], [3.0, 4.0]])
zeros = torch.zeros(3, 4)
rand = torch.rand(2, 3)

Check shape, type and device

Inspect a tensor's properties.

x.shape, x.dtype, x.device

Reshape a tensor

Change the shape. -1 infers one dimension.

x.reshape(-1, 2)
x.unsqueeze(0)
x.squeeze()

Convert to and from NumPy

Share memory with NumPy arrays on the CPU.

t = torch.from_numpy(arr)
arr = t.numpy()

Multiply matrices

Matrix multiplication with the @ operator.

y = a @ b

Pick the best device

Use a GPU if available, including Apple Silicon.

device = (
    "cuda" if torch.cuda.is_available()
    else "mps" if torch.backends.mps.is_available()
    else "cpu"
)
x = x.to(device)

Was this page helpful?