Laboratory Task 5 – Tensor Manipulations

Contents

Laboratory Task 5 – Tensor Manipulations#

Name: Joanna Reyda Santos
Section: DS4A

# 1. Standard Imports
import torch
import numpy as np
import matplotlib.pyplot as plt
# 2. Create the set_seed function
def set_seed(seed: int):
    """Sets the random seed for PyTorch and NumPy."""
    torch.manual_seed(seed)
    np.random.seed(seed)
# 3. Create a seeded NumPy array
set_seed(42)
arr = np.random.randint(0, 5, size=6)
print(f"NumPy array 'arr': {arr}\n")
NumPy array 'arr': [3 4 2 4 4 1]
# 4. Create a tensor 'x'
x = torch.from_numpy(arr)
print(f"Tensor 'x': {x}\n")
Tensor 'x': tensor([3, 4, 2, 4, 4, 1], dtype=torch.int32)
# 5. Change dtype to int64
x = x.to(torch.int64)
print(f"Dtype of 'x': {x.dtype}\n")
Dtype of 'x': torch.int64
# 6. Reshape x into a 3x2 tensor
x_reshaped = x.reshape(3, 2)
print(f"Reshaped 'x' (3x2):\n{x_reshaped}\n")
Reshaped 'x' (3x2):
tensor([[3, 4],
        [2, 4],
        [4, 1]])
# 7. Get the right-hand column
right_column = x_reshaped[:, 1]
print(f"Right-hand column: {right_column}\n")
Right-hand column: tensor([4, 4, 1])
# 8. Get square values
x_squared = x_reshaped ** 2
print(f"Squared values:\n{x_squared}\n")
Squared values:
tensor([[ 9, 16],
        [ 4, 16],
        [16,  1]])
# 9. Create tensor y for matrix multiplication
set_seed(42)
y = torch.randint(0, 5, (2, 3), dtype=torch.int64)
print(f"Tensor 'y' (2x3):\n{y}\n")
Tensor 'y' (2x3):
tensor([[2, 2, 1],
        [4, 1, 0]])
# 10. Find the matrix product
matrix_product = torch.matmul(x_reshaped, y)
print(f"Matrix product of x and y:\n{matrix_product}\n")
Matrix product of x and y:
tensor([[22, 10,  3],
        [20,  8,  2],
        [12,  9,  4]])

Reflection#

From the tensor operations and outputs, I confirmed that PyTorch handles numerical data efficiently — reshaping, slicing, and performing matrix operations with ease. The computed matrix product validated my understanding of how tensors interact dimensionally. This hands-on practice helped me visualize how tensors act as the foundation for data flow inside deep learning models.