Skip to content

Artificial IntelligencePyTorch from scratch

0. PyTorch fundamentals

Guide · PyTorch, Tensors, Broadcasting · updated on 24/11/2026

Author: Ángel Fernández Caravaca
Date: March 12, 2026

What is PyTorch?

PyTorch is an open source deep learning framework, originally developed by Meta's AI research lab (FAIR). It has become the dominant tool in both academic research and production environments, thanks to its Python-centred design philosophy, its flexibility for rapid prototyping and its performance in large-scale training.

At its core, PyTorch is built on two fundamental abstractions:

  • torch.Tensor: the main data structure, functionally equivalent to NumPy's ndarray, but designed for hardware-accelerated parallel computation (NVIDIA GPUs through CUDA, Apple Silicon through MPS).
  • torch.autograd: an automatic differentiation engine that records every operation on tensors and computes gradients through backpropagation, the mathematical basis of neural network training.

The architectural advantage: dynamic computational graphs

PyTorch's most defining architectural feature is its implementation of dynamic computational graphs (also known as the Define-by-Run paradigm).

Unlike older frameworks (e.g. the early versions of TensorFlow 1.x), which required you to build a static, precompiled computation graph before any data passed through it, PyTorch builds the graph on the fly, operation by operation, as the Python code runs.

This design offers key engineering advantages:

Feature Static graph Dynamic graph (PyTorch)
Debugging Requires special tools Native Python debuggers (pdb, print)
Control flow Must be coded in the graph's DSL Standard Python if, for, while
Interoperability Often isolated Direct integration with NumPy, Pandas, SciPy
Flexibility Limited Ideal for variable-length sequences and recursive models
  • Native debugging: since execution is immediate, you can use standard Python debuggers (such as pdb) and simple print calls to inspect the values of tensors and their gradients at any step.
  • Control-flow flexibility: it natively supports standard Python control flow (if, for, while) inside the model's forward pass, which makes it structurally ideal for complex architectures such as recurrent networks with variable-length sequences or recursive structures.
  • Ecosystem interoperability: it avoids creating an isolated sub-language, which guarantees zero-copy interoperability with libraries such as NumPy, Pandas and SciPy.

Tensors and ranks:

A tensor is a generalisation of scalars, vectors and matrices to an arbitrary number of dimensions. In PyTorch, any piece of data is represented as a torch.Tensor. The rank of a tensor is its number of dimensions (ndim):

  • Rank-0 tensor \(\rightarrow\) () \(\rightarrow\) No dimensions, a mathematical scalar.
  • Rank-1 tensor \(\rightarrow\) (N,) \(\rightarrow\) A flat 1D array/vector, with no implicit row or column orientation.
  • Rank-2 tensor \(\rightarrow\) (H, W) or (Batch, Features) \(\rightarrow\) A 2D matrix, including explicit row (1, N) and column (N, 1) vectors.
  • Rank-3 tensor \(\rightarrow\) (C, H, W) \(\rightarrow\) A 3D tensor, such as a multichannel spatial matrix (a single image) or a temporal sequence of embeddings.
  • Rank-4 tensor \(\rightarrow\) (B, C, H, W) \(\rightarrow\) A 4D tensor, usually representing a batch of 3D tensors; it is the standard input format for most neural network layers.
Tensors

Understanding a tensor's rank is essential, because most neural network layers impose strict dimensional requirements. For example, Conv2d always expects a rank-4 input.

Data types

PyTorch supports a very comprehensive type system for tensors. The numeric suffix (8, 16, 32, 64) indicates the number of bits used to store each value:

  • More bits → greater precision or range, but more memory use and slower computation.
  • Fewer bits → less memory and higher throughput (especially on GPU), at the cost of numerical precision.

The u prefix (e.g. uint8) indicates unsigned types: they only accept zero and positive integers, which doubles the representable positive range compared with their signed equivalent.

PyTorch default types: float32 for floating-point tensors and int64 for integer tensors. NumPy, on the other hand, uses float64 by default, which can cause silent precision mismatches when combining the two.

Common types:

Type Bits Use
torch.bool 1 Boolean masks
torch.int8 / uint8 8 Quantised models, image pixel values
torch.float16 / bfloat16 16 Mixed-precision training
torch.float32 32 Default for network weights
torch.float64 64 High-precision scientific computing

Type conversion is done with .to(dtype=...) or with convenience methods such as .float(), .int() or .bool().

Tensor indexing and slicing

PyTorch follows NumPy's indexing conventions. Tensors can be accessed with standard Python slicing notation [start:stop:step] along any dimension.

Key concepts:

  • Row selection: tensor[i, :] selects the whole i-th row.
  • Column selection: tensor[:, j] selects the whole j-th column.
  • Sub-tensor extraction: tensor[-2:, -2:] extracts the bottom-right 2×2 block using negative indices.
  • Boolean masks: a boolean tensor of the same shape can be used to filter the elements that meet a condition (tensor[tensor > 5]).
  • torch.where(condition): returns the indices of the elements that meet a condition, analogously to np.where.
  • torch.masked_select(tensor, mask): extracts a flat 1D tensor with all the elements where the mask is True.

Shape manipulation

Changing the shape of tensors is a fundamental operation in any deep learning pipeline. PyTorch offers several tools:

reshape / view

Both change the logical shape of a tensor without modifying the underlying data. The total number of elements must be preserved.

  • .view() requires the tensor to be contiguous in memory (that is, its logical layout must match its physical layout in memory).
  • .reshape() is more permissive: it calls .contiguous() internally if needed, so it is safer for general use.

squeeze / unsqueeze

These operations add or remove size-1 dimensions without changing the volume of data.

  • .unsqueeze(dim): inserts a new axis at position dim.
  • .squeeze(dim): removes the axis at position dim if its size is 1.

Their main use is to guarantee dimensional compatibility with the network's layers and with the broadcasting rules. For example, a single image of shape (C, H, W) must be turned into (1, C, H, W) with unsqueeze before going into a Conv2d layer.

permute / transpose

  • .permute(*dims): reorders all the dimensions at once from their positional indices (a generalisation of the transpose).
  • .T: reverses the order of all the dimensions (only reliable and not deprecated on 2D tensors).

Warning

Both .permute() and .T on tensors of rank > 2 produce non-contiguous tensors (they reorder the strides without moving bytes), which will make .view() raise a RuntimeError. The fix is .contiguous().view(...).

Memory: views, clones and contiguity

Understanding who owns the memory is key to writing correct code and debugging it.

Operation Copies memory? Shares the underlying data?
.view() No Yes: changes propagate
.reshape() Sometimes Usually yes
.clone() Yes No: a completely independent copy
.numpy() No Yes: zero-copy bridge
torch.from_numpy() No Yes: zero-copy bridge
torch.tensor(np_array) Yes No: strict copy

The zero-copy bridge between PyTorch and NumPy (through .numpy() and torch.from_numpy()) means that modifying the NumPy array also modifies the tensor, and vice versa. Use .clone() before converting when you need them to be independent.

Contiguity: a tensor is contiguous when its elements are stored sequentially in memory in the same order as their logical indexing. Operations such as .T and .permute() alter the strides (the jump between elements in memory) without physically moving the data, and produce non-contiguous tensors.

