File size: 11,981 Bytes
2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab 2c7f915 4b95eab | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 | {
"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
}
|