PyTorch Intro
PyTorch is a Python library for building and training models. It stores numbers in tensors and tracks maths to find gradients.
A first tensor
A tensor is a container that holds numbers. This tensor holds one row of three numbers.
import torch
x = torch.tensor([1.0, 2.0, 3.0])
print(x)Adding tensors
Maths on tensors works cell by cell. Matching cells are added together.
a = torch.tensor([1.0, 2.0])
b = torch.tensor([10.0, 20.0])
print(a + b)A gradient in action
A gradient shows how much the answer moves when the input moves. The flag requires_grad=True asks PyTorch to track the maths.
x = torch.tensor(3.0, requires_grad=True)
y = x * x
y.backward()
print(x.grad)Example
import torch
print("Welcome to PyTorch")
values = torch.tensor([2.0, 3.0, 5.0])
print(values)
print(values * 2)Key points
- PyTorch: a Python library that stores numbers in tensors and finds gradients for training
- Use import torch to load PyTorch in a program
- Use torch.tensor to build a tensor from a list
- Gradient: a number that shows how much the answer moves when an input moves
- Autograd: the part of PyTorch that tracks maths and fills in gradients
- Use backward() to ask for the gradients of a finished calculation
In this example, the program prints a welcome line first. It then builds a tensor with three decimal numbers. The next line prints the tensor. The last line doubles every number in the tensor and prints the doubled tensor.
Try it Yourself
Edit the code, then press Run.
Running is simulated Β· Python Playground
Exercise
What is a tensor in PyTorch?