Aggregation and reduction operations

PyTorch offers a wide set of aggregation functions: .sum(), .mean(), .std(), .min(), .max(), .argmin(), .argmax().

A key parameter is dim, which indicates the axis along which the reduction is applied:

  • For a tensor of shape (B, C, H, W):
  • tensor.sum(dim=0) collapses the batch dimension → resulting shape (C, H, W).
  • tensor.mean(dim=1) collapses the channel dimension → resulting shape (B, H, W).

The keepdim=True argument keeps the reduced dimension as a size-1 axis, which is essential for broadcasting in later operations (e.g. standardising by subtracting each row's mean without causing shape errors).

Broadcasting

Broadcasting is a mechanism that lets PyTorch perform arithmetic operations between tensors of different but compatible shapes without explicitly replicating the data.

Two shapes are compatible for broadcasting if, aligned from the right, each pair of dimensions is equal or one of them is 1. For example:

1
2
3
(4, 3)  +  (1, 3)  →  (4, 3)   ✓ — the (1, 3) tensor is "virtually" replicated across every row
(4, 1)  +  (1, 3)  →  (4, 3)   ✓ — outer-product-style expansion
(4, 3)  +  (4,)    →  ERROR     ✗ — the shapes don't line up from the right

Broadcasting avoids explicit loops and duplicated memory, which lets you write concise and efficient vectorised code. A practical example is generating a multiplication table as a (10, 10) tensor through the outer product of a (10, 1) column vector and a (1, 10) row vector.

Concatenating vs. stacking

Both operations combine several tensors, but they differ in a fundamental way:

Operation Effect on the shape New dimension?
torch.cat([t1, t2], dim=d) Grows an existing dimension No
torch.stack([t1, t2], dim=d) Inserts a new dimension at position d Yes

For tensors of shape (2, 4): - torch.cat([...], dim=0) → (6, 4): stacks rows. - torch.cat([...], dim=1) → (2, 12): stacks columns. - torch.stack([...], dim=0) → (3, 2, 4): creates a new leading dimension.

torch.cat requires the shapes to match in every dimension except the concatenation axis. Tensors of different rank can't be concatenated directly: they must first be aligned with unsqueeze.

Sparse tensors

In many real cases (natural language processing, graph neural networks, recommender systems), data matrices are almost entirely full of zeros. Storing them as dense tensors wastes memory and computation.

PyTorch supports sparse tensors in COO format (Coordinate format), which only store the indices and values of the non-zero elements:

Dense:    [[0, 0, 0], [0, 5, 0], [0, 0, 3]]
Sparse:   indices=[[1,2],[1,2]], values=[5, 3]

When are sparse tensors worth it?

  • Memory efficiency: only relevant with high sparsity ratios (usually > 90 % zeros), since the cost of storing the indices must be offset by the saving on zeros.
  • Computation speed-up: specialised sparse operators (e.g. torch.smm) skip arithmetic with zeros entirely.

Reproducibility and random seeds

Training neural networks involves stochastic operations (random weight initialisation, data shuffling, dropout). Without controlling randomness, results can't be reproduced between runs, and debugging, comparison and publication are no longer reliable.

torch.manual_seed(seed) initialises the pseudo-random number generator (PRNG) in a deterministic state. Any call to a random function after setting the seed will always produce the same sequence of values.

Why is reproducibility critical?

  1. Debugging: it lets you isolate whether a training run's behaviour is due to code changes or to random variation.
  2. Fair comparison: it guarantees that two variants of a model start from identical conditions.
  3. Scientific integrity: it lets others replicate published results exactly.

Tip

Full reproducibility in multi-GPU environments requires additional steps: setting the seed for numpy and random, and setting torch.backends.cudnn.deterministic = True.


Installation

Create your conda/Python environment for PyTorch and follow these instructions. Bear in mind that:

  • Python version \(\geq\) 3.10
  • GPU or CPU: if you want to use PyTorch on your GPU, you must install it with CUDA support. To find out the highest CUDA version your current drivers support, run nvidia-smi in the terminal and look at the "CUDA Version" field in the top right corner.

Exercises

Use the official documentation while solving the exercises. All of them can be solved with just import torch.

Exercise 0

Check your PyTorch version and the available CUDA devices (their names).

Show solution
import torch

# 0. PyTorch version:
print(f'PyTorch version: {torch.__version__}')

if torch.cuda.is_available():
    number_of_devices = torch.cuda.device_count()
    print(f'There are {number_of_devices} CUDA devices.')
    for i in range(number_of_devices):
        print(f'Device ({i}): {torch.cuda.get_device_name(i)}')
else:
    print(f'There are no available devices')
Output
1
2
3
PyTorch version: 2.10.0+cu130
There are 1 CUDA devices.
Device (0): NVIDIA GeForce RTX 3050 Ti Laptop GPU

Exercise 1

Create a tensor of zeros of shape (3,4), a tensor of ones of shape (2,2,2) and a tensor of random values of shape (5,5).

Show solution
# Tensor of zeros:
zeros_tensor = torch.zeros((3,4))
H,W = zeros_tensor.shape
print(f'Zeros tensor of shape {H, W} (Rank {zeros_tensor.ndim})')
print(zeros_tensor)
print('-----'*10)

# Tensor of ones:
ones_tensor = torch.ones((2,2,2))
C, H, W = ones_tensor.shape
print(f'Ones tensor of shape {C,H,W} (Rank {ones_tensor.ndim})')
print(ones_tensor)
print('-----'*10)

# Tensor of random values:
random_tensor = torch.rand((5,5)) # rand --> Uniform values in [0,1); randn --> normally distributed values (mean: 0, std: 1)
H,W = random_tensor.shape
print(f'Random tensor of shape {H, W} (Rank {random_tensor.ndim})')
print(random_tensor)
print('-----'*10)
Output
Zeros tensor of shape (3, 4) (Rank 2)
tensor([[0., 0., 0., 0.],
        [0., 0., 0., 0.],
        [0., 0., 0., 0.]])
--------------------------------------------------
Ones tensor of shape (2, 2, 2) (Rank 3)
tensor([[[1., 1.],
         [1., 1.]],

        [[1., 1.],
         [1., 1.]]])
--------------------------------------------------
Random tensor of shape (5, 5) (Rank 2)
tensor([[0.2861, 0.3519, 0.7477, 0.8301, 0.2608],
        [0.5543, 0.0464, 0.9719, 0.9535, 0.7934],
        [0.2176, 0.1497, 0.0542, 0.3513, 0.3675],
        [0.7323, 0.8206, 0.7207, 0.9941, 0.7988],
        [0.1230, 0.6500, 0.3912, 0.2492, 0.3577]])
--------------------------------------------------

Exercise 2

Given two tensors a=[1,2,3] and b = [4,5,6], compute their sum, their difference, their element-wise product and their matrix product.

Note: torch.matmul is more versatile than torch.dot. Whereas torch.dot strictly computes the dot product of two 1D vectors, torch.matmul supports matrix multiplication and batched operations with higher-dimensional tensors (rank 1 or above).

Show solution
# Define a and b as tensors:
a = torch.tensor([1,2,3])
b = torch.tensor([4,5,6])

print(f'Tensors:')
print(a, b)
print('-----'*10)

# Sum:
c = torch.add(a,b) # = a + b
print(f'Sum: {c}')
print('-----'*10)

# Difference:
c = torch.sub(a,b) # = a - b
print(f'Difference: {c}')
print('-----'*10)

# Element-wise product:
c = torch.mul(a, b) # = a*b
print(f'Element-wise product: {c}')
print('-----'*10)

# Matrix product:
c = torch.matmul(a, b) #  = a@b ; torch.matmul is more complete than torch.dot
print(f'Matrix product: {c}')
Output
Tensors:
tensor([1, 2, 3]) tensor([4, 5, 6])
--------------------------------------------------
Sum: tensor([5, 7, 9])
--------------------------------------------------
Difference: tensor([-3, -3, -3])
--------------------------------------------------
Element-wise product: tensor([ 4, 10, 18])
--------------------------------------------------
Matrix product: 32

Exercise 3

Create a tensor of shape (4,4) with values from 1 to 16 and extract: - The second row. - The third column. - The bottom-right 2x2 sub-tensor.

Show solution
# Create the tensor:
tensor = torch.arange(1, 17).reshape(4, 4)
print(f'Original:\n', tensor)
print('-----'*10)

# Second row
second_row = tensor[1, :]
print(f'Second raw:\n', second_row)
print('-----'*10)

# Third column
third_column = tensor[:, 2]
print(f'Third column:\n', third_column)
print('-----'*10)

# Sub-tensor:
subtensor = tensor[-2:, -2:]
print(f'2x2 subtensor:', subtensor)
Output
Original:
 tensor([[ 1,  2,  3,  4],
        [ 5,  6,  7,  8],
        [ 9, 10, 11, 12],
        [13, 14, 15, 16]])
--------------------------------------------------
Second raw:
 tensor([5, 6, 7, 8])
--------------------------------------------------
Third column:
 tensor([ 3,  7, 11, 15])
--------------------------------------------------
2x2 subtensor: tensor([[11, 12],
        [15, 16]])

Exercise 4

Create a tensor of shape (2,3,4), change it to (6,4), then to (24,) and back to (2,3,4).

Show solution
# Create the tensor:
tensor = torch.randn((2,3,4))
C, H, W = tensor.shape
print(f'Original: Shape {C,H,W} --> (Rank {tensor.ndim})')
print(tensor)
print('-----'*10)

# Reshape (6,4)
tensor64 = torch.reshape(tensor, (6,4))
H, W = tensor64.shape
print(f'Reshape 1: Shape {H,W} --> (Rank {tensor64.ndim})')
print(tensor64)
print('-----'*10)

# Reshape (24, )
tensor24 = torch.reshape(tensor64, (24,))
H = tensor24.shape[0]
print(f'Reshape 2: Shape {H,} --> (Rank {tensor24.ndim})')
print(tensor24)
print('-----'*10)
Output
Original: Shape (2, 3, 4) --> (Rank 3)
tensor([[[ 0.7857, -0.6520, -1.0382,  1.7333],
         [ 0.7122,  0.6091,  0.3604,  1.1149],
         [-1.1315, -1.8505, -0.1439,  1.0320]],

        [[ 1.3702, -0.1992,  0.0673, -1.2631],
         [-0.5917,  0.3701,  0.2839,  0.2437],
         [ 0.1191, -0.1460, -0.0730, -0.6370]]])
--------------------------------------------------
Reshape 1: Shape (6, 4) --> (Rank 2)
tensor([[ 0.7857, -0.6520, -1.0382,  1.7333],
        [ 0.7122,  0.6091,  0.3604,  1.1149],
        [-1.1315, -1.8505, -0.1439,  1.0320],
        [ 1.3702, -0.1992,  0.0673, -1.2631],
        [-0.5917,  0.3701,  0.2839,  0.2437],
        [ 0.1191, -0.1460, -0.0730, -0.6370]])
--------------------------------------------------
Reshape 2: Shape (24,) --> (Rank 1)
tensor([ 0.7857, -0.6520, -1.0382,  1.7333,  0.7122,  0.6091,  0.3604,  1.1149,
        -1.1315, -1.8505, -0.1439,  1.0320,  1.3702, -0.1992,  0.0673, -1.2631,
        -0.5917,  0.3701,  0.2839,  0.2437,  0.1191, -0.1460, -0.0730, -0.6370])
--------------------------------------------------
1
2
3
4
5
6
# Back to the original shape:
tensor = torch.reshape(tensor24, (2,3,4))
C, H, W = tensor.shape
print(f'Back to Original: Shape {C,H,W} --> (Rank {tensor.ndim})')
print(tensor)
print('-----'*10)
Output
1
2
3
4
5
6
7
8
9
Back to Original: Shape (2, 3, 4) --> (Rank 3)
tensor([[[ 0.7857, -0.6520, -1.0382,  1.7333],
         [ 0.7122,  0.6091,  0.3604,  1.1149],
         [-1.1315, -1.8505, -0.1439,  1.0320]],

        [[ 1.3702, -0.1992,  0.0673, -1.2631],
         [-0.5917,  0.3701,  0.2839,  0.2437],
         [ 0.1191, -0.1460, -0.0730, -0.6370]]])
--------------------------------------------------

Exercise 5

Create a tensor from the Python list [1,2,3,4,5]. Then create the same tensor from a NumPy array. Convert the tensor back to NumPy. Do they share memory?

Show solution
# Create the list:
python_list = [1,2,3,4,5]
print(f'Original Python list:')
print(f'Type: {type(python_list)}')
print(python_list)
print('-----'*10)

# Tensor from the Python list:
tensor = torch.tensor(python_list)
print(f'Tensor from Python list:  ')
print(f'Type: {type(tensor)}')
print(tensor)
print('-----'*10)

# NumPy array from the tensor:
np_array = tensor.numpy()
print(f'Numpy array from Tensor: ')
print(f'Type: {type(np_array)}')
print(np_array)

# Back to a tensor:
# tensor2 = torch.tensor(np_array)
tensor2 = torch.from_numpy(np_array)
print(f'Back to tensor:')
print(f'Type: {type(tensor2)}')
print(tensor2)
print('-----'*10)

# Shared memory?
print(f'Do they share memory?')
np_array[2] = 10
print((np_array == tensor2.numpy()).all())
Output
Original Python list:
Type: <class 'list'>
[1, 2, 3, 4, 5]
--------------------------------------------------
Tensor from Python list:  
Type: <class 'torch.Tensor'>
tensor([1, 2, 3, 4, 5])
--------------------------------------------------
Numpy array from Tensor: 
Type: <class 'numpy.ndarray'>
[1 2 3 4 5]
Back to tensor:
Type: <class 'torch.Tensor'>
tensor([1, 2, 3, 4, 5])
--------------------------------------------------
Do they share memory?
True

Comment: .numpy() and torch.from_numpy() create a view of the original data, that is, both objects share the same memory buffer (modifying one affects the other). In contrast, the torch.tensor() function forces a strict copy of the data into a new memory location.

Exercise 6

Create the following tensors:

  • A 5x5 identity matrix with torch.eye().
  • A tensor of evenly spaced values between 0 and 1 with torch.linspace().
  • A tensor of logarithmically spaced values with torch.logspace().
Show solution
# Identity matrix:
identity = torch.eye(5,5)
print('Identity matrix: \n', identity)
print('-----'*10)

# Using torch.linspace()
linspaced = torch.linspace(0, 10, 11) # --> [0,1,2,3,4,5,6,7,8,9, 10]
print(f'Tensor from torch.linspace(): \n', linspaced)
print('-----'*10)

# Using torch.logspace()
logspaced = torch.logspace(0, 4, 5) # --> [10**0, 10**1, 10**2, 10**3, 10**4]
print(f'Tensor from torch.logspace:\n', logspaced)
print('-----'*10)
Output
Identity matrix: 
 tensor([[1., 0., 0., 0., 0.],
        [0., 1., 0., 0., 0.],
        [0., 0., 1., 0., 0.],
        [0., 0., 0., 1., 0.],
        [0., 0., 0., 0., 1.]])
--------------------------------------------------
Tensor from torch.linspace(): 
 tensor([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9., 10.])
--------------------------------------------------
Tensor from torch.logspace:
 tensor([1.0000e+00, 1.0000e+01, 1.0000e+02, 1.0000e+03, 1.0000e+04])
--------------------------------------------------

Exercise 7

Create an integer tensor (int32), a floating-point one (float64) and a boolean one. Convert them into one another with .to() or .float(). What happens when you convert a boolean to an integer?

Show solution

Question: What do the numeric suffixes of the data types (e.g. 8, 16, 32, 64) represent?

They represent the number of bits reserved to store the value. For example, int8 means each integer takes up 8 bits (1 byte) of memory. More bits provide a wider range of representable values (for integers) or greater precision (for floating point), but they also use more memory and can increase computation time.

Question: What does the 'u' prefix mean in primitive types such as uint8?

The "u" stands for unsigned. It indicates that the type can't store negative numbers: it is restricted exclusively to zero and positive integers.

# Integer tensor:
tensor_int32 = torch.randint(0, 10, size=(3,3), dtype=torch.int32)
print(f'Integer tensor:')
print(tensor_int32)
print('-----'*10)

# Floating-point tensor:
tensor_float64 = torch.randn((3,3), dtype=torch.float64)
print(f'Float tensor:')
print(tensor_float64)
print('-----'*10)

# Conversions between them:
    # Float to int:
float64_2_int32 = tensor_float64.to(dtype=torch.int32)
print(f'Float to integer')
print(float64_2_int32)
print('-----'*10)

    # Int to float:
int32_2_float64 = tensor_int32.to(dtype=torch.float64)
print(f'Integer to float')
print(int32_2_float64)

# Boolean to integer:
tensor_bool = torch.randint(0,2, (3,3), dtype=torch.bool)
print(f'Bool tensor:')
print(tensor_bool)
print('-----'*10)

bool_2_int = tensor_bool.to(dtype=torch.int32)
print(f'Bool to integer:')
print(bool_2_int)
print('-----'*10)
Output
Integer tensor:
tensor([[7, 2, 4],
        [8, 8, 0],
        [9, 5, 4]], dtype=torch.int32)
--------------------------------------------------
Float tensor:
tensor([[-0.3864, -0.7791, -0.1250],
        [ 2.0061,  1.1591, -0.5972],
        [-1.2908, -3.8352, -0.9284]], dtype=torch.float64)
--------------------------------------------------
Float to integer
tensor([[ 0,  0,  0],
        [ 2,  1,  0],
        [-1, -3,  0]], dtype=torch.int32)
--------------------------------------------------
Integer to float
tensor([[7., 2., 4.],
        [8., 8., 0.],
        [9., 5., 4.]], dtype=torch.float64)
Bool tensor:
tensor([[False,  True, False],
        [False,  True,  True],
        [False, False, False]])
--------------------------------------------------
Bool to integer:
tensor([[0, 1, 0],
        [0, 1, 1],
        [0, 0, 0]], dtype=torch.int32)
--------------------------------------------------

Comment: in the previous outputs the tensor's dtype was not shown explicitly. PyTorch omits this information in the console for the default types (float32 for floating point and int64 for integers). Now that a type other than the default has been specified, it does appear. Watch out when mixing frameworks: NumPy uses float64 by default instead of float32.

Exercise 8

Given a random tensor of shape (6, 6), compute its mean, standard deviation, minimum and maximum, and their indices with argmin and argmax. Then repeat the calculations by rows and by columns (dim=0 and dim=1).

Show solution
# Create a random tensor:
tensor = torch.randint(0, 10, (6,6), dtype=torch.float32)
print(f'Original: \n', tensor)
print('-----'*10)

# Mean and standard deviation
tensor_mean = tensor.mean()
tensor_std = tensor.std()
print(f"Mean ± std: {tensor_mean.item():.4f} ± {tensor_std.item():.4f}")
print('-----'*10)

tensor = tensor.to(dtype=torch.int16)
minimum = tensor.min()
min_index = torch.argmin(tensor) # --> Returns the index of the first occurrence, as if the tensor were flattened
all_min_indexes = torch.where(tensor == minimum) # --> Returns a tuple of tensors (tensor([a1, b1,c1,...], tensor([a2, b2, c2, ...]))
all_min_coords = list(zip(all_min_indexes[0].tolist(), all_min_indexes[1].tolist()))
print(f'Minimum {minimum:.2f} at {min_index}')
print(f'Other minima at {all_min_coords}')
print()

# Maximum:
maximum = tensor.max()
max_index = torch.argmax(tensor)
all_max_indexes = torch.where(tensor == maximum)
all_max_coords = list(zip(all_max_indexes[0].tolist(), all_max_indexes[1].tolist()))
print(f'Maximum {maximum:.2f} at {max_index}')
print(f'Other maxima at {all_max_coords}')
print('-----'*10)

# Minimum by rows and columns:
rows_minimum = tensor.min(dim=1).values # --> When dim is used, it returns a namedtuple
row_min_index = torch.argmin(tensor, dim=1).tolist() # --> When dim is used, it returns all the indices (.tolist())
print(f'Rows minima {rows_minimum.numpy()} at {row_min_index}')
print()
cols_minimum = tensor.min(dim=0).values
col_min_index = torch.argmin(tensor, dim=0).tolist()
print(f'Cols minima {cols_minimum.numpy()} at {col_min_index}')
print('-----'*10)

# Maximum by rows and columns:
rows_maximum = tensor.max(dim=1).values
row_max_index = torch.argmax(tensor, dim=1).tolist()
print(f'Rows maxima {rows_maximum.numpy()} at {row_max_index}')
print()
cols_maximum = tensor.max(dim=0).values
col_max_index = torch.argmax(tensor, dim=0).tolist()
print(f'Cols maxima {cols_maximum.numpy()} at {col_max_index}')
print('-----'*10)
Output
Original: 
 tensor([[4., 1., 9., 0., 9., 2.],
        [4., 5., 7., 3., 1., 7.],
        [9., 7., 6., 0., 7., 8.],
        [5., 1., 9., 8., 8., 6.],
        [0., 3., 3., 9., 9., 5.],
        [0., 8., 4., 0., 8., 3.]])
--------------------------------------------------
Mean ± std: 4.9444 ± 3.2066
--------------------------------------------------
Minimum 0.00 at 3
Other minima at [(0, 3), (2, 3), (4, 0), (5, 0), (5, 3)]

Maximum 9.00 at 2
Other maxima at [(0, 2), (0, 4), (2, 0), (3, 2), (4, 3), (4, 4)]
--------------------------------------------------
Rows minima [0 1 0 1 0 0] at [3, 4, 3, 1, 0, 0]

Cols minima [0 1 3 0 1 2] at [4, 0, 4, 0, 1, 0]
--------------------------------------------------
Rows maxima [9 7 9 9 9 8] at [2, 2, 0, 2, 3, 1]

Cols maxima [9 8 9 9 9 8] at [2, 5, 0, 4, 0, 2]
--------------------------------------------------

Exercise 9

Create a tensor of shape (3, 4, 5) and practise with sum(), mean() and max() specifying different dimensions (dim=0, dim=1, dim=2). Notice how the shape of the result changes.

Show solution
1
2
3
4
# Create a random tensor:
tensor = torch.randint(0, 10, (3,4,5), dtype=torch.float32)
print(f'Original: \n', tensor)
print('-----'*10)
Output
Original: 
 tensor([[[3., 8., 9., 2., 2.],
         [2., 8., 1., 8., 0.],
         [9., 4., 1., 0., 7.],
         [6., 8., 3., 5., 8.]],

        [[9., 2., 6., 5., 7.],
         [2., 1., 6., 0., 5.],
         [7., 6., 4., 9., 9.],
         [4., 8., 2., 1., 4.]],

        [[1., 8., 1., 7., 7.],
         [6., 8., 7., 6., 9.],
         [2., 2., 3., 4., 9.],
         [0., 6., 2., 0., 1.]]])
--------------------------------------------------
1
2
3
4
5
6
7
8
9
# Sum along the channels (dim=0): (3,4,5) -->(4,5)
channels_sum = tensor.sum(dim=0)
print(f'Channels sum:\n', channels_sum)
# Sum along the height (dim=1): (3,4,5) --> (3,5)
height_sum = tensor.sum(dim=1)
print(f'Height sum:\n', height_sum)
# Sum along the width (dim=2): (3,4,5) --> (3,4)
width_sum = tensor.sum(dim=2)
print(f'Width sum:\n',width_sum)
Output
Channels sum:
 tensor([[13., 18., 16., 14., 16.],
        [10., 17., 14., 14., 14.],
        [18., 12.,  8., 13., 25.],
        [10., 22.,  7.,  6., 13.]])
Height sum:
 tensor([[20., 28., 14., 15., 17.],
        [22., 17., 18., 15., 25.],
        [ 9., 24., 13., 17., 26.]])
Width sum:
 tensor([[24., 19., 21., 30.],
        [29., 14., 35., 19.],
        [24., 36., 20.,  9.]])
1
2
3
4
5
6
7
8
9
# Mean along the channels (dim=0): (3,4,5) -->(4,5)
channels_mean = tensor.mean(dim=0)
print(f'Channels mean:\n', channels_mean)
# Mean along the height (dim=1): (3,4,5) --> (3,5)
height_mean = tensor.mean(dim=1)
print(f'Height mean:\n', height_mean)
# Mean along the width (dim=2): (3,4,5) --> (3,4)
width_mean = tensor.mean(dim=2)
print(f'Width mean:\n',width_mean)
Output
Channels mean:
 tensor([[4.3333, 6.0000, 5.3333, 4.6667, 5.3333],
        [3.3333, 5.6667, 4.6667, 4.6667, 4.6667],
        [6.0000, 4.0000, 2.6667, 4.3333, 8.3333],
        [3.3333, 7.3333, 2.3333, 2.0000, 4.3333]])
Height mean:
 tensor([[5.0000, 7.0000, 3.5000, 3.7500, 4.2500],
        [5.5000, 4.2500, 4.5000, 3.7500, 6.2500],
        [2.2500, 6.0000, 3.2500, 4.2500, 6.5000]])
Width mean:
 tensor([[4.8000, 3.8000, 4.2000, 6.0000],
        [5.8000, 2.8000, 7.0000, 3.8000],
        [4.8000, 7.2000, 4.0000, 1.8000]])
1
2
3
4
5
6
7
8
9
# Maximum along the channels (dim=0): (3,4,5) -->(4,5)
channels_max = tensor.max(dim=0).values
print(f'Channels max:\n', channels_max)
# Maximum along the height (dim=1): (3,4,5) --> (3,5)
height_max = tensor.max(dim=1).values
print(f'Height max:\n', height_max)
# Maximum along the width (dim=2): (3,4,5) --> (3,4)
width_max = tensor.max(dim=2)
print(f'Width max:\n',width_max)
Output
Channels max:
 tensor([[9., 8., 9., 7., 7.],
        [6., 8., 7., 8., 9.],
        [9., 6., 4., 9., 9.],
        [6., 8., 3., 5., 8.]])
Height max:
 tensor([[9., 8., 9., 8., 8.],
        [9., 8., 6., 9., 9.],
        [6., 8., 7., 7., 9.]])
Width max:
 torch.return_types.max(
values=tensor([[9., 8., 9., 8.],
        [9., 6., 9., 8.],
        [8., 9., 9., 6.]]),
indices=tensor([[2, 1, 0, 1],
        [0, 2, 3, 1],
        [1, 4, 4, 1]]))

Exercise 10

Create a 2D tensor with random values and transpose it. Then manually standardise each row so that they all have mean 0 and standard deviation 1.

Show solution

To standardise an element manually, you need to compute: $$ z = \frac{x - \mu}{\sigma} $$

where \(\mu\) is the mean and \(\sigma\) the standard deviation.

# Create a tensor and transpose it:
tensor = torch.rand(3,3)
tensor_T = tensor.T
print(f'Original: \n', tensor)
print('-----'*10)
print(f'Transpose: \n', tensor_T)
print('-----'*10)

# Standardise the rows:
rows_means = tensor_T.mean(dim=1, keepdim=True) # keepdim = False -> (3,); keepdim=True -> (3,1)
rows_std = tensor_T.std(dim=1, keepdim=True)
tensor_std = (tensor_T- rows_means)/rows_std
print(f'Standarized tensor:\n', tensor_std)
Output
Original: 
 tensor([[0.0599, 0.4072, 0.0125],
        [0.5584, 0.8129, 0.4754],
        [0.3624, 0.4954, 0.3939]])
--------------------------------------------------
Transpose: 
 tensor([[0.0599, 0.5584, 0.3624],
        [0.4072, 0.8129, 0.4954],
        [0.0125, 0.4754, 0.3939]])
--------------------------------------------------
Standarized tensor:
 tensor([[-1.0632,  0.9217,  0.1415],
        [-0.7714,  1.1298, -0.3584],
        [-1.1389,  0.7344,  0.4045]])

Exercise 11

Given two random integer tensors with values from 1 to 10, create boolean masks for: the elements greater than 5 and the elements that are equal in both tensors. Use those masks to filter values with boolean indexing.

Show solution
# Random integer tensors:
A = torch.randint(0, 11, (3,3))
print('Original tensor A: \n', A)
print('-----'*10)
B = torch.randint(0, 11, (3,3))
print('Original tensor B:\n', B)
print('-----'*10)

# Boolean mask:
mask_A = torch.greater(A, 5)
print('Mask A > 5:\n', mask_A)
print('-----'*10)
mask_B = torch.greater(B, 5)
print('Mask B > 5:\n', mask_B)
print('-----'*10)

# Comparison:
mask_eq = (A == B) # A torch-specific way???
print('Mask A = B:\n', mask_eq)
print('-----'*10)

# Shared values:
shared_values = torch.masked_select(A, mask_eq) # = A[mask_eq]
print('Shared values:\n', shared_values)
Output
Original tensor A: 
 tensor([[ 7,  8,  1],
        [10,  4,  4],
        [ 8,  4,  2]])
--------------------------------------------------
Original tensor B:
 tensor([[0, 9, 6],
        [1, 9, 3],
        [8, 0, 7]])
--------------------------------------------------
Mask A > 5:
 tensor([[ True,  True, False],
        [ True, False, False],
        [ True, False, False]])
--------------------------------------------------
Mask B > 5:
 tensor([[False,  True,  True],
        [False,  True, False],
        [ True, False,  True]])
--------------------------------------------------
Mask A = B:
 tensor([[False, False, False],
        [False, False, False],
        [ True, False, False]])
--------------------------------------------------
Shared values:
 tensor([8])

Exercise 12

Create a tensor of shape (3, 1, 4, 1, 2). Remove all the size-1 dimensions with squeeze(). Then add dimensions at different positions with unsqueeze(). What is this useful for in practice?

Show solution

The main purpose of manipulating size-1 dimensions with squeeze() and unsqueeze() is to guarantee strict topological alignment between your data structures and the rigid dimensional requirements of the network's layers, the loss functions and broadcasting operations. These operations add no volume of data, but they help your data meet the dimensional requirements of deep learning structures.

For example, a Conv2d layer always expects data of shape (B, C, H, W) \(\Rightarrow\) if you only have one image (C, H, W), you must use unsqueeze(0) to insert an extra dimension at the start, that is, (1, C, H, W), so that you can use the Conv2D layer.

1
2
3
tensor = torch.randint(0, 100, (3,1,4,1,2))
print('Original: \n', tensor)
print('-----'*10)
Output
Original: 
 tensor([[[[[40, 78]],

          [[55, 65]],

          [[31, 73]],

          [[86, 43]]]],



        [[[[64, 90]],

          [[34, 43]],

          [[88, 49]],

          [[81, 94]]]],



        [[[[46, 36]],

          [[25, 22]],

          [[98, 66]],

          [[48, 98]]]]])
--------------------------------------------------
1
2
3
# Squeeze all the size-1 dimensions:
squeezed_tensor = torch.squeeze(tensor, dim=[1,3]) # = tensor.squeeze(dim=[1,3])
print('Squeezed:\n', squeezed_tensor)
Output
Squeezed:
 tensor([[[40, 78],
         [55, 65],
         [31, 73],
         [86, 43]],

        [[64, 90],
         [34, 43],
         [88, 49],
         [81, 94]],

        [[46, 36],
         [25, 22],
         [98, 66],
         [48, 98]]])
1
2
3
# Unsqueeze to recover the size-1 dimensions:
unsqueezed_tensor = torch.unsqueeze(squeezed_tensor, dim=1).unsqueeze(dim=3)
print('Unsqueezed:\n', unsqueezed_tensor)
Output
Unsqueezed:
 tensor([[[[[40, 78]],

          [[55, 65]],

          [[31, 73]],

          [[86, 43]]]],



        [[[[64, 90]],

          [[34, 43]],

          [[88, 49]],

          [[81, 94]]]],



        [[[[46, 36]],

          [[25, 22]],

          [[98, 66]],

          [[48, 98]]]]])

Exercise 13

Create three tensors of shape (2, 4) and explore the differences between: - torch.cat() along different axes. - torch.stack(): what new dimension does it create?

Show solution
tensor1 = torch.randint(0, 10, (2,4))
tensor2 = torch.randint(0, 10, (2,4))
tensor3 = torch.randint(0, 10, (2,4))

print('Original 1:\n', tensor1)
print('-----'*10)

print('Original 2:\n', tensor2)
print('-----'*10)

print('Original 3:\n', tensor3)
print('-----'*10)
Output
Original 1:
 tensor([[7, 6, 2, 8],
        [9, 6, 7, 9]])
--------------------------------------------------
Original 2:
 tensor([[9, 5, 6, 9],
        [7, 8, 2, 4]])
--------------------------------------------------
Original 3:
 tensor([[0, 8, 7, 0],
        [1, 6, 0, 0]])
--------------------------------------------------
cat_dim0 = torch.cat([tensor1, tensor2, tensor3], dim=0) # (2,4) --> (6,4)
print('Concat along dim = 0 --> Concat along rows:')
H,W = cat_dim0.shape
print(f'Shape {H,W}')
print(cat_dim0)
print('-----'*10)

cat_dim1 = torch.cat([tensor1, tensor2, tensor3], dim=1) # (2,4) --> (2, 12)
print('Concat along dim = 1 --> Concat along columns:')
H,W = cat_dim1.shape
print(f'Shape {H,W}')
print(cat_dim1)
Output
Concat along dim = 0 --> Concat along rows:
Shape (6, 4)
tensor([[7, 6, 2, 8],
        [9, 6, 7, 9],
        [9, 5, 6, 9],
        [7, 8, 2, 4],
        [0, 8, 7, 0],
        [1, 6, 0, 0]])
--------------------------------------------------
Concat along dim = 1 --> Concat along columns:
Shape (2, 12)
tensor([[7, 6, 2, 8, 9, 5, 6, 9, 0, 8, 7, 0],
        [9, 6, 7, 9, 7, 8, 2, 4, 1, 6, 0, 0]])
stack_dim0 = torch.stack([tensor1, tensor2, tensor3], dim=0) # (2,4) --> (3,2,4)
print('Stack along dim=0 --> Adds an extra dim at the beginning:')
C, H, W = stack_dim0.shape
print(f'Shape: {C,H,W}')
print(stack_dim0)

stack_dim1 = torch.stack([tensor1, tensor2, tensor3], dim=1) # (2,4) --> (2,3,4)
print('Stack along dim=1 --> Adds an extra between the two original dims:')
C, H, W = stack_dim1.shape
print(f'Shape: {C,H,W}')
print(stack_dim1)
Output
Stack along dim=0 --> Adds an extra dim at the beginning:
Shape: (3, 2, 4)
tensor([[[7, 6, 2, 8],
         [9, 6, 7, 9]],

        [[9, 5, 6, 9],
         [7, 8, 2, 4]],

        [[0, 8, 7, 0],
         [1, 6, 0, 0]]])
Stack along dim=1 --> Adds an extra between the two original dims:
Shape: (2, 3, 4)
tensor([[[7, 6, 2, 8],
         [9, 5, 6, 9],
         [0, 8, 7, 0]],

        [[9, 6, 7, 9],
         [7, 8, 2, 4],
         [1, 6, 0, 0]]])

Exercise 14

Create a tensor that simulates an image of shape (3, 32, 64) (channels, height, width). Turn it into the format (64, 3, 32) with permute(). Then practise with transpose().

Show solution
tensor = torch.randint(0,10, (3,32,64))
C,H,W = tensor.shape
print(f'Original Shape: {C,H,W}')

permuted_tensor = torch.permute(tensor, dims=(2,0,1)) # --> Expects the positional indices of the dimensions.
C,H,W = permuted_tensor.shape
print(f'Permuted Shape: {C,H,W}')

transposed_tensor = tensor.T
C,H,W = transposed_tensor.shape
print(f'Transposed Shape: {C,H,W}')
Output
1
2
3
4
5
Original Shape: (3, 32, 64)
Permuted Shape: (64, 3, 32)
Transposed Shape: (64, 32, 3)
/tmp/ipykernel_9892/1995679435.py:9: UserWarning: The use of `x.T` on tensors of dimension other than 2 to reverse their shape is deprecated and it will throw an error in a future release. Consider `x.mT` to transpose batches of matrices or `x.permute(*torch.arange(x.ndim - 1, -1, -1))` to reverse the dimensions of a tensor. (Triggered internally at /pytorch/aten/src/ATen/native/TensorShape.cpp:4480.)
  transposed_tensor = tensor.T

Exercise 15

Without using loops, add a 1D tensor of shape (3,) to a matrix of shape (4, 3). Then try to concatenate a (3,) tensor with a (4,) one: what error do you get and why? How would you fix it? (Recommendation: use the try control structure).

Show solution
1
2
3
4
5
6
7
8
9
tensor3 = torch.randint(0,10, (3,))
print('Tensor (3,):\n', tensor3)
print('-----'*10)
tensor43 = torch.randint(0,10, (4,3))
print('Tensor (4,3):\n', tensor43)
print('-----'*10)
tensor4 = torch.randint(0,10, (4,))
print('Tensor (4,):\n',tensor4)
print('-----'*10)
Output
Tensor (3,):
 tensor([5, 9, 7])
--------------------------------------------------
Tensor (4,3):
 tensor([[2, 3, 6],
        [8, 8, 0],
        [7, 8, 1],
        [1, 1, 8]])
--------------------------------------------------
Tensor (4,):
 tensor([6, 2, 5, 7])
--------------------------------------------------
# Concatenate (3, ) and (4,3)
try:
    tensor343 = torch.cat([tensor3, tensor43]) # dim = 0 by default
except Exception as e:
    print(f'Error of dimensions: {e}')
    print(f'Notice that you are trying to concat a (3,) and a (4,3), a Rank 1 tensor and Rank 2 tensor')
print('-----'*10)

# Concatenate (3,) and (4, )
try:
    print('(3,) and (4, ) can be concatenated along dim=0')
    tensor34_dim0 = torch.cat([tensor3, tensor4])
    print('Tensor (3,) concat (4,) dim=0:\n', tensor34_dim0)
except Exception as e:
    print(f'Error of dimensions: {e}')
print('-----'*10)

# How to fix it?
try:
    tensor343 = torch.cat([tensor3.unsqueeze(0) , tensor43])
    print(f'How to fix it? --> For example, we could unsqueeze the tensor.')
    print('Tensor (1,3)(4,3):\n', tensor343)
except Exception as e:
    print(f'Error: {e}')
Output
Error of dimensions: Tensors must have same number of dimensions: got 1 and 2
Notice that you are trying to concat a (3,) and a (4,3), a Rank 1 tensor and Rank 2 tensor
--------------------------------------------------
(3,) and (4, ) can be concatenated along dim=0
Tensor (3,) concat (4,) dim=0:
 tensor([5, 9, 7, 6, 2, 5, 7])
--------------------------------------------------
How to fix it? --> For example, we could unsqueeze the tensor.
Tensor (1,3)(4,3):
 tensor([[5, 9, 7],
        [2, 3, 6],
        [8, 8, 0],
        [7, 8, 1],
        [1, 1, 8]])

Exercise 16

Using broadcasting and no loops, generate the multiplication table from 1 to 10 as a (10, 10) tensor. Hint: you will need a column vector and a row vector.

Show solution
1
2
3
4
5
6
a = torch.arange(1, 11).unsqueeze(1)   # (10, 1)
b = torch.arange(1, 11).unsqueeze(0)   # (1, 10)
# Table:
print('Multiplication table:')
table = torch.matmul(a,b)
print(table)
Output
Multiplication table:
tensor([[  1,   2,   3,   4,   5,   6,   7,   8,   9,  10],
        [  2,   4,   6,   8,  10,  12,  14,  16,  18,  20],
        [  3,   6,   9,  12,  15,  18,  21,  24,  27,  30],
        [  4,   8,  12,  16,  20,  24,  28,  32,  36,  40],
        [  5,  10,  15,  20,  25,  30,  35,  40,  45,  50],
        [  6,  12,  18,  24,  30,  36,  42,  48,  54,  60],
        [  7,  14,  21,  28,  35,  42,  49,  56,  63,  70],
        [  8,  16,  24,  32,  40,  48,  56,  64,  72,  80],
        [  9,  18,  27,  36,  45,  54,  63,  72,  81,  90],
        [ 10,  20,  30,  40,  50,  60,  70,  80,  90, 100]])

Exercise 17

Create a tensor of shape (4, 4) and obtain from it one tensor with .view(16) and another with .clone(). Modify the original tensor and see which of the derived ones changes. Then try to use .view(16) on a non-contiguous tensor: what error occurs? Solve it with .contiguous().

Show solution

A tensor is considered contiguous when its logical structure (how the elements are indexed in each dimension) exactly matches the flat, sequential layout of those elements in physical memory (RAM or VRAM). In contrast, a tensor becomes non-contiguous when operations on the metadata, such as .T or .permute(), alter its logical shape by modifying the strides without actually moving the underlying bytes. That is why reading a non-contiguous tensor forces the hardware pointer to jump between non-adjacent memory addresses, which breaks the strict linear alignment required by high-efficiency restructuring methods such as .view().

1
2
3
4
5
6
7
8
9
tensor = torch.randint(0,10, (4,4))
tensor_view = tensor.view(16) # <--- Allows the shape to change
tensor_clone = tensor.clone()
print('Original:\n', tensor)
print('-----'*10)
print('Tensor from view: \n', tensor_view)
print('-----'*10)
print('Tensor from clone:\n', tensor_clone)
print('-----'*10)
Output
Original:
 tensor([[5, 3, 6, 1],
        [7, 0, 2, 9],
        [8, 3, 5, 4],
        [1, 0, 8, 0]])
--------------------------------------------------
Tensor from view: 
 tensor([5, 3, 6, 1, 7, 0, 2, 9, 8, 3, 5, 4, 1, 0, 8, 0])
--------------------------------------------------
Tensor from clone:
 tensor([[5, 3, 6, 1],
        [7, 0, 2, 9],
        [8, 3, 5, 4],
        [1, 0, 8, 0]])
--------------------------------------------------
1
2
3
4
5
6
7
tensor[0:,0] = 10
print('Original Mod:\n', tensor)
print('-----'*10)
print('Tensor from view: \n', tensor_view)
print('-----'*10)
print('Tensor from clone:\n', tensor_clone)
print('-----'*10)
Output
Original Mod:
 tensor([[10,  3,  6,  1],
        [10,  0,  2,  9],
        [10,  3,  5,  4],
        [10,  0,  8,  0]])
--------------------------------------------------
Tensor from view: 
 tensor([10,  3,  6,  1, 10,  0,  2,  9, 10,  3,  5,  4, 10,  0,  8,  0])
--------------------------------------------------
Tensor from clone:
 tensor([[5, 3, 6, 1],
        [7, 0, 2, 9],
        [8, 3, 5, 4],
        [1, 0, 8, 0]])
--------------------------------------------------
noncontiguous = tensor.T
try:
    print('New View:\n', noncontiguous.view(16))
except Exception as e:
    print(f'Error --> {e}')
print('-----'*10)
try:
    print('New View (fixed):\n', noncontiguous.contiguous().view(16))
except Exception as e:
    print(f'Error --> {e}')
Output
1
2
3
4
Error --> view size is not compatible with input tensor's size and stride (at least one dimension spans across two contiguous subspaces). Use .reshape(...) instead.
--------------------------------------------------
New View (fixed):
 tensor([10, 10, 10, 10,  3,  0,  3,  0,  6,  2,  5,  8,  1,  9,  4,  0])

Exercise 18

Create a 5x5 dense tensor initialised with zeros and insert random values at 5 different random positions. Convert this dense tensor into a sparse representation with .to_sparse(). What computational and memory advantages do sparse tensors offer?

Show solution

They are useful when the data is sparse (for example, in the states of Conway's Game of Life).

  • Memory efficiency: it avoids reserving RAM for empty space, since it only stores the non-zero values and their spatial indices. (Note: it only pays off with extreme sparsity ratios, usually >90 % zeros, because of the cost of storing the coordinates).

  • Computation speed-up: specialised sparse operators (e.g. torch.smm) skip floating-point operations with zeros, which greatly reduces execution time.

tensor = torch.zeros(5, 5)
random_row_indexes = torch.randint(0, 5, (5,))
random_col_indexes = torch.randint(0, 5, (5,))
tensor[random_row_indexes , random_col_indexes] = torch.rand(5)
print('Original:')
print(tensor)
print('-----'*10)
sparse_torch = tensor.to_sparse()
print('Sparse:')
print(sparse_torch)
Output
Original:
tensor([[0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.6486, 0.0000, 0.6012],
        [0.0000, 0.6122, 0.0000, 0.0000, 0.0000],
        [0.0000, 0.0000, 0.2419, 0.0000, 0.9379]])
--------------------------------------------------
Sparse:
tensor(indices=tensor([[2, 2, 3, 4, 4],
                       [2, 4, 1, 2, 4]]),
       values=tensor([0.6486, 0.6012, 0.6122, 0.2419, 0.9379]),
       size=(5, 5), nnz=5, layout=torch.sparse_coo)

Exercise 19

Generate two random tensors of shape (3, 3) without setting a seed: do they match? Now call torch.manual_seed(42) before each generation and check again. Do a small experiment: generate 5 pairs of random tensors (with and without a fixed seed). Why is reproducibility critical when training neural networks?

Show solution
1
2
3
4
for i in range(5):
    tensor_fullrandom = torch.randint(0,10, (3,3))
    print('Random Tensor:\n ', tensor_fullrandom)
    print('-----'*10)
Output
Random Tensor:
  tensor([[6, 9, 9],
        [3, 6, 9],
        [9, 0, 0]])
--------------------------------------------------
Random Tensor:
  tensor([[2, 6, 3],
        [4, 9, 3],
        [2, 2, 4]])
--------------------------------------------------
Random Tensor:
  tensor([[9, 7, 1],
        [6, 5, 1],
        [0, 9, 7]])
--------------------------------------------------
Random Tensor:
  tensor([[8, 0, 1],
        [6, 8, 6],
        [4, 3, 4]])
--------------------------------------------------
Random Tensor:
  tensor([[5, 9, 5],
        [1, 9, 5],
        [3, 1, 6]])
--------------------------------------------------
1
2
3
4
5
for i in range(5):
    torch.manual_seed(42)
    tensor_42 = torch.randint(0,10, (3,3))
    print('Tensor with seed 42:\n ', tensor_42)
    print('-----'*10)
Output
Tensor with seed 42:
  tensor([[2, 7, 6],
        [4, 6, 5],
        [0, 4, 0]])
--------------------------------------------------
Tensor with seed 42:
  tensor([[2, 7, 6],
        [4, 6, 5],
        [0, 4, 0]])
--------------------------------------------------
Tensor with seed 42:
  tensor([[2, 7, 6],
        [4, 6, 5],
        [0, 4, 0]])
--------------------------------------------------
Tensor with seed 42:
  tensor([[2, 7, 6],
        [4, 6, 5],
        [0, 4, 0]])
--------------------------------------------------
Tensor with seed 42:
  tensor([[2, 7, 6],
        [4, 6, 5],
        [0, 4, 0]])
--------------------------------------------------

Exercise 20

Generate a tensor of shape (100, 5) that simulates a dataset of 100 samples with 5 features. For each feature, compute the mean, standard deviation, minimum and maximum. Normalise the dataset with min-max scaling using exclusively tensor operations (no loops).

Show solution
# 1. Generate a tensor of shape (100, 5)
torch.manual_seed(42)
data = torch.randn(100, 5)
print('Original dataset:\n', data[:5]) # <--- Show only 5 rows
print('-----'*10)
# 2. Statistics per feature
mean   = data.mean(dim=0)
std    = data.std(dim=0)
minval = data.min(dim=0).values
maxval = data.max(dim=0).values

print(f'Means: {mean}')
print(f'Stds: {std}')
print(f'minVals: {minval}')
print(f'maxVals: {maxval}')
print('-----'*10)
# 3. Min-max normalisation: fully vectorised, no loops
data_norm = (data - minval) / (maxval - minval)
minimum = data_norm.min()
maximum = data_norm.max()
print(f'Norm dataset minimum: {minimum}')
print(f'Norm dataset maximum: {maximum}')
Output
Original dataset:
 tensor([[ 1.9269,  1.4873,  0.9007, -2.1055,  0.6784],
        [-1.2345, -0.0431, -1.6047, -0.7521,  1.6487],
        [-0.3925, -1.4036, -0.7279, -0.5594, -0.7688],
        [ 0.7624,  1.6423, -0.1596, -0.4974,  0.4396],
        [-0.7581,  1.0783,  0.8008,  1.6806,  1.2791]])
--------------------------------------------------
Means: tensor([ 0.0403,  0.1950, -0.0625,  0.0008,  0.0445])
Stds: tensor([1.0335, 1.0593, 0.8403, 1.0259, 0.8871])
minVals: tensor([-2.3184, -2.5095, -1.7223, -2.4885, -2.5850])
maxVals: tensor([2.1442, 2.8340, 1.9653, 2.0487, 1.9890])
--------------------------------------------------
Norm dataset minimum: 0.0
Norm dataset maximum: 1.0

Summary

The topics in this entry are the essential foundation of any deep learning workflow in PyTorch. A solid understanding of tensor ranks, data types, shape manipulation, memory semantics, broadcasting and normalisation is a prerequisite for correctly building, debugging and optimising neural network architectures.

See also