Laboratory Task 5 - PyTorch Basics#
DS Elective 4 - Deep Learning#
Name: Keith Laspoña
Year & Section: DS4A
1. Perform Standard Imports#
import numpy as np
import torch
import sys
import random
2. Create a function called set_seed() that accepts seed: int as a parameter, this function must return nothing but just set the seed to a certain value.#
def set_seed(seed:int):
np.random.seed(seed)
torch.manual_seed(seed)
3. Create a NumPy array called “arr” that contains 6 random integers between 0 (inclusive) and 5 (exclusive), call the set_seed() function and use 42 as the seed parameter.#
set_seed(42)
arr = np.random.randint(0,5, size=6)
print(arr)
print(arr.dtype)
print(type(arr))
[3 4 2 4 4 1]
int32
<class 'numpy.ndarray'>
4. Create a tensor “x” from the array above#
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#
x = x.type(torch.int64)
print(x)
print(x.dtype)
tensor([3, 4, 2, 4, 4, 1])
torch.int64
6. Reshape x into a 3x2 tensor#
x = x.reshape(3, 2)
print (x)
print (x.dtype)
tensor([[3, 4],
[2, 4],
[4, 1]])
torch.int64
7. Return the right-hand column of tensor x#
x = x
right_hand_col = x[:, 1:]
right_hand_col
tensor([[4],
[4],
[1]])
8. Without changing x, return a tensor of square values of x#
There are several ways to do this.
x = x
square_val = x ** 2
square_val
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). Use 42 as seed. Think about what shape it should have to permit matrix multiplication.
y = torch.randint(0, 5, (2, 3))
set_seed(42)
y
tensor([[0, 4, 1],
[2, 0, 0]])
10. Find the matrix product of x and y.#
matrix_prod = torch.matmul(x,y)
matrix_prod
tensor([[ 8, 12, 3],
[ 8, 8, 2],
[ 2, 16, 4]])