Laboratory Task 5

Laboratory Task 5#


  1. Perform Standard Imports

import numpy as np
import torch
  1. 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)
  1. 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.

seed = 42
set_seed(seed)
arr = np.random.randint(low=0, high=5, size=6)
arr
array([3, 4, 2, 4, 4, 1], dtype=int32)
  1. Create a tensor “x” from the array above.

x = torch.from_numpy(arr)
x
tensor([3, 4, 2, 4, 4, 1], dtype=torch.int32)
  1. Change the dtype of x from int32 to int64.

x = x.type(torch.int64)
x
tensor([3, 4, 2, 4, 4, 1])
  1. Reshape x into a 3x2 tensor.

x = x.reshape(3,2)
x
tensor([[3, 4],
        [2, 4],
        [4, 1]])
  1. Return the right-hand column of tensor x.

x[:,1]
tensor([4, 4, 1])
  1. Without changing x, return a tensor of square values of x.

torch.square(x)
tensor([[ 9, 16],
        [ 4, 16],
        [16,  1]])
  1. Create a tensor y with the same number of elements as x, that can be matrix-multiplied with x.

torch.manual_seed(seed)
y = torch.randint_like(x.T, 0, 5)
y
tensor([[2, 1, 1],
        [2, 4, 0]])
  1. Find the matrix product of x and y.

torch.mm(x,y)
tensor([[14, 19,  3],
        [12, 18,  2],
        [10,  8,  4]])