Skip to content

================

by Jawad Haider

02 - PyTorch Basics Exercises SOLUTION


Image
Copyright Qalmaqihir
For more information, visit us at www.github.com/qalmaqihir/



PyTorch Basics Exercises - SOLUTIONS

For these exercises we’ll create a tensor and perform several operations on it.

IMPORTANT NOTE! Make sure you don’t run the cells directly above the example output shown,
otherwise you will end up writing over the example output!

1. Perform standard imports

Import torch and NumPy

# CODE HERE
import torch
import numpy as np

2. Set the random seed for NumPy and PyTorch both to “42”

This allows us to share the same “random” results.

# CODE HERE
np.random.seed(42)
torch.manual_seed(42);  # the semicolon suppresses the jupyter output line

3. Create a NumPy array called “arr” that contains 6 random integers between 0 (inclusive) and 5 (exclusive)

# CODE HERE
# DON'T WRITE HERE
arr = np.random.randint(0,5,6)
print(arr)
[3 4 2 4 4 1]

4. Create a tensor “x” from the array above

# CODE HERE
# DON'T WRITE HERE
x = torch.from_numpy(arr)
print(x)
tensor([3, 4, 2, 4, 4, 1], dtype=torch.int32)

5. Change the dtype of x from ‘int32’ to ‘int64’

Note: ‘int64’ is also called ‘LongTensor’

# CODE HERE
# DON'T WRITE HERE
x = x.type(torch.int64)
# x = x.type(torch.LongTensor)
print(x.type())
torch.LongTensor

6. Reshape x into a 3x2 tensor

There are several ways to do this.

# CODE HERE
# DON'T WRITE HERE
x = x.view(3,2)
# x = x.reshape(3,2)
# x.resize_(3,2)
print(x)
tensor([[3, 4],
        [2, 4],
        [4, 1]])

7. Return the right-hand column of tensor x

# CODE HERE
# DON'T WRITE HERE
print(x[:,1:])
# print(x[:,1])
tensor([[4],
        [4],
        [1]])

8. Without changing x, return a tensor of square values of x

There are several ways to do this.

# CODE HERE
# DON'T WRITE HERE
print(x*x)
# print(x**2)
# print(x.mul(x))
# print(x.pow(2))
# print(torch.mul(x,x))
tensor([[ 9, 16],
        [ 4, 16],
        [16,  1]])

9. Create a tensor “y” with the same number of elements as x, that can be matrix-multiplied with x

Use PyTorch directly (not NumPy) to create a tensor of random integers between 0 (inclusive) and 5 (exclusive).
Think about what shape it should have to permit matrix multiplication.

# CODE HERE
# DON'T WRITE HERE
y = torch.randint(0,5,(2,3))
print(y)
tensor([[2, 2, 1],
        [4, 1, 0]])

10. Find the matrix product of x and y

# CODE HERE
# DON'T WRITE HERE
print(x.mm(y))
tensor([[22, 10,  3],
        [20,  8,  2],
        [12,  9,  4]])

Great job!