Laboratory Task 5#
Genheylou Felisilda - DS4A
Instructions: Pytorch Excercises
Perform Standard Imports
Create a function called
set_seed()that acceptsseed: intas a parameter, this function must return nothing but just set the seed to a certain valueCreate a NumPy array called “arr” that contains 6 random integers between 0 (inclusive) and 5 (exclusive), call the
set_seed()function and use42as the seed parameter.Create a tensor “x” from the array above
Change the dtype of x from
int32toint64Reshape
xinto a 3x2 tensor
There are several ways to do this.Return the right-hand column of tensor `x
Without changing x, return a tensor of square values of `x
There are several ways to do this.Create a tensor
ywith the same number of elements asx, 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.Find the matrix product of
xand `y
#1 Perform Standard Imports
import torch
import numpy as np
import sys
#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.
arr = np.random.randint(0,5, size=6)
arr
array([4, 4, 2, 4, 4, 2], dtype=int32)
#4 Create a tensor "x" from the array above
x = torch.from_numpy(arr)
print(x)
tensor([4, 4, 2, 4, 4, 2], dtype=torch.int32)
#5 Change the dtype of x from int32 to int64
print("Old:", x.dtype)
x = x.type(torch.int64)
print("New:", x.dtype)
Old: torch.int32
New: torch.int64
#6 Reshape x into a 3x2 tensor
reshaped = x.reshape(3,2)
reshaped
tensor([[4, 4],
[2, 4],
[4, 2]])
#7 Return the right-hand column of tensor x
right_col = reshaped[:, 1:]
right_col
tensor([[4],
[4],
[2]])
#8 Without changing x, return a tensor of square values of x
x_squared = reshaped ** 2
x_squared
tensor([[16, 16],
[ 4, 16],
[16, 4]])
#9 Create a tensor y with the same number of elements as x, that can be matrix-multiplied with x
torch.manual_seed(42)
y = torch.rand(2,3)
y
tensor([[0.8823, 0.9150, 0.3829],
[0.9593, 0.3904, 0.6009]])
#10 Find the matrix product of x and y.
product = y.mul(y)
product
tensor([[0.7784, 0.8372, 0.1466],
[0.9203, 0.1524, 0.3611]])