{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Question 2: Predict Age from Face Images\n", "\n", "You are provided with a face image dataset containing 2000 images of human faces. Your objective is to develop a regression model using PyTorch that accurately predicts the age of a person based on their face image.\n", "\n", "You are provided with the code to download and load the dataset.\n", "\n", "Your work will be evaluated based on the completion of the following tasks:\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 1. Load and Process Data (Provided)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### **1. Load and Process Data (Provided)**\n", "\n", "The code below is provided for you. It:\n", "1. Loads images from the `images` folder.\n", "2. Loads labels from `labels.csv`.\n", "3. Splits the data into training and testing sets (`X_train`, `X_test`, `y_train`, `y_test`).\n", "\n", "**Just run these cell to load the data.**" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import kagglehub\n", "\n", "# Download latest version\n", "path = kagglehub.dataset_download(\"mohammad2012191/q2-ka-ai-2026\")\n", "\n", "print(\"Path to dataset files:\", path)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import os\n", "import pandas as pd\n", "import numpy as np\n", "from PIL import Image\n", "from sklearn.model_selection import train_test_split\n", "\n", "# Load Labels\n", "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n", "img_dir = os.path.join(path, \"images\")\n", "\n", "images = []\n", "ages = []\n", "\n", "# Load Images and Resize\n", "print(\"Loading images...\")\n", "for index, row in labels_df.iterrows():\n", " img_name = row.iloc[0]\n", " age = row.iloc[1]\n", " img_path = os.path.join(img_dir, img_name)\n", " \n", " if os.path.exists(img_path):\n", " img = Image.open(img_path).convert('RGB')\n", " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n", " images.append(img_array)\n", " ages.append(age)\n", "\n", "X = np.array(images)\n", "y = np.array(ages)\n", "\n", "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n", "X = np.transpose(X, (0, 3, 1, 2))\n", "\n", "# Split Data\n", "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n", "\n", "print(f\"X_train shape: {X_train.shape}\")\n", "print(f\"X_test shape: {X_test.shape}\")\n", "print(f\"y_train shape: {y_train.shape}\")\n", "print(f\"y_test shape: {y_test.shape}\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## **Part 1: Prepare Data for PyTorch**\n", "\n", "**Tasks:**\n", "1. **Convert to Tensors:** Convert the numpy arrays (`X_train`, `X_test`, `y_train`, `y_test`) into PyTorch tensors.\n", "2. **Create Datasets:** Use `TensorDataset` to create `train_dataset` and `test_dataset` from the tensors.\n", "3. **Create DataLoaders:** Create `train_loader` and `test_loader` with a batch size of 32. \n", "4. **Inspect Data:** Print the shape of one batch from the train loader and \n", "5. **Display a few images:** Use matplotlib to display a few images." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "\n", "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n", "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n", "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n", "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from torch.utils.data import TensorDataset\n", "\n", "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n", "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from torch.utils.data import DataLoader\n", "\n", "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n", "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "images, labels = next(iter(train_loader))\n", "print(f\"Batch images shape: {images.shape}\")\n", "print(f\"Batch labels shape: {labels.shape}\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt\n", "\n", "plt.figure(figsize=(10, 5))\n", "for i in range(4):\n", " plt.subplot(1, 4, i+1)\n", " img = images[i].permute(1, 2, 0).numpy()\n", " plt.imshow(img)\n", " plt.title(f\"Age: {labels[i].item():.0f}\")\n", " plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 2: Model\n", "\n", "**Tasks:**\n", "\n", "1. Create a model class with **4 linear layers**\n", "2. Create a training loop function\n", "3. Create a validation loop function\n", "4. Define the device, model, loss function, and optimizer\n", "5. Start training for **20 epochs** and track training and validation losses" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch.nn as nn\n", "\n", "class AgeModel(nn.Module):\n", " def __init__(self, input_dim, hidden_dim, output_dim):\n", " super(AgeModel, self).__init__()\n", " self.layer1 = nn.Linear(input_dim, hidden_dim)\n", " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n", " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n", " self.layer4 = nn.Linear(hidden_dim, output_dim)\n", " self.relu = nn.ReLU()\n", "\n", " def forward(self, x):\n", " x = self.relu(self.layer1(x))\n", " x = self.relu(self.layer2(x))\n", " x = self.relu(self.layer3(x))\n", " x = self.layer4(x)\n", " return x.squeeze()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n", " # Set the model to training mode\n", " model.train()\n", "\n", " running_loss = 0.0\n", "\n", " for X_batch, y_batch in train_loader:\n", " # Move batch to the selected device\n", " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", " y_batch = y_batch.to(device)\n", "\n", " # Forward pass\n", " outputs = model(X_batch)\n", " loss = criterion(outputs, y_batch)\n", "\n", " # Backward pass & optimization\n", " optimizer.zero_grad() # Clear previous gradients\n", " loss.backward() # Compute gradients\n", " optimizer.step() # Update model parameters\n", "\n", " running_loss += loss.item()\n", "\n", " # Average loss over all batches\n", " avg_loss = running_loss / len(train_loader)\n", "\n", " return avg_loss" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def validate(model, criterion, test_loader, device):\n", " # Set the model to evaluation mode\n", " model.eval()\n", "\n", " running_loss = 0.0\n", "\n", " with torch.no_grad():\n", " for X_batch, y_batch in test_loader:\n", " # Move data to device\n", " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n", " y_batch = y_batch.to(device)\n", "\n", " # Forward pass\n", " outputs = model(X_batch)\n", " loss = criterion(outputs, y_batch)\n", " running_loss += loss.item()\n", "\n", " avg_loss = running_loss / len(test_loader)\n", "\n", " return avg_loss" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n", "\n", "input_dim = 36 * 36 * 3\n", "hidden_dim = 128\n", "output_dim = 1\n", "\n", "model = AgeModel(input_dim, hidden_dim, output_dim).to(device)\n", "\n", "num_epochs = 20\n", "learning_rate = 0.001\n", "\n", "criterion = nn.MSELoss()\n", "optimizer = torch.optim.AdamW(model.parameters(), learning_rate)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Run Training\n", "train_losses = []\n", "val_losses = []\n", "\n", "print('Starting Training...')\n", "for epoch in range(num_epochs):\n", " # Train one epoch\n", " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n", "\n", " # Validate\n", " val_loss = validate(model, criterion, test_loader, device)\n", "\n", " train_losses.append(train_loss)\n", " val_losses.append(val_loss)\n", "\n", " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n", "\n", "print('Training Complete!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Part 3: Plots\n", "\n", "**Tasks:**\n", "\n", "1. Plot the training and validation loss over epochs\n", "2. **Bonus:** Plot some predictions with their actual images (show predicted age vs actual age)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "plt.plot(train_losses, label='Train Loss')\n", "plt.plot(val_losses, label='Validation Loss')\n", "plt.title('Loss over Epochs')\n", "plt.xlabel('Epoch')\n", "plt.ylabel('Loss')\n", "plt.legend()\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model.eval()\n", "images, labels = next(iter(test_loader))\n", "images = images.to(device)\n", "with torch.no_grad():\n", " preds = model(images.view(images.size(0), -1))\n", "\n", "plt.figure(figsize=(10, 5))\n", "for i in range(4):\n", " plt.subplot(1, 4, i+1)\n", " img = images[i].cpu().permute(1, 2, 0).numpy()\n", " plt.imshow(img)\n", " plt.title(f\"Real: {labels[i].item():.0f}\\nPred: {preds[i].item():.0f}\")\n", " plt.axis(\"off\")\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.18" } }, "nbformat": 4, "nbformat_minor": 4 }