CodeBlanks Logo Icon CodeBlanks

What is PyTorch?

PyTorch is a deep learning library developed by Facebook.

What is PyTorch?

PyTorch is one of the most widely used libraries for deep learning. It offers three things:

  • Tensor: a multi-dimensional array like a NumPy array that can also run on the GPU.
  • Autograd: a system that automatically computes the derivatives of the operations performed.
  • nn: a toolbox of layers, loss functions and optimisers.
import torch
x = torch.tensor([1.0, 2.0, 3.0])
print(x * 2)          # tensor([2., 4., 6.])
print(x.sum().item()) # 6.0

Code runs line by line (eager); debugging is like ordinary Python.

item() and tolist()

To go from tensors to ordinary Python values, item() (single-element tensor) and tolist() (any shape) are used. They are handy when printing and saving outputs:

t = torch.tensor([[1, 2], [3, 4]])
print(t.sum().item())   # 10   (Python int)
print(t.tolist())       # [[1, 2], [3, 4]]
print(t.max().item())   # 4

On a multi-element tensor, item() raises an error.

Practice First tensor

Create torch.tensor([[1, 2, 3], [4, 5, 6]]). Print it multiplied by 10 with tolist(), then the sum of all elements with item().

Starter code

model.py
import torch

# buraya yaz

Sample solution

model.py
import torch

t = torch.tensor([[1, 2, 3], [4, 5, 6]])
print((t * 10).tolist())
print(t.sum().item())

Expected output

[[10, 20, 30], [40, 50, 60]]
21

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What are the two key features that set PyTorch apart from NumPy?

  • Shorter code and coloured output
  • Reading tables and plotting
  • There is no difference
  • GPU support and automatic differentiation Correct answer

Explanation: Tensors can be moved to the GPU and autograd computes gradients by itself.

2 Turn a single-element tensor into a Python number.

Question
toplam = t.sum().____()
Answer
toplam = t.sum().item()

Explanation: item() returns the value of a scalar tensor.

3 Match the concepts.

Term Meaning
torch.tensor Multi-dimensional array
autograd Automatic differentiation
torch.nn Layers and losses
tolist() To a Python list

All lessons in Advanced