Skip to content

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

by Jawad Haider

02 - PyTorch Basics Exercises


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



PyTorch Basics Exercises

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

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

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

# CODE HERE

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

# CODE HERE
# DON'T WRITE HERE
[3 4 2 4 4 1]

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

# CODE HERE
# DON'T WRITE HERE
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
torch.LongTensor

6. Reshape x into a 3x2 tensor

There are several ways to do this.

# CODE HERE
# DON'T WRITE HERE
tensor([[3, 4],
        [2, 4],
        [4, 1]])

7. Return the right-hand column of tensor x

# CODE HERE
# DON'T WRITE HERE
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
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
tensor([[2, 2, 1],
        [4, 1, 0]])

10. Find the matrix product of x and y

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

Great job!