Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Classifying Flowers | Neural Networks in PyTorch
PyTorch Essentials

book
Challenge: Classifying Flowers

Task

Swipe to start coding

Your goal is to train and evaluate a simple neural network using the Iris dataset, which consists of flower measurements and species classification.

  1. Split the dataset into training and testing sets allocating 20% for the test set and setting random state to 42.
  2. Convert X_train and X_test into PyTorch tensors of type float32.
  3. Convert y_train and y_test into PyTorch tensors of type long.
  4. Define a neural network model by creating the IrisModel class.
  5. Implement two fully connected layers and apply the ReLU activation function in the hidden layer.
  6. Initialize the model with the correct input size, hidden layer size equal to 16, and output size.
  7. Define the loss as cross-entropy loss and the optimizer as Adam with a learning rate of 0.01.
  8. Train the model for 100 epochs by performing forward propagation, computing loss, performing backpropagation, and updating the model's parameters.
  9. Set the model to evaluation mode after training.
  10. Disable gradient computation during testing to improve efficiency.
  11. Compute predictions on the test set using the trained model.
  12. Determine the predicted class labels based on raw predictions.

Solution

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pandas as pd
from sklearn.model_selection import train_test_split

torch.manual_seed(42)
iris_df = pd.read_csv("https://content-media-cdn.codefinity.com/courses/1dd2b0f6-6ec0-40e6-a570-ed0ac2209666/section_2/iris.csv")
X = iris_df.drop(columns=["species"]).values
y = iris_df["species"].values
# Split the data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Create tensors
X_train_tensor = torch.tensor(X_train, dtype=torch.float32)
X_test_tensor = torch.tensor(X_test, dtype=torch.float32)
y_train_tensor = torch.tensor(y_train, dtype=torch.long)
y_test_tensor = torch.tensor(y_test, dtype=torch.long)

# Define the model
class IrisModel(torch.nn.Module):
def __init__(self, input_size, hidden_size, output_size):
# Call the __init__ method of the parent class
super().__init__()
# Define the layers
self.fc1 = nn.Linear(input_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, output_size)

# Pass data through layers with activation functions
def forward(self, x):
# Apply ReLU to the outputs of the hidden layer
x = F.relu(self.fc1(x))
# Compute the output
x = self.fc2(x)
return x

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 3. Chapter 4
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import pandas as pd
from sklearn.model_selection import train_test_split

torch.manual_seed(42)
iris_df = pd.read_csv("https://content-media-cdn.codefinity.com/courses/1dd2b0f6-6ec0-40e6-a570-ed0ac2209666/section_2/iris.csv")
X = iris_df.drop(columns=["species"]).values
y = iris_df["species"].values
# Split the data
X_train, X_test, y_train, y_test = ___
# Create tensors
X_train_tensor = ___
X_test_tensor = ___
y_train_tensor = ___
y_test_tensor =___

# Define the model
___:
def __init__(self, input_size, hidden_size, output_size):
# Call the __init__ method of the parent class
___
# Define the layers
self.fc1 = ___
self.fc2 = ___

# Pass data through layers with activation functions
def forward(self, x):
# Apply ReLU to the output of the hidden layer
x = ___
# Compute the output
x = ___
return x

input_size = X.shape[1]
output_size = len(iris_df["species"].unique())
# Initialize the model
model = IrisModel(input_size=___, hidden_size=___, output_size=___)
# Define loss and optimizer
criterion = torch.nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.01)

epochs = 100
for epoch in range(epochs):
# Zero out gradients from the previous step
___
# Compute predictions
y_pred = ___
# Compute the loss
loss = ___
# Compute gradients
___
# Update parameters
___

if epoch % 10 == 0:
print(f"Epoch {epoch}, Loss: {loss.item()}")

# Set the model to evaluation mode
___
# Disable gradient computation for evaluation
toggle bottom row
some-alt