Chapter 3: PyTorch Tensors

Quiz - Tensor Initialisation

face Luca Grillotti

Let’s check whether you’ve actually understood what we have discussed. Try applying what you have learnt in the previous pages to the following tasks.

1 2 3

Question 1

Create a tensor of shape (7, 3, 1) such that all its elements are equal to 2

Sample solution:

Here is a possible solution:

tensor = torch.zeros(size=(7, 3, 1)) + 2

Question 2

Create a tensor of shape (3, 2) such that all its elements are sampled from a normal distribution of mean 5 and variance 3.

Sample solution:

Here is a possible solution. Remember that if a variable X follows a normal distribution of mean 0 and variance 1, then sigma * X + mu follows a normal distribution with mean mu and variance sigma*sigma.

import math
variance = 3
mean = 5
tensor = torch.randn(size=(3, 2)) * math.sqrt(variance) + mean

Question 3

Suppose you are given a tensor t (you can give it the size you want). Create a tensor having the same shape as t such that: all its elements are sampled from a uniform distribution between -1 and 2. Your code should be robust to the dimensionality of t: if you change the shape of t, the shape of your random tensor should adapt!

Sample solution:

Here is a possible solution. Remember that if X is a random variable following a uniform distribution between 0 and 1, then: - (upper_bound - lower_bound) * X follows a uniform distribution between 0 and (upper_bound - lower_bound) - lower_bound + (upper_bound - lower_bound) * X follows a uniform distribution between lower_bound and upper_bound

t = torch.randn(size=(1, 6, 2)) # example of tensor t
lower_bound = -1
upper_bound = 2
tensor = lower_bound + torch.rand_like(t) * (upper_bound - lower_bound)