Laboratory Task 5#
\(name:\) Dane Casey C. Casino
\(Section:\) DS4A
Perform Standard Imports
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.
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.
Create a tensor “x” from the array above
Change the dtype of x from int32 to int64
Reshape x into 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 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.
Find the matrix product of x and 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.
set_seed(42)
arr = np.random.randint(0, 5, size=6)
print("Numpy array:", arr)
Numpy array: [3 4 2 4 4 1]
# 4. Create a tensor "x" from the array above
x = torch.from_numpy(arr)
x
tensor([3, 4, 2, 4, 4, 1], dtype=torch.int32)
# 5. Change the dtype of x from int32 to int64
x = x.to(torch.int64)
print("Tensor x with dtype int64:", x)
Tensor x with dtype int64: tensor([3, 4, 2, 4, 4, 1])
# 6. Reshape x into a 3x2 tensor
x = x.view(3, 2)
print("Reshaped tensor x:", x)
Reshaped tensor x: tensor([[3, 4],
[2, 4],
[4, 1]])
# 7. Return the right-hand column of tensor x
right_column = x[:, 1]
print("Right hand column of x:", right_column)
Right hand column of x: tensor([4, 4, 1])
# 8. Without changing x, return a tensor of square values of x
x_sqaured = x.pow(2)
print("Tensor x squared:", x_sqaured)
Tensor x squared: 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
set_seed (42)
y = torch.randint(0, 5, size=(2, 3))
print("Tensor y:", y)
Tensor y: tensor([[2, 2, 1],
[4, 1, 0]])
# 10. Find the matrix product of x and y.
product = torch.matmul(x, y)
print("Matrix product of x and y:", product)
Matrix product of x and y: tensor([[22, 10, 3],
[20, 8, 2],
[12, 9, 4]])