PyTorch Exercises
Problem 1: Create a 1D PyTorch tensor containing the numbers 1 through 5. Multiply the tensor by 2, and then convert the final PyTorch tensor back into a standard NumPy array.
import torch
import numpy as np
# 1. Create a PyTorch tensor
numbers = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0])
# 2. Perform element-wise math (Vectorization)
multiplied_tensor = numbers * 2
# 3. Convert back to a NumPy array
numpy_array = multiplied_tensor.numpy()
print("PyTorch Tensor:
", multiplied_tensor)
print("
NumPy Array:
", numpy_array)
Problem 2: Just like TensorFlow’s GradientTape, PyTorch calculates derivatives for you. Create a tensor for $x = 2.0$ and tell PyTorch to track its gradients. Then, calculate the equation $y = 3x^2 + 2x$, and use PyTorch to find the derivative of $y$ with respect to $x$.(Note: The calculus derivative is $6x + 2$, so if $x=2$, the answer should be $14$).
import torch
# 1. Create a tensor and tell PyTorch to track its operations
x = torch.tensor(2.0, requires_grad=True)
# 2. Define the mathematical equation
y = 3 * x**2 + 2 * x
# 3. Trigger the automatic gradient calculation
y.backward()
# 4. Extract the calculated derivative
derivative = x.grad
print(f"The value of x is: {x.item()}")
print(f"The derivative of the equation at x=2 is: {derivative.item()}")
Problem 3: While PyTorch has a Sequential API, the standard way to build neural networks in PyTorch is using Object-Oriented Python (Classes). Build a simple neural network class with one hidden layer (using a ReLU activation) and an output layer. Then, pass some dummy data through it to get a prediction.
import torch
import torch.nn as nn
import torch.nn.functional as F
# 1. Define the Neural Network Class
class SimpleNet(nn.Module):
def __init__(self):
super(SimpleNet, self).__init__()
# Define the layers (e.g., 4 inputs, 8 hidden neurons, 3 outputs)
self.hidden_layer = nn.Linear(4, 8)
self.output_layer = nn.Linear(8, 3)
def forward(self, x):
# Define how data flows through the layers
x = self.hidden_layer(x)
x = F.relu(x) # Apply activation function
x = self.output_layer(x)
return x
# 2. Initialize the model
model = SimpleNet()
# 3. Create a dummy input tensor (1 batch of 4 features)
dummy_input = torch.randn(1, 4)
# 4. Pass the data through the model (this automatically calls the forward method)
prediction = model(dummy_input)
print("Dummy Input:
", dummy_input)
print("
Model Prediction (Raw outputs for 3 categories):
", prediction)