Laboratory Task 5#
Perform Standard Imports
import numpy as np
import torch
Create a function called
set_seed()that acceptsseed: intas 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)
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)
Create a tensor “x” from the array above.
x = torch.from_numpy(arr)
x
tensor([3, 4, 2, 4, 4, 1], dtype=torch.int32)
Change the dtype of
xfromint32toint64.
x = x.type(torch.int64)
x
tensor([3, 4, 2, 4, 4, 1])
Reshape
xinto a 3x2 tensor.
x = x.reshape(3,2)
x
tensor([[3, 4],
[2, 4],
[4, 1]])
Return the right-hand column of tensor
x.
x[:,1]
tensor([4, 4, 1])
Without changing
x, return a tensor of square values ofx.
torch.square(x)
tensor([[ 9, 16],
[ 4, 16],
[16, 1]])
Create a tensor
ywith the same number of elements asx, that can be matrix-multiplied withx.
torch.manual_seed(seed)
y = torch.randint_like(x.T, 0, 5)
y
tensor([[2, 1, 1],
[2, 4, 0]])
Find the matrix product of
xandy.
torch.mm(x,y)
tensor([[14, 19, 3],
[12, 18, 2],
[10, 8, 4]])