Intro to AI Stage 2 practical exam: 1038 dual-graded students, rubric, solutions (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- submissions_extracted/296/Q2.ipynb +441 -0
- submissions_extracted/296/Q3.ipynb +338 -0
- submissions_extracted/297/Q1.ipynb +310 -0
- submissions_extracted/297/Q2.ipynb +274 -0
- submissions_extracted/297/Q3.ipynb +218 -0
- submissions_extracted/298/Q1.ipynb +281 -0
- submissions_extracted/298/Q2.ipynb +392 -0
- submissions_extracted/298/Q3.ipynb +251 -0
- submissions_extracted/299/Q1.ipynb +324 -0
- submissions_extracted/299/Q2.ipynb +413 -0
- submissions_extracted/299/Q3.ipynb +312 -0
- submissions_extracted/3/Q1.ipynb +201 -0
- submissions_extracted/3/Q2.ipynb +192 -0
- submissions_extracted/3/Q3.ipynb +185 -0
- submissions_extracted/30/Q1.ipynb +223 -0
- submissions_extracted/30/Q2.ipynb +192 -0
- submissions_extracted/30/Q3.ipynb +160 -0
- submissions_extracted/300/Q1.ipynb +244 -0
- submissions_extracted/300/Q2.ipynb +274 -0
- submissions_extracted/300/Q3.ipynb +207 -0
- submissions_extracted/301/Q1.ipynb +282 -0
- submissions_extracted/301/Q2.ipynb +372 -0
- submissions_extracted/301/Q3.ipynb +249 -0
- submissions_extracted/302/Q1.ipynb +237 -0
- submissions_extracted/302/Q2.ipynb +335 -0
- submissions_extracted/302/Q3.ipynb +226 -0
- submissions_extracted/303/Q1.ipynb +381 -0
- submissions_extracted/303/Q2.ipynb +413 -0
- submissions_extracted/303/Q3.ipynb +325 -0
- submissions_extracted/304/Q1.ipynb +400 -0
- submissions_extracted/304/Q2.ipynb +368 -0
- submissions_extracted/304/Q3.ipynb +341 -0
- submissions_extracted/305/Q1.ipynb +272 -0
- submissions_extracted/305/Q2.ipynb +391 -0
- submissions_extracted/305/Q3.ipynb +267 -0
- submissions_extracted/306/Q1.ipynb +373 -0
- submissions_extracted/306/Q2.ipynb +383 -0
- submissions_extracted/306/Q3.ipynb +281 -0
- submissions_extracted/307/Q1.ipynb +255 -0
- submissions_extracted/307/Q2.ipynb +341 -0
- submissions_extracted/307/Q3.ipynb +200 -0
- submissions_extracted/308/Q1.ipynb +325 -0
- submissions_extracted/308/Q2.ipynb +453 -0
- submissions_extracted/308/Q3.ipynb +464 -0
- submissions_extracted/309/Q1.ipynb +327 -0
- submissions_extracted/309/Q2.ipynb +466 -0
- submissions_extracted/309/Q3.ipynb +362 -0
- submissions_extracted/31/Q1.ipynb +186 -0
- submissions_extracted/31/Q2.ipynb +198 -0
- submissions_extracted/31/Q3.ipynb +168 -0
submissions_extracted/296/Q2.ipynb
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import torch\n",
|
| 10 |
+
"import torch.nn as nn\n",
|
| 11 |
+
"from torch.optim import AdamW\n",
|
| 12 |
+
"import matplotlib.pyplot as plt\n",
|
| 13 |
+
"import torch.nn.functional as F\n",
|
| 14 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 15 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 16 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder"
|
| 17 |
+
],
|
| 18 |
+
"execution_count": null,
|
| 19 |
+
"outputs": []
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "code",
|
| 23 |
+
"metadata": {},
|
| 24 |
+
"source": [
|
| 25 |
+
"import kagglehub\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Download latest version\n",
|
| 28 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"print(\"Path to dataset files:\", path)"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"import os\n",
|
| 40 |
+
"import pandas as pd\n",
|
| 41 |
+
"import numpy as np\n",
|
| 42 |
+
"from PIL import Image\n",
|
| 43 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Load Labels\n",
|
| 46 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 47 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"images = []\n",
|
| 50 |
+
"ages = []\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"# Load Images and Resize\n",
|
| 53 |
+
"print(\"Loading images...\")\n",
|
| 54 |
+
"for index, row in labels_df.iterrows():\n",
|
| 55 |
+
" img_name = row.iloc[0]\n",
|
| 56 |
+
" age = row.iloc[1]\n",
|
| 57 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
" if os.path.exists(img_path):\n",
|
| 60 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 61 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 62 |
+
" images.append(img_array)\n",
|
| 63 |
+
" ages.append(age)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"X = np.array(images)\n",
|
| 66 |
+
"y = np.array(ages)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 69 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Split Data\n",
|
| 72 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 75 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 76 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 77 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 89 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 90 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 91 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 2. Create TensorDataset objects\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 103 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# 3. Create DataLoaders\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"# DataLoader for training data\n",
|
| 115 |
+
"train_loader = DataLoader(\n",
|
| 116 |
+
" train_dataset,\n",
|
| 117 |
+
" batch_size=32,\n",
|
| 118 |
+
" shuffle=True,\n",
|
| 119 |
+
" num_workers=2\n",
|
| 120 |
+
")\n",
|
| 121 |
+
"# DataLoader for test/validation data\n",
|
| 122 |
+
"test_loader = DataLoader(\n",
|
| 123 |
+
" test_dataset,\n",
|
| 124 |
+
" batch_size=32,\n",
|
| 125 |
+
" shuffle=False,\n",
|
| 126 |
+
" num_workers=2\n",
|
| 127 |
+
")\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# 4. Print shape of one batch\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 141 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 142 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# 5. Display sample images\n",
|
| 152 |
+
"images, labels = next(iter(train_loader))\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"# Display the first 6 images in the batch\n",
|
| 155 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"for i in range(6):\n",
|
| 158 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 161 |
+
" img = images[i].permute(1, 2, 0) # this was to fix the shape but view wont work because the view corupts the images\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" plt.imshow(img)\n",
|
| 164 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 165 |
+
" plt.axis('off')\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"plt.tight_layout()\n",
|
| 168 |
+
"plt.show()"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 1: Write your model class here:\n",
|
| 178 |
+
"class NN4Layer(nn.Module):\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 181 |
+
" super(NN4Layer, self).__init__()\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 184 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 187 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 190 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 193 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # activation function for non-linearity\n",
|
| 196 |
+
" self.relu = nn.ReLU()\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # Defines how input data flows through the network\n",
|
| 199 |
+
" def forward(self, x):\n",
|
| 200 |
+
" # Layer 1\n",
|
| 201 |
+
" z1 = self.layer1(x)\n",
|
| 202 |
+
" a1 = self.relu(z1)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" # Layer 2\n",
|
| 205 |
+
" z2 = self.layer2(a1)\n",
|
| 206 |
+
" a2 = self.relu(z2)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Layer 3\n",
|
| 209 |
+
" z3 = self.layer3(a2)\n",
|
| 210 |
+
" a3 = self.relu(z3)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # Output layer\n",
|
| 213 |
+
" z4 = self.layer4(a3)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" return z4"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 2: Write your training loop here:\n",
|
| 226 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 227 |
+
" # Set the model to training mode\n",
|
| 228 |
+
" model.train()\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" running_loss = 0.0\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 233 |
+
" # Move batch to the selected device\n",
|
| 234 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 235 |
+
" y_batch = y_batch.to(device)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" # Forward pass\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" outputs = model(X_batch)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Backward pass & optimization\n",
|
| 244 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 245 |
+
" loss.backward() # Compute gradients\n",
|
| 246 |
+
" optimizer.step() # Update model parameters\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" running_loss += loss.item()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Average loss over all batches\n",
|
| 251 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" return avg_loss"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task 3: Write your validation loop here:\n",
|
| 263 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 264 |
+
" # Set the model to evaluation mode\n",
|
| 265 |
+
" model.eval()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" running_loss = 0.0\n",
|
| 268 |
+
" correct = 0\n",
|
| 269 |
+
" total = 0\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" with torch.no_grad():\n",
|
| 272 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 273 |
+
" # Move data to device\n",
|
| 274 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 275 |
+
" y_batch = y_batch.to(device)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Forward pass\n",
|
| 278 |
+
" # TODO: make predictions\n",
|
| 279 |
+
" outputs = model(X_batch)\n",
|
| 280 |
+
" # TODO: compute loss\n",
|
| 281 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 282 |
+
" running_loss += loss.item()\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 285 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # TODO: Multiclass predictions\n",
|
| 288 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
" # Accuracy calculation\n",
|
| 291 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 292 |
+
" total += y_batch.size(0)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 295 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"\n",
|
| 298 |
+
" return avg_loss"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 308 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"# Model parameters\n",
|
| 311 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 312 |
+
"input_dim = 3*36*36\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"hidden_dim = 30\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"# regretion\n",
|
| 318 |
+
"output_dim = 1\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 321 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"# TODO: Print the model architecture\n",
|
| 324 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 325 |
+
"print(model)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"# Calculate the total number of trainable parameters\n",
|
| 328 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 329 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 330 |
+
"num_epochs = 20\n",
|
| 331 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 332 |
+
"learning_rate = 0.0009\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 335 |
+
"criterion = nn.MSELoss()\n",
|
| 336 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 337 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n"
|
| 338 |
+
],
|
| 339 |
+
"execution_count": null,
|
| 340 |
+
"outputs": []
|
| 341 |
+
},
|
| 342 |
+
{
|
| 343 |
+
"cell_type": "code",
|
| 344 |
+
"metadata": {},
|
| 345 |
+
"source": [
|
| 346 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 347 |
+
"train_losses = []\n",
|
| 348 |
+
"val_losses = []\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"print('Starting Training...')\n",
|
| 351 |
+
"for epoch in range(num_epochs):\n",
|
| 352 |
+
" # Train one epoch\n",
|
| 353 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 354 |
+
"\n",
|
| 355 |
+
" # Validate\n",
|
| 356 |
+
" val_loss= validate(model, criterion, test_loader, device)\n",
|
| 357 |
+
"\n",
|
| 358 |
+
" train_losses.append(train_loss)\n",
|
| 359 |
+
" val_losses.append(val_loss)\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"print('Training Complete!')"
|
| 364 |
+
],
|
| 365 |
+
"execution_count": null,
|
| 366 |
+
"outputs": []
|
| 367 |
+
},
|
| 368 |
+
{
|
| 369 |
+
"cell_type": "code",
|
| 370 |
+
"metadata": {},
|
| 371 |
+
"source": [
|
| 372 |
+
"# Task 1: Write your code here:\n",
|
| 373 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 376 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 377 |
+
"plt.title('Loss over Epochs')\n",
|
| 378 |
+
"plt.xlabel('Epoch')\n",
|
| 379 |
+
"plt.ylabel('Loss')\n",
|
| 380 |
+
"plt.legend()\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"plt.tight_layout()\n",
|
| 383 |
+
"plt.show()\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"# the loss is not interpretabel since i am using MSE loss you didnt have the sentax for the MAE loss so i had to use MSE"
|
| 386 |
+
],
|
| 387 |
+
"execution_count": null,
|
| 388 |
+
"outputs": []
|
| 389 |
+
},
|
| 390 |
+
{
|
| 391 |
+
"cell_type": "code",
|
| 392 |
+
"metadata": {},
|
| 393 |
+
"source": [
|
| 394 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 395 |
+
"#images, labels = next(iter(test_loader))\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"\n",
|
| 398 |
+
"# Display the first 6 images in the batch\n",
|
| 399 |
+
"#plt.figure(figsize=(8, 4))\n",
|
| 400 |
+
"\n",
|
| 401 |
+
"#for i in range(6):\n",
|
| 402 |
+
" #plt.subplot(2, 3, i + 1)\n",
|
| 403 |
+
" #outputs = model(images[i].permute(1, 2, 0))\n",
|
| 404 |
+
" #probabilities = F.softmax(outputs, dim=1)\n",
|
| 405 |
+
"\n",
|
| 406 |
+
" # TODO: Multiclass predictions\n",
|
| 407 |
+
" #predicted = torch.argmax(probabilities, dim=1)\n",
|
| 408 |
+
"\n",
|
| 409 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 410 |
+
" #img = images[i].permute(1, 2, 0) # this was to fix the shape but view wont work because the view corupts the images\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" #plt.imshow(img)\n",
|
| 413 |
+
" #plt.title(f\"Label: {labels[i].item()}\" + f\"vs pred: {predicted}\")\n",
|
| 414 |
+
" #plt.axis('off')\n",
|
| 415 |
+
"\n",
|
| 416 |
+
"#plt.tight_layout()\n",
|
| 417 |
+
"#plt.show()"
|
| 418 |
+
],
|
| 419 |
+
"execution_count": null,
|
| 420 |
+
"outputs": []
|
| 421 |
+
},
|
| 422 |
+
{
|
| 423 |
+
"cell_type": "code",
|
| 424 |
+
"metadata": {},
|
| 425 |
+
"source": [],
|
| 426 |
+
"execution_count": null,
|
| 427 |
+
"outputs": []
|
| 428 |
+
}
|
| 429 |
+
],
|
| 430 |
+
"metadata": {
|
| 431 |
+
"kernelspec": {
|
| 432 |
+
"display_name": "Python 3",
|
| 433 |
+
"name": "python3"
|
| 434 |
+
},
|
| 435 |
+
"language_info": {
|
| 436 |
+
"name": "python"
|
| 437 |
+
}
|
| 438 |
+
},
|
| 439 |
+
"nbformat": 4,
|
| 440 |
+
"nbformat_minor": 0
|
| 441 |
+
}
|
submissions_extracted/296/Q3.ipynb
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"pip install catboost"
|
| 8 |
+
],
|
| 9 |
+
"execution_count": null,
|
| 10 |
+
"outputs": []
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "code",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"import numpy as np\n",
|
| 17 |
+
"import pandas as pd\n",
|
| 18 |
+
"import matplotlib.pyplot as plt\n",
|
| 19 |
+
"import os\n",
|
| 20 |
+
"import kagglehub\n",
|
| 21 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 22 |
+
"from catboost import CatBoostClassifier\n",
|
| 23 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 24 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 27 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 28 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 29 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"import kagglehub\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"# Download latest version\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"print(\"Path to dataset files:\", path)"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 1: Write your code here:\n",
|
| 58 |
+
"Q3_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 59 |
+
"Q3_data = pd.read_csv(Q3_path)"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 2: Write your code here:\n",
|
| 69 |
+
"Q3_data.head()"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 3: Write your code here:\n",
|
| 79 |
+
"Q3_data.info()"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Task 4: Write your code here:\n",
|
| 89 |
+
"Q3_data.describe()"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"# Task 1: Write your code here:\n",
|
| 99 |
+
"categorical_cols = Q3_data.select_dtypes(include=[\"object\"]).columns\n",
|
| 100 |
+
"num_cols = Q3_data.select_dtypes(include=[\"int64\", \"float64\"]).columns\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"for col in categorical_cols:\n",
|
| 103 |
+
" Q3_data[col] = Q3_data[col].fillna(Q3_data[col].mode()[0])\n",
|
| 104 |
+
"for col in num_cols:\n",
|
| 105 |
+
" Q3_data[col] = Q3_data[col].fillna(Q3_data[col].mean())\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"Q3_data.head()"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# Task 2: Write your code here:\n",
|
| 118 |
+
"def check_duplicates(df):\n",
|
| 119 |
+
" duplicates = df.duplicated().sum()\n",
|
| 120 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 121 |
+
" if duplicates > 0:\n",
|
| 122 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 123 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 124 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 125 |
+
" else:\n",
|
| 126 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"check_duplicates(Q3_data)\n",
|
| 129 |
+
"Q3_data.info()"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"#there is no categorical columns but i wrote the code just in case\n",
|
| 139 |
+
"print(categorical_cols)"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 3: Write your code here:\n",
|
| 149 |
+
"#in comment because we dont need it\n",
|
| 150 |
+
"#for col in categorical_cols:\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" #le = LabelEncoder()\n",
|
| 153 |
+
" #Q3_data[col] = le.fit_transform(Q3_data[col].astype(str))\n",
|
| 154 |
+
"\n"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 4: Write your code here:\n",
|
| 164 |
+
"# no scaling for my target\n",
|
| 165 |
+
"features_cols = Q3_data.select_dtypes(include=[\"int64\", \"float64\", \"object\"]).columns.drop(\"Target\")\n",
|
| 166 |
+
"scaler = StandardScaler()\n",
|
| 167 |
+
"Q3_data[features_cols] = scaler.fit_transform(Q3_data[features_cols])\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"Q3_data.head()"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 5: Write your code here:\n",
|
| 179 |
+
"Q3_data[\"Target\"].hist()\n",
|
| 180 |
+
"# it is clearly inbalanced"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Task 1: Write your code here:\n",
|
| 190 |
+
"X = Q3_data[features_cols]\n",
|
| 191 |
+
"y = Q3_data[\"Target\"]\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"X.info()\n"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 203 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 204 |
+
"lr_accuracy = []\n",
|
| 205 |
+
"lr_f1 = []\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"model = CatBoostClassifier(\n",
|
| 208 |
+
" verbose=0,\n",
|
| 209 |
+
" n_estimators=20,\n",
|
| 210 |
+
" max_depth=4)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 213 |
+
" # indexing for each fold\n",
|
| 214 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 215 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" model.fit(X_train, y_train)\n",
|
| 218 |
+
" y_pred = model.predict(X_test)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 221 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" lr_accuracy.append(accuracy)\n",
|
| 225 |
+
" lr_f1.append(f1)\n",
|
| 226 |
+
" # showing class distribution\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"print(\"LOGISTIC REGRESSION Performance:\")\n",
|
| 234 |
+
"print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n",
|
| 235 |
+
"print(f\" F1: {np.mean(lr_f1):.4f}\")\n"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 244 |
+
"# Task 1: Write your code here:\n",
|
| 245 |
+
"feature_importance = pd.DataFrame({\n",
|
| 246 |
+
" 'feature': features_cols,\n",
|
| 247 |
+
" 'importance': model.feature_importances_\n",
|
| 248 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"# to get the feature at the top since the graghp dosnt show it\n",
|
| 251 |
+
"print(feature_importance[\"feature\"][0])\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 254 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 255 |
+
"plt.xlabel('Importance')\n",
|
| 256 |
+
"plt.title('Feature Importance')\n",
|
| 257 |
+
"plt.gca().invert_yaxis()\n",
|
| 258 |
+
"plt.show()"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"# Task 2: Write your code here:\n",
|
| 268 |
+
"print(feature_importance[\"feature\"][0])\n"
|
| 269 |
+
],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"# Task Bonus: Write your code here:\n",
|
| 278 |
+
"X_new = X[\"P_2\"]\n",
|
| 279 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 280 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 281 |
+
"lr_accuracy = []\n",
|
| 282 |
+
"lr_f1 = []\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"model = CatBoostClassifier(\n",
|
| 285 |
+
" verbose=0,\n",
|
| 286 |
+
" n_estimators=20,\n",
|
| 287 |
+
" max_depth=4)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # use the singel feature only but same y\n",
|
| 290 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X_new, y), start=1):\n",
|
| 291 |
+
" # indexing for each fold\n",
|
| 292 |
+
" X_train_new, X_test_new = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 293 |
+
" y_train_new, y_test_new = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" model.fit(X_train_new, y_train_new)\n",
|
| 296 |
+
" y_pred_new = model.predict(X_test_new)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
" accuracy = accuracy_score(y_test_new, y_pred_new)\n",
|
| 299 |
+
" f1 = f1_score(y_test_new, y_pred_new, zero_division=0)\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" lr_accuracy.append(accuracy)\n",
|
| 303 |
+
" lr_f1.append(f1)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"print(\"LOGISTIC REGRESSION Performance:\")\n",
|
| 308 |
+
"print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n",
|
| 309 |
+
"print(f\" F1: {np.mean(lr_f1):.4f}\")\n",
|
| 310 |
+
"\n"
|
| 311 |
+
],
|
| 312 |
+
"execution_count": null,
|
| 313 |
+
"outputs": []
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "code",
|
| 317 |
+
"metadata": {},
|
| 318 |
+
"source": [
|
| 319 |
+
"# with all features Accuracy: 0.8363\n",
|
| 320 |
+
"# F1: 0.6827\n",
|
| 321 |
+
"# as you can see we got same acc and F1 score even with using 1 featuer only"
|
| 322 |
+
],
|
| 323 |
+
"execution_count": null,
|
| 324 |
+
"outputs": []
|
| 325 |
+
}
|
| 326 |
+
],
|
| 327 |
+
"metadata": {
|
| 328 |
+
"kernelspec": {
|
| 329 |
+
"display_name": "Python 3",
|
| 330 |
+
"name": "python3"
|
| 331 |
+
},
|
| 332 |
+
"language_info": {
|
| 333 |
+
"name": "python"
|
| 334 |
+
}
|
| 335 |
+
},
|
| 336 |
+
"nbformat": 4,
|
| 337 |
+
"nbformat_minor": 0
|
| 338 |
+
}
|
submissions_extracted/297/Q1.ipynb
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"import matplotlib.pyplot as plt\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 17 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 18 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 19 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"# Download latest version\n",
|
| 24 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(\"Path to dataset files:\", path)"
|
| 27 |
+
],
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"source": [
|
| 35 |
+
"df = pd.read_csv(path + \"/Q1_data.csv\")\n"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"df.head()\n"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"df.info()\n"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"df.describe()\n"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"plt.hist(df[\"Delivery_Time\"], bins=20)\n",
|
| 72 |
+
"plt.xlabel(\"Delivery Time\")\n",
|
| 73 |
+
"plt.ylabel(\"Frequency\")\n",
|
| 74 |
+
"plt.title(\"Delivery Time Distribution\")\n",
|
| 75 |
+
"plt.show()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"df = df.drop(columns=[\"Order_ID\"])\n"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns\n",
|
| 94 |
+
"cat_cols = df.select_dtypes(include=[\"object\"]).columns"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"for col in num_cols:\n",
|
| 104 |
+
" df[col] = df[col].fillna(df[col].median())"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"df = pd.get_dummies(df, drop_first=True)\n"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"X = df.drop(columns=[\"Delivery_Time\"])\n",
|
| 123 |
+
"y = df[\"Delivery_Time\"]\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"scaler = StandardScaler()\n",
|
| 126 |
+
"X_scaled = scaler.fit_transform(X)"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"y = df[\"Delivery_Time\"]\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"if y.nunique() <= 10:\n",
|
| 138 |
+
" counts = y.value_counts()\n",
|
| 139 |
+
" ratio = counts.min() / counts.max()\n",
|
| 140 |
+
"\n",
|
| 141 |
+
" print(\"Classification target\")\n",
|
| 142 |
+
" print(\"Class counts:\\n\", counts)\n",
|
| 143 |
+
" print(\"Imbalance ratio:\", round(ratio, 2))\n",
|
| 144 |
+
"else:\n",
|
| 145 |
+
" print(\"Regression target\")\n",
|
| 146 |
+
" print(y.describe())"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"import numpy as np\n",
|
| 156 |
+
"from sklearn.model_selection import KFold, StratifiedKFold\n",
|
| 157 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 158 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"X = df.drop(columns=[\"Delivery_Time\"])\n",
|
| 161 |
+
"y = df[\"Delivery_Time\"]\n"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# Task 2,3,4,5: CV split + Train RandomForest + Evaluate using MAE + Print average MAE\n",
|
| 171 |
+
"import numpy as np\n",
|
| 172 |
+
"from sklearn.model_selection import KFold, StratifiedKFold\n",
|
| 173 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 174 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"if y.nunique() <= 10:\n",
|
| 178 |
+
" cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 179 |
+
" splits = cv.split(X, y)\n",
|
| 180 |
+
"else:\n",
|
| 181 |
+
" cv = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 182 |
+
" splits = cv.split(X)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"mae_scores = []\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"for train_idx, test_idx in splits:\n",
|
| 187 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 188 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" model = RandomForestRegressor(random_state=42)\n",
|
| 191 |
+
" model.fit(X_train, y_train)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" y_pred = model.predict(X_test)\n",
|
| 194 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 195 |
+
" mae_scores.append(mae)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"print(\"MAE scores per fold:\", np.round(mae_scores, 3))\n",
|
| 198 |
+
"print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"import matplotlib.pyplot as plt\n",
|
| 208 |
+
"import pandas as pd\n",
|
| 209 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"# Train a final model on the entire dataset X and y\n",
|
| 212 |
+
"# This model variable will then be used for feature importance\n",
|
| 213 |
+
"model = RandomForestRegressor(random_state=42)\n",
|
| 214 |
+
"model.fit(X, y)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"feature_importance = pd.Series(\n",
|
| 217 |
+
" model.feature_importances_, index=X.columns\n",
|
| 218 |
+
").sort_values(ascending=False)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"plt.figure(figsize=(8,4))\n",
|
| 221 |
+
"feature_importance.plot(kind=\"bar\")\n",
|
| 222 |
+
"plt.ylabel(\"Importance\")\n",
|
| 223 |
+
"plt.title(\"Feature Importance\")\n",
|
| 224 |
+
"plt.show()"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"import matplotlib.pyplot as plt\n",
|
| 234 |
+
"import pandas as pd\n",
|
| 235 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"# Ensure model is defined if this cell is run independently\n",
|
| 238 |
+
"# Check if 'model' exists in global scope and is an instance of RandomForestRegressor\n",
|
| 239 |
+
"if 'model' not in globals() or not isinstance(globals().get('model'), RandomForestRegressor):\n",
|
| 240 |
+
" # If not, train a new model for this cell's execution\n",
|
| 241 |
+
" model = RandomForestRegressor(random_state=42)\n",
|
| 242 |
+
" model.fit(X, y)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"y_pred = model.predict(X)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"plt.figure(figsize=(6,4))\n",
|
| 247 |
+
"plt.hist(y_pred, bins=20)\n",
|
| 248 |
+
"plt.xlabel(\"Predicted Delivery Time\")\n",
|
| 249 |
+
"plt.ylabel(\"Frequency\")\n",
|
| 250 |
+
"plt.title(\"Predicted Delivery Time Distribution\")\n",
|
| 251 |
+
"plt.show()"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"!pip install catboost\n",
|
| 261 |
+
"import numpy as np\n",
|
| 262 |
+
"from sklearn.model_selection import KFold\n",
|
| 263 |
+
"from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor\n",
|
| 264 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 265 |
+
"from catboost import CatBoostRegressor # Added CatBoostRegressor import\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"mae_scores = []\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"for train_idx, test_idx in kf.split(X):\n",
|
| 272 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 273 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" rf = RandomForestRegressor(random_state=42)\n",
|
| 276 |
+
" cb = CatBoostRegressor(verbose=0, random_state=42)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" rf.fit(X_train, y_train)\n",
|
| 279 |
+
" cb.fit(X_train, y_train)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" pred_rf = rf.predict(X_test)\n",
|
| 282 |
+
" pred_cb = cb.predict(X_test)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" pred_avg = (pred_rf + pred_cb) / 2\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" mae = mean_absolute_error(y_test, pred_avg)\n",
|
| 287 |
+
" mae_scores.append(mae)\n",
|
| 288 |
+
" # Evaluate with MAE on averaged predictions; store per‑fold score\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"print(\"MAE per fold:\", np.round(mae_scores, 3))\n",
|
| 291 |
+
"print(\"Average MAE:\", round(np.mean(mae_scores), 3))\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# Report fold‑wise MAE (rounded) and the overall cross‑validated average MAE"
|
| 294 |
+
],
|
| 295 |
+
"execution_count": null,
|
| 296 |
+
"outputs": []
|
| 297 |
+
}
|
| 298 |
+
],
|
| 299 |
+
"metadata": {
|
| 300 |
+
"kernelspec": {
|
| 301 |
+
"display_name": "Python 3",
|
| 302 |
+
"name": "python3"
|
| 303 |
+
},
|
| 304 |
+
"language_info": {
|
| 305 |
+
"name": "python"
|
| 306 |
+
}
|
| 307 |
+
},
|
| 308 |
+
"nbformat": 4,
|
| 309 |
+
"nbformat_minor": 0
|
| 310 |
+
}
|
submissions_extracted/297/Q2.ipynb
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"import torch\n",
|
| 69 |
+
"from torch.utils.data import TensorDataset, DataLoader\n",
|
| 70 |
+
"import matplotlib.pyplot as plt\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 73 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 74 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 75 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 85 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 95 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"images_batch, ages_batch = next(iter(train_loader))\n",
|
| 105 |
+
"print(\"Images batch shape:\", images_batch.shape)\n",
|
| 106 |
+
"print(\"Ages batch shape:\", ages_batch.shape)\n",
|
| 107 |
+
"#DataLoader loads the dataset in mini‑batches, which makes training faster and more memory‑efficient"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"plt.figure(figsize=(8,4))\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"for i in range(6):\n",
|
| 119 |
+
" img = images_batch[i].permute(1, 2, 0) # Convert from (C, H, W) to (H, W, C)\n",
|
| 120 |
+
" plt.subplot(2, 3, i+1)\n",
|
| 121 |
+
" plt.imshow(img)\n",
|
| 122 |
+
" plt.title(f\"Age: {ages_batch[i].item()}\")\n",
|
| 123 |
+
" plt.axis(\"off\")\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"plt.tight_layout()\n",
|
| 126 |
+
"plt.show()"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"import torch\n",
|
| 136 |
+
"import torch.nn as nn\n",
|
| 137 |
+
"import torch.optim as optim\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"class AgeMLP(nn.Module):\n",
|
| 140 |
+
" def __init__(self, input_size):\n",
|
| 141 |
+
" super(AgeMLP, self).__init__()\n",
|
| 142 |
+
" self.net = nn.Sequential(\n",
|
| 143 |
+
" nn.Linear(input_size, 512),\n",
|
| 144 |
+
" nn.ReLU(),\n",
|
| 145 |
+
" nn.Linear(512, 256),\n",
|
| 146 |
+
" nn.ReLU(),\n",
|
| 147 |
+
" nn.Linear(256, 128),\n",
|
| 148 |
+
" nn.ReLU(),\n",
|
| 149 |
+
" nn.Linear(128, 1)\n",
|
| 150 |
+
" )\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" def forward(self, x):\n",
|
| 153 |
+
" x = x.view(x.size(0), -1) # flatten\n",
|
| 154 |
+
" return self.net(x)\n",
|
| 155 |
+
"\n"
|
| 156 |
+
],
|
| 157 |
+
"execution_count": null,
|
| 158 |
+
"outputs": []
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"cell_type": "code",
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"source": [
|
| 164 |
+
"def train_one_epoch(model, loader, criterion, optimizer, device):\n",
|
| 165 |
+
" model.train()\n",
|
| 166 |
+
" total_loss = 0\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" for X_batch, y_batch in loader:\n",
|
| 169 |
+
" X_batch = X_batch.to(device)\n",
|
| 170 |
+
" y_batch = y_batch.to(device).float().view(-1, 1)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" optimizer.zero_grad()\n",
|
| 173 |
+
" preds = model(X_batch)\n",
|
| 174 |
+
" loss = criterion(preds, y_batch)\n",
|
| 175 |
+
" loss.backward()\n",
|
| 176 |
+
" optimizer.step()\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" total_loss += loss.item()\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" return total_loss / len(loader)"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"def validate(model, loader, criterion, device):\n",
|
| 190 |
+
" model.eval()\n",
|
| 191 |
+
" total_loss = 0\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" with torch.no_grad():\n",
|
| 194 |
+
" for X_batch, y_batch in loader:\n",
|
| 195 |
+
" X_batch = X_batch.to(device)\n",
|
| 196 |
+
" y_batch = y_batch.to(device).float().view(-1, 1)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" preds = model(X_batch)\n",
|
| 199 |
+
" loss = criterion(preds, y_batch)\n",
|
| 200 |
+
" total_loss += loss.item()\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" return total_loss / len(loader)"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"sample_X, _ = next(iter(train_loader))\n",
|
| 214 |
+
"input_size = sample_X[0].numel()\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"model = AgeMLP(input_size).to(device)\n",
|
| 217 |
+
"criterion = nn.MSELoss()\n",
|
| 218 |
+
"optimizer = optim.Adam(model.parameters(), lr=0.001)\n"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"train_losses = []\n",
|
| 228 |
+
"val_losses = []\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"epochs = 20\n",
|
| 231 |
+
"for epoch in range(epochs):\n",
|
| 232 |
+
" train_loss = train_one_epoch(model, train_loader, criterion, optimizer, device)\n",
|
| 233 |
+
" val_loss = validate(model, test_loader, criterion, device)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" train_losses.append(train_loss)\n",
|
| 236 |
+
" val_losses.append(val_loss)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" print(f\"Epoch [{epoch+1}/{epochs}] | Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f}\")\n"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"import matplotlib.pyplot as plt\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"plt.plot(train_losses, label=\"Train Loss\")\n",
|
| 250 |
+
"plt.plot(val_losses, label=\"Validation Loss\")\n",
|
| 251 |
+
"plt.xlabel(\"Epoch\")\n",
|
| 252 |
+
"plt.ylabel(\"Loss (MSE)\")\n",
|
| 253 |
+
"plt.title(\"Training vs Validation Loss\")\n",
|
| 254 |
+
"plt.legend()\n",
|
| 255 |
+
"plt.show()\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# If the gap between train and validation curves widens, it suggests overfitting\n"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
}
|
| 262 |
+
],
|
| 263 |
+
"metadata": {
|
| 264 |
+
"kernelspec": {
|
| 265 |
+
"display_name": "Python 3",
|
| 266 |
+
"name": "python3"
|
| 267 |
+
},
|
| 268 |
+
"language_info": {
|
| 269 |
+
"name": "python"
|
| 270 |
+
}
|
| 271 |
+
},
|
| 272 |
+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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"# Download latest version\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"print(\"Path to dataset files:\", path)"
|
| 19 |
+
],
|
| 20 |
+
"execution_count": null,
|
| 21 |
+
"outputs": []
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"source": [
|
| 27 |
+
"\n",
|
| 28 |
+
"df = pd.read_csv(path + \"/Q3_data.csv\")\n"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"df.head()\n"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"df.info()\n"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"df.describe()\n"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"import pandas as pd\n",
|
| 65 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"target_col = df.columns[-1]\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"missing = df.isnull().sum()\n",
|
| 70 |
+
"print(\"Columns with missing values:\\n\", missing[missing > 0])\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"num_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"int64\", \"float64\"]).columns\n",
|
| 73 |
+
"cat_cols = df.drop(columns=[target_col]).select_dtypes(include=[\"object\"]).columns\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"for col in num_cols:\n",
|
| 76 |
+
" df[col] = df[col].fillna(df[col].median())\n",
|
| 77 |
+
"for col in cat_cols:\n",
|
| 78 |
+
" df[col] = df[col].fillna(df[col].mode()[0])\n"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"df = df.drop_duplicates()\n"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"if len(cat_cols) > 0:\n",
|
| 97 |
+
" df = pd.get_dummies(df, columns=cat_cols, drop_first=True)"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"X = df.drop(columns=[target_col])\n",
|
| 107 |
+
"y = df[target_col]\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"scaler = StandardScaler()\n",
|
| 110 |
+
"X_scaled = scaler.fit_transform(X)"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"counts = y.value_counts()\n",
|
| 120 |
+
"ratio = counts.min() / counts.max()\n",
|
| 121 |
+
"print(\"Target counts:\\n\", counts)\n",
|
| 122 |
+
"print(\"Minority/Majority ratio:\", round(ratio, 3))\n",
|
| 123 |
+
"print(\"Imbalanced:\", \"Yes\" if ratio < 0.5 else \"No\")"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"import numpy as np\n",
|
| 133 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 134 |
+
"from sklearn.ensemble import GradientBoostingClassifier\n",
|
| 135 |
+
"from sklearn.metrics import accuracy_score, f1_score"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 145 |
+
"# Note: Keeps class distribution in each fold.\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"scores = []\n",
|
| 148 |
+
"use_f1 = (y.value_counts().min() / y.value_counts().max()) < 0.5\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"for train_idx, test_idx in skf.split(X, y):\n",
|
| 151 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 152 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" model = GradientBoostingClassifier(random_state=42)\n",
|
| 155 |
+
" model.fit(X_train, y_train)\n",
|
| 156 |
+
" # Note: Model is trained on each fold.\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" y_pred = model.predict(X_test)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" if use_f1:\n",
|
| 161 |
+
" score = f1_score(y_test, y_pred)\n",
|
| 162 |
+
" metric_name = \"F1\"\n",
|
| 163 |
+
" # Note: F1 is used when data is imbalanced.\n",
|
| 164 |
+
" else:\n",
|
| 165 |
+
" score = accuracy_score(y_test, y_pred)\n",
|
| 166 |
+
" metric_name = \"Accuracy\"\n",
|
| 167 |
+
" # Note: Accuracy is used when classes are balanced.\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" scores.append(score)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"# Task 5: Print average score\n",
|
| 172 |
+
"print(f\"{metric_name} per fold:\", np.round(scores, 3))\n",
|
| 173 |
+
"print(f\"Average {metric_name}:\", round(np.mean(scores), 3))\n",
|
| 174 |
+
"# Note: Final score is averaged across folds."
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task 1: Write your code here:"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 2: Write your code here:"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task Bonus: Write your code here:"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
}
|
| 206 |
+
],
|
| 207 |
+
"metadata": {
|
| 208 |
+
"kernelspec": {
|
| 209 |
+
"display_name": "Python 3",
|
| 210 |
+
"name": "python3"
|
| 211 |
+
},
|
| 212 |
+
"language_info": {
|
| 213 |
+
"name": "python"
|
| 214 |
+
}
|
| 215 |
+
},
|
| 216 |
+
"nbformat": 4,
|
| 217 |
+
"nbformat_minor": 0
|
| 218 |
+
}
|
submissions_extracted/298/Q1.ipynb
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import numpy as np\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import matplotlib.pyplot as plt\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import kagglehub\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"import warnings\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')"
|
| 20 |
+
],
|
| 21 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Download latest version\n",
|
| 31 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(\"Path to dataset files:\", path)"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 1: Write your code here:\n",
|
| 43 |
+
"res_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 44 |
+
"df_res = pd.read_csv(res_path)\n",
|
| 45 |
+
"\n"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 2: Write your code here:\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"Dataset shape: {df_res.shape}\")\n",
|
| 57 |
+
"df_res.head()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"# Task 3: Write your code here:\n",
|
| 67 |
+
"df_res.info()"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 4: Write your code here:\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"df_res.describe()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 5: Write your code here:\n",
|
| 88 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 89 |
+
"plt.hist(df_res['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 90 |
+
"plt.title('delivery_time')\n",
|
| 91 |
+
"plt.show()"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# Task 1: Write your code here:\n",
|
| 101 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 102 |
+
"cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n",
|
| 103 |
+
"df_clean = df_res[cols].copy()\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"# Drop rows where target (price) or key features are missing - can't predict without them\n",
|
| 106 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 107 |
+
"df_clean = df_clean.drop(columns=['Order_ID'])\n",
|
| 108 |
+
"print(f\"After dropping {df_clean.shape}\")\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# Task 2: Write your code here:\n",
|
| 118 |
+
"# Drop rows where target (price) or key features are missing - can't predict without them\n",
|
| 119 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 120 |
+
"df_clean = df_clean.dropna(subset=['Courier_Experience_yrs', 'Delivery_Time'])\n",
|
| 121 |
+
"print(f\"After dropping missing : {df_clean.shape}\")\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 126 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 127 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 3: Write your code here:\n",
|
| 139 |
+
"df_clean.drop_duplicates(inplace=True)"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 4: Write your code here:\n",
|
| 149 |
+
"\n"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 4: Write your code here:\n",
|
| 159 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"col= [\"Weather\" , \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n",
|
| 162 |
+
"print('data before encoding:\\n', df_clean) #show before encoding\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
|
| 165 |
+
"df_clean = onehot_encoder.fit_transform(df_clean[col]) # Apply fit_transform to the copied\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"print('\\nData after encoding:\\n', df_clean) #show after encoding"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 5: Write your code here:\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"print('data before scaling:\\n', df_clean) #show before scaling\n",
|
| 181 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 182 |
+
"df_clean = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"print('\\nData after scaling:\\n', df_clean) #show after scaling\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 6: Write your code here:"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 1: Write your code here:\n",
|
| 203 |
+
"target_column = \"Delivery_Time\"\n",
|
| 204 |
+
"X = df_clean.drop(target_column, axis=1)\n",
|
| 205 |
+
"y = df_clean[target_column]"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 215 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"mae_scores = []\n",
|
| 218 |
+
"rmse_scores = []\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"for train_idx, val_idx in kfold.split(X_train_scaled):\n",
|
| 221 |
+
" X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
|
| 222 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" # Train and predict\n",
|
| 225 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 226 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Calculate metrics\n",
|
| 229 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 230 |
+
" rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 233 |
+
"rmse_scores = np.array(rmse_scores)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 236 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
|
| 237 |
+
"print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 1: Write your code here:"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 2: Write your code here:"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task Bonus: Write your code here:"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
}
|
| 269 |
+
],
|
| 270 |
+
"metadata": {
|
| 271 |
+
"kernelspec": {
|
| 272 |
+
"display_name": "Python 3",
|
| 273 |
+
"name": "python3"
|
| 274 |
+
},
|
| 275 |
+
"language_info": {
|
| 276 |
+
"name": "python"
|
| 277 |
+
}
|
| 278 |
+
},
|
| 279 |
+
"nbformat": 4,
|
| 280 |
+
"nbformat_minor": 0
|
| 281 |
+
}
|
submissions_extracted/298/Q2.ipynb
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"import torch\n",
|
| 27 |
+
"import torch.nn as nn\n",
|
| 28 |
+
"from torch.optim import AdamW\n",
|
| 29 |
+
"import matplotlib.pyplot as plt\n",
|
| 30 |
+
"import torch.nn.functional as F\n",
|
| 31 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 32 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 33 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"import torch\n",
|
| 36 |
+
"import torch.nn as nn\n",
|
| 37 |
+
"from torchvision.datasets import MNIST\n",
|
| 38 |
+
"from torch.utils.data import DataLoader\n",
|
| 39 |
+
"from torch.optim import Adam\n",
|
| 40 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 41 |
+
"import torch.nn.functional as F\n",
|
| 42 |
+
"import matplotlib.pyplot as plt\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"# Load Labels\n",
|
| 45 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 46 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"images = []\n",
|
| 49 |
+
"ages = []\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"# Load Images and Resize\n",
|
| 52 |
+
"print(\"Loading images...\")\n",
|
| 53 |
+
"for index, row in labels_df.iterrows():\n",
|
| 54 |
+
" img_name = row.iloc[0]\n",
|
| 55 |
+
" age = row.iloc[1]\n",
|
| 56 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
" if os.path.exists(img_path):\n",
|
| 59 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 60 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 61 |
+
" images.append(img_array)\n",
|
| 62 |
+
" ages.append(age)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"X = np.array(images)\n",
|
| 65 |
+
"y = np.array(ages)\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 68 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"# Split Data\n",
|
| 71 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 74 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 75 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 76 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 86 |
+
"X_train = torch.tensor(X_train , dtype=torch.float32)\n",
|
| 87 |
+
"X_test = torch.tensor(X_test , dtype=torch.float32)\n",
|
| 88 |
+
"y_train = torch.tensor(y_train , dtype=torch.float32)\n",
|
| 89 |
+
"y_test = torch.tensor(y_test , dtype=torch.float32)\n",
|
| 90 |
+
"\n"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# 2. Create TensorDataset objects\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 102 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 3. Create DataLoaders\n",
|
| 112 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 113 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# 4. Print shape of one batch\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# Print dataset sizes\n",
|
| 127 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 128 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"# Get the first batch from the training DataLoader\n",
|
| 131 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 132 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 133 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# 5. Display sample images\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"for i in range(1):\n",
|
| 145 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 146 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 147 |
+
" plt.title(f\"Label: {y_batch[i].item()}\")\n",
|
| 148 |
+
" plt.axis('off')\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"plt.tight_layout()\n",
|
| 151 |
+
"plt.show()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 1: Write your model class here:\n",
|
| 161 |
+
"class NN4Layer(nn.Module):\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 164 |
+
" super(NN4Layer, self).__init__()\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 167 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 170 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 173 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # ReLU activation for non-linearity\n",
|
| 178 |
+
" self.relu = nn.ReLU()\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Defines how input data flows through the network\n",
|
| 181 |
+
" def forward(self, x):\n",
|
| 182 |
+
" # First hidden layer\n",
|
| 183 |
+
" z1 = self.layer1(x)\n",
|
| 184 |
+
" a1 = self.relu(z1)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Second hidden layer\n",
|
| 187 |
+
" z2 = self.layer2(a1)\n",
|
| 188 |
+
" a2 = self.relu(z2)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Output layer (raw scores / logits)\n",
|
| 191 |
+
" z3 = self.layer3(a2)\n",
|
| 192 |
+
" a3 = self.relu(z3)\n",
|
| 193 |
+
" output = self.layer3(a3)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return output"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 2: Write your training loop here:\n",
|
| 205 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 206 |
+
" # Set the model to training mode\n",
|
| 207 |
+
" model.train()\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" running_loss = 0.0\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 212 |
+
" # Move batch to the selected device\n",
|
| 213 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 214 |
+
" y_batch = y_batch.to(device)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Forward pass\n",
|
| 217 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 218 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Backward pass & optimization\n",
|
| 221 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 222 |
+
" loss.backward() # Compute gradients\n",
|
| 223 |
+
" optimizer.step() # Update model parameters\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" running_loss += loss.item()\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Average loss over all batches\n",
|
| 228 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" return avg_loss"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 240 |
+
" # Set the model to evaluation mode\n",
|
| 241 |
+
" model.eval()\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" running_loss = 0.0\n",
|
| 244 |
+
" correct = 0\n",
|
| 245 |
+
" total = 0\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" with torch.no_grad():\n",
|
| 248 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 249 |
+
" # Move data to device\n",
|
| 250 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 251 |
+
" y_batch = y_batch.to(device)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Forward pass\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 258 |
+
" running_loss += loss.item()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Accuracy calculation\n",
|
| 266 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 267 |
+
" total += y_batch.size(0)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 270 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 271 |
+
" accuracy = correct / total\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" return avg_loss, accuracy\n"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 283 |
+
"# Device setup\n",
|
| 284 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"# Model parameters\n",
|
| 287 |
+
"input_dim = 36 * 36\n",
|
| 288 |
+
"hidden_dim = 14 # Design choice\n",
|
| 289 |
+
"output_dim = 10 # Digits 0–9\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Instantiate model\n",
|
| 292 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"# Print the model architecture\n",
|
| 295 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 296 |
+
"print(model)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"# Calculate the total number of trainable parameters\n",
|
| 299 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 300 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"source": [
|
| 309 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"num_epochs = 20\n",
|
| 312 |
+
"learning_rate = 0.001\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 315 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 316 |
+
"# Define optimizer\n",
|
| 317 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 318 |
+
],
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"outputs": []
|
| 321 |
+
},
|
| 322 |
+
{
|
| 323 |
+
"cell_type": "code",
|
| 324 |
+
"metadata": {},
|
| 325 |
+
"source": [
|
| 326 |
+
"# Run Training\n",
|
| 327 |
+
"train_losses = []\n",
|
| 328 |
+
"val_losses = []\n",
|
| 329 |
+
"val_accuracies = []\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"print('Starting Training...')\n",
|
| 332 |
+
"for epoch in range(num_epochs):\n",
|
| 333 |
+
" # Train one epoch\n",
|
| 334 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" # Validate\n",
|
| 337 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" train_losses.append(train_loss)\n",
|
| 340 |
+
" val_losses.append(val_loss)\n",
|
| 341 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"print('Training Complete!')"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"cell_type": "code",
|
| 352 |
+
"metadata": {},
|
| 353 |
+
"source": [
|
| 354 |
+
"# Task 1: Write your code here:\n",
|
| 355 |
+
"# Plotting results\n",
|
| 356 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 357 |
+
"\n",
|
| 358 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 359 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 360 |
+
"plt.title('Loss over Epochs')\n",
|
| 361 |
+
"plt.xlabel('Epoch')\n",
|
| 362 |
+
"plt.ylabel('Loss')\n",
|
| 363 |
+
"plt.legend()\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"plt.tight_layout()\n",
|
| 366 |
+
"plt.show()"
|
| 367 |
+
],
|
| 368 |
+
"execution_count": null,
|
| 369 |
+
"outputs": []
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"cell_type": "code",
|
| 373 |
+
"metadata": {},
|
| 374 |
+
"source": [
|
| 375 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 376 |
+
],
|
| 377 |
+
"execution_count": null,
|
| 378 |
+
"outputs": []
|
| 379 |
+
}
|
| 380 |
+
],
|
| 381 |
+
"metadata": {
|
| 382 |
+
"kernelspec": {
|
| 383 |
+
"display_name": "Python 3",
|
| 384 |
+
"name": "python3"
|
| 385 |
+
},
|
| 386 |
+
"language_info": {
|
| 387 |
+
"name": "python"
|
| 388 |
+
}
|
| 389 |
+
},
|
| 390 |
+
"nbformat": 4,
|
| 391 |
+
"nbformat_minor": 0
|
| 392 |
+
}
|
submissions_extracted/298/Q3.ipynb
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"# Download latest version\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"print(\"Path to dataset files:\", path)"
|
| 24 |
+
],
|
| 25 |
+
"execution_count": null,
|
| 26 |
+
"outputs": []
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"# Task 1: Write your code here:\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"res_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 35 |
+
"df = pd.read_csv(res_path)"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 2: Write your code here:\n",
|
| 45 |
+
"df.head()"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 3: Write your code here:\n",
|
| 55 |
+
"df.info()"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 4: Write your code here:\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"df.describe()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 1: Write your code here:\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"def check_missing_values(df):\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" # Get missing values using pandas\n",
|
| 81 |
+
" missing_values = df.isnull().sum()\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" print(\"Missing Values per Column:\")\n",
|
| 84 |
+
" print(missing_values[missing_values > 0])\n",
|
| 85 |
+
"\n",
|
| 86 |
+
" if missing_values.any():\n",
|
| 87 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 88 |
+
" else:\n",
|
| 89 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"check_missing_values(df)"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
" # Task 2: Write your code here:\n",
|
| 101 |
+
"duplicates = df.duplicated().sum()"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# Task 3: Write your code here:\n",
|
| 111 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"for col in df:\n",
|
| 114 |
+
" le = LabelEncoder()\n",
|
| 115 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 116 |
+
"\n"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 4: Write your code here:\n",
|
| 126 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"for col in df:\n",
|
| 130 |
+
" scaler = StandardScaler()\n",
|
| 131 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"df.head()"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 5: Write your code here:"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 1: Write your code here:\n",
|
| 154 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"target_column = \"Target\"\n",
|
| 157 |
+
"X = df.drop(target_column, axis=1)\n",
|
| 158 |
+
"y = df[target_column]\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 161 |
+
" X, y,\n",
|
| 162 |
+
" test_size=0.2, # 20% for test, remaining 80% for train\n",
|
| 163 |
+
" random_state=42, # reproducible output\n",
|
| 164 |
+
" shuffle=True, # representative splits\n",
|
| 165 |
+
" stratify=y # preserve class distribution\n",
|
| 166 |
+
")"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"from sklearn.model_selection import KFold\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Iterate through folds\n",
|
| 183 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 184 |
+
" # indexing for each fold\n",
|
| 185 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 186 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 187 |
+
" # print shapes\n",
|
| 188 |
+
" print(f\"Fold {fold}\")\n",
|
| 189 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 190 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 191 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 192 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 193 |
+
" print(\"-\" * 30)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"# Calculate metrics\n",
|
| 199 |
+
"accuracy = accuracy_score(y_test, y_pred)\n",
|
| 200 |
+
"precision = precision_score(y_test, y_pred)\n",
|
| 201 |
+
"recall = recall_score(y_test, y_pred)\n",
|
| 202 |
+
"f1 = f1_score(y_test, y_pred)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"print(\"Accuracy :\", accuracy)\n",
|
| 205 |
+
"print(\"Precision:\", precision)\n",
|
| 206 |
+
"print(\"Recall :\", recall)\n",
|
| 207 |
+
"print(\"F1 Score :\", f1)\n"
|
| 208 |
+
],
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"outputs": []
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"cell_type": "code",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"source": [
|
| 216 |
+
"# Task 1: Write your code here:"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 2: Write your code here:"
|
| 226 |
+
],
|
| 227 |
+
"execution_count": null,
|
| 228 |
+
"outputs": []
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"# Task Bonus: Write your code here:"
|
| 235 |
+
],
|
| 236 |
+
"execution_count": null,
|
| 237 |
+
"outputs": []
|
| 238 |
+
}
|
| 239 |
+
],
|
| 240 |
+
"metadata": {
|
| 241 |
+
"kernelspec": {
|
| 242 |
+
"display_name": "Python 3",
|
| 243 |
+
"name": "python3"
|
| 244 |
+
},
|
| 245 |
+
"language_info": {
|
| 246 |
+
"name": "python"
|
| 247 |
+
}
|
| 248 |
+
},
|
| 249 |
+
"nbformat": 4,
|
| 250 |
+
"nbformat_minor": 0
|
| 251 |
+
}
|
submissions_extracted/299/Q1.ipynb
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"# Task 1: Write your code here:\n",
|
| 22 |
+
"import os\n",
|
| 23 |
+
"import pandas as pd # import panadas to read file\n",
|
| 24 |
+
"food_path = os.path.join(path, 'Q1_data.csv') # access to file path\n",
|
| 25 |
+
"data = pd.read_csv(food_path) # read the file"
|
| 26 |
+
],
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"source": [
|
| 34 |
+
"# Task 2: Write your code here:\n",
|
| 35 |
+
"data.head()"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 3: Write your code here:\n",
|
| 45 |
+
"data.info()"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 4: Write your code here:\n",
|
| 55 |
+
"data.describe()"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 5: Write your code here:\n",
|
| 65 |
+
"import matplotlib.pyplot as plt # import to visualization\n",
|
| 66 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 67 |
+
"plt.scatter(data['Distance_km'],data['Preparation_Time_min'], c=data['Delivery_Time']) # use the distance an d time as factors to spread the plots\n",
|
| 68 |
+
"plt.colorbar(label='dleviery time')\n",
|
| 69 |
+
"plt.title('Geographic Distribution of delivery time')\n",
|
| 70 |
+
"plt.xlabel('Distance')\n",
|
| 71 |
+
"plt.ylabel('Preparation_Time_min')\n",
|
| 72 |
+
"plt.show()\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"# or can just plot histogram\n",
|
| 75 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 76 |
+
"plt.hist(data['Delivery_Time'], bins=60, edgecolor='black')\n",
|
| 77 |
+
"plt.title('Distribution of Delivery_Time')\n",
|
| 78 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 79 |
+
"plt.ylabel('Count')\n",
|
| 80 |
+
"plt.show()\n"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 1: Write your code here:\n",
|
| 90 |
+
"data = data.drop(columns='Order_ID', axis=1).copy()"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 2: Write your code here:\n",
|
| 100 |
+
"# fill with mode for the object variables\n",
|
| 101 |
+
"data['Weather'] = data['Weather'].fillna(data['Weather'].mode()[0])\n",
|
| 102 |
+
"data['Traffic_Level'] = data['Traffic_Level'].fillna(data['Traffic_Level'].mode()[0])\n",
|
| 103 |
+
"data['Time_of_Day'] = data['Time_of_Day'].fillna(data['Time_of_Day'].mode()[0])\n",
|
| 104 |
+
"# fill with mean for the float variables\n",
|
| 105 |
+
"data['Courier_Experience_yrs'] = data['Courier_Experience_yrs'].fillna(data['Courier_Experience_yrs'].mean())\n",
|
| 106 |
+
"data['Delivery_Time'] = data['Delivery_Time'].fillna(data['Delivery_Time'].mean())\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# Task 3: Write your code here:\n",
|
| 116 |
+
"# Do we have duplicate samples?\n",
|
| 117 |
+
"def check_duplicates(data):\n",
|
| 118 |
+
" duplicates = data.duplicated().sum() # calculate the duplication\n",
|
| 119 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 120 |
+
" if duplicates > 0:\n",
|
| 121 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 122 |
+
" data.drop_duplicates(inplace=True) # handle the duplicate\n",
|
| 123 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 124 |
+
" else:\n",
|
| 125 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"check_duplicates(data)"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 4: Write your code here:\n",
|
| 137 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder [[1.0.0],[0.1.0],[0.0.1]]\n",
|
| 138 |
+
"from sklearn.preprocessing import LabelEncoder #import LabelEncoder as [0,1,2]\n",
|
| 139 |
+
"# Do we have categorical columns? # to encode\n",
|
| 140 |
+
"categorical_cols = data.select_dtypes(include=[\"object\"]).columns # check for categorical types to handle it if needed\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"print(\"Categorical Columns:\", list(categorical_cols)) # print the categorical columns\n",
|
| 143 |
+
"# we have Categorical Columns: ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 144 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"for col in categorical_cols:\n",
|
| 147 |
+
" le = LabelEncoder()\n",
|
| 148 |
+
" data[col] = le.fit_transform(data[col].astype(str))\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"data.head()"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# serate features and target\n",
|
| 160 |
+
"from sklearn.model_selection import train_test_split #for split data in % between train and test dataset\n",
|
| 161 |
+
"target_column = \"Delivery_Time\"\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"X = data.drop(target_column, axis=1)\n",
|
| 164 |
+
"y = data[target_column]\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 168 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 169 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 5: Write your code here:\n",
|
| 179 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler as small range \"best for Linear regression , logistic regression , SVM\n",
|
| 180 |
+
"# Scale features - fit on train, transform both\n",
|
| 181 |
+
"scaler = StandardScaler()\n",
|
| 182 |
+
"X_train_scaled = scaler.fit_transform(X_train) # used fit to calculate the scale and transform to apply it\n",
|
| 183 |
+
"X_test_scaled = scaler.transform(X_test) #no fit here because it is test so we do not need a calculation\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
|
| 186 |
+
"pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "code",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": [
|
| 195 |
+
"# Task 6: Write your code here:\n",
|
| 196 |
+
"#it is regression ans regression check the skewed"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 1: Write your code here:# sperate features and target\n",
|
| 206 |
+
"from sklearn.model_selection import KFold\n",
|
| 207 |
+
"target_column = \"Delivery_Time\"\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"X = data.drop(target_column, axis=1)\n",
|
| 210 |
+
"y = data[target_column]\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 214 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 215 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 216 |
+
],
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"outputs": []
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 225 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 226 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 227 |
+
"from sklearn.metrics import mean_absolute_error #for regression metrics\n",
|
| 228 |
+
"import numpy as np\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 234 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 235 |
+
"# Storage for logistic regression results for each fold\n",
|
| 236 |
+
"mae_scores = []\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"model = RandomForestRegressor()\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"for train_idx, test_idx in skf.split(X_train ,X_test ):\n",
|
| 241 |
+
" X_train, X_test = X_train[train_idx], X_train[test_idx]\n",
|
| 242 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" # Train model\n",
|
| 245 |
+
" model.fit(X_train, y_train)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" # Predict\n",
|
| 248 |
+
" y_pred = model.predict(X_test)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Evaluation metrics\n",
|
| 251 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"# Print Evaluation Metrics\n",
|
| 255 |
+
"print(\"\\nModel Evaluation Metrics \")\n",
|
| 256 |
+
"print(f\"MAE : {np.mean(mae_scores):.2f}\")\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"# Print the averaged score across all folds\n",
|
| 259 |
+
"for x in mae_scores:\n",
|
| 260 |
+
" print(f\"\\n{x}:\")\n",
|
| 261 |
+
" print(f\" avg: {np.mean(mae_scores[x]['avg']):.4f}\")"
|
| 262 |
+
],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"cell_type": "code",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [
|
| 270 |
+
"# Task 1: Write your code here:\n",
|
| 271 |
+
"# Plot feature importance\n",
|
| 272 |
+
"importance = pd.DataFrame({\n",
|
| 273 |
+
" 'feature': X,\n",
|
| 274 |
+
" 'importance': model.feature_importances_\n",
|
| 275 |
+
"})\n",
|
| 276 |
+
"importance = importance.sort_values('importance', ascending=True).tail(10)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 279 |
+
"plt.barh(importance['feature'], importance['importance'])\n",
|
| 280 |
+
"plt.title('Top 10 Feature Importance')\n",
|
| 281 |
+
"plt.xlabel('Importance')\n",
|
| 282 |
+
"plt.tight_layout()\n",
|
| 283 |
+
"plt.show()"
|
| 284 |
+
],
|
| 285 |
+
"execution_count": null,
|
| 286 |
+
"outputs": []
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"cell_type": "code",
|
| 290 |
+
"metadata": {},
|
| 291 |
+
"source": [
|
| 292 |
+
"# Task 2: Write your code here:\n",
|
| 293 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 294 |
+
"plt.hist(y_pred, bins=30, edgecolor='black')\n",
|
| 295 |
+
"plt.title('Distribution of Predictions')\n",
|
| 296 |
+
"plt.xlabel('Predicted dilevery time')\n",
|
| 297 |
+
"plt.ylabel('Count')\n",
|
| 298 |
+
"plt.show()"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task Bonus: Write your code here:"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
}
|
| 312 |
+
],
|
| 313 |
+
"metadata": {
|
| 314 |
+
"kernelspec": {
|
| 315 |
+
"display_name": "Python 3",
|
| 316 |
+
"name": "python3"
|
| 317 |
+
},
|
| 318 |
+
"language_info": {
|
| 319 |
+
"name": "python"
|
| 320 |
+
}
|
| 321 |
+
},
|
| 322 |
+
"nbformat": 4,
|
| 323 |
+
"nbformat_minor": 0
|
| 324 |
+
}
|
submissions_extracted/299/Q2.ipynb
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import torch\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"# convert tensors\n",
|
| 73 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 74 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 75 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 76 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 77 |
+
"\n"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 2. Create TensorDataset objects\n",
|
| 87 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"# Create TensorDatasets for training and testing\n",
|
| 91 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 92 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# 3. Create DataLoaders\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 104 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 105 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# 4. Print shape of one batch\n",
|
| 115 |
+
"# Get the first batch from the training DataLoader\n",
|
| 116 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 117 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 118 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# 5. Display sample images\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"import matplotlib.pyplot as plt\n",
|
| 130 |
+
"# Get one batch of images and labels\n",
|
| 131 |
+
"images, labels = next(iter(train_loader))\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"# Display the first 6 images in the batch\n",
|
| 134 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"plt.subplot( 2,3,1)\n",
|
| 137 |
+
"plt.imshow(images[1].squeeze(), cmap='gray')\n",
|
| 138 |
+
"plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 139 |
+
"plt.axis('off')\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"plt.tight_layout()\n",
|
| 142 |
+
"plt.show()"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 1: Write your model class here:\n",
|
| 152 |
+
"import torch.nn as nn\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"class NN4Layer(nn.Module):\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 157 |
+
" super(NN4Layer, self).__init__()\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 160 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 163 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 166 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 169 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # ReLU activation for non-linearity\n",
|
| 172 |
+
" self.relu = nn.ReLU()\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" # Defines how input data flows through the network\n",
|
| 175 |
+
" def forward(self, x):\n",
|
| 176 |
+
" # First hidden layer\n",
|
| 177 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Second hidden layer\n",
|
| 180 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # Third hidden layer\n",
|
| 183 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # Output layer (raw scores / logits)\n",
|
| 186 |
+
" output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
|
| 187 |
+
" # bc cross entropy deal with it\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" return output"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"# Task 2: Write your training loop here:\n",
|
| 199 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 200 |
+
" # Set the model to training mode\n",
|
| 201 |
+
" model.train()\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" running_loss = 0.0\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 206 |
+
" # Move batch to the selected device\n",
|
| 207 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 208 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,) do not use view bc it only use in binary and linear regression\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Forward pass (outputs are logits)\n",
|
| 211 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 212 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Backward pass & optimization\n",
|
| 215 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 216 |
+
" loss.backward() # Compute gradients\n",
|
| 217 |
+
" optimizer.step() # Update model parameters\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" running_loss += loss.item()\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Average loss over all batches\n",
|
| 222 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" return avg_loss"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"# Task 3: Write your validation loop here:\n",
|
| 234 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 235 |
+
" # Set the model to evaluation mode ** to do not update the weight\n",
|
| 236 |
+
" model.eval()\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" running_loss = 0.0\n",
|
| 239 |
+
" correct = 0\n",
|
| 240 |
+
" total = 0\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" with torch.no_grad(): # for the same gradient\n",
|
| 243 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 244 |
+
" # Move data to device\n",
|
| 245 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 246 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" # Forward pass\n",
|
| 249 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 250 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 251 |
+
" running_loss += loss.item()\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Apply Softmax to get probabilities\n",
|
| 254 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" # Pick the classes with highest probabilities\n",
|
| 257 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Accuracy calculation\n",
|
| 260 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 261 |
+
" total += y_batch.size(0)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 264 |
+
" accuracy = correct / total\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" return avg_loss, accuracy"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 276 |
+
"from torch.optim import AdamW\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"num_epochs = 20\n",
|
| 279 |
+
"learning_rate = 0.001\n",
|
| 280 |
+
"# Device setup\n",
|
| 281 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 282 |
+
"# Model parameters\n",
|
| 283 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 284 |
+
"hidden_dim = 14 # Design choice ** can split it many hidden_dim like (hidden_dim1= 4 , hidden_dim2= 6 , hidden_dim3= 4)\n",
|
| 285 |
+
"output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Instantiate model\n",
|
| 288 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 291 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 292 |
+
"# Define optimizer\n",
|
| 293 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 294 |
+
],
|
| 295 |
+
"execution_count": null,
|
| 296 |
+
"outputs": []
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "code",
|
| 300 |
+
"metadata": {},
|
| 301 |
+
"source": [
|
| 302 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 303 |
+
" # Set the model to training mode\n",
|
| 304 |
+
" model.train()\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" running_loss = 0.0\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 309 |
+
" # Move batch to the selected device\n",
|
| 310 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 311 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,) do not use view bc it only use in binary and linear regression\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" # Forward pass (outputs are logits)\n",
|
| 314 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 315 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" # Backward pass & optimization\n",
|
| 318 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 319 |
+
" loss.backward() # Compute gradients\n",
|
| 320 |
+
" optimizer.step() # Update model parameters\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" running_loss += loss.item()\n",
|
| 323 |
+
"\n",
|
| 324 |
+
" # Average loss over all batches\n",
|
| 325 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" return avg_loss"
|
| 328 |
+
],
|
| 329 |
+
"execution_count": null,
|
| 330 |
+
"outputs": []
|
| 331 |
+
},
|
| 332 |
+
{
|
| 333 |
+
"cell_type": "code",
|
| 334 |
+
"metadata": {},
|
| 335 |
+
"source": [
|
| 336 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"# Print the model architecture\n",
|
| 339 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 340 |
+
"print(model)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"# Calculate the total number of trainable parameters\n",
|
| 344 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 345 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"# Run Training\n",
|
| 348 |
+
"train_losses = []\n",
|
| 349 |
+
"val_losses = []\n",
|
| 350 |
+
"val_accuracies = []\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"print('Starting Training...')\n",
|
| 353 |
+
"for epoch in range(num_epochs):\n",
|
| 354 |
+
" # Train one epoch\n",
|
| 355 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" # Validate\n",
|
| 358 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 359 |
+
"\n",
|
| 360 |
+
" train_losses.append(train_loss)\n",
|
| 361 |
+
" val_losses.append(val_loss)\n",
|
| 362 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 363 |
+
"\n",
|
| 364 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"print('Training Complete!')\n"
|
| 367 |
+
],
|
| 368 |
+
"execution_count": null,
|
| 369 |
+
"outputs": []
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"cell_type": "code",
|
| 373 |
+
"metadata": {},
|
| 374 |
+
"source": [
|
| 375 |
+
"# Task 1: Write your code here:\n",
|
| 376 |
+
"# Plotting results\n",
|
| 377 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 380 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 381 |
+
"plt.title('Loss over Epochs')\n",
|
| 382 |
+
"plt.xlabel('Epoch')\n",
|
| 383 |
+
"plt.ylabel('Loss')\n",
|
| 384 |
+
"plt.legend()\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"plt.tight_layout()\n",
|
| 387 |
+
"plt.show()"
|
| 388 |
+
],
|
| 389 |
+
"execution_count": null,
|
| 390 |
+
"outputs": []
|
| 391 |
+
},
|
| 392 |
+
{
|
| 393 |
+
"cell_type": "code",
|
| 394 |
+
"metadata": {},
|
| 395 |
+
"source": [
|
| 396 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 397 |
+
],
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"outputs": []
|
| 400 |
+
}
|
| 401 |
+
],
|
| 402 |
+
"metadata": {
|
| 403 |
+
"kernelspec": {
|
| 404 |
+
"display_name": "Python 3",
|
| 405 |
+
"name": "python3"
|
| 406 |
+
},
|
| 407 |
+
"language_info": {
|
| 408 |
+
"name": "python"
|
| 409 |
+
}
|
| 410 |
+
},
|
| 411 |
+
"nbformat": 4,
|
| 412 |
+
"nbformat_minor": 0
|
| 413 |
+
}
|
submissions_extracted/299/Q3.ipynb
ADDED
|
@@ -0,0 +1,312 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"# Task 1: Write your code here:\n",
|
| 27 |
+
"import pandas as pd\n",
|
| 28 |
+
"import os\n",
|
| 29 |
+
"datapath = os.path.join(path, 'Q3_data.csv')\n",
|
| 30 |
+
"data = pd.read_csv(datapath)"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 2: Write your code here:\n",
|
| 40 |
+
"data.head()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 3: Write your code here:\n",
|
| 50 |
+
"data.info()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 4: Write your code here:\n",
|
| 60 |
+
"data.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 1: Write your code here:\n",
|
| 70 |
+
"# Analyze missing values\n",
|
| 71 |
+
"missing_percentage = (data.isnull().sum() / len(data)) * 100\n",
|
| 72 |
+
"missing_data = pd.DataFrame({\n",
|
| 73 |
+
" 'Column': missing_percentage.index,\n",
|
| 74 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 75 |
+
"})\n",
|
| 76 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 79 |
+
"missing_data.head(10)"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# 2. Do we have missing values?\n",
|
| 89 |
+
"def check_missing_values(df):\n",
|
| 90 |
+
" missing_values = data.isnull().sum() # importat *****\n",
|
| 91 |
+
" print(\"Missing Values per Column:\")\n",
|
| 92 |
+
" print(missing_values[missing_values > 0]) # print the column with missing values\n",
|
| 93 |
+
" if missing_values.any(): # if the missing values is greater than 0\n",
|
| 94 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 95 |
+
" else:\n",
|
| 96 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"check_missing_values(data)"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"data_clean = data.drop(columns= ['D_87' , 'D_88', 'B_39' , 'D_110' , 'D_111' , 'D_108' , 'B_42' , 'D_73', 'D_135' ,'D_136'] , axis =1).copy()"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# Task 2: Write your code here:\n",
|
| 117 |
+
"# Check and remove duplicates if any exist\n",
|
| 118 |
+
"# 4. Do we have duplicate samples?\n",
|
| 119 |
+
"def check_duplicates(df):\n",
|
| 120 |
+
" duplicates = data_clean.duplicated().sum() # calculate the duplication\n",
|
| 121 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 122 |
+
" if duplicates > 0:\n",
|
| 123 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 124 |
+
" df.drop_duplicates(inplace=True) # handle the duplicate\n",
|
| 125 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 126 |
+
" else:\n",
|
| 127 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"check_duplicates(data_clean)"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 3: Write your code here:\n",
|
| 139 |
+
"#Encode categorical variables if needed\n",
|
| 140 |
+
"# 3. Do we have categorical columns? # to encode\n",
|
| 141 |
+
"categorical_cols = data_clean.select_dtypes(include=[\"object\"]).columns # check for categorical types to handle it if needed\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print(\"Categorical Columns:\", list(categorical_cols)) # print the categorical columns"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 4: Write your code here:\n",
|
| 153 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler as small range \"best for Linear regression , logistic regression , SVM\n",
|
| 154 |
+
"import numpy as np\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"#Apply feature scaling to numerical features (Use StandardScaler)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"# Scale features - fit on train, transform both\n",
|
| 159 |
+
"scaler = StandardScaler()\n",
|
| 160 |
+
"data_clean_scaled = scaler.fit_transform(data_clean) # used fit to calculate the scale and transform to apply it\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"print(f\"\\nScaled ranges - Min: {data_clean_scaled.min():.2f}, Max: {data_clean_scaled.max():.2f}\")\n"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"# Task 5: Write your code here:\n",
|
| 172 |
+
"# Check for target imbalance and state if it is imbalanced or not\n",
|
| 173 |
+
"# 1. What does our target variable (charges) look like? # check skewed\n",
|
| 174 |
+
"target_column = data_clean_scaled['Target']\n",
|
| 175 |
+
"def check_target_distribution(df, target_column):\n",
|
| 176 |
+
" data_clean_scaled[target_column].hist(bins=30, edgecolor='black') # hist means histogram as the figure .. bin is how many rectangles we have\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 179 |
+
" plt.xlabel(target_column)\n",
|
| 180 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 181 |
+
" plt.grid(False)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" plt.show()\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"check_target_distribution(data_clean_scaled, \"Target\")"
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 1: Write your code here:\n",
|
| 195 |
+
"# serate features and target\n",
|
| 196 |
+
"target_column = \"Target\"\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"X = data.drop(target_column, axis=1)\n",
|
| 199 |
+
"y = data[target_column]"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 209 |
+
"import numpy as np\n",
|
| 210 |
+
"import pandas as pd\n",
|
| 211 |
+
"from catboost import CatBoostRegressor\n",
|
| 212 |
+
"from sklearn.model_selection import KFold #split data in folds and git the average of error *regression data *small dataset\n",
|
| 213 |
+
"from sklearn.model_selection import StratifiedKFold #important for classification problems *Ensures fair and reliable evaluation when classes are imbalanced\n",
|
| 214 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score #for Classification Metrics\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"n_splits = 5 # K\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 219 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 220 |
+
"model = CatBoostClassifier(\n",
|
| 221 |
+
" verbose=0,\n",
|
| 222 |
+
" n_estimators=320,\n",
|
| 223 |
+
" max_depth=4\n",
|
| 224 |
+
" )\n",
|
| 225 |
+
"model[name] = {'accuracy': [], 'f1': []}\n",
|
| 226 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 227 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # 1. Split data\n",
|
| 230 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 231 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # 2. Train & Validate sklearn models\n",
|
| 234 |
+
" print(f\"Training ...\")\n",
|
| 235 |
+
" model.fit(X_train, y_train) # train\n",
|
| 236 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 239 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 240 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" model[name]['accuracy'].append(accuracy)\n",
|
| 243 |
+
" model[name]['f1'].append(f1)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"print(f\" Accuracy: {np.mean(model['accuracy']):.4f}\")\n",
|
| 246 |
+
"print(f\" F1-Score: {np.mean(model['f1']):.4f}\")"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 1: Write your code here:\n",
|
| 256 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 257 |
+
"import matplotlib.pyplot as plt #\n",
|
| 258 |
+
"importances = {}\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"# Create a 1x3 plot\n",
|
| 263 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 264 |
+
"axes = axes.flatten()\n",
|
| 265 |
+
"features = X.columns\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 268 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 269 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" ax = axes[i]\n",
|
| 272 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 273 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 274 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"plt.tight_layout()\n",
|
| 277 |
+
"plt.show()"
|
| 278 |
+
],
|
| 279 |
+
"execution_count": null,
|
| 280 |
+
"outputs": []
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"cell_type": "code",
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"source": [
|
| 286 |
+
"# Task 2: Write your code here:"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Task Bonus: Write your code here:"
|
| 296 |
+
],
|
| 297 |
+
"execution_count": null,
|
| 298 |
+
"outputs": []
|
| 299 |
+
}
|
| 300 |
+
],
|
| 301 |
+
"metadata": {
|
| 302 |
+
"kernelspec": {
|
| 303 |
+
"display_name": "Python 3",
|
| 304 |
+
"name": "python3"
|
| 305 |
+
},
|
| 306 |
+
"language_info": {
|
| 307 |
+
"name": "python"
|
| 308 |
+
}
|
| 309 |
+
},
|
| 310 |
+
"nbformat": 4,
|
| 311 |
+
"nbformat_minor": 0
|
| 312 |
+
}
|
submissions_extracted/3/Q1.ipynb
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import seaborn as sns\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"import os\n",
|
| 14 |
+
"from tqdm import tqdm\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"import warnings\n",
|
| 17 |
+
"warnings.filterwarnings('ignore')\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"# Download latest version\n",
|
| 20 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"print(\"Path to dataset files:\", path)"
|
| 23 |
+
],
|
| 24 |
+
"execution_count": null,
|
| 25 |
+
"outputs": []
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"# Task 1: Write your code here:\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"df = pd.read_csv(csv_path)"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 2: Write your code here:\n",
|
| 45 |
+
"df.head()"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 3: Write your code here:\n",
|
| 55 |
+
"df.info()"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 4: Write your code here:\n",
|
| 65 |
+
"df.describe()"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"# Task 5: Write your code here:\n",
|
| 75 |
+
"def check_target_distribution(df, target_column):\n",
|
| 76 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 77 |
+
"\n",
|
| 78 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 79 |
+
" plt.xlabel(target_column)\n",
|
| 80 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 81 |
+
" plt.grid(False)\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" plt.show()\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"check_target_distribution(df, \"delivery_time\")"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 1: Write your code here:"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 2: Write your code here:"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 3: Write your code here:"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 4: Write your code here:"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 5: Write your code here:"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 6: Write your code here:"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 1: Write your code here:"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 1: Write your code here:"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2: Write your code here:"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task Bonus: Write your code here:"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
}
|
| 189 |
+
],
|
| 190 |
+
"metadata": {
|
| 191 |
+
"kernelspec": {
|
| 192 |
+
"display_name": "Python 3",
|
| 193 |
+
"name": "python3"
|
| 194 |
+
},
|
| 195 |
+
"language_info": {
|
| 196 |
+
"name": "python"
|
| 197 |
+
}
|
| 198 |
+
},
|
| 199 |
+
"nbformat": 4,
|
| 200 |
+
"nbformat_minor": 0
|
| 201 |
+
}
|
submissions_extracted/3/Q2.ipynb
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"\n"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# 2. Create TensorDataset objects\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"\n"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# 3. Create DataLoaders\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# 4. Print shape of one batch\n",
|
| 102 |
+
"\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 5. Display sample images\n",
|
| 112 |
+
"\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 1: Write your model class here:"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 2: Write your training loop here:"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 3: Write your validation loop here:"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 5: Start training for 20 epochs:"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 1: Write your code here:"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
}
|
| 180 |
+
],
|
| 181 |
+
"metadata": {
|
| 182 |
+
"kernelspec": {
|
| 183 |
+
"display_name": "Python 3",
|
| 184 |
+
"name": "python3"
|
| 185 |
+
},
|
| 186 |
+
"language_info": {
|
| 187 |
+
"name": "python"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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import numpy as np\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"import os\n",
|
| 15 |
+
"from tqdm import tqdm\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"import warnings\n",
|
| 18 |
+
"warnings.filterwarnings('ignore')\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"# Download latest version\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(\"Path to dataset files:\", path)"
|
| 27 |
+
],
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"source": [
|
| 35 |
+
"# Task 1: Write your code here:\n",
|
| 36 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"df = pd.read_csv(csv_path)"
|
| 39 |
+
],
|
| 40 |
+
"execution_count": null,
|
| 41 |
+
"outputs": []
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"cell_type": "code",
|
| 45 |
+
"metadata": {},
|
| 46 |
+
"source": [
|
| 47 |
+
"# Task 2: Write your code here:\n",
|
| 48 |
+
"df.head()"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 3: Write your code here:\n",
|
| 58 |
+
"df.info()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 4: Write your code here:\n",
|
| 68 |
+
"df.describe()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 1: Write your code here:\n",
|
| 78 |
+
"def check_missing_values(df):\n",
|
| 79 |
+
" missing_values = df.isnull().sum()\n",
|
| 80 |
+
" print(\"Missing Values per Column:\")\n",
|
| 81 |
+
" print(missing_values[missing_values > 0])\n",
|
| 82 |
+
" if missing_values.any():\n",
|
| 83 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 84 |
+
" else:\n",
|
| 85 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"check_missing_values(df)"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 2: Write your code here:"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 3: Write your code here:"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 4: Write your code here:"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 5: Write your code here:"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# Task 1: Write your code here:"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 1: Write your code here:"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 2: Write your code here:"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task Bonus: Write your code here:"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
}
|
| 173 |
+
],
|
| 174 |
+
"metadata": {
|
| 175 |
+
"kernelspec": {
|
| 176 |
+
"display_name": "Python 3",
|
| 177 |
+
"name": "python3"
|
| 178 |
+
},
|
| 179 |
+
"language_info": {
|
| 180 |
+
"name": "python"
|
| 181 |
+
}
|
| 182 |
+
},
|
| 183 |
+
"nbformat": 4,
|
| 184 |
+
"nbformat_minor": 0
|
| 185 |
+
}
|
submissions_extracted/30/Q1.ipynb
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 12 |
+
"import kagglehub\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 16 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 17 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"import warnings\n",
|
| 20 |
+
"warnings.filterwarnings('ignore')\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"food_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 35 |
+
"df = pd.read_csv(food_path)"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 2: Write your code here:\n",
|
| 45 |
+
"df.head()"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 3: Write your code here:\n",
|
| 55 |
+
"df.info"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 4: Write your code here:\n",
|
| 65 |
+
"df.describe()"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"# Task 5: Write your code here:\n",
|
| 75 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 76 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 77 |
+
"plt.title('Delivery Time' )\n",
|
| 78 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 79 |
+
"plt.ylabel('Frequency')\n",
|
| 80 |
+
"plt.show()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 1: Write your code here:\n",
|
| 90 |
+
"df.drop(columns=['Order_ID'])"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 2: Write your code here:\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"cols = ['Weather', 'Traffic_Level', 'Time_of_Day']\n",
|
| 104 |
+
"df_clean = df[cols].copy()\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specif\n",
|
| 107 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 108 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"print(\"Missing values remaining:\", df.isnull().sum().sum())\n",
|
| 114 |
+
"\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 3: Write your code here:\n",
|
| 124 |
+
"def check_duplicates(df):\n",
|
| 125 |
+
" duplicates = df.duplicated().sum()\n",
|
| 126 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 127 |
+
" if duplicates > 0:\n",
|
| 128 |
+
" print(\"Dropping Duplicates ... \")\n",
|
| 129 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 130 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 131 |
+
" else:\n",
|
| 132 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"check_duplicates(df)"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 4: Write your code here:"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 5: Write your code here:"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 6: Write your code here:"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# Task 1: Write your code here:"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"# Task 1: Write your code here:"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 2: Write your code here:"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task Bonus: Write your code here:"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
}
|
| 211 |
+
],
|
| 212 |
+
"metadata": {
|
| 213 |
+
"kernelspec": {
|
| 214 |
+
"display_name": "Python 3",
|
| 215 |
+
"name": "python3"
|
| 216 |
+
},
|
| 217 |
+
"language_info": {
|
| 218 |
+
"name": "python"
|
| 219 |
+
}
|
| 220 |
+
},
|
| 221 |
+
"nbformat": 4,
|
| 222 |
+
"nbformat_minor": 0
|
| 223 |
+
}
|
submiss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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"\n"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# 2. Create TensorDataset objects\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"\n"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# 3. Create DataLoaders\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# 4. Print shape of one batch\n",
|
| 102 |
+
"\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 5. Display sample images\n",
|
| 112 |
+
"\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 1: Write your model class here:"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 2: Write your training loop here:"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 3: Write your validation loop here:"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 5: Start training for 20 epochs:"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 1: Write your code here:"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
}
|
| 180 |
+
],
|
| 181 |
+
"metadata": {
|
| 182 |
+
"kernelspec": {
|
| 183 |
+
"display_name": "Python 3",
|
| 184 |
+
"name": "python3"
|
| 185 |
+
},
|
| 186 |
+
"language_info": {
|
| 187 |
+
"name": "python"
|
| 188 |
+
}
|
| 189 |
+
},
|
| 190 |
+
"nbformat": 4,
|
| 191 |
+
"nbformat_minor": 0
|
| 192 |
+
}
|
submissions_extracted/30/Q3.ipynb
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"# Task 1: Write your code here:"
|
| 27 |
+
],
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"source": [
|
| 35 |
+
"# Task 2: Write your code here:"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 3: Write your code here:"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"# Task 4: Write your code here:"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 1: Write your code here:"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 2: Write your code here:"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Task 3: Write your code here:"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 4: Write your code here:"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"# Task 5: Write your code here:"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# Task 1: Write your code here:"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 1: Write your code here:"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 2: Write your code here:"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task Bonus: Write your code here:"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
}
|
| 148 |
+
],
|
| 149 |
+
"metadata": {
|
| 150 |
+
"kernelspec": {
|
| 151 |
+
"display_name": "Python 3",
|
| 152 |
+
"name": "python3"
|
| 153 |
+
},
|
| 154 |
+
"language_info": {
|
| 155 |
+
"name": "python"
|
| 156 |
+
}
|
| 157 |
+
},
|
| 158 |
+
"nbformat": 4,
|
| 159 |
+
"nbformat_minor": 0
|
| 160 |
+
}
|
submissions_extracted/300/Q1.ipynb
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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NER/q1-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"# Task 1: Write your code here:\n",
|
| 22 |
+
"import os\n",
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"import matplotlib.pyplot as plt\n",
|
| 25 |
+
"import seaborn as sns\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"csv_file = os.path.join(path, \"Q1_data.csv\")\n",
|
| 28 |
+
"df=pd.read_csv(csv_file)\n",
|
| 29 |
+
"\n"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"# Task 2: Write your code here:\n",
|
| 39 |
+
"df.head()"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 3: Write your code here:\n",
|
| 49 |
+
"df.info()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:\n",
|
| 59 |
+
"df.describe()"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 5: Write your code here:\n",
|
| 69 |
+
"def check(df,target_name):\n",
|
| 70 |
+
" df[target_name].hist(bins=30,edgecolor='black')\n",
|
| 71 |
+
"\n",
|
| 72 |
+
" plt.title(f'Distribution of {target_name}')\n",
|
| 73 |
+
" plt.xlabel(target_name)\n",
|
| 74 |
+
" plt.ylabel('Frequency')\n",
|
| 75 |
+
" plt.show()\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"check(df,\"Delivery_Time\")"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# Task 1: Write your code here:\n",
|
| 87 |
+
"df_cols=[\t'Order_ID'\t,'Distance_km',\t'Preparation_Time_min\t','Courier_Experience_yrs'\t,'Delivery_Time']\n",
|
| 88 |
+
"df_cleans[df_col]=df[df_cols].copy\n",
|
| 89 |
+
"df_cleans=df_cleans.drop(\t'Order_ID')"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"# Task 2: Write your code here:\n",
|
| 99 |
+
"df_clean=df.copy()\n",
|
| 100 |
+
"df_clean.drop(columns='Order_ID')\n",
|
| 101 |
+
"print(df_clean.isna().sum())\n",
|
| 102 |
+
"for col in[\t'Order_ID'\t,'Distance_km',\t'Preparation_Time_min\t','Courier_Experience_yrs'\t,'Delivery_Time']:\n",
|
| 103 |
+
" df_clean[col]=df_clean[col].fillna(df_clean[col].mean())\n",
|
| 104 |
+
" print(df_clean[col].isna().sum())\n"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 3: Write your code here:\n",
|
| 114 |
+
"df_clean=df.drop_duplicates()"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 4: Write your code here:\n",
|
| 124 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 125 |
+
"encoder=OneHotEncoder(sparse_output=False)\n",
|
| 126 |
+
"data_encoded=encoder.fit_transform(df)\n"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 5: Write your code here:\n",
|
| 136 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 137 |
+
"scaler=StandardScaler()\n",
|
| 138 |
+
"df_scaled=scaler.fit_transform(df)\n",
|
| 139 |
+
"print(df_scaled)"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 6: Write your code here:"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 1: Write your code here:\n",
|
| 158 |
+
"x=df.drop('Delivery_Time',axis=1)\n",
|
| 159 |
+
"y=df['Delivery_Time']\n",
|
| 160 |
+
"\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 170 |
+
"from sklearn.model_selection import KFold, StratifiedKFold\n",
|
| 171 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 172 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 173 |
+
"import numpy as np\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"kf=KFold(n_splits=5,shuffle=True,random_state=42)\n",
|
| 176 |
+
"mae_scores=[]\n",
|
| 177 |
+
"for foldID,(train_index,test_index) in enumerate(kf.split(x,y)):\n",
|
| 178 |
+
" x_train,x_test=x.iloc[train_index],x.iloc[test_index]\n",
|
| 179 |
+
" y_train,y_test=y.iloc[train_index],y.iloc[test_index]\n",
|
| 180 |
+
" model=RandomForestRegressor()\n",
|
| 181 |
+
" model.fit(x_train,y_train)\n",
|
| 182 |
+
" y_pred=model.predict(x_test)\n",
|
| 183 |
+
" mae=mean_absolute_error(y_test,y_pred)\n",
|
| 184 |
+
"print(f\"mae:${mae:,.2f}\")\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 1: Write your code here:\n",
|
| 194 |
+
"feature_importances=pd.DataFrame({\n",
|
| 195 |
+
" 'feature':x.columns,\n",
|
| 196 |
+
" 'importance':model.feature_importances_\n",
|
| 197 |
+
"})\n",
|
| 198 |
+
"plt.figure(figsize=(10,6))\n",
|
| 199 |
+
"sns.barplot(x='feature',y='importance',data=feature_importances)\n",
|
| 200 |
+
"plt.title('Feature Importance')\n",
|
| 201 |
+
"plt.show()\n",
|
| 202 |
+
"\n"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 2: Write your code here:\n",
|
| 212 |
+
"y_pred=model.predict(x)\n",
|
| 213 |
+
"plt.figure(figsize=(10,6))\n",
|
| 214 |
+
"plt.hist(y_pred,bins=30,edgecolor='black',alpha=0.7)\n",
|
| 215 |
+
"plt.title('Predicted Delivery Time Histogram')\n",
|
| 216 |
+
"plt.xlabel('Delivery Time (min)')\n",
|
| 217 |
+
"plt.ylabel('Frequency')\n",
|
| 218 |
+
"plt.show()"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"# Task Bonus: Write your code here:"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
}
|
| 232 |
+
],
|
| 233 |
+
"metadata": {
|
| 234 |
+
"kernelspec": {
|
| 235 |
+
"display_name": "Python 3",
|
| 236 |
+
"name": "python3"
|
| 237 |
+
},
|
| 238 |
+
"language_info": {
|
| 239 |
+
"name": "python"
|
| 240 |
+
}
|
| 241 |
+
},
|
| 242 |
+
"nbformat": 4,
|
| 243 |
+
"nbformat_minor": 0
|
| 244 |
+
}
|
submissions_extracted/300/Q2.ipynb
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"X_train=torch.from_numpy(X_train)\n",
|
| 71 |
+
"X_test=torch.from_numpy(X_test)\n",
|
| 72 |
+
"y_train=torch.from_numpy(y_train)\n",
|
| 73 |
+
"y_test=torch.from_numpy(y_test)\n",
|
| 74 |
+
"\n"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# 2. Create TensorDataset objects\n",
|
| 84 |
+
"from torch.utils.data import TensorDataset\n",
|
| 85 |
+
"train_dataset=TensorDataset(X_train,y_train)\n",
|
| 86 |
+
"test_dataset=TensorDataset(X_test,y_test)\n",
|
| 87 |
+
"\n"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 3. Create DataLoaders\n",
|
| 97 |
+
"from torch.utils.data import DataLoader\n",
|
| 98 |
+
"train_loader=DataLoader(train_dataset,batch_size=32,shuffle=True)\n",
|
| 99 |
+
"test_loader=DataLoader(test_dataset,batch_size=32,shuffle=True)\n",
|
| 100 |
+
"\n"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# 4. Print shape of one batch\n",
|
| 110 |
+
"X_batch,y_batch=next(iter(train_loader))\n",
|
| 111 |
+
"print(X_batch.shape)\n",
|
| 112 |
+
"print(y_batch.shape)\n",
|
| 113 |
+
"\n"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# 5. Display sample images\n",
|
| 123 |
+
"import matplotlib.pyplot as plt\n",
|
| 124 |
+
"images,labels=next(iter(train_loader))\n",
|
| 125 |
+
"plt.figure(figsize=(10,10))\n",
|
| 126 |
+
"for i in range(16):\n",
|
| 127 |
+
" plt.subplot(4,4,i+1)\n",
|
| 128 |
+
" plt.imshow(images[i].permute(1,2,0))\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"\n"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 1: Write your model class here:\n",
|
| 140 |
+
"from torch import nn\n",
|
| 141 |
+
"class NN4_layer(nn.Module):\n",
|
| 142 |
+
" def __init__(self,inputD,HiddenD,outputD):\n",
|
| 143 |
+
" super(NN4_layer,self).__init__()\n",
|
| 144 |
+
" self.l1= nn.Linear(inputD,HiddenD)\n",
|
| 145 |
+
" self.l2= nn.Linear(HiddenD,HiddenD)\n",
|
| 146 |
+
" self.l3= nn.Linear(HiddenD,HiddenD)\n",
|
| 147 |
+
" self.l4= nn.Linear(HiddenD,outputD)\n",
|
| 148 |
+
" self.relu=nn.ReLU()\n",
|
| 149 |
+
" def forward(self,x):\n",
|
| 150 |
+
" z1=self.l1(x)\n",
|
| 151 |
+
" a1=self.relu(z1)\n",
|
| 152 |
+
" z2=self.l2(a1)\n",
|
| 153 |
+
" a2=self.relu(z2)\n",
|
| 154 |
+
" z3=self.l3(a2)\n",
|
| 155 |
+
" a3=self.relu(z3)\n",
|
| 156 |
+
" outputs=self.l4(a3)\n",
|
| 157 |
+
" return outputs\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 2: Write your training loop here:\n",
|
| 167 |
+
"def train_loop(criterian,model,train_loader,device,optimizer):\n",
|
| 168 |
+
" model.train()\n",
|
| 169 |
+
" running_loss=0.0\n",
|
| 170 |
+
" for batch,(X,y) in enumerate(train_loader):\n",
|
| 171 |
+
" X,y=X.to(device),y.to(device)\n",
|
| 172 |
+
" output=model(X)\n",
|
| 173 |
+
" loss=criterian(output,y)\n",
|
| 174 |
+
" optimizer.zero_grad()\n",
|
| 175 |
+
" loss.backward()\n",
|
| 176 |
+
" optimizer.step()\n",
|
| 177 |
+
" running_loss+=loss.item()"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 3: Write your validation loop here:\n",
|
| 187 |
+
"def validation_loop(criterian,model,test_loader,device):\n",
|
| 188 |
+
" model.eval()\n",
|
| 189 |
+
" running_loss=0.0\n",
|
| 190 |
+
" correct=0\n",
|
| 191 |
+
" total=0\n",
|
| 192 |
+
" with torch.no_grad():\n",
|
| 193 |
+
" for batch,(X,y) in enumerate(test_loader):\n",
|
| 194 |
+
" X,y=X.to(device),y.to(device)\n",
|
| 195 |
+
" output=model(X)\n",
|
| 196 |
+
" loss=criterian(output,y)\n",
|
| 197 |
+
" running_loss+=loss.item()\n",
|
| 198 |
+
" probability=F.softmax(output,dim=1)\n",
|
| 199 |
+
" predicted=torch.argmax(probability,dim=1)\n",
|
| 200 |
+
" total+=y.size(0)\n",
|
| 201 |
+
" correct+=(predicted==y).sum().item()\n",
|
| 202 |
+
" accuracy=correct/total\n",
|
| 203 |
+
" return running_loss,accuracy"
|
| 204 |
+
],
|
| 205 |
+
"execution_count": null,
|
| 206 |
+
"outputs": []
|
| 207 |
+
},
|
| 208 |
+
{
|
| 209 |
+
"cell_type": "code",
|
| 210 |
+
"metadata": {},
|
| 211 |
+
"source": [
|
| 212 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 213 |
+
"device=torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 214 |
+
"model=NN4_layer(3*64*64,512,1).to(device)\n",
|
| 215 |
+
"criterian=nn.CrossEntropyLoss()\n",
|
| 216 |
+
"optimizer=torch.optim.Adam(model.parameters(),lr=0.001)"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 226 |
+
"train_losses=[]\n",
|
| 227 |
+
"test_losses=[]\n",
|
| 228 |
+
"accuracy_list=[]\n",
|
| 229 |
+
"for epoch in range(20):\n",
|
| 230 |
+
" train_loss=train_loop(criterian,model,train_loader,device,optimizer)\n",
|
| 231 |
+
" test_loss,accuracy=validation_loop(criterian,model,test_loader,device)\n",
|
| 232 |
+
" train_losses.append(train_loss)\n",
|
| 233 |
+
" test_losses.append(test_loss)\n",
|
| 234 |
+
" accuracy_list.append(accuracy)\n",
|
| 235 |
+
" print(f\"Epoch {epoch+1}/{20}, Train Loss: {train_loss:.4f}, Test Loss: {test_loss:.4f}, Accuracy: {accuracy:.4f}\")"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 244 |
+
"# Task 1: Write your code here:\n",
|
| 245 |
+
"plt.plot(train_losses,label=\"train_loss\")\n",
|
| 246 |
+
"plt.plot(test_losses,label=\"test_loss\")\n",
|
| 247 |
+
"plt.legend()\n",
|
| 248 |
+
"plt.show()"
|
| 249 |
+
],
|
| 250 |
+
"execution_count": null,
|
| 251 |
+
"outputs": []
|
| 252 |
+
},
|
| 253 |
+
{
|
| 254 |
+
"cell_type": "code",
|
| 255 |
+
"metadata": {},
|
| 256 |
+
"source": [
|
| 257 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
}
|
| 262 |
+
],
|
| 263 |
+
"metadata": {
|
| 264 |
+
"kernelspec": {
|
| 265 |
+
"display_name": "Python 3",
|
| 266 |
+
"name": "python3"
|
| 267 |
+
},
|
| 268 |
+
"language_info": {
|
| 269 |
+
"name": "python"
|
| 270 |
+
}
|
| 271 |
+
},
|
| 272 |
+
"nbformat": 4,
|
| 273 |
+
"nbformat_minor": 0
|
| 274 |
+
}
|
submissions_extracted/300/Q3.ipynb
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"from IPython.utils.text import Path\n",
|
| 27 |
+
"# Task 1: Write your code here:\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"df = pd.read_csv(f\"{path}/Q3_data.csv\")"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"# Task 2: Write your code here:\n",
|
| 39 |
+
"df.head()"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 3: Write your code here:\n",
|
| 49 |
+
"df.info()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:\n",
|
| 59 |
+
"df.describe()"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 1: Write your code here:\n",
|
| 69 |
+
"nissing_values = df.isnull().sum()\n",
|
| 70 |
+
"print(nissing_values)"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 2: Write your code here:\n",
|
| 80 |
+
"df = df.drop_duplicates()\n",
|
| 81 |
+
"print(df)"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Task 3: Write your code here:\n",
|
| 91 |
+
"categorical_columns = df.select_dtypes(include=['object']).columns\n",
|
| 92 |
+
"df = pd.get_dummies(df, columns=categorical_columns, drop_first=True)\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# Task 4: Write your code here:\n",
|
| 102 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"numerical_columns = df.select_dtypes(include=['int64', 'float64']).columns\n",
|
| 105 |
+
"scaler = StandardScaler()\n",
|
| 106 |
+
"df[numerical_columns] = scaler.fit_transform(df[numerical_columns])\n",
|
| 107 |
+
"print(df)\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# Task 5: Write your code here:\n",
|
| 117 |
+
"target_counts = df['Target'].value_counts()\n",
|
| 118 |
+
"print(target_counts)"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 1: Write your code here:\n",
|
| 128 |
+
"features_columns = df.columns.drop('Target')\n",
|
| 129 |
+
"X = df[features_columns]\n",
|
| 130 |
+
"y = df['Target']\n"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 2,3,4,5: Write your code here\n",
|
| 140 |
+
"from catboost import CatBoostClassifier\n",
|
| 141 |
+
"from sklearn.model_selection import StratifiedKFold,train_test_split\n",
|
| 142 |
+
"from sklearn.metrics import accuracy_score,f1_score\n",
|
| 143 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 144 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 145 |
+
"kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 146 |
+
"model=CatBoostClassifier(iterations=100, learning_rate=0.1, depth=6, loss_function='Logloss', random_seed=42)\n",
|
| 147 |
+
"model.fit(X_train, y_train)\n",
|
| 148 |
+
"y_pred = model.predict(X_test)\n",
|
| 149 |
+
"accuracy = accuracy_score(y_test, y_pred)\n",
|
| 150 |
+
"f1 = f1_score(y_test, y_pred)\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 1: Write your code here:\n",
|
| 162 |
+
"import matplotlib.pyplot as plt\n",
|
| 163 |
+
"feature_importance = pd.DataFrame({'Feature': X.columns, 'Importance': model.feature_importances_})\n",
|
| 164 |
+
"feature_importance = feature_importance.sort_values(by='Importance', ascending=False)\n",
|
| 165 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 166 |
+
"plt.bar(feature_importance['Feature'], feature_importance['Importance'])\n",
|
| 167 |
+
"plt.xlabel('Features')\n",
|
| 168 |
+
"plt.ylabel('Importance')\n",
|
| 169 |
+
"plt.title('Feature Importance')\n",
|
| 170 |
+
"plt.xticks(rotation=90)\n"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# Task 2: Write your code here:\n",
|
| 180 |
+
"golden_feature = feature_importance.iloc[0]['Feature']\n",
|
| 181 |
+
"print(\"Golden Feature:\", golden_feature)"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task Bonus: Write your code here:"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
}
|
| 195 |
+
],
|
| 196 |
+
"metadata": {
|
| 197 |
+
"kernelspec": {
|
| 198 |
+
"display_name": "Python 3",
|
| 199 |
+
"name": "python3"
|
| 200 |
+
},
|
| 201 |
+
"language_info": {
|
| 202 |
+
"name": "python"
|
| 203 |
+
}
|
| 204 |
+
},
|
| 205 |
+
"nbformat": 4,
|
| 206 |
+
"nbformat_minor": 0
|
| 207 |
+
}
|
submissions_extracted/301/Q1.ipynb
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 15 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"from tqdm import tqdm\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"food_delivery = os.path.join(path, 'Q1_data.csv')\n",
|
| 35 |
+
"df_food_delivery = pd.read_csv(food_delivery)\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"\n"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 2: Write your code here:\n",
|
| 47 |
+
"print(f\"Dataset shape: {df_food_delivery.shape}\")\n",
|
| 48 |
+
"df_food_delivery.head(10)\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 3: Write your code here:\n",
|
| 58 |
+
"df_food_delivery.info()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 4: Write your code here:\n",
|
| 68 |
+
"df_food_delivery.describe()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 5: Write your code here:\n",
|
| 78 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 79 |
+
"plt.hist(df_food_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 80 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 81 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 82 |
+
"plt.ylabel('Frequency')\n",
|
| 83 |
+
"plt.show()"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 1: Write your code here:\n",
|
| 93 |
+
"df_clean = df_food_delivery.copy()\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"df_clean = df_clean.drop(columns=['Order_ID'])\n",
|
| 96 |
+
"df_clean.describe()\n"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 2: Write your code here:\n",
|
| 106 |
+
"missing_percentage = (df_clean.isnull().sum() / len(df_clean)) * 100\n",
|
| 107 |
+
"missing_data = pd.DataFrame({\n",
|
| 108 |
+
" 'Column': missing_percentage.index,\n",
|
| 109 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 110 |
+
"})\n",
|
| 111 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 114 |
+
"missing_data.head(10)\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"for col in ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']:\n",
|
| 118 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# Task 3: Write your code here:\n",
|
| 132 |
+
"def check_duplicates(df):\n",
|
| 133 |
+
" duplicates = df.duplicated().sum()\n",
|
| 134 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 135 |
+
" if duplicates > 0:\n",
|
| 136 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 137 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 138 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 139 |
+
" else:\n",
|
| 140 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"check_duplicates(df_clean)"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 4: Write your code here:\n",
|
| 152 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
|
| 159 |
+
"df_clean = onehot_encoder.fit_transform(categorical_cols.array.reshape(-1,1)) # Apply fit_transform to the copied\n",
|
| 160 |
+
"\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 5: Write your code here:\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"features = df_clean.Columns.drop(\"Delivery_Time\")\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 174 |
+
"df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"print('\\nData after scaling:\\n', df_clean) #show after scaling\n"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"# Task 6: Write your code here:\n"
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 1: Write your code here:\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 197 |
+
"y = df_clean['Delivery_Time'].astype(float)"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 209 |
+
"from sklearn.model_selection import KFold\n",
|
| 210 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"model = RandomForestRegressor(n_estimators=200)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 219 |
+
" print(f\"\\nFold {fold_idx + 1}/{5}\")\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 222 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" print(f\"Training {model}...\")\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Train\n",
|
| 228 |
+
" model.fit(X_train, y_train)\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" # Predict\n",
|
| 231 |
+
" y_pred = model.predict(X_test)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Calculate metrics\n",
|
| 234 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" print(f\" MAE: {mae}\")\n",
|
| 238 |
+
"\n"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 1: Write your code here:"
|
| 248 |
+
],
|
| 249 |
+
"execution_count": null,
|
| 250 |
+
"outputs": []
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"# Task 2: Write your code here:"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task Bonus: Write your code here:"
|
| 266 |
+
],
|
| 267 |
+
"execution_count": null,
|
| 268 |
+
"outputs": []
|
| 269 |
+
}
|
| 270 |
+
],
|
| 271 |
+
"metadata": {
|
| 272 |
+
"kernelspec": {
|
| 273 |
+
"display_name": "Python 3",
|
| 274 |
+
"name": "python3"
|
| 275 |
+
},
|
| 276 |
+
"language_info": {
|
| 277 |
+
"name": "python"
|
| 278 |
+
}
|
| 279 |
+
},
|
| 280 |
+
"nbformat": 4,
|
| 281 |
+
"nbformat_minor": 0
|
| 282 |
+
}
|
submissions_extracted/301/Q2.ipynb
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"import torch.nn as nn\n",
|
| 12 |
+
"from torch.optim import AdamW\n",
|
| 13 |
+
"import matplotlib.pyplot as plt\n",
|
| 14 |
+
"import torch.nn.functional as F\n",
|
| 15 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 16 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 17 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"# Download latest version\n",
|
| 21 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"print(\"Path to dataset files:\", path)"
|
| 24 |
+
],
|
| 25 |
+
"execution_count": null,
|
| 26 |
+
"outputs": []
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"import os\n",
|
| 33 |
+
"import pandas as pd\n",
|
| 34 |
+
"import numpy as np\n",
|
| 35 |
+
"from PIL import Image\n",
|
| 36 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"# Load Labels\n",
|
| 39 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 40 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"images = []\n",
|
| 43 |
+
"ages = []\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"# Load Images and Resize\n",
|
| 46 |
+
"print(\"Loading images...\")\n",
|
| 47 |
+
"for index, row in labels_df.iterrows():\n",
|
| 48 |
+
" img_name = row.iloc[0]\n",
|
| 49 |
+
" age = row.iloc[1]\n",
|
| 50 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 51 |
+
"\n",
|
| 52 |
+
" if os.path.exists(img_path):\n",
|
| 53 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 54 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 55 |
+
" images.append(img_array)\n",
|
| 56 |
+
" ages.append(age)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"X = np.array(images)\n",
|
| 59 |
+
"y = np.array(ages)\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 62 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"# Split Data\n",
|
| 65 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 68 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 69 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 70 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 80 |
+
"import torch\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
|
| 83 |
+
"X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
|
| 84 |
+
"y_train = torch.tensor(y_train.values, dtype=torch.long)\n",
|
| 85 |
+
"y_test = torch.tensor(y_test.values, dtype=torch.long)\n"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# 2. Create TensorDataset objects\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 97 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 98 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 99 |
+
"\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# 3. Create DataLoaders\n",
|
| 109 |
+
"from torch.utils.data import DataLoader\n",
|
| 110 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 111 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 112 |
+
"\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# 4. Print shape of one batch\n",
|
| 122 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 123 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 124 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# 5. Display sample images\n",
|
| 134 |
+
"\n"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 1: Write your model class here:\n",
|
| 144 |
+
"class NN4Layer(nn.Module):\n",
|
| 145 |
+
"\n",
|
| 146 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 147 |
+
" super(NN4Layer, self).__init__()\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 150 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 153 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 156 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 159 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # ReLU activation for non-linearity\n",
|
| 162 |
+
" self.relu = nn.ReLU()\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # Defines how input data flows through the network\n",
|
| 165 |
+
" def forward(self, x):\n",
|
| 166 |
+
" # First hidden layer\n",
|
| 167 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" # Second hidden layer\n",
|
| 170 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # Third hidden layer\n",
|
| 173 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Output layer (raw scores / logits)\n",
|
| 176 |
+
" output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" return output\n"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 2: Write your training loop here:\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 190 |
+
" # Set the model to training mode\n",
|
| 191 |
+
" model.train()\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" running_loss = 0.0\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 196 |
+
" # Move batch to the selected device\n",
|
| 197 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 198 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Forward pass (outputs are logits)\n",
|
| 201 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 202 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" # Backward pass & optimization\n",
|
| 205 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 206 |
+
" loss.backward() # Compute gradients\n",
|
| 207 |
+
" optimizer.step() # Update model parameters\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" running_loss += loss.item()\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # Average loss over all batches\n",
|
| 212 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" return avg_loss\n"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 3: Write your validation loop here:\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 226 |
+
" # Set the model to evaluation mode\n",
|
| 227 |
+
" model.eval()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" running_loss = 0.0\n",
|
| 230 |
+
" correct = 0\n",
|
| 231 |
+
" total = 0\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" with torch.no_grad():\n",
|
| 234 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 235 |
+
" # Move data to device\n",
|
| 236 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 237 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # Forward pass\n",
|
| 240 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 241 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 242 |
+
" running_loss += loss.item()\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" # Apply Softmax to get probabilities\n",
|
| 245 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" # Pick the classes with highest probabilities\n",
|
| 248 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Accuracy calculation\n",
|
| 251 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 252 |
+
" total += y_batch.size(0)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 255 |
+
" accuracy = correct / total\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" return avg_loss, accuracy\n"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"cell_type": "code",
|
| 264 |
+
"metadata": {},
|
| 265 |
+
"source": [
|
| 266 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 267 |
+
"# Device setup\n",
|
| 268 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"# Model parameters\n",
|
| 271 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 272 |
+
"hidden_dim = 14 # Design choice\n",
|
| 273 |
+
"output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"# Instantiate model\n",
|
| 276 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Print the model architecture\n",
|
| 279 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 280 |
+
"print(model)\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"# Calculate the total number of trainable parameters\n",
|
| 283 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 284 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 285 |
+
"\n"
|
| 286 |
+
],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [
|
| 294 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"num_epochs = 20\n",
|
| 298 |
+
"learning_rate = 0.001\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 301 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 302 |
+
"# Define optimizer\n",
|
| 303 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Run Training\n",
|
| 306 |
+
"train_losses = []\n",
|
| 307 |
+
"val_losses = []\n",
|
| 308 |
+
"val_accuracies = []\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"print('Starting Training...')\n",
|
| 311 |
+
"for epoch in range(num_epochs):\n",
|
| 312 |
+
" # Train one epoch\n",
|
| 313 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
" # Validate\n",
|
| 316 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" train_losses.append(train_loss)\n",
|
| 319 |
+
" val_losses.append(val_loss)\n",
|
| 320 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"print('Training Complete!')\n"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"cell_type": "code",
|
| 331 |
+
"metadata": {},
|
| 332 |
+
"source": [
|
| 333 |
+
"# Task 1: Write your code here:\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"# Plotting results\n",
|
| 336 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 339 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 340 |
+
"plt.title('Loss over Epochs')\n",
|
| 341 |
+
"plt.xlabel('Epoch')\n",
|
| 342 |
+
"plt.ylabel('Loss')\n",
|
| 343 |
+
"plt.legend()\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"plt.tight_layout()\n",
|
| 346 |
+
"plt.show()"
|
| 347 |
+
],
|
| 348 |
+
"execution_count": null,
|
| 349 |
+
"outputs": []
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"cell_type": "code",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"source": [
|
| 355 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 356 |
+
],
|
| 357 |
+
"execution_count": null,
|
| 358 |
+
"outputs": []
|
| 359 |
+
}
|
| 360 |
+
],
|
| 361 |
+
"metadata": {
|
| 362 |
+
"kernelspec": {
|
| 363 |
+
"display_name": "Python 3",
|
| 364 |
+
"name": "python3"
|
| 365 |
+
},
|
| 366 |
+
"language_info": {
|
| 367 |
+
"name": "python"
|
| 368 |
+
}
|
| 369 |
+
},
|
| 370 |
+
"nbformat": 4,
|
| 371 |
+
"nbformat_minor": 0
|
| 372 |
+
}
|
submissions_extracted/301/Q3.ipynb
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 16 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Download latest version\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"data = os.path.join(path, 'Q3_data.csv')\n",
|
| 35 |
+
"df = pd.read_csv(data)\n",
|
| 36 |
+
"\n"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 2: Write your code here:\n",
|
| 46 |
+
"df.head(10)"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 3: Write your code here:\n",
|
| 56 |
+
"df.info()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 4: Write your code here:\n",
|
| 66 |
+
"df.describe()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 1: Write your code here:\n",
|
| 76 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
|
| 77 |
+
"missing_data = pd.DataFrame({\n",
|
| 78 |
+
" 'Column': missing_percentage.index,\n",
|
| 79 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 80 |
+
"})\n",
|
| 81 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 84 |
+
"missing_data.head(10)\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"for col in missing_data:\n",
|
| 88 |
+
" df[col] = df[col].fillna('unknown')\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# Task 2: Write your code here:\n",
|
| 101 |
+
"def check_duplicates(df):\n",
|
| 102 |
+
" duplicates = df.duplicated().sum()\n",
|
| 103 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 104 |
+
" if duplicates > 0:\n",
|
| 105 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 106 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 107 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 108 |
+
" else:\n",
|
| 109 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"check_duplicates(df)"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 3: Write your code here:\n",
|
| 121 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
|
| 128 |
+
"df_clean = onehot_encoder.fit_transform(categorical_cols.array.reshape(-1,1)) # Apply fit_transform to the copied\n"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# Task 4: Write your code here:\n",
|
| 138 |
+
"features = df_clean.Columns.drop(\"\")\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 141 |
+
"df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print('\\nData after scaling:\\n', df_clean) #show after scaling"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 5: Write your code here:"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 1: Write your code here:\n",
|
| 162 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 163 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"\n",
|
| 173 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"from sklearn.ensemble import Cat\n",
|
| 176 |
+
"from sklearn.model_selection import KFold\n",
|
| 177 |
+
"from sklearn.metrics import accuracy_score,f1_score\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"model = RandomForestRegressor(n_estimators=200)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 186 |
+
" print(f\"\\nFold {fold_idx + 1}/{5}\")\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 189 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" print(f\"Training {model}...\")\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Train\n",
|
| 195 |
+
" model.fit(X_train, y_train)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Predict\n",
|
| 198 |
+
" y_pred = model.predict(X_test)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Calculate metrics\n",
|
| 201 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" print(f\" MAE: {mae}\")\n",
|
| 205 |
+
"\n"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 1: Write your code here:"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 2: Write your code here:"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task Bonus: Write your code here:"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
}
|
| 237 |
+
],
|
| 238 |
+
"metadata": {
|
| 239 |
+
"kernelspec": {
|
| 240 |
+
"display_name": "Python 3",
|
| 241 |
+
"name": "python3"
|
| 242 |
+
},
|
| 243 |
+
"language_info": {
|
| 244 |
+
"name": "python"
|
| 245 |
+
}
|
| 246 |
+
},
|
| 247 |
+
"nbformat": 4,
|
| 248 |
+
"nbformat_minor": 0
|
| 249 |
+
}
|
submissions_extracted/302/Q1.ipynb
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import numpy as np\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import matplotlib.pyplot as plt\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 16 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 17 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"import warnings\n",
|
| 20 |
+
"warnings.filterwarnings('ignore')\n",
|
| 21 |
+
"import kagglehub\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"# Download latest version\n",
|
| 24 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"print(\"Path to dataset files:\", path)"
|
| 27 |
+
],
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"source": [
|
| 35 |
+
"d_path = os.path.join(path, 'Q1_data.csv') ## To Read The csv file\n",
|
| 36 |
+
"df_delv = pd.read_csv(d_path)\n",
|
| 37 |
+
"\n"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 2: Write your code here:\n",
|
| 47 |
+
"print(f\"Shape: {df_delv.shape}\")\n",
|
| 48 |
+
"df_delv.head() ## To print only the head of the table"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 3: Write your code here:print(f\"Shape: {df_delv.shape}\")\n",
|
| 58 |
+
"df_delv.info() ## To print All the info about the data"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 4: Write your code here:\n",
|
| 68 |
+
"df_delv.describe() ## To print The info as a table"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 5: Write your code here:\n",
|
| 78 |
+
"plt.figure(figsize=(10, 5)) ## To graph the data we can choose any number of bins\n",
|
| 79 |
+
"plt.hist(df_delv['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 80 |
+
"plt.title('delivery Distribution')\n",
|
| 81 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 82 |
+
"plt.ylabel('Frequency')\n",
|
| 83 |
+
"plt.show()\n"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 1: Write your code here:\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"df_clean = df_delv.dropna(subset=['Order_ID']).copy() ## To clean the data and copy it to the original data\n",
|
| 95 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 2: Write your code here:\n",
|
| 105 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs','Delivery_Time']:\n",
|
| 106 |
+
" df_clean[col] = df_clean[col].fillna('unknown') ## Fill the missing data with none\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# Task 3: Write your code here:\n",
|
| 116 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum()) ## cheake if there is any missing data stell there\n",
|
| 117 |
+
"\n"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 4: Write your code here:\n",
|
| 127 |
+
"## there is no categorical variables"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 5: Write your code here:\n",
|
| 137 |
+
"standard_scaler = StandardScaler() ## Use the function to transfir\n",
|
| 138 |
+
"df_clean= standard_scaler.fit_transform(df_clean)\n"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 6: Write your code here:\n",
|
| 148 |
+
"print(f\"Delivery : {df_delv['Delivery_Time'].sum()}\") ## To cheak the imbalance\n",
|
| 149 |
+
"print(f\" Not Delivery : {(df_delv['Delivery_Time'] == 0).sum()}\")"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 1: Write your code here:\n",
|
| 159 |
+
"feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs'] ## but the feature in\n",
|
| 160 |
+
"X = df_clean[feature_cols]\n",
|
| 161 |
+
"y = df_clean['Delivery_Time']\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 164 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 174 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 175 |
+
" class_weight='balanced', random_state=42)\n",
|
| 176 |
+
"model.fit(X_train,y_train)\n",
|
| 177 |
+
"print(\"Model trained!\")\n",
|
| 178 |
+
"y_pred = model.predict(X_test)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"print(f\"MAE: ${mae:,.2f}\")"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task 1: Write your code here:\n",
|
| 192 |
+
"feature_importance = pd.DataFrame({\n",
|
| 193 |
+
" 'feature': feature_cols,\n",
|
| 194 |
+
" 'importance': model.feature_importances_\n",
|
| 195 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 198 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 199 |
+
"plt.xlabel('Importance')\n",
|
| 200 |
+
"plt.title('Feature Importance')\n",
|
| 201 |
+
"plt.gca().invert_yaxis()\n",
|
| 202 |
+
"plt.show()"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 2: Write your code here:\n"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# Task Bonus: Write your code here:"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
}
|
| 225 |
+
],
|
| 226 |
+
"metadata": {
|
| 227 |
+
"kernelspec": {
|
| 228 |
+
"display_name": "Python 3",
|
| 229 |
+
"name": "python3"
|
| 230 |
+
},
|
| 231 |
+
"language_info": {
|
| 232 |
+
"name": "python"
|
| 233 |
+
}
|
| 234 |
+
},
|
| 235 |
+
"nbformat": 4,
|
| 236 |
+
"nbformat_minor": 0
|
| 237 |
+
}
|
submissions_extracted/302/Q2.ipynb
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"import torch\n",
|
| 27 |
+
"import torch.nn as nn\n",
|
| 28 |
+
"from torch.optim import AdamW\n",
|
| 29 |
+
"import matplotlib.pyplot as plt\n",
|
| 30 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 31 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 32 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 33 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 34 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# Load Labels\n",
|
| 37 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 38 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"images = []\n",
|
| 41 |
+
"ages = []\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"# Load Images and Resize\n",
|
| 44 |
+
"print(\"Loading images...\")\n",
|
| 45 |
+
"for index, row in labels_df.iterrows():\n",
|
| 46 |
+
" img_name = row.iloc[0]\n",
|
| 47 |
+
" age = row.iloc[1]\n",
|
| 48 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
" if os.path.exists(img_path):\n",
|
| 51 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 52 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 53 |
+
" images.append(img_array)\n",
|
| 54 |
+
" ages.append(age)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"X = np.array(images)\n",
|
| 57 |
+
"y = np.array(ages)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 60 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Split Data\n",
|
| 63 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 66 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 67 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 68 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 80 |
+
"test_dataset = TensorDataset(X_test, y_test)"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# 2. Create TensorDataset objects\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 3. Create DataLoaders\n",
|
| 101 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 102 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"\n"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# 4. Print shape of one batch\n",
|
| 114 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 115 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 116 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"images, labels = next(iter(train_loader))\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"for i in range(6):\n",
|
| 130 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 133 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 134 |
+
"\n",
|
| 135 |
+
" plt.imshow(img)\n",
|
| 136 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 137 |
+
" plt.axis('off')\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"plt.tight_layout()\n",
|
| 140 |
+
"plt.show()\n"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 1: Write your model class here:\n",
|
| 150 |
+
"class NN4Layer(nn.Module):\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 153 |
+
" super(NN4Layer, self).__init__()\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" self.relu = nn.ReLU()\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" def forward(self, x):\n",
|
| 167 |
+
" z1 = self.layer1(x)\n",
|
| 168 |
+
" a1 = self.relu(z1)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" z2 = self.layer2(a1)\n",
|
| 171 |
+
" a2 = self.relu(z2)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" z3 = self.layer3(a2)\n",
|
| 174 |
+
" a3 = self.relu(z3)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" z4 = self.layer5(a3)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" return z4"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 2: Write your training loop here:\n",
|
| 191 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 192 |
+
" # Set the model to training mode\n",
|
| 193 |
+
" model.train()\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" running_loss = 0.0\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 198 |
+
" # Move batch to the selected device\n",
|
| 199 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 200 |
+
" y_batch = y_batch.to(device)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # Forward pass\n",
|
| 203 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 204 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Backward pass & optimization\n",
|
| 207 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 208 |
+
" loss.backward() # Compute gradients\n",
|
| 209 |
+
" optimizer.step() # Update model parameters\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" running_loss += loss.item()\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Average loss over all batches\n",
|
| 214 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" return avg_loss"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 3: Write your validation loop here:\n",
|
| 226 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 227 |
+
" # Set the model to evaluation mode\n",
|
| 228 |
+
" model.eval()\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" running_loss = 0.0\n",
|
| 231 |
+
" correct = 0\n",
|
| 232 |
+
" total = 0\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" with torch.no_grad():\n",
|
| 235 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 236 |
+
" # Move data to device\n",
|
| 237 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 238 |
+
" y_batch = y_batch.to(device)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Forward pass\n",
|
| 241 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 242 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 243 |
+
" running_loss += loss.item()\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # Accuracy calculation\n",
|
| 250 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 251 |
+
" total += y_batch.size(0)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 254 |
+
" accuracy = correct / total\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" return avg_loss, accuracy"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 266 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 276 |
+
"input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"hidden_dim = 64 # Design choice\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"output_dim = 10 # CIFAR-10 classes\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 285 |
+
"print(model)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Calculate the total number of trainable parameters\n",
|
| 288 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 289 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 290 |
+
],
|
| 291 |
+
"execution_count": null,
|
| 292 |
+
"outputs": []
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"source": [
|
| 298 |
+
"# Task 1: Write your code here:\n",
|
| 299 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"plt.plot(train_one_epoch, label='Train Loss')\n",
|
| 302 |
+
"plt.plot(validate, label='Validation Loss')\n",
|
| 303 |
+
"plt.title('Loss over Epochs')\n",
|
| 304 |
+
"plt.xlabel('Epoch')\n",
|
| 305 |
+
"plt.ylabel('Loss')\n",
|
| 306 |
+
"plt.legend()\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"plt.tight_layout()\n",
|
| 309 |
+
"plt.show()"
|
| 310 |
+
],
|
| 311 |
+
"execution_count": null,
|
| 312 |
+
"outputs": []
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"cell_type": "code",
|
| 316 |
+
"metadata": {},
|
| 317 |
+
"source": [
|
| 318 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 319 |
+
],
|
| 320 |
+
"execution_count": null,
|
| 321 |
+
"outputs": []
|
| 322 |
+
}
|
| 323 |
+
],
|
| 324 |
+
"metadata": {
|
| 325 |
+
"kernelspec": {
|
| 326 |
+
"display_name": "Python 3",
|
| 327 |
+
"name": "python3"
|
| 328 |
+
},
|
| 329 |
+
"language_info": {
|
| 330 |
+
"name": "python"
|
| 331 |
+
}
|
| 332 |
+
},
|
| 333 |
+
"nbformat": 4,
|
| 334 |
+
"nbformat_minor": 0
|
| 335 |
+
}
|
submissions_extracted/302/Q3.ipynb
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import seaborn as sns\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"from tqdm import tqdm\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"# Download latest version\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"print(\"Path to dataset files:\", path)"
|
| 23 |
+
],
|
| 24 |
+
"execution_count": null,
|
| 25 |
+
"outputs": []
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"# Task 1: Write your code here:\n",
|
| 32 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"df = pd.read_csv(csv_path)\n"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 2: Write your code here:\n",
|
| 44 |
+
"df.head()"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"# Task 3: Write your code here:\n",
|
| 54 |
+
"df.info()"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"# Task 4: Write your code here:\n",
|
| 64 |
+
"df.describe()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 1: Write your code here:\n",
|
| 74 |
+
"def check_missing_values(df):\n",
|
| 75 |
+
"\n",
|
| 76 |
+
" # Get missing values using pandas\n",
|
| 77 |
+
" missing_values = df.isnull().sum()\n",
|
| 78 |
+
"\n",
|
| 79 |
+
" print(\"Missing Values per Column:\")\n",
|
| 80 |
+
" print(missing_values[missing_values > 0])\n",
|
| 81 |
+
"\n",
|
| 82 |
+
" if missing_values.any():\n",
|
| 83 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 84 |
+
" else:\n",
|
| 85 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"check_missing_values(df)"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 2: Write your code here:\n",
|
| 97 |
+
"def check_duplicates(df):\n",
|
| 98 |
+
"\n",
|
| 99 |
+
" #TODO: get duplicated data using pandas\n",
|
| 100 |
+
" duplicates = df.duplicated().sum()\n",
|
| 101 |
+
"\n",
|
| 102 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 103 |
+
" if duplicates > 0:\n",
|
| 104 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 105 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 106 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 107 |
+
" else:\n",
|
| 108 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"check_duplicates(df)\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"## there is no duplicate"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 3: Write your code here:\n",
|
| 122 |
+
"## there is no categorical variables\n"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# Task 4: Write your code here:\n",
|
| 132 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 133 |
+
"standard_scaler = StandardScaler()\n",
|
| 134 |
+
"df= standard_scaler.fit_transform(df)\n"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 5: Write your code here:\n",
|
| 144 |
+
"print(f\" The Target: {df['Target'].sum()}\")\n",
|
| 145 |
+
"print(f\" Not The Target : {(df['Target'] == 0).sum()}\")"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 1: Write your code here:\n",
|
| 155 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"feature_cols = ['P_2', 'D_39','B_1', 'B_2','S_3','R_1','D_41','B_3','D_41','D_42','D_43','D_137','D_138','D_139','D_140','D_141','D_142','D_143','D_144','D_145']\n",
|
| 158 |
+
"X = df[feature_cols]\n",
|
| 159 |
+
"y = df['Target']\n",
|
| 160 |
+
"\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 170 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 171 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 1: Write your code here:\n",
|
| 181 |
+
"feature_importance = pd.DataFrame({\n",
|
| 182 |
+
" 'feature': feature_cols,\n",
|
| 183 |
+
" 'importance': model.feature_importances_\n",
|
| 184 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 187 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 188 |
+
"plt.xlabel('Importance')\n",
|
| 189 |
+
"plt.title('Feature Importance')\n",
|
| 190 |
+
"plt.gca().invert_yaxis()\n",
|
| 191 |
+
"plt.show()"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"# Task 2: Write your code here:"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task Bonus: Write your code here:"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
}
|
| 214 |
+
],
|
| 215 |
+
"metadata": {
|
| 216 |
+
"kernelspec": {
|
| 217 |
+
"display_name": "Python 3",
|
| 218 |
+
"name": "python3"
|
| 219 |
+
},
|
| 220 |
+
"language_info": {
|
| 221 |
+
"name": "python"
|
| 222 |
+
}
|
| 223 |
+
},
|
| 224 |
+
"nbformat": 4,
|
| 225 |
+
"nbformat_minor": 0
|
| 226 |
+
}
|
submissions_extracted/303/Q1.ipynb
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import pandas as pd\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import matplotlib.pyplot as plt\n",
|
| 10 |
+
"import seaborn as sns\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"from tqdm import tqdm\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"%matplotlib inline"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"import kagglehub\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"# Download latest version\n",
|
| 26 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"print(\"Path to dataset files:\", path)"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"# Task 1: Write your code here:\n",
|
| 38 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"df = pd.read_csv(csv_path)"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 2: Write your code here:\n",
|
| 50 |
+
"df.head()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 3: Write your code here:\n",
|
| 60 |
+
"df.info()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 4: Write your code here:\n",
|
| 70 |
+
"df.describe()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 5: Write your code here: Plot the target distribution (delivery_time)\n",
|
| 80 |
+
"def check_target_distribution(df, target_column):\n",
|
| 81 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 84 |
+
" plt.xlabel(target_column)\n",
|
| 85 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 86 |
+
" plt.grid(False)\n",
|
| 87 |
+
"\n",
|
| 88 |
+
" plt.show()\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 1: Write your code here: Drop the 'Order_ID' column from the data\n",
|
| 100 |
+
"df = df.drop(columns=\"Order_ID\", axis=1)"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# Task 2: Write your code here: Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"# Check for missing values:\n",
|
| 112 |
+
"def check_missing_values(df):\n",
|
| 113 |
+
" missing_values = df.isnull().sum()\n",
|
| 114 |
+
" print(\"Missing Values per Column:\")\n",
|
| 115 |
+
" print(missing_values[missing_values > 0])\n",
|
| 116 |
+
" if missing_values.any():\n",
|
| 117 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 118 |
+
" else:\n",
|
| 119 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"check_missing_values(df)\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Drop missing values:\n",
|
| 124 |
+
"df = df.dropna()\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"check_missing_values(df)\n"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 3: Write your code here: Check and remove duplicates if any exist\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"def check_duplicates(df):\n",
|
| 138 |
+
" duplicates = df.duplicated().sum()\n",
|
| 139 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 140 |
+
" if duplicates > 0:\n",
|
| 141 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 142 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 143 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 144 |
+
" else:\n",
|
| 145 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"check_duplicates(df)"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 4: Write your code here: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
|
| 157 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 160 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"le = LabelEncoder()\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"# Encode the target column\n",
|
| 165 |
+
"df['Weather'] = le.fit_transform(df['Weather'])\n",
|
| 166 |
+
"df['Traffic_Level'] = le.fit_transform(df['Traffic_Level'])\n",
|
| 167 |
+
"df['Time_of_Day'] = le.fit_transform(df['Time_of_Day'])\n",
|
| 168 |
+
"df['Vehicle_Type'] = le.fit_transform(df['Vehicle_Type'])\n"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"df.head()"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
|
| 191 |
+
"scaler = StandardScaler()\n",
|
| 192 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 193 |
+
"df\n"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"# The data is not imbalanced"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# Task 1: Write your code here:\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 216 |
+
"y = df['Delivery_Time'].astype(float)\n"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 226 |
+
"from sklearn.model_selection import StratifiedKFold, train_test_split\n",
|
| 227 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 228 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"n_splits = 10\n",
|
| 231 |
+
"rf_mae = []\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 237 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" model = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Train\n",
|
| 244 |
+
" model = model.fit(X_train, y_train)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # Predict\n",
|
| 247 |
+
" y_pred = model.predict(X_test)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # Calculate metrics\n",
|
| 250 |
+
" mea = mean_absolute_error(y_test, y_pred)\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # Store results\n",
|
| 253 |
+
" rf_mae.append(mea)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"average_losses = np.mean(rf_mae, axis=0)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"print(\"Average MAE\", average_losses)\n"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"cell_type": "code",
|
| 264 |
+
"metadata": {},
|
| 265 |
+
"source": [
|
| 266 |
+
"# Task 1: Write your code here:\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"import matplotlib.pyplot as plt\n",
|
| 269 |
+
"import seaborn as sns\n",
|
| 270 |
+
"import pandas as pd\n",
|
| 271 |
+
"import numpy as np\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"feature_cols = \t['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"# Feature importance\n",
|
| 276 |
+
"importance = pd.DataFrame({\n",
|
| 277 |
+
" 'feature': feature_cols,\n",
|
| 278 |
+
" 'importance': model.feature_importances_\n",
|
| 279 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 282 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 283 |
+
"plt.xlabel('Importance')\n",
|
| 284 |
+
"plt.title('Feature Importance')\n",
|
| 285 |
+
"plt.gca().invert_yaxis()\n",
|
| 286 |
+
"plt.show()\n",
|
| 287 |
+
"\n"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"# Task 2: Write your code here:\n",
|
| 297 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 298 |
+
"plt.hist(y_pred)\n",
|
| 299 |
+
"plt.title('Predicted Delivery Time')\n",
|
| 300 |
+
"plt.xlabel('Percentage')\n",
|
| 301 |
+
"plt.ylabel('Predicted value')\n",
|
| 302 |
+
"plt.legend()"
|
| 303 |
+
],
|
| 304 |
+
"execution_count": null,
|
| 305 |
+
"outputs": []
|
| 306 |
+
},
|
| 307 |
+
{
|
| 308 |
+
"cell_type": "code",
|
| 309 |
+
"metadata": {},
|
| 310 |
+
"source": [
|
| 311 |
+
"# Task Bonus: Write your code here:\n",
|
| 312 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 313 |
+
"from sklearn.svm import SVR\n",
|
| 314 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 315 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 316 |
+
"from lightgbm import LGBMRegressor\n",
|
| 317 |
+
"#!pip install catboost\n",
|
| 318 |
+
"from catboost import CatBoostRegressor\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"models = {\n",
|
| 321 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 322 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 323 |
+
"}\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"all_results = {}\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"for name in models:\n",
|
| 328 |
+
" all_results[name] = {'mae': []}\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 333 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
| 336 |
+
"\n",
|
| 337 |
+
" for model_name, model in models.items():\n",
|
| 338 |
+
" print(f\"Training {model_name}...\")\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" # Train\n",
|
| 341 |
+
" model.fit(X_train, y_train)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" # Predict\n",
|
| 344 |
+
" y_pred = model.predict(X_test)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" # Calculate metrics\n",
|
| 347 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" # Store results\n",
|
| 350 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"for model_name in all_results:\n",
|
| 353 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 354 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"\n"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"cell_type": "code",
|
| 364 |
+
"metadata": {},
|
| 365 |
+
"source": [],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
}
|
| 369 |
+
],
|
| 370 |
+
"metadata": {
|
| 371 |
+
"kernelspec": {
|
| 372 |
+
"display_name": "Python 3",
|
| 373 |
+
"name": "python3"
|
| 374 |
+
},
|
| 375 |
+
"language_info": {
|
| 376 |
+
"name": "python"
|
| 377 |
+
}
|
| 378 |
+
},
|
| 379 |
+
"nbformat": 4,
|
| 380 |
+
"nbformat_minor": 0
|
| 381 |
+
}
|
submissions_extracted/303/Q2.ipynb
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 72 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 73 |
+
"y_train = torch.tensor(y_train, dtype=torch.long)\n",
|
| 74 |
+
"y_test = torch.tensor(y_test, dtype=torch.long)\n",
|
| 75 |
+
"\n"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# 2. Create TensorDataset objects\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 89 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 90 |
+
"\n"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# 3. Create DataLoaders\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True,num_workers=2)\n",
|
| 102 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False,num_workers=2)\n",
|
| 103 |
+
"\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# 4. Print shape of one batch\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 115 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 116 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 122 |
+
"print(f\"Label: {sample_label}\")"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# 5. Display sample images\n",
|
| 132 |
+
"import matplotlib.pyplot as plt\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"# Get one batch of images and labels\n",
|
| 135 |
+
"images, labels = next(iter(train_loader))\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# Display the first 6 images in the batch\n",
|
| 138 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"for i in range(6):\n",
|
| 141 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 142 |
+
" plt.imshow(images[i])\n",
|
| 143 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 144 |
+
" plt.axis('off')\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"plt.tight_layout()\n",
|
| 147 |
+
"plt.show()\n"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 1: Write your model class here:\n",
|
| 157 |
+
"import torch\n",
|
| 158 |
+
"import torch.nn as nn\n",
|
| 159 |
+
"import torch.nn.functional as F\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"class NN4Layer(nn.Module):\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 164 |
+
" super(NN4Layer, self).__init__()\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" self.layer5 = nn.Linear(hidden_dim, output_dim)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # ReLU activation for non-linearity\n",
|
| 177 |
+
" self.relu = nn.ReLU()\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Defines how input data flows through the network\n",
|
| 180 |
+
" def forward(self, x):\n",
|
| 181 |
+
" # First hidden layer\n",
|
| 182 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" # Second hidden layer\n",
|
| 185 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Third hidden layer\n",
|
| 188 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" a4 = self.relu(self.layer4(a3))\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # Output layer (raw scores / logits)\n",
|
| 193 |
+
" output = self.layer5(a4)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return output"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 2: Write your training loop here:\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 207 |
+
" # Set the model to training mode\n",
|
| 208 |
+
" model.train()\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" running_loss = 0.0\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 213 |
+
" # Move batch to the selected device\n",
|
| 214 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 215 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Forward pass (outputs are logits)\n",
|
| 218 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 219 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Backward pass & optimization\n",
|
| 222 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 223 |
+
" loss.backward() # Compute gradients\n",
|
| 224 |
+
" optimizer.step() # Update model parameters\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" running_loss += loss.item()\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Average loss over all batches\n",
|
| 229 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" return avg_loss\n"
|
| 232 |
+
],
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"outputs": []
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"metadata": {},
|
| 239 |
+
"source": [
|
| 240 |
+
"# Task 3: Write your validation loop here:\n",
|
| 241 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 242 |
+
" # Set the model to evaluation mode\n",
|
| 243 |
+
" model.eval()\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" running_loss = 0.0\n",
|
| 246 |
+
" correct = 0\n",
|
| 247 |
+
" total = 0\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" with torch.no_grad():\n",
|
| 250 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 251 |
+
" # Move data to device\n",
|
| 252 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 253 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Forward pass\n",
|
| 256 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 257 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 258 |
+
" running_loss += loss.item()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Apply Softmax to get probabilities\n",
|
| 261 |
+
" probabilities = F.softmax(outputs, dim=1) # why are we applying it here?\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Pick the classes with highest probabilities\n",
|
| 264 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" # Accuracy calculation\n",
|
| 267 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 268 |
+
" total += y_batch.size(0)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 271 |
+
" accuracy = correct / total\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" return avg_loss, accuracy"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 283 |
+
"from torch.optim import AdamW\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 286 |
+
"print(\"Running Model on:\", device)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"input_dim = 32 * 36 * 3\n",
|
| 289 |
+
"hidden_dim = 36\n",
|
| 290 |
+
"output_dim = 1\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"num_epochs = 20\n",
|
| 295 |
+
"learning_rate = 0.001\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"criterion = nn.MSELoss()\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Print the model architecture\n",
|
| 302 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 303 |
+
"print(model)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Calculate the total number of trainable parameters\n",
|
| 306 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 309 |
+
],
|
| 310 |
+
"execution_count": null,
|
| 311 |
+
"outputs": []
|
| 312 |
+
},
|
| 313 |
+
{
|
| 314 |
+
"cell_type": "code",
|
| 315 |
+
"metadata": {},
|
| 316 |
+
"source": [
|
| 317 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 318 |
+
"train_losses = []\n",
|
| 319 |
+
"val_losses = []\n",
|
| 320 |
+
"val_accuracies = []\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"print('Starting Training...')\n",
|
| 323 |
+
"for epoch in range(num_epochs):\n",
|
| 324 |
+
" # Train one epoch\n",
|
| 325 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" # Validate\n",
|
| 328 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" train_losses.append(train_loss)\n",
|
| 331 |
+
" val_losses.append(val_loss)\n",
|
| 332 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"print('Training Complete!')"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"# Task 1: Write your code here:\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"# Plotting results\n",
|
| 348 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 351 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 352 |
+
"plt.title('Loss over Epochs')\n",
|
| 353 |
+
"plt.xlabel('Epoch')\n",
|
| 354 |
+
"plt.ylabel('Loss')\n",
|
| 355 |
+
"plt.legend()\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"plt.tight_layout()\n",
|
| 358 |
+
"plt.show()"
|
| 359 |
+
],
|
| 360 |
+
"execution_count": null,
|
| 361 |
+
"outputs": []
|
| 362 |
+
},
|
| 363 |
+
{
|
| 364 |
+
"cell_type": "code",
|
| 365 |
+
"metadata": {},
|
| 366 |
+
"source": [
|
| 367 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"# Set model to evaluation mode\n",
|
| 370 |
+
"model.eval()\n",
|
| 371 |
+
"# Get one batch from the test DataLoader\n",
|
| 372 |
+
"images, labels = next(iter(test_loader))\n",
|
| 373 |
+
"# Move images to device\n",
|
| 374 |
+
"images = images.to(device)\n",
|
| 375 |
+
"labels = labels.to(device)\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"with torch.no_grad():\n",
|
| 378 |
+
" # Flatten images before passing to the model\n",
|
| 379 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 380 |
+
" predictions = torch.argmax(outputs, dim=1)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"# Move tensors back to CPU for plotting\n",
|
| 383 |
+
"images = images.cpu()\n",
|
| 384 |
+
"labels = labels.cpu()\n",
|
| 385 |
+
"predictions = predictions.cpu()\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"# Plot first 6 predictions\n",
|
| 388 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 389 |
+
"for i in range(6):\n",
|
| 390 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 391 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 392 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 393 |
+
" plt.axis('off')\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"plt.tight_layout()\n",
|
| 396 |
+
"plt.show()"
|
| 397 |
+
],
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"outputs": []
|
| 400 |
+
}
|
| 401 |
+
],
|
| 402 |
+
"metadata": {
|
| 403 |
+
"kernelspec": {
|
| 404 |
+
"display_name": "Python 3",
|
| 405 |
+
"name": "python3"
|
| 406 |
+
},
|
| 407 |
+
"language_info": {
|
| 408 |
+
"name": "python"
|
| 409 |
+
}
|
| 410 |
+
},
|
| 411 |
+
"nbformat": 4,
|
| 412 |
+
"nbformat_minor": 0
|
| 413 |
+
}
|
submissions_extracted/303/Q3.ipynb
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import pandas as pd\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import matplotlib.pyplot as plt\n",
|
| 10 |
+
"import seaborn as sns\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"from tqdm import tqdm\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"%matplotlib inline"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"import kagglehub\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Download latest version\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(\"Path to dataset files:\", path)"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 1: Write your code here:\n",
|
| 43 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"df = pd.read_csv(csv_path)"
|
| 46 |
+
],
|
| 47 |
+
"execution_count": null,
|
| 48 |
+
"outputs": []
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"cell_type": "code",
|
| 52 |
+
"metadata": {},
|
| 53 |
+
"source": [
|
| 54 |
+
"# Task 2: Write your code here:\n",
|
| 55 |
+
"df.head()"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"# Task 3: Write your code here:\n",
|
| 65 |
+
"df.info()"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"# Task 4: Write your code here:\n",
|
| 75 |
+
"df.describe()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# Task 1: Write your code here:\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"# Check for missing values:\n",
|
| 87 |
+
"def check_missing_values(df):\n",
|
| 88 |
+
" missing_values = df.isnull().sum()\n",
|
| 89 |
+
" print(\"Missing Values per Column:\")\n",
|
| 90 |
+
" print(missing_values[missing_values > 0])\n",
|
| 91 |
+
" if missing_values.any():\n",
|
| 92 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 93 |
+
" else:\n",
|
| 94 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"check_missing_values(df)\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"for col in df.columns:\n",
|
| 100 |
+
" df[col.title()] = df[col.title()].fillna(df[col.title()].mean())\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"check_missing_values(df)\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"df"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 2: Write your code here:\n",
|
| 121 |
+
"def check_duplicates(df):\n",
|
| 122 |
+
" duplicates = df.duplicated().sum()\n",
|
| 123 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 124 |
+
" if duplicates > 0:\n",
|
| 125 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 126 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 127 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 128 |
+
" else:\n",
|
| 129 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"check_duplicates(df)"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"# Task 3: Write your code here:\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 143 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 4: Write your code here:\n",
|
| 153 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
|
| 156 |
+
"scaler = StandardScaler()\n",
|
| 157 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 158 |
+
"df"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 5: Write your code here:\n",
|
| 168 |
+
"def check_target_distribution(df, target_column):\n",
|
| 169 |
+
" df[target_column].hist(bins=2, edgecolor='black')\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 172 |
+
" plt.xlabel(target_column)\n",
|
| 173 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 174 |
+
" plt.grid(False)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" plt.show()\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"check_target_distribution(df, \"Target\")\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"# There is target imbalance"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Task 1: Write your code here:\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 192 |
+
"y = df['Target'].astype(float)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"X.head()"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 204 |
+
"from sklearn.model_selection import StratifiedKFold, train_test_split\n",
|
| 205 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 206 |
+
"#!pip install catboost\n",
|
| 207 |
+
"from catboost import CatBoostClassifier\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"n_splits = 5\n",
|
| 210 |
+
"cb_accuracy = []\n",
|
| 211 |
+
"cb_f1 = []\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"skf = StratifiedKFold(n_splits, shuffle=True, random_state=42)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 216 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" model = CatBoostClassifier(verbose=0)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Train\n",
|
| 223 |
+
" model = model.fit(X_train, y_train)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Predict\n",
|
| 226 |
+
" y_pred = model.predict(X_test)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Calculate metrics\n",
|
| 229 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 230 |
+
" f1 = f1_score(y_test, y_pred)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # Store results\n",
|
| 233 |
+
" cb_accuracy.append(accuracy)\n",
|
| 234 |
+
" cb_f1.append(cb_f1)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"avg_accuracy = np.mean(cb_accuracy, axis=0)\n",
|
| 237 |
+
"avg_f1 = np.mean(cb_f1, axis=0)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"print(avg_accuracy)\n",
|
| 240 |
+
"print(avg_f1)\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"\n"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"print(model)"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"# Task 1: Write your code here:\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"import matplotlib.pyplot as plt\n",
|
| 264 |
+
"import seaborn as sns\n",
|
| 265 |
+
"import pandas as pd\n",
|
| 266 |
+
"import numpy as np\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"feature_cols = \t['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"# Feature importance\n",
|
| 271 |
+
"importance = pd.DataFrame({\n",
|
| 272 |
+
" 'feature': feature_cols,\n",
|
| 273 |
+
" 'importance': model.feature_importances_\n",
|
| 274 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 277 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 278 |
+
"plt.xlabel('Importance')\n",
|
| 279 |
+
"plt.title('Feature Importance')\n",
|
| 280 |
+
"plt.gca().invert_yaxis()\n",
|
| 281 |
+
"plt.show()"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"source": [
|
| 290 |
+
"# Task 2: Write your code here:\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"#importance['feature'[0]"
|
| 293 |
+
],
|
| 294 |
+
"execution_count": null,
|
| 295 |
+
"outputs": []
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "code",
|
| 299 |
+
"metadata": {},
|
| 300 |
+
"source": [
|
| 301 |
+
"# Task Bonus: Write your code here:"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [],
|
| 310 |
+
"execution_count": null,
|
| 311 |
+
"outputs": []
|
| 312 |
+
}
|
| 313 |
+
],
|
| 314 |
+
"metadata": {
|
| 315 |
+
"kernelspec": {
|
| 316 |
+
"display_name": "Python 3",
|
| 317 |
+
"name": "python3"
|
| 318 |
+
},
|
| 319 |
+
"language_info": {
|
| 320 |
+
"name": "python"
|
| 321 |
+
}
|
| 322 |
+
},
|
| 323 |
+
"nbformat": 4,
|
| 324 |
+
"nbformat_minor": 0
|
| 325 |
+
}
|
submissions_extracted/304/Q1.ipynb
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"from IPython.display import clear_output\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"%pip install kagglehub catboost lightgbm tqdm -q\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"clear_output()"
|
| 12 |
+
],
|
| 13 |
+
"execution_count": null,
|
| 14 |
+
"outputs": []
|
| 15 |
+
},
|
| 16 |
+
{
|
| 17 |
+
"cell_type": "code",
|
| 18 |
+
"metadata": {},
|
| 19 |
+
"source": [
|
| 20 |
+
"import pandas as pd\n",
|
| 21 |
+
"import numpy as np\n",
|
| 22 |
+
"import matplotlib.pyplot as plt\n",
|
| 23 |
+
"import seaborn as sns\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"from tqdm import tqdm\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"%matplotlib inline"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"import kagglehub\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"# Download latest version\n",
|
| 39 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"print(\"Path to dataset files:\", path)"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 1: Write your code here:\n",
|
| 51 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"df = pd.read_csv(csv_path)"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 2: Write your code here:\n",
|
| 63 |
+
"df.head()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 3: Write your code here:\n",
|
| 73 |
+
"df.info()"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 4: Write your code here:\n",
|
| 83 |
+
"df.describe()"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 5: Write your code here:\n",
|
| 93 |
+
"def check_target_distribution(df, target_column):\n",
|
| 94 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 95 |
+
"\n",
|
| 96 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 97 |
+
" plt.xlabel(target_column)\n",
|
| 98 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 99 |
+
" plt.grid(False)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
" plt.show()\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 1: Write your code here:\n",
|
| 113 |
+
"df = df.drop(columns=\"Order_ID\", axis=1)"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"df.head()"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# Task 2: Write your code here:\n",
|
| 132 |
+
"def check_missing_values(df):\n",
|
| 133 |
+
" missing_values = df.isnull().sum()\n",
|
| 134 |
+
" print(\"Missing Values per Column:\")\n",
|
| 135 |
+
" print(missing_values[missing_values > 0])\n",
|
| 136 |
+
" if missing_values.any():\n",
|
| 137 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 138 |
+
" else:\n",
|
| 139 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"check_missing_values(df)\n",
|
| 142 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 3: Write your code here:\n",
|
| 154 |
+
"def check_duplicates(df):\n",
|
| 155 |
+
" duplicates = df.duplicated().sum()\n",
|
| 156 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 157 |
+
" if duplicates > 0:\n",
|
| 158 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 159 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 160 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 161 |
+
" else:\n",
|
| 162 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"check_duplicates(df)"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 4: Write your code here:\n",
|
| 174 |
+
"col_name = pd.DataFrame({\"col_name\": [\"Distance_km,Weather\", \"Traffic_Level\",\"Time_of_Day\",\"Vehicle_Type\",\"Preparation_Time_min\",\"Courier_Experience_yrs\"\t,\"Delivery_Time\"]})\n",
|
| 175 |
+
"from sklearn.preprocessing import StandardScaler, MinMaxScaler, OneHotEncoder, LabelEncoder, OrdinalEncoder\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"print('data before encoding:\\n',col_name )\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False)\n",
|
| 180 |
+
"data_onehot_encoded = onehot_encoder.fit_transform(col_name)\n",
|
| 181 |
+
"print('\\nData after encoding:\\n', data_onehot_encoded)"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"df.describe()"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 5: Write your code here:\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"scaler = StandardScaler()\n",
|
| 206 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 207 |
+
"df.head()\n"
|
| 208 |
+
],
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"outputs": []
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"cell_type": "code",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"source": [
|
| 216 |
+
"# Task 6: Write your code here:\n",
|
| 217 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 218 |
+
" print(\"Target Distribution:\")\n",
|
| 219 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 220 |
+
" sns.countplot(x=df[target_column])\n",
|
| 221 |
+
" plt.title(\"Target Distribution\")\n",
|
| 222 |
+
" plt.show()\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"check_target_imbalance(df, \"Delivery_Time\")"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"# Task 1: Write your code here:\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 236 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Mean Squared Error in NumPy\n",
|
| 246 |
+
"from sklearn.model_selection import KFold\n",
|
| 247 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 248 |
+
"def mean_squared_error(y, y_hat):\n",
|
| 249 |
+
" return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 259 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 260 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 261 |
+
" losses = []\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
|
| 264 |
+
" y_hat = np.dot(X, theta)\n",
|
| 265 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 266 |
+
" theta -= learning_rate * gradient\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" loss = mean_squared_error(y, y_hat)\n",
|
| 269 |
+
" losses.append(loss)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" return theta, losses"
|
| 272 |
+
],
|
| 273 |
+
"execution_count": null,
|
| 274 |
+
"outputs": []
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"cell_type": "code",
|
| 278 |
+
"metadata": {},
|
| 279 |
+
"source": [
|
| 280 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 281 |
+
"from sklearn.model_selection import KFold\n",
|
| 282 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 283 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 286 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 287 |
+
"# Storage for linear regression results for each fold\n",
|
| 288 |
+
"lr_losses = []\n",
|
| 289 |
+
"lr_mse = []\n",
|
| 290 |
+
"lr_rmse = []\n",
|
| 291 |
+
"lr_r2 = []\n"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [
|
| 300 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 301 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 304 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" # Train\n",
|
| 307 |
+
" theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" # Validate\n",
|
| 310 |
+
" y_pred = np.dot(X_test.values, theta)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" # Calculate evaluation metrics\n",
|
| 313 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 314 |
+
" rmse = np.sqrt(mse)\n",
|
| 315 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" # Store results\n",
|
| 318 |
+
" lr_losses.append(losses)\n",
|
| 319 |
+
" lr_mse.append(mse)\n",
|
| 320 |
+
" lr_rmse.append(rmse)\n",
|
| 321 |
+
" lr_r2.append(r2)"
|
| 322 |
+
],
|
| 323 |
+
"execution_count": null,
|
| 324 |
+
"outputs": []
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"cell_type": "code",
|
| 328 |
+
"metadata": {},
|
| 329 |
+
"source": [
|
| 330 |
+
"# Task 1: Write your code here:\n",
|
| 331 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 332 |
+
"from sklearn.svm import SVR\n",
|
| 333 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 334 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 335 |
+
"from lightgbm import LGBMRegressor\n",
|
| 336 |
+
"from catboost import CatBoostRegressor\n"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"coeffs = {}\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
|
| 348 |
+
"coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
|
| 351 |
+
"axes = axes.flatten()\n",
|
| 352 |
+
"features = X.columns\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 355 |
+
" # Sort features by absolute coefficient value\n",
|
| 356 |
+
" absolute_coef = np.abs(coef)\n",
|
| 357 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" ax = axes[i]\n",
|
| 360 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 361 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 362 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"plt.tight_layout()\n",
|
| 365 |
+
"plt.show()"
|
| 366 |
+
],
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"outputs": []
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "code",
|
| 372 |
+
"metadata": {},
|
| 373 |
+
"source": [
|
| 374 |
+
"# Task 2: Write your code here:"
|
| 375 |
+
],
|
| 376 |
+
"execution_count": null,
|
| 377 |
+
"outputs": []
|
| 378 |
+
},
|
| 379 |
+
{
|
| 380 |
+
"cell_type": "code",
|
| 381 |
+
"metadata": {},
|
| 382 |
+
"source": [
|
| 383 |
+
"# Task Bonus: Write your code here:"
|
| 384 |
+
],
|
| 385 |
+
"execution_count": null,
|
| 386 |
+
"outputs": []
|
| 387 |
+
}
|
| 388 |
+
],
|
| 389 |
+
"metadata": {
|
| 390 |
+
"kernelspec": {
|
| 391 |
+
"display_name": "Python 3",
|
| 392 |
+
"name": "python3"
|
| 393 |
+
},
|
| 394 |
+
"language_info": {
|
| 395 |
+
"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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Create tensors\n",
|
| 72 |
+
"x = torch.tensor([1.0, 2.0, 3.0])\n",
|
| 73 |
+
"y = torch.randn(3)\n",
|
| 74 |
+
"print(\"x:\", x)\n",
|
| 75 |
+
"print(\"y:\", y)\n",
|
| 76 |
+
"print(\"Shape of x:\", x.shape)\n",
|
| 77 |
+
"\n"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 2. Create TensorDataset objects\n",
|
| 87 |
+
"import torch\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n",
|
| 90 |
+
"x = torch.randn(32, 3, 28, 28)\n",
|
| 91 |
+
"x_flat = x.flatten(start_dim=1)\n",
|
| 92 |
+
"print(\"Flatten:\", x_flat.shape) # (32, 2352)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"# 2️⃣ Squeeze - Remove dimensions with size 1\n",
|
| 95 |
+
"x = torch.randn(1, 3, 28, 28)\n",
|
| 96 |
+
"x_sq = x.squeeze()\n",
|
| 97 |
+
"print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"# 3️⃣ Unsqueeze - Add a new dimension of size 1\n",
|
| 100 |
+
"x = torch.randn(3, 28, 28)\n",
|
| 101 |
+
"x_unsq = x.unsqueeze(0)\n",
|
| 102 |
+
"print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"# 4️⃣ View - Reshape freely while keeping same number of elements\n",
|
| 105 |
+
"x = torch.randn(32, 28, 28, 3)\n",
|
| 106 |
+
"x_view = x.view(32, -1) # Flatten all except batch\n",
|
| 107 |
+
"print(\"View:\", x_view.shape) # (32, 28*28*3)\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"from torchvision.datasets import MNIST\n",
|
| 110 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Training dataset\n",
|
| 113 |
+
"train_dataset = MNIST(\n",
|
| 114 |
+
" root='./datasets', # Dataset storage path\n",
|
| 115 |
+
" train=True, # Use training data\n",
|
| 116 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 117 |
+
" download=True # Download if not available\n",
|
| 118 |
+
")\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Testing dataset\n",
|
| 121 |
+
"test_dataset = MNIST(\n",
|
| 122 |
+
" root='./datasets', # Dataset storage path\n",
|
| 123 |
+
" train=False, # Use test data\n",
|
| 124 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 125 |
+
" download=True # Download if not available\n",
|
| 126 |
+
")\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"# print one sample from the dataset\n",
|
| 129 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 130 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 133 |
+
"print(f\"Label: {sample_label}\")\n"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# 3. Create DataLoaders\n",
|
| 143 |
+
"from torch.utils.data import DataLoader\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"train_loader = DataLoader(\n",
|
| 146 |
+
" train_dataset,\n",
|
| 147 |
+
" batch_size=32,\n",
|
| 148 |
+
" shuffle=True,\n",
|
| 149 |
+
" num_workers=2\n",
|
| 150 |
+
")\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"test_loader = DataLoader(\n",
|
| 153 |
+
" test_dataset,\n",
|
| 154 |
+
" batch_size=32,\n",
|
| 155 |
+
" shuffle=False,\n",
|
| 156 |
+
" num_workers=2\n",
|
| 157 |
+
")\n",
|
| 158 |
+
"# Get the first batch from the training DataLoader\n",
|
| 159 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 160 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 161 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# 4. Print shape of one batch\n",
|
| 171 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 172 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.long)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 175 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.long)\n"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# 5. Display sample images\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 1: Write your model class here:class SimpleNN(nn.Module):\n",
|
| 194 |
+
"import torch.nn as nn\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"# Create a linear layer: 3 input features -> 1 output\n",
|
| 197 |
+
"linear = nn.Linear(in_features=3, out_features=1)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"# Example input: batch of 4 samples, each with 3 features\n",
|
| 200 |
+
"x = torch.randn(4, 3)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"# Forward through the layer\n",
|
| 203 |
+
"y = linear(x)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
|
| 206 |
+
"print(\"Output shape:\", y.shape) # torch.Size([4, 1])"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 2: Write your training loop here:\n",
|
| 216 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 217 |
+
" # Set the model to training mode\n",
|
| 218 |
+
" model.train()\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" running_loss = 0.0\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 223 |
+
" # Move batch to the selected device\n",
|
| 224 |
+
" X_batch = X_batch.to(device)\n",
|
| 225 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Forward pass\n",
|
| 228 |
+
" outputs = model(X_batch)\n",
|
| 229 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Backward pass & optimization\n",
|
| 232 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 233 |
+
" loss.backward() # Compute gradients\n",
|
| 234 |
+
" optimizer.step() # Update model parameters\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" running_loss += loss.item()\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" # Average loss over all batches\n",
|
| 239 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" return avg_loss"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task 3: Write your validation loop here:\n",
|
| 251 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 252 |
+
" # Set the model to evaluation mode\n",
|
| 253 |
+
" model.eval()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" running_loss = 0.0\n",
|
| 256 |
+
" correct = 0\n",
|
| 257 |
+
" total = 0\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 260 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 261 |
+
" # Move batch to the selected device\n",
|
| 262 |
+
" X_batch = X_batch.to(device)\n",
|
| 263 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Forward pass\n",
|
| 266 |
+
" outputs = model(X_batch)\n",
|
| 267 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 268 |
+
" running_loss += loss.item()\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # Binary predictions\n",
|
| 271 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Accuracy calculation\n",
|
| 274 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 275 |
+
" total += y_batch.size(0)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 278 |
+
" accuracy = correct / total\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" return avg_loss, accuracy"
|
| 281 |
+
],
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"outputs": []
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"metadata": {},
|
| 288 |
+
"source": [
|
| 289 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 290 |
+
"print(f\"Using device: {device}\")"
|
| 291 |
+
],
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"outputs": []
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "code",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"# Task 5: Start training for 20 epochs:# Device configuration\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"num_epochs = 20\n",
|
| 303 |
+
"learning_rate = 0.001\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Model, Criterion, Optimizer\n",
|
| 306 |
+
"input_dim = X_train.shape[1]\n",
|
| 307 |
+
"hidden_dim = 10\n",
|
| 308 |
+
"model =NN2Layer(input_dim, hidden_dim).to(device)\n",
|
| 309 |
+
"criterion = nn.BCELoss()\n",
|
| 310 |
+
"optimizer = Adam(model.parameters(), lr=learning_rate)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"# Run Training\n",
|
| 314 |
+
"train_losses = []\n",
|
| 315 |
+
"val_losses = []\n",
|
| 316 |
+
"val_accuracies = []\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"print('Starting Training...')\n",
|
| 319 |
+
"for epoch in range(num_epochs):\n",
|
| 320 |
+
" # Train one epoch\n",
|
| 321 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" # Validate\n",
|
| 324 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" train_losses.append(train_loss)\n",
|
| 327 |
+
" val_losses.append(val_loss)\n",
|
| 328 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 331 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"print('Training Complete!')"
|
| 334 |
+
],
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"outputs": []
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"cell_type": "code",
|
| 340 |
+
"metadata": {},
|
| 341 |
+
"source": [
|
| 342 |
+
"# Task 1: Write your code here:"
|
| 343 |
+
],
|
| 344 |
+
"execution_count": null,
|
| 345 |
+
"outputs": []
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"cell_type": "code",
|
| 349 |
+
"metadata": {},
|
| 350 |
+
"source": [
|
| 351 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 352 |
+
],
|
| 353 |
+
"execution_count": null,
|
| 354 |
+
"outputs": []
|
| 355 |
+
}
|
| 356 |
+
],
|
| 357 |
+
"metadata": {
|
| 358 |
+
"kernelspec": {
|
| 359 |
+
"display_name": "Python 3",
|
| 360 |
+
"name": "python3"
|
| 361 |
+
},
|
| 362 |
+
"language_info": {
|
| 363 |
+
"name": "python"
|
| 364 |
+
}
|
| 365 |
+
},
|
| 366 |
+
"nbformat": 4,
|
| 367 |
+
"nbformat_minor": 0
|
| 368 |
+
}
|
submissions_extracted/304/Q3.ipynb
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"# Task 1: Write your code here:\n",
|
| 27 |
+
"from IPython.display import clear_output\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"clear_output()\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"import pandas as pd\n",
|
| 34 |
+
"import numpy as np\n",
|
| 35 |
+
"import matplotlib.pyplot as plt\n",
|
| 36 |
+
"import seaborn as sns\n",
|
| 37 |
+
"import kagglehub\n",
|
| 38 |
+
"import os\n",
|
| 39 |
+
"from tqdm import tqdm\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"%matplotlib inline\n",
|
| 42 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"df = pd.read_csv(csv_path)\n"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"# Task 2: Write your code here:\n",
|
| 54 |
+
"df.head()"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"# Task 3: Write your code here:\n",
|
| 64 |
+
"df.info()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 4: Write your code here:\n",
|
| 74 |
+
"df.describe()"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# Task 1: Write your code here:\n",
|
| 84 |
+
"def check_missing_values(df):\n",
|
| 85 |
+
" missing_values = df.isnull().sum()\n",
|
| 86 |
+
" print(\"Missing Values per Column:\")\n",
|
| 87 |
+
" print(missing_values[missing_values > 0])\n",
|
| 88 |
+
" if missing_values.any():\n",
|
| 89 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 90 |
+
" else:\n",
|
| 91 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"check_missing_values(df)"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 2: Write your code here:\n",
|
| 103 |
+
"def check_duplicates(df):\n",
|
| 104 |
+
" duplicates = df.duplicated().sum()\n",
|
| 105 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 106 |
+
" if duplicates > 0:\n",
|
| 107 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 108 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 109 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 110 |
+
" else:\n",
|
| 111 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"check_duplicates(df)"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# Task 3: Write your code here:\n",
|
| 123 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"label_encoders = {}\n",
|
| 130 |
+
"for col in categorical_cols:\n",
|
| 131 |
+
" le = LabelEncoder()\n",
|
| 132 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 133 |
+
" label_encoders[col] = le\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"df"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 4: Write your code here:\n",
|
| 145 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"scaler = StandardScaler()\n",
|
| 150 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 151 |
+
"df.head()\n"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 5: Write your code here:\n",
|
| 161 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 162 |
+
" print(\"Target Distribution:\")\n",
|
| 163 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 164 |
+
" sns.countplot(x=df[target_column])\n",
|
| 165 |
+
" plt.title(\"Target Distribution\")\n",
|
| 166 |
+
" plt.show()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"check_target_imbalance(df, \"Target\")"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 1: Write your code here:\n",
|
| 178 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 179 |
+
"y = df['Target'].astype(float)"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 189 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 190 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 191 |
+
" losses = []\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
|
| 194 |
+
" z = np.dot(X, theta)\n",
|
| 195 |
+
" y_hat = sigmoid(z)\n",
|
| 196 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 197 |
+
" theta -= learning_rate * gradient\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" loss = binary_cross_entropy(y, y_hat)\n",
|
| 200 |
+
" losses.append(loss)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" return theta, losses\n",
|
| 203 |
+
" # sigmoid in NumPy\n",
|
| 204 |
+
"def sigmoid(z):\n",
|
| 205 |
+
" return 1 / (1 + np.exp(-z))\n",
|
| 206 |
+
" # BCE in NumPy\n",
|
| 207 |
+
"def binary_cross_entropy(y, y_hat):\n",
|
| 208 |
+
" epsilon = 1e-15 # Very small number to prevent log(0)\n",
|
| 209 |
+
" y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
|
| 212 |
+
" return loss"
|
| 213 |
+
],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"source": [
|
| 221 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 222 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 223 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 224 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 227 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 228 |
+
"# Storage for logistic regression results for each fold\n",
|
| 229 |
+
"lr_losses = []\n",
|
| 230 |
+
"lr_accuracy = []\n",
|
| 231 |
+
"lr_precision = []\n",
|
| 232 |
+
"lr_recall = []\n",
|
| 233 |
+
"lr_f1 = []\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 236 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 239 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Train\n",
|
| 242 |
+
" theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" # Validate\n",
|
| 245 |
+
" y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
|
| 246 |
+
" y_pred = (y_pred_proba >= 0.5).astype(int)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" # Calculate evaluation metrics\n",
|
| 249 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 250 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 251 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 252 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" # Store results\n",
|
| 255 |
+
" lr_losses.append(losses)\n",
|
| 256 |
+
" lr_accuracy.append(accuracy)\n",
|
| 257 |
+
" lr_precision.append(precision)\n",
|
| 258 |
+
" lr_recall.append(recall)\n",
|
| 259 |
+
" lr_f1.append(f1)\n",
|
| 260 |
+
" avg_loss = np.mean(lr_losses, axis=0)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 263 |
+
"plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
|
| 264 |
+
"plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
|
| 265 |
+
"plt.xlabel('Iteration')\n",
|
| 266 |
+
"plt.ylabel('Binary Cross-Entropy Loss')\n",
|
| 267 |
+
"plt.legend()\n",
|
| 268 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 269 |
+
"plt.show()\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"print(\"LOGISTIC REGRESSION Performance:\")\n",
|
| 272 |
+
"print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n",
|
| 273 |
+
"print(f\" Precision: {np.mean(lr_precision):.4f}\")\n",
|
| 274 |
+
"print(f\" Recall: {np.mean(lr_recall):.4f}\")\n",
|
| 275 |
+
"print(f\" F1-Score: {np.mean(lr_f1):.4f}\")"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task 1: Write your code here:\n",
|
| 285 |
+
"importances = {}\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
|
| 288 |
+
"importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n",
|
| 289 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Create a 1x3 plot\n",
|
| 292 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 293 |
+
"axes = axes.flatten()\n",
|
| 294 |
+
"features = X.columns\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 297 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 298 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" ax = axes[i]\n",
|
| 301 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 302 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 303 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"plt.tight_layout()\n",
|
| 306 |
+
"plt.show()"
|
| 307 |
+
],
|
| 308 |
+
"execution_count": null,
|
| 309 |
+
"outputs": []
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"cell_type": "code",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"# Task 2: Write your code here:\n"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Task Bonus: Write your code here:"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
}
|
| 329 |
+
],
|
| 330 |
+
"metadata": {
|
| 331 |
+
"kernelspec": {
|
| 332 |
+
"display_name": "Python 3",
|
| 333 |
+
"name": "python3"
|
| 334 |
+
},
|
| 335 |
+
"language_info": {
|
| 336 |
+
"name": "python"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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import os\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 12 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 14 |
+
"from IPython.display import clear_output\n",
|
| 15 |
+
"import numpy as np\n",
|
| 16 |
+
"%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n",
|
| 17 |
+
"from sklearn.model_selection import KFold\n",
|
| 18 |
+
"import seaborn as sns\n",
|
| 19 |
+
"from tqdm import tqdm\n",
|
| 20 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 21 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"clear_output()\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"# Download latest version\n",
|
| 26 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"print(\"Path to dataset files:\", path)"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"\n",
|
| 38 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"df = pd.read_csv(csv_path)x`"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"csv_path = os.path.join(path, \"Advertising.csv\")\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"df = pd.read_csv(csv_path)\n",
|
| 52 |
+
"df = df.drop(columns=\"Unnamed: 0\", axis=1)\n",
|
| 53 |
+
"df.head()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"df.head()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"df.info()"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"df.describe()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"def check_target_distribution(df, target_column):\n",
|
| 90 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 91 |
+
"\n",
|
| 92 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 93 |
+
" plt.xlabel(target_column)\n",
|
| 94 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 95 |
+
" plt.grid(False)\n",
|
| 96 |
+
"\n",
|
| 97 |
+
" plt.show()\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"df = df.drop(columns=\"Order_ID\", axis=1)"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"def check_missing_values(df):\n",
|
| 118 |
+
" missing_values = df.isnull().sum()\n",
|
| 119 |
+
" print(\"Missing Values per Column:\")\n",
|
| 120 |
+
" print(missing_values[missing_values > 0])\n",
|
| 121 |
+
" if missing_values.any():\n",
|
| 122 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 123 |
+
" else:\n",
|
| 124 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"check_missing_values(df)"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"def check_duplicates(df):\n",
|
| 136 |
+
" duplicates = df.duplicated().sum()\n",
|
| 137 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 138 |
+
" if duplicates > 0:\n",
|
| 139 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 140 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 141 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 142 |
+
" else:\n",
|
| 143 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"check_duplicates(df)"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"def encode_categorical_columns(df):\n",
|
| 155 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 156 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"label_encoders = encode_categorical_columns(df)"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n",
|
| 168 |
+
"print('data before scaling:\\n', data_for_scale) #show before scaling\n",
|
| 169 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 170 |
+
"data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"#Is the target imbalanced?\n",
|
| 182 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 183 |
+
" print(\"Target Distribution:\")\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" df[target_column].hist()\n",
|
| 186 |
+
" plt.show()\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"check_target_imbalance(df, \"Delivery_Time\")\n",
|
| 189 |
+
"#we can see that is not balanced"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"X = df.drop(\"Delivery_Time\", axis=1)\n",
|
| 199 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 211 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"# Train Random Forest Regressor\n",
|
| 214 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 215 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 216 |
+
"print(\"Model trained!\")"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Transmission distribution\n",
|
| 226 |
+
"transmission_counts = df.drop['transmission'].value_counts()\n",
|
| 227 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 228 |
+
"plt.bar(transmission_counts.index, transmission_counts.values, color='teal')\n",
|
| 229 |
+
"plt.title('Transmission Distribution')\n",
|
| 230 |
+
"plt.xlabel('Transmission Type')\n",
|
| 231 |
+
"plt.ylabel('Count')\n",
|
| 232 |
+
"plt.xticks(rotation=45)\n",
|
| 233 |
+
"plt.show()"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [],
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"outputs": []
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"cell_type": "code",
|
| 247 |
+
"metadata": {},
|
| 248 |
+
"source": [
|
| 249 |
+
"# Year distribution\n",
|
| 250 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 251 |
+
"plt.hist(df_cars['year'].dropna(), bins=30, edgecolor='black', color='orange')\n",
|
| 252 |
+
"plt.title('Year Distribution')\n",
|
| 253 |
+
"plt.xlabel('Year')\n",
|
| 254 |
+
"plt.ylabel('Frequency')\n",
|
| 255 |
+
"plt.show()"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
}
|
| 260 |
+
],
|
| 261 |
+
"metadata": {
|
| 262 |
+
"kernelspec": {
|
| 263 |
+
"display_name": "Python 3",
|
| 264 |
+
"name": "python3"
|
| 265 |
+
},
|
| 266 |
+
"language_info": {
|
| 267 |
+
"name": "python"
|
| 268 |
+
}
|
| 269 |
+
},
|
| 270 |
+
"nbformat": 4,
|
| 271 |
+
"nbformat_minor": 0
|
| 272 |
+
}
|
submissions_extracted/305/Q2.ipynb
ADDED
|
@@ -0,0 +1,391 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"from torchvision.datasets import MNIST\n",
|
| 9 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 10 |
+
"from torch.utils.data import DataLoader\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import torch.nn as nn\n",
|
| 13 |
+
"from torchvision.datasets import CIFAR10\n",
|
| 14 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 15 |
+
"from torch.utils.data import DataLoader\n",
|
| 16 |
+
"import matplotlib.pyplot as plt\n",
|
| 17 |
+
"import torch.nn as nn\n",
|
| 18 |
+
"import torch.nn.functional as F\n",
|
| 19 |
+
"import torch\n",
|
| 20 |
+
"from torch.optim import AdamW\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"import os\n",
|
| 34 |
+
"import pandas as pd\n",
|
| 35 |
+
"import numpy as np\n",
|
| 36 |
+
"from PIL import Image\n",
|
| 37 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"# Load Labels\n",
|
| 40 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 41 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"images = []\n",
|
| 44 |
+
"ages = []\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"# Load Images and Resize\n",
|
| 47 |
+
"print(\"Loading images...\")\n",
|
| 48 |
+
"for index, row in labels_df.iterrows():\n",
|
| 49 |
+
" img_name = row.iloc[0]\n",
|
| 50 |
+
" age = row.iloc[1]\n",
|
| 51 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 52 |
+
"\n",
|
| 53 |
+
" if os.path.exists(img_path):\n",
|
| 54 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 55 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 56 |
+
" images.append(img_array)\n",
|
| 57 |
+
" ages.append(age)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"X = np.array(images)\n",
|
| 60 |
+
"y = np.array(ages)\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 63 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"# Split Data\n",
|
| 66 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 69 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 70 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 71 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Training dataset\n",
|
| 81 |
+
"train_dataset = MNIST(\n",
|
| 82 |
+
" root='./datasets', # Dataset storage path\n",
|
| 83 |
+
" train=True, # Use training data\n",
|
| 84 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 85 |
+
" download=True # Download if not available\n",
|
| 86 |
+
")\n",
|
| 87 |
+
"# Testing dataset\n",
|
| 88 |
+
"test_dataset = MNIST(\n",
|
| 89 |
+
" root='./datasets', # Dataset storage path\n",
|
| 90 |
+
" train=False, # Use test data\n",
|
| 91 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 92 |
+
" download=True # Download if not available\n",
|
| 93 |
+
")"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# 2. Create TensorDataset objects\n",
|
| 103 |
+
"# print one sample from the dataset\n",
|
| 104 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 105 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 108 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 109 |
+
"\n"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# 3. Create DataLoaders\n",
|
| 119 |
+
"# DataLoader for training data\n",
|
| 120 |
+
"train_loader = DataLoader(\n",
|
| 121 |
+
" train_dataset,\n",
|
| 122 |
+
" batch_size=32,\n",
|
| 123 |
+
" shuffle=True,\n",
|
| 124 |
+
" num_workers=2\n",
|
| 125 |
+
")\n",
|
| 126 |
+
"# DataLoader for test/validation data\n",
|
| 127 |
+
"test_loader = DataLoader(\n",
|
| 128 |
+
" test_dataset,\n",
|
| 129 |
+
" batch_size=32,\n",
|
| 130 |
+
" shuffle=False,\n",
|
| 131 |
+
" num_workers=2\n",
|
| 132 |
+
")\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"\n"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Get the first batch from the training DataLoader\n",
|
| 144 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 145 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 146 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# 5. Display sample images\n",
|
| 156 |
+
"# Get one batch of images and labels\n",
|
| 157 |
+
"images, labels = next(iter(train_loader))\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"# Display the first 6 images in the batch\n",
|
| 160 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"for i in range(6):\n",
|
| 163 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 164 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 165 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 166 |
+
" plt.axis('off')\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"plt.tight_layout()\n",
|
| 169 |
+
"plt.show()\n"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"class NN4Layer(nn.Module):\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 181 |
+
" super(NN4Layer, self).__init__()\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" # activation function for non-linearity\n",
|
| 192 |
+
" self.relu = nn.ReLU()\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Defines how input data flows through the network\n",
|
| 195 |
+
" def forward(self, x):\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" z1 = self.layer1(x)\n",
|
| 198 |
+
" a1 = self.relu(z1)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" z2 = self.layer2(a1)\n",
|
| 202 |
+
" a2 = self.relu(z2)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" # Layer 3\n",
|
| 205 |
+
" z3 = self.layer3(a2)\n",
|
| 206 |
+
" a3 = self.relu(z3)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Layer 4\n",
|
| 209 |
+
" z4 = self.layer4(a3)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" return z4\n"
|
| 216 |
+
],
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"outputs": []
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 225 |
+
" # Set the model to training mode\n",
|
| 226 |
+
" model.train()\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" running_loss = 0.0\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 231 |
+
" # Move batch to the selected device\n",
|
| 232 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 233 |
+
" y_batch = y_batch.to(device)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Forward pass\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" outputs = model(X_batch)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Backward pass & optimization\n",
|
| 242 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 243 |
+
" loss.backward() # Compute gradients\n",
|
| 244 |
+
" optimizer.step() # Update model parameters\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" running_loss += loss.item()\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" # Average loss over all batches\n",
|
| 249 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" return avg_loss"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
" def validate(model, criterion, test_loader, device):\n",
|
| 261 |
+
" # Set the model to evaluation mode\n",
|
| 262 |
+
" model.eval()\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" running_loss = 0.0\n",
|
| 265 |
+
" correct = 0\n",
|
| 266 |
+
" total = 0\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" with torch.no_grad():\n",
|
| 269 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 270 |
+
" # Move data to device\n",
|
| 271 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 272 |
+
" y_batch = y_batch.to(device)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" # Forward pass\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" outputs = model(X_batch)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 279 |
+
" running_loss += loss.item()\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # Accuracy calculation\n",
|
| 288 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 289 |
+
" total += y_batch.size(0)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" accuracy = correct / total\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" return avg_loss, accuracy\n"
|
| 296 |
+
],
|
| 297 |
+
"execution_count": null,
|
| 298 |
+
"outputs": []
|
| 299 |
+
},
|
| 300 |
+
{
|
| 301 |
+
"cell_type": "code",
|
| 302 |
+
"metadata": {},
|
| 303 |
+
"source": [
|
| 304 |
+
"learning_rate = 0.001\n",
|
| 305 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"input_dim = 3 * 32 * 32\n",
|
| 308 |
+
"hidden_dim = 64\n",
|
| 309 |
+
"output_dim = 10\n",
|
| 310 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"# Task 5: S# Run Training\n",
|
| 322 |
+
"num_epochs = 15\n",
|
| 323 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 324 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"train_losses = []\n",
|
| 327 |
+
"val_losses = []\n",
|
| 328 |
+
"val_accuracies = []\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"print('Starting Training...')\n",
|
| 331 |
+
"for epoch in range(num_epochs):\n",
|
| 332 |
+
" # Train one epoch\n",
|
| 333 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" # Validate\n",
|
| 336 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" train_losses.append(train_loss)\n",
|
| 340 |
+
" val_losses.append(val_loss)\n",
|
| 341 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"print('Training Complete!')"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
},
|
| 350 |
+
{
|
| 351 |
+
"cell_type": "code",
|
| 352 |
+
"metadata": {},
|
| 353 |
+
"source": [
|
| 354 |
+
"# Task 1: Write your code her# Plotting results\n",
|
| 355 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 358 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 359 |
+
"plt.title('Loss over Epochs')\n",
|
| 360 |
+
"plt.xlabel('Epoch')\n",
|
| 361 |
+
"plt.ylabel('Loss')\n",
|
| 362 |
+
"plt.legend()\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"plt.tight_layout()\n",
|
| 365 |
+
"plt.show()"
|
| 366 |
+
],
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"outputs": []
|
| 369 |
+
},
|
| 370 |
+
{
|
| 371 |
+
"cell_type": "code",
|
| 372 |
+
"metadata": {},
|
| 373 |
+
"source": [
|
| 374 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 375 |
+
],
|
| 376 |
+
"execution_count": null,
|
| 377 |
+
"outputs": []
|
| 378 |
+
}
|
| 379 |
+
],
|
| 380 |
+
"metadata": {
|
| 381 |
+
"kernelspec": {
|
| 382 |
+
"display_name": "Python 3",
|
| 383 |
+
"name": "python3"
|
| 384 |
+
},
|
| 385 |
+
"language_info": {
|
| 386 |
+
"name": "python"
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 13 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 15 |
+
"from IPython.display import clear_output\n",
|
| 16 |
+
"import numpy as np\n",
|
| 17 |
+
"%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n",
|
| 18 |
+
"from sklearn.model_selection import KFold\n",
|
| 19 |
+
"import seaborn as sns\n",
|
| 20 |
+
"from tqdm import tqdm\n",
|
| 21 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 22 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 23 |
+
"import optuna\n",
|
| 24 |
+
"tqdm.pandas()\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 27 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 28 |
+
"from sklearn.model_selection import KFold\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"from lightgbm import LGBMClassifier\n",
|
| 31 |
+
"from xgboost import XGBClassifier\n",
|
| 32 |
+
"from catboost import CatBoostClassifier\n",
|
| 33 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 34 |
+
"from sklearn.ensemble import VotingClassifier\n",
|
| 35 |
+
"from sklearn.metrics import f1_score\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"# Download latest version\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"print(\"Path to dataset files:\", path)"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"df = pd.read_csv(csv_path)\n"
|
| 56 |
+
],
|
| 57 |
+
"execution_count": null,
|
| 58 |
+
"outputs": []
|
| 59 |
+
},
|
| 60 |
+
{
|
| 61 |
+
"cell_type": "code",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"df.head()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"df.info()"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"df.describe()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"def check_missing_values(df):\n",
|
| 92 |
+
" missing_values = df.isnull().sum()\n",
|
| 93 |
+
" print(\"Missing Values per Column:\")\n",
|
| 94 |
+
" print(missing_values[missing_values > 0])\n",
|
| 95 |
+
" if missing_values.any():\n",
|
| 96 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 97 |
+
" else:\n",
|
| 98 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"check_missing_values(df)"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"def check_duplicates(df):\n",
|
| 110 |
+
" duplicates = df.duplicated().sum()\n",
|
| 111 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 112 |
+
" if duplicates > 0:\n",
|
| 113 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 114 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 115 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 116 |
+
" else:\n",
|
| 117 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"check_duplicates(df)"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"def encode_categorical_columns(df):\n",
|
| 129 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 130 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"label_encoders = encode_categorical_columns(df)"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"data_for_scale = pd.DataFrame({\"Feature_1\": [11, 40, 19,12],\"Feature_2\": [2384, 439, 3282,576]})\n",
|
| 142 |
+
"print('data before scaling:\\n', data_for_scale) #show before scaling\n",
|
| 143 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 144 |
+
"data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"#Is the target imbalanced?\n",
|
| 156 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 157 |
+
" print(\"Target Distribution:\")\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" df[target_column].hist()\n",
|
| 160 |
+
" plt.show()\n",
|
| 161 |
+
"\n",
|
| 162 |
+
"check_target_imbalance(df,\"B_1\")\n",
|
| 163 |
+
"#we can see that is not balanced\n",
|
| 164 |
+
"check_target_imbalance(df,\"P_2\")\n",
|
| 165 |
+
"check_target_imbalance(df,\"D_39\")\n",
|
| 166 |
+
"\n"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"X = df.drop(\"D_145\", axis=1)\n",
|
| 176 |
+
"y = df['D_145'].astype(float)"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"# Define classification models\n",
|
| 186 |
+
"models = {\n",
|
| 187 |
+
" \"Logistic Regression\": LogisticRegression(max_iter=10000),\n",
|
| 188 |
+
" \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n",
|
| 189 |
+
" \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n",
|
| 190 |
+
"}\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"models[\"Ensemble\"] = VotingClassifier(estimators=[\n",
|
| 193 |
+
" ('lr', models[\"CatBoost Classifier\"]), ('rf', models[\"Logistic Regression\"]), ('gnb', models[\"Random Forest Classifier\"])], voting=\"soft\")\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"for model_name, model in models.items():\n",
|
| 196 |
+
" scores_accuracy = []\n",
|
| 197 |
+
" scores_precision = []\n",
|
| 198 |
+
" scores_recall = []\n",
|
| 199 |
+
" scores_f1 = []\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" # Stratified 5-Fold Cross-Validation\n",
|
| 202 |
+
" skf = KFold(n_splits=5)\n",
|
| 203 |
+
" for train_index, test_index in skf.split(X, y):\n",
|
| 204 |
+
" # Split data into training and testing sets\n",
|
| 205 |
+
" X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
|
| 206 |
+
" y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 207 |
+
" # Train the model\n",
|
| 208 |
+
" model.fit(X_Train, y_Train)\n",
|
| 209 |
+
" # Predict on the test set\n",
|
| 210 |
+
" y_pred = model.predict(X_Test)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # Calculate metrics\n",
|
| 213 |
+
" scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Print the results\n",
|
| 216 |
+
" print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n",
|
| 217 |
+
" print(\"\\n\")\n"
|
| 218 |
+
],
|
| 219 |
+
"execution_count": null,
|
| 220 |
+
"outputs": []
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "code",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"# Year distribution\n",
|
| 227 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 228 |
+
"plt.hist(df['year'].dropna(), bins=30, edgecolor='black', color='orange')\n",
|
| 229 |
+
"plt.title('Year Distribution')\n",
|
| 230 |
+
"plt.xlabel('Year')\n",
|
| 231 |
+
"plt.ylabel('Frequency')\n",
|
| 232 |
+
"plt.show()"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task 2: Write your code here:"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task Bonus: Write your code here:"
|
| 251 |
+
],
|
| 252 |
+
"execution_count": null,
|
| 253 |
+
"outputs": []
|
| 254 |
+
}
|
| 255 |
+
],
|
| 256 |
+
"metadata": {
|
| 257 |
+
"kernelspec": {
|
| 258 |
+
"display_name": "Python 3",
|
| 259 |
+
"name": "python3"
|
| 260 |
+
},
|
| 261 |
+
"language_info": {
|
| 262 |
+
"name": "python"
|
| 263 |
+
}
|
| 264 |
+
},
|
| 265 |
+
"nbformat": 4,
|
| 266 |
+
"nbformat_minor": 0
|
| 267 |
+
}
|
submissions_extracted/306/Q1.ipynb
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import seaborn as sns\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"import os\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"# Download latest version\n",
|
| 17 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"print(os.listdir(path))"
|
| 22 |
+
],
|
| 23 |
+
"execution_count": null,
|
| 24 |
+
"outputs": []
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"# Task 1: Write your code here:\n",
|
| 31 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 32 |
+
"df = pd.read_csv(csv_path)\n"
|
| 33 |
+
],
|
| 34 |
+
"execution_count": null,
|
| 35 |
+
"outputs": []
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"source": [
|
| 41 |
+
"# Task 2: Write your code here:\n",
|
| 42 |
+
"df.head(20)"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 3: Write your code here:\n",
|
| 52 |
+
"df.info()"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 4: Write your code here:\n",
|
| 62 |
+
"df.describe()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 5: Write your code here:\n",
|
| 72 |
+
"def check_target_distribution(df, target_column):\n",
|
| 73 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 74 |
+
"\n",
|
| 75 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 76 |
+
" plt.xlabel(target_column)\n",
|
| 77 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 78 |
+
" plt.grid(False)\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" plt.show()\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 1: Write your code here:\n",
|
| 92 |
+
"df = df.drop(columns=\"Order_ID \t\", axis=1)\n",
|
| 93 |
+
"df.head()"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 2: Write your code here:\n",
|
| 103 |
+
"def check_missing_values(df):\n",
|
| 104 |
+
" missing_values = df.isnull().sum()\n",
|
| 105 |
+
" print(\"Missing Values per Column:\")\n",
|
| 106 |
+
" print(missing_values[missing_values > 0])\n",
|
| 107 |
+
" if missing_values.any():\n",
|
| 108 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 109 |
+
" else:\n",
|
| 110 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"check_missing_values(df)"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 122 |
+
"cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n",
|
| 123 |
+
"df_clean = df[cols].copy()\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"# Drop rows where target (delivery time) or key features are missing - can't predict without them\n",
|
| 126 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 127 |
+
"df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level', 'Courier_Experience_yrs'])\n",
|
| 128 |
+
"print(f\"After dropping missing Delivery_Time/Weather/Traffic_Level: {df_clean.shape}\")"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 138 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 139 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Fill Courier_Experience_yrs with mean\n",
|
| 142 |
+
"#df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean()[0])\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 3: Write your code here:\n",
|
| 154 |
+
"def check_duplicates(df):\n",
|
| 155 |
+
" duplicates = df.duplicated().sum()\n",
|
| 156 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 157 |
+
" if duplicates > 0:\n",
|
| 158 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 159 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 160 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 161 |
+
" else:\n",
|
| 162 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"check_duplicates(df)"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 4: Write your code here:\n",
|
| 174 |
+
"#Do we have categorical columns?\n",
|
| 175 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 189 |
+
"for col in categorical_cols:\n",
|
| 190 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 191 |
+
" le = LabelEncoder()\n",
|
| 192 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 193 |
+
"df"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 5: Write your code here:\n",
|
| 203 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"print('data before scaling:\\n', df) #show before scaling\n",
|
| 206 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 207 |
+
"data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 6: Write your code here:\n",
|
| 219 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 220 |
+
" print(\"Target Distribution:\")\n",
|
| 221 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 222 |
+
" sns.countplot(x=df[target_column])\n",
|
| 223 |
+
" plt.title(\"Target Distribution\")\n",
|
| 224 |
+
" plt.show()\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"check_target_imbalance(df, \"Delivery_Time\")"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"# Task 1: Write your code here:\n",
|
| 236 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 237 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 247 |
+
"from tqdm import tqdm\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"def mean_squared_error(y, y_hat):\n",
|
| 250 |
+
" return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 255 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 256 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 257 |
+
" losses = []\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
|
| 260 |
+
" y_hat = np.dot(X, theta)\n",
|
| 261 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 262 |
+
" theta -= learning_rate * gradient\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" loss = mean_squared_error(y, y_hat)\n",
|
| 265 |
+
" losses.append(loss)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" return theta, losses\n",
|
| 268 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 269 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 272 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 275 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Train\n",
|
| 278 |
+
" theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Validate\n",
|
| 281 |
+
" y_pred = np.dot(X_test.values, theta)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" # Calculate evaluation metrics\n",
|
| 284 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 285 |
+
" rmse = np.sqrt(mse)\n",
|
| 286 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# Make predictions and calculate MAE\n",
|
| 289 |
+
"valid_pred = model.predict(X_valid)\n",
|
| 290 |
+
"model_mae = mean_absolute_error(y_valid, valid_pred)\n",
|
| 291 |
+
"print(f\"Model MAE: {model_mae:.4f}\")\n"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task 1: Write your code here:"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task 2: Write your code here:"
|
| 317 |
+
],
|
| 318 |
+
"execution_count": null,
|
| 319 |
+
"outputs": []
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"cell_type": "code",
|
| 323 |
+
"metadata": {},
|
| 324 |
+
"source": [
|
| 325 |
+
"# Task Bonus: Write your code here:\n",
|
| 326 |
+
"models = {\n",
|
| 327 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 328 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 329 |
+
"}\n",
|
| 330 |
+
"all_results = {}\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"for name in models:\n",
|
| 333 |
+
" all_results[name] = {'mae': []}\n",
|
| 334 |
+
" kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 337 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 340 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" for model_name, model in models.items():\n",
|
| 343 |
+
" print(f\"Training {model_name}...\")\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" # Train\n",
|
| 346 |
+
" model.fit(X_train, y_train)\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" # Predict\n",
|
| 349 |
+
" y_pred = model.predict(X_test)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" # Calculate metrics\n",
|
| 352 |
+
" mae = sklearn_mae(y_test, y_pred)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" # Store results\n",
|
| 355 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 356 |
+
""
|
| 357 |
+
],
|
| 358 |
+
"execution_count": null,
|
| 359 |
+
"outputs": []
|
| 360 |
+
}
|
| 361 |
+
],
|
| 362 |
+
"metadata": {
|
| 363 |
+
"kernelspec": {
|
| 364 |
+
"display_name": "Python 3",
|
| 365 |
+
"name": "python3"
|
| 366 |
+
},
|
| 367 |
+
"language_info": {
|
| 368 |
+
"name": "python"
|
| 369 |
+
}
|
| 370 |
+
},
|
| 371 |
+
"nbformat": 4,
|
| 372 |
+
"nbformat_minor": 0
|
| 373 |
+
}
|
submissions_extracted/306/Q2.ipynb
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 27 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 28 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 29 |
+
"from torch.utils.data import TensorDataset\n",
|
| 30 |
+
"from torch.utils.data import DataLoader\n",
|
| 31 |
+
"import matplotlib.pyplot as plt\n",
|
| 32 |
+
"import torch.nn as nn\n",
|
| 33 |
+
"import torch.optim as optim\n",
|
| 34 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 35 |
+
"import torch\n",
|
| 36 |
+
"from torch.optim import Adam\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"# Load Labels\n",
|
| 40 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 41 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"images = []\n",
|
| 44 |
+
"ages = []\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"# Load Images and Resize\n",
|
| 47 |
+
"print(\"Loading images...\")\n",
|
| 48 |
+
"for index, row in labels_df.iterrows():\n",
|
| 49 |
+
" img_name = row.iloc[0]\n",
|
| 50 |
+
" age = row.iloc[1]\n",
|
| 51 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 52 |
+
"\n",
|
| 53 |
+
" if os.path.exists(img_path):\n",
|
| 54 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 55 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 56 |
+
" images.append(img_array)\n",
|
| 57 |
+
" ages.append(age)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"X = np.array(images)\n",
|
| 60 |
+
"y = np.array(ages)\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 63 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"# Split Data\n",
|
| 66 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 69 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 70 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 71 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 81 |
+
"# transform to tensors\n",
|
| 82 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 83 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 84 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 85 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 86 |
+
"\n"
|
| 87 |
+
],
|
| 88 |
+
"execution_count": null,
|
| 89 |
+
"outputs": []
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"source": [
|
| 95 |
+
"# 2. Create TensorDataset objects\n",
|
| 96 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 97 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# 3. Create DataLoaders\n",
|
| 109 |
+
"#in batches\n",
|
| 110 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 111 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"\n"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# 4. Print shape of one batch\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# Print dataset sizes\n",
|
| 125 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 126 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"# Get the first batch from the training DataLoader\n",
|
| 129 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 130 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 131 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 132 |
+
"\n"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# 5. Display sample images\n",
|
| 142 |
+
"# Get one batch of images and labels\n",
|
| 143 |
+
"images, labels = next(iter(train_loader))\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Display the first 6 images in the batch\n",
|
| 146 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"for i in range(6):\n",
|
| 149 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 152 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" plt.imshow(img)\n",
|
| 155 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 156 |
+
" plt.axis('off')\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"plt.tight_layout()\n",
|
| 159 |
+
"plt.show()"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task 1: Write your model class here:\n",
|
| 169 |
+
"class NN4Layer(nn.Module):\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 172 |
+
" super(NN4Layer, self).__init__()\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 175 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 178 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 181 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 184 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # ReLU activation for non-linearity\n",
|
| 187 |
+
" self.relu = nn.ReLU()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Defines how input data flows through the network\n",
|
| 190 |
+
" def forward(self, x):\n",
|
| 191 |
+
" # First hidden layer\n",
|
| 192 |
+
" z1 = self.layer1(x)\n",
|
| 193 |
+
" a1 = self.relu(z1)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Second hidden layer\n",
|
| 196 |
+
" z2 = self.layer2(a1)\n",
|
| 197 |
+
" a2 = self.relu(z2)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" # Third hidden layer\n",
|
| 200 |
+
" z3 = self.layer2(a2)\n",
|
| 201 |
+
" a3 = self.relu(z3)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" # Output layer (raw scores / logits)\n",
|
| 204 |
+
" output = self.layer3(a3) # there is something missing here, remember? :)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" return output"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 2: Write your training loop here:\n",
|
| 216 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 217 |
+
" # Set the model to training mode\n",
|
| 218 |
+
" model.train()\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" running_loss = 0.0\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 223 |
+
" # Move batch to the selected device\n",
|
| 224 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 225 |
+
" y_batch = y_batch.to(device)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Forward pass\n",
|
| 228 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 229 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Backward pass & optimization\n",
|
| 232 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 233 |
+
" loss.backward() # Compute gradients\n",
|
| 234 |
+
" optimizer.step() # Update model parameters\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" running_loss += loss.item()\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" # Average loss over all batches\n",
|
| 239 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" return avg_loss"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task 3: Write your validation loop here:\n",
|
| 251 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 252 |
+
" # Set the model to evaluation mode\n",
|
| 253 |
+
" model.eval()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" running_loss = 0.0\n",
|
| 256 |
+
" correct = 0\n",
|
| 257 |
+
" total = 0\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" with torch.no_grad():\n",
|
| 260 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 261 |
+
" # Move data to device\n",
|
| 262 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 263 |
+
" y_batch = y_batch.to(device)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Forward pass\n",
|
| 266 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 267 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 268 |
+
" running_loss += loss.item()\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # Apply Softmax to get probabilities\n",
|
| 271 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Multiclass predictions\n",
|
| 274 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" # Accuracy calculation\n",
|
| 277 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 278 |
+
" total += y_batch.size(0)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 281 |
+
" accuracy = correct / total\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" return avg_loss, accuracy\n"
|
| 284 |
+
],
|
| 285 |
+
"execution_count": null,
|
| 286 |
+
"outputs": []
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"cell_type": "code",
|
| 290 |
+
"metadata": {},
|
| 291 |
+
"source": [
|
| 292 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 293 |
+
"# Device setup\n",
|
| 294 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Model parameters\n",
|
| 297 |
+
"input_dim = 32 * 32 # MNIST images flattened\n",
|
| 298 |
+
"hidden_dim = 14 # Design choice\n",
|
| 299 |
+
"output_dim = 100 # Digits 0–9\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Instantiate model\n",
|
| 302 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"# Print the model architecture\n",
|
| 305 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 306 |
+
"print(model)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Calculate the total number of trainable parameters\n",
|
| 309 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 310 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 311 |
+
"\n"
|
| 312 |
+
],
|
| 313 |
+
"execution_count": null,
|
| 314 |
+
"outputs": []
|
| 315 |
+
},
|
| 316 |
+
{
|
| 317 |
+
"cell_type": "code",
|
| 318 |
+
"metadata": {},
|
| 319 |
+
"source": [
|
| 320 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 321 |
+
"num_epochs = 20\n",
|
| 322 |
+
"learning_rate = 0.001\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 325 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 326 |
+
"# Define optimizer\n",
|
| 327 |
+
"optimizer = Adam(model.parameters(), learning_rate)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# Run Training\n",
|
| 330 |
+
"train_losses = []\n",
|
| 331 |
+
"val_losses = []\n",
|
| 332 |
+
"val_accuracies = []\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"print('Starting Training...')\n",
|
| 335 |
+
"for epoch in range(num_epochs):\n",
|
| 336 |
+
" # Train one epoch\n",
|
| 337 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" # Validate\n",
|
| 340 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" train_losses.append(train_loss)\n",
|
| 343 |
+
" val_losses.append(val_loss)\n",
|
| 344 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"print('Training Complete!')"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"# Task 1: Write your code here:"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"cell_type": "code",
|
| 364 |
+
"metadata": {},
|
| 365 |
+
"source": [
|
| 366 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 367 |
+
],
|
| 368 |
+
"execution_count": null,
|
| 369 |
+
"outputs": []
|
| 370 |
+
}
|
| 371 |
+
],
|
| 372 |
+
"metadata": {
|
| 373 |
+
"kernelspec": {
|
| 374 |
+
"display_name": "Python 3",
|
| 375 |
+
"name": "python3"
|
| 376 |
+
},
|
| 377 |
+
"language_info": {
|
| 378 |
+
"name": "python"
|
| 379 |
+
}
|
| 380 |
+
},
|
| 381 |
+
"nbformat": 4,
|
| 382 |
+
"nbformat_minor": 0
|
| 383 |
+
}
|
submissions_extracted/306/Q3.ipynb
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import numpy as np\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 16 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 17 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 18 |
+
"import os\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 28 |
+
"print(os.listdir(path))"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"# Task 1: Write your code here:\n",
|
| 38 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 39 |
+
"df = pd.read_csv(csv_path)\n",
|
| 40 |
+
"\n"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 2: Write your code here:\n",
|
| 50 |
+
"df.head()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 3: Write your code here:\n",
|
| 60 |
+
"df.info()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 4: Write your code here:\n",
|
| 70 |
+
"df.describe()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 1: Write your code here:\n",
|
| 80 |
+
"def check_missing_values(df):\n",
|
| 81 |
+
" missing_values = df.isnull().sum()\n",
|
| 82 |
+
" print(\"Missing Values per Column:\")\n",
|
| 83 |
+
" print(missing_values[missing_values > 0])\n",
|
| 84 |
+
" if missing_values.any():\n",
|
| 85 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 86 |
+
" else:\n",
|
| 87 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"check_missing_values(df)"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 2: Write your code here:\n",
|
| 106 |
+
"def check_duplicates(df):\n",
|
| 107 |
+
" duplicates = df.duplicated().sum()\n",
|
| 108 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 109 |
+
" if duplicates > 0:\n",
|
| 110 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 111 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 112 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 113 |
+
" else:\n",
|
| 114 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"check_duplicates(df)"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 3: Write your code here:\n",
|
| 126 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# Task 4: Write your code here:\n",
|
| 138 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"print('data before scaling:\\n', df) #show before scaling\n",
|
| 141 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 142 |
+
"data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 5: Write your code here:\n",
|
| 154 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 155 |
+
" print(\"Target Distribution:\")\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 158 |
+
" plt.show()\n"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 1: Write your code here:\n",
|
| 168 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 169 |
+
"y = df['Target'].astype(float)"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 179 |
+
"%pip install catboost\n",
|
| 180 |
+
"import numpy as np\n",
|
| 181 |
+
"import pandas as pd\n",
|
| 182 |
+
"import matplotlib.pyplot as plt\n",
|
| 183 |
+
"import seaborn as sns\n",
|
| 184 |
+
"from scipy import stats\n",
|
| 185 |
+
"from tqdm import tqdm\n",
|
| 186 |
+
"import optuna\n",
|
| 187 |
+
"tqdm.pandas()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 190 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 191 |
+
"from sklearn.model_selection import KFold\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"from lightgbm import LGBMClassifier\n",
|
| 194 |
+
"from xgboost import XGBClassifier\n",
|
| 195 |
+
"from catboost import CatBoostClassifier\n",
|
| 196 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 197 |
+
"from sklearn.ensemble import VotingClassifier\n",
|
| 198 |
+
"from sklearn.metrics import f1_score\n",
|
| 199 |
+
"models = {\n",
|
| 200 |
+
" \"Logistic Regression\": LogisticRegression(max_iter=10000),\n",
|
| 201 |
+
" \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n",
|
| 202 |
+
" \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n",
|
| 203 |
+
"}\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"models[\"Ensemble\"] = VotingClassifier(estimators=[\n",
|
| 206 |
+
" ('lr', models[\"CatBoost Classifier\"]), ('rf', models[\"Logistic Regression\"]), ('gnb', models[\"Random Forest Classifier\"])], voting=\"soft\")\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"for model_name, model in models.items():\n",
|
| 209 |
+
" scores_accuracy = []\n",
|
| 210 |
+
" scores_precision = []\n",
|
| 211 |
+
" scores_recall = []\n",
|
| 212 |
+
" scores_f1 = []\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Stratified 5-Fold Cross-Validation\n",
|
| 215 |
+
" skf = KFold(n_splits=5)\n",
|
| 216 |
+
" for train_index, test_index in skf.split(X, y):\n",
|
| 217 |
+
" # Split data into training and testing sets\n",
|
| 218 |
+
" X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
|
| 219 |
+
" y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 220 |
+
" # Train the model\n",
|
| 221 |
+
" model.fit(X_Train, y_Train)\n",
|
| 222 |
+
" # Predict on the test set\n",
|
| 223 |
+
" y_pred = model.predict(X_Test)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Calculate metrics\n",
|
| 226 |
+
" scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Print the results\n",
|
| 229 |
+
" print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n",
|
| 230 |
+
" print(\"\\n\")\n"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"# Task 1: Write your code here:\n",
|
| 240 |
+
"plt.figure(figsize=(18, 14))\n",
|
| 241 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 242 |
+
"plt.xlabel('Importance Score')\n",
|
| 243 |
+
"plt.ylabel('Features')\n",
|
| 244 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 245 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 246 |
+
"plt.show()"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 2: Write your code here:"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task Bonus: Write your code here:"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
}
|
| 269 |
+
],
|
| 270 |
+
"metadata": {
|
| 271 |
+
"kernelspec": {
|
| 272 |
+
"display_name": "Python 3",
|
| 273 |
+
"name": "python3"
|
| 274 |
+
},
|
| 275 |
+
"language_info": {
|
| 276 |
+
"name": "python"
|
| 277 |
+
}
|
| 278 |
+
},
|
| 279 |
+
"nbformat": 4,
|
| 280 |
+
"nbformat_minor": 0
|
| 281 |
+
}
|
submissions_extracted/307/Q1.ipynb
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import numpy as np\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import matplotlib.pyplot as plt\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"import kagglehub\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 28 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 29 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 30 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"import warnings\n",
|
| 33 |
+
"warnings.filterwarnings('ignore')"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task\n",
|
| 43 |
+
"delivery_path = os.path.join(path,'Q1_data.csv')\n",
|
| 44 |
+
"df_delivey = pd.read_csv(delivery_path)\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"print(f\"Dataset shape: {delivery_path}\")\n",
|
| 47 |
+
"\n"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 2:\n",
|
| 57 |
+
"delivery_path.head()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"df_delivey.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4:\n",
|
| 76 |
+
"df_delivey.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 5:\n",
|
| 86 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 87 |
+
"plt.hist(df_delivey['price'].dropna(), bins=50, edgecolor='black')\n",
|
| 88 |
+
"plt.title('delivery_time')\n",
|
| 89 |
+
"plt.xlabel('time')\n",
|
| 90 |
+
"plt.ylabel('Frequency')\n",
|
| 91 |
+
"plt.show()"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"\n",
|
| 101 |
+
"cols = ['Order_ID']\n",
|
| 102 |
+
"df_clean = df_delivey[cols].copy()\n",
|
| 103 |
+
"df_clean = df_clean.dropna(subset=['Order_ID'])\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 2: Write your code here:\n",
|
| 113 |
+
"categorical_cols = ['Order_ID']\n",
|
| 114 |
+
"for col in categorical_cols:\n",
|
| 115 |
+
" le = LabelEncoder()\n",
|
| 116 |
+
" df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"df_clean.head()"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 3:\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"df_clean['Order'] = df_clean['order'] / (df_clean['order'])"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 4:\n"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 5:\n",
|
| 148 |
+
"X_train.head(1)\n",
|
| 149 |
+
"scaler = StandardScaler()\n",
|
| 150 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 151 |
+
"X_test_scaled = scaler.transform(X_test)\n"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 6:\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 1: Write your code here:\n",
|
| 170 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 171 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 181 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"mae_scores = []\n",
|
| 184 |
+
"rmse_scores = []\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"for train_idx, val_idx in kfold.split(X_train_scaled):\n",
|
| 187 |
+
" X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
|
| 188 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Train and predict\n",
|
| 191 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 192 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Calculate metrics\n",
|
| 195 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 196 |
+
" rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 199 |
+
"rmse_scores = np.array(rmse_scores)"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"# Task 1: '\n",
|
| 209 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 210 |
+
"plt.hist(df_pokemon['delivey_time'].dropna(), bins=30, edgecolor='black')\n",
|
| 211 |
+
"plt.title('delivery_time')\n",
|
| 212 |
+
"plt.xlabel('time')\n",
|
| 213 |
+
"plt.ylabel('time ')\n",
|
| 214 |
+
"plt.show()"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 2: Write your code here:\n",
|
| 224 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 225 |
+
"plt.hist(df_pokemon['sp_attack'].dropna(), bins=30, edgecolor='black', color='yellow')\n",
|
| 226 |
+
"plt.title('delivery_time')\n",
|
| 227 |
+
"plt.xlabel('deliveey_time')\n",
|
| 228 |
+
"plt.ylabel('Frequency')\n",
|
| 229 |
+
"plt.show()"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Task Bonus: Write your code here:"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
}
|
| 243 |
+
],
|
| 244 |
+
"metadata": {
|
| 245 |
+
"kernelspec": {
|
| 246 |
+
"display_name": "Python 3",
|
| 247 |
+
"name": "python3"
|
| 248 |
+
},
|
| 249 |
+
"language_info": {
|
| 250 |
+
"name": "python"
|
| 251 |
+
}
|
| 252 |
+
},
|
| 253 |
+
"nbformat": 4,
|
| 254 |
+
"nbformat_minor": 0
|
| 255 |
+
}
|
submissions_extracted/307/Q2.ipynb
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Create tensors\n",
|
| 72 |
+
"x = torch.tensor([1.0, 2.0, 3.0])\n",
|
| 73 |
+
"y = torch.randn(3)\n",
|
| 74 |
+
"print(\"x:\", x)\n",
|
| 75 |
+
"print(\"y:\", y)\n",
|
| 76 |
+
"a = torch.tensor([1.0, 2.0, 3.0])\n",
|
| 77 |
+
"b = torch.tensor([4.0, 5.0, 6.0])\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# Element-wise operations\n",
|
| 80 |
+
"print(\"Addition:\", a + b)\n",
|
| 81 |
+
"print(\"Multiplication:\", a * b)\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"# Matrix multiplication\n",
|
| 84 |
+
"A = torch.randn(2, 3)\n",
|
| 85 |
+
"B = torch.randn(3, 2)\n",
|
| 86 |
+
"C = A @ B\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"print(\"Matrix multiplication result shape:\", C.shape)\n",
|
| 89 |
+
"# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n",
|
| 90 |
+
"x = torch.randn(32, 3, 28, 28)\n",
|
| 91 |
+
"x_flat = x.flatten(start_dim=1)\n",
|
| 92 |
+
"print(\"Flatten:\", x_flat.shape) # (32, 2352)\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"# 2️⃣ Squeeze - Remove dimensions with size 1\n",
|
| 95 |
+
"x = torch.randn(1, 3, 28, 28)\n",
|
| 96 |
+
"x_sq = x.squeeze()\n",
|
| 97 |
+
"print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"# 3️⃣ Unsqueeze - Add a new dimension of size 1\n",
|
| 100 |
+
"x = torch.randn(3, 28, 28)\n",
|
| 101 |
+
"x_unsq = x.unsqueeze(0)\n",
|
| 102 |
+
"print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"# 4️⃣ View - Reshape freely while keeping same number of elements\n",
|
| 105 |
+
"x = torch.randn(32, 28, 28, 3)\n",
|
| 106 |
+
"x_view = x.view(32, -1) #flatten all batch\n",
|
| 107 |
+
"print(\"View:\", x_view.shape) # (32, 28*28*3)\n",
|
| 108 |
+
"# Create a float32 tensor\n",
|
| 109 |
+
"x = torch.tensor([1.2, 2.3, 3.4], dtype=torch.float32)\n",
|
| 110 |
+
"print(x.dtype) # Output: torch.float32\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Convert to float16\n",
|
| 113 |
+
"x_half = x.to(torch.float16)\n",
|
| 114 |
+
"print(x_half.dtype) # Output: torch.float16\n",
|
| 115 |
+
"\n",
|
| 116 |
+
""
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# 2. Create TensorDataset objects\n",
|
| 126 |
+
"from torchvision.datasets import MNIST\n",
|
| 127 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# Training dataset\n",
|
| 130 |
+
"train_dataset = MNIST(\n",
|
| 131 |
+
" root='./datasets', # Dataset storage path\n",
|
| 132 |
+
" train=True, # Use training data\n",
|
| 133 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 134 |
+
" download=True # Download if not available\n",
|
| 135 |
+
")\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# Testing dataset\n",
|
| 138 |
+
"test_dataset = MNIST(\n",
|
| 139 |
+
" root='./datasets', # Dataset storage path\n",
|
| 140 |
+
" train=False, # Use test data\n",
|
| 141 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 142 |
+
" download=True # Download if not available\n",
|
| 143 |
+
")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# print one sample from the dataset\n",
|
| 146 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 147 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 150 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# 3. Create DataLoaders\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"test_loader = kagglehub.dataset_load(\n",
|
| 165 |
+
" test_dataset,\n",
|
| 166 |
+
" batch_size=32,\n",
|
| 167 |
+
" shuffle=False,\n",
|
| 168 |
+
" num_workers=2\n",
|
| 169 |
+
")"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# 4. Print shape of one batch\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 181 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 182 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# 5. Display sample images\n",
|
| 194 |
+
"\n"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"# Task 1: Write your model class here:\n",
|
| 204 |
+
"# Create a linear layer: 4 input features -> 1 output\n",
|
| 205 |
+
"linear = nn.Linear(in_features=4, out_features=1)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"# Example input: batch of 4 samples, each with 3 features\n",
|
| 208 |
+
"x = torch.randn(4, 3)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"# Forward through the layer\n",
|
| 211 |
+
"y = linear(x)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
|
| 214 |
+
"print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 2: Write your training loop here:\n",
|
| 224 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 225 |
+
" # Set the model to training mode\n",
|
| 226 |
+
" model.train()\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" running_loss = 0.0\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 231 |
+
" # Move batch to the selected device\n",
|
| 232 |
+
" X_batch = X_batch.to(device)\n",
|
| 233 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Forward pass\n",
|
| 236 |
+
" outputs = model(X_batch)\n",
|
| 237 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # Backward pass & optimization\n",
|
| 240 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 241 |
+
" loss.backward() # Compute gradients\n",
|
| 242 |
+
" optimizer.step() # Update model parameters\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" running_loss += loss.item()\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # Average loss over all batches\n",
|
| 247 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" return avg_loss"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"# Task 3: Write your validation loop here:\n",
|
| 259 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 260 |
+
" # Set the model to evaluation mode\n",
|
| 261 |
+
" model.eval()\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" running_loss = 0.0\n",
|
| 264 |
+
" correct = 0\n",
|
| 265 |
+
" total = 0\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 268 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 269 |
+
" # Move batch to the selected device\n",
|
| 270 |
+
" X_batch = X_batch.to(device)\n",
|
| 271 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Forward pass\n",
|
| 274 |
+
" outputs = model(X_batch)\n",
|
| 275 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 276 |
+
" running_loss += loss.item()\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # Binary predictions\n",
|
| 279 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" # Accuracy calculation\n",
|
| 282 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 283 |
+
" total += y_batch.size(0)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 286 |
+
" accuracy = correct / total\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" return avg_loss, accuracy\n"
|
| 289 |
+
],
|
| 290 |
+
"execution_count": null,
|
| 291 |
+
"outputs": []
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"cell_type": "code",
|
| 295 |
+
"metadata": {},
|
| 296 |
+
"source": [
|
| 297 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 298 |
+
],
|
| 299 |
+
"execution_count": null,
|
| 300 |
+
"outputs": []
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"cell_type": "code",
|
| 304 |
+
"metadata": {},
|
| 305 |
+
"source": [
|
| 306 |
+
"# Task 5: Start training for 20 epochs:"
|
| 307 |
+
],
|
| 308 |
+
"execution_count": null,
|
| 309 |
+
"outputs": []
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"cell_type": "code",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"# Task 1: Write your code here:"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
}
|
| 329 |
+
],
|
| 330 |
+
"metadata": {
|
| 331 |
+
"kernelspec": {
|
| 332 |
+
"display_name": "Python 3",
|
| 333 |
+
"name": "python3"
|
| 334 |
+
},
|
| 335 |
+
"language_info": {
|
| 336 |
+
"name": "python"
|
| 337 |
+
}
|
| 338 |
+
},
|
| 339 |
+
"nbformat": 4,
|
| 340 |
+
"nbformat_minor": 0
|
| 341 |
+
}
|
submissions_extracted/307/Q3.ipynb
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 18 |
+
"import numpy as np\n",
|
| 19 |
+
"import pandas as pd\n",
|
| 20 |
+
"import matplotlib.pyplot as plt\n",
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import kagglehub\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 25 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 26 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 27 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"import warnings\n",
|
| 30 |
+
"warnings.filterwarnings('ignore')"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 1: Write your code here:\n",
|
| 40 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"df = pd.read_csv(csv_path)\n",
|
| 43 |
+
"df = df.drop(columns=\"Unnamed: 0\", axis=1)\n",
|
| 44 |
+
"df.head()"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"# Task 2: Write your code here:\n",
|
| 54 |
+
"read_path.head()"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"# Task 3: Write your code here:\n",
|
| 64 |
+
"read_path.info()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 4: Write your code here:\n",
|
| 74 |
+
"read_path.describe()"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# Task 1: Write your code here:\n",
|
| 84 |
+
"def check_missing_values(df):\n",
|
| 85 |
+
" missing_values = df.isnull().sum()\n",
|
| 86 |
+
" print(\"Missing Values per Column:\")\n",
|
| 87 |
+
" print(missing_values[missing_values > 0])\n",
|
| 88 |
+
" if missing_values.any():\n",
|
| 89 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 90 |
+
" else:\n",
|
| 91 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"check_missing_values(df)"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 2: Write your code here:\n"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 3: Write your code here:\n",
|
| 112 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 4: Write your code here:\n",
|
| 124 |
+
"df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# Fill cylinders with mode - discrete feature, mode is most representative\n",
|
| 127 |
+
"df_clean['cylinders'] = df_clean['cylinders'].fillna(df_clean['cylinders'].mode()[0])\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"print(\"Missing values remaining:\",df_clean.isnull().sum().sum())\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 5: Write your code here:"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 1: Write your code here:"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 1: Write your code here:"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"# Task 2: Write your code here:"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task Bonus: Write your code here:"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
}
|
| 188 |
+
],
|
| 189 |
+
"metadata": {
|
| 190 |
+
"kernelspec": {
|
| 191 |
+
"display_name": "Python 3",
|
| 192 |
+
"name": "python3"
|
| 193 |
+
},
|
| 194 |
+
"language_info": {
|
| 195 |
+
"name": "python"
|
| 196 |
+
}
|
| 197 |
+
},
|
| 198 |
+
"nbformat": 4,
|
| 199 |
+
"nbformat_minor": 0
|
| 200 |
+
}
|
submissions_extracted/308/Q1.ipynb
ADDED
|
@@ -0,0 +1,325 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"# Task 1: Write your code here:\n",
|
| 22 |
+
"import numpy as np\n",
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"import matplotlib.pyplot as plt\n",
|
| 25 |
+
"import os\n",
|
| 26 |
+
"# Load the dataset\n",
|
| 27 |
+
"cars_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 28 |
+
"df = pd.read_csv(cars_path)"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"# Task 2: Write your code here:\n",
|
| 38 |
+
"print(f\"Dataset shape: {df.shape}\")\n",
|
| 39 |
+
"df.head()"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 3: Write your code here:\n",
|
| 49 |
+
"df.info()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:\n",
|
| 59 |
+
"df.describe()"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 5: Write your code here:\n",
|
| 69 |
+
"# Price distribution (target variable)\n",
|
| 70 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 71 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 72 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 73 |
+
"plt.xlabel('Delivery Time')\n",
|
| 74 |
+
"plt.ylabel('Frequency')\n",
|
| 75 |
+
"plt.show()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# Task 1: Write your code here:\n",
|
| 85 |
+
"df = df.drop(columns=\"Order_ID\", axis=1)"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 2: Write your code here:\n",
|
| 95 |
+
"def check_missing_values(df):\n",
|
| 96 |
+
" missing_values = df.isnull().sum()\n",
|
| 97 |
+
" print(\"Missing Values per Column:\")\n",
|
| 98 |
+
" print(missing_values[missing_values > 0])\n",
|
| 99 |
+
" if missing_values.any():\n",
|
| 100 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 101 |
+
" else:\n",
|
| 102 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"check_missing_values(df)"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 3: Write your code here:\n",
|
| 114 |
+
"def check_duplicates(df):\n",
|
| 115 |
+
" duplicates = df.duplicated().sum()\n",
|
| 116 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 117 |
+
" if duplicates > 0:\n",
|
| 118 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 119 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 120 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 121 |
+
" else:\n",
|
| 122 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"check_duplicates(df)"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 4: Write your code here:\n",
|
| 134 |
+
"from sklearn.preprocessing import LabelEncoder,OneHotEncoder\n",
|
| 135 |
+
"print(\"Separating target variable and features...\")\n",
|
| 136 |
+
"X = df.drop('Delivery_Time', axis=1)\n",
|
| 137 |
+
"y = df['Delivery_Time']\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"print(\"Applying Label Encoding to target variable 'y'...\")\n",
|
| 140 |
+
"label_encoder = LabelEncoder()\n",
|
| 141 |
+
"y_encoded = label_encoder.fit_transform(y)\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n",
|
| 144 |
+
"onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n",
|
| 145 |
+
"X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"print(\"Verification of encoded data shapes:\")\n",
|
| 148 |
+
"print(f\"Shape of X_encoded: {X_encoded.shape}\")\n",
|
| 149 |
+
"print(f\"Shape of y_encoded: {y_encoded.shape}\")\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"print(\"First 5 rows of X_encoded:\")\n",
|
| 152 |
+
"display(X_encoded.head())\n",
|
| 153 |
+
"print(\"First 5 elements of y_encoded:\")\n",
|
| 154 |
+
"print(y_encoded[:5])"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 5: Write your code here:\n",
|
| 164 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"scaler = StandardScaler()\n",
|
| 169 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 170 |
+
"df.head()"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# Task 6: Write your code here:\n",
|
| 180 |
+
"import seaborn as sns\n",
|
| 181 |
+
"from sklearn.model_selection import train_test_split, KFold, cross_val_score\n",
|
| 182 |
+
"print(\"\\nValue counts for the target variable 'Delivery_Time':\")\n",
|
| 183 |
+
"class_distribution = df['Delivery_Time'].value_counts()\n",
|
| 184 |
+
"print(class_distribution)\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"plt.figure(figsize=(6, 4))\n",
|
| 194 |
+
"sns.countplot(data=df, x='Delivery_Time')\n",
|
| 195 |
+
"plt.title('Distribution of Target Variable (Class)')\n",
|
| 196 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 197 |
+
"plt.ylabel('Count')\n",
|
| 198 |
+
"plt.show()"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"# Task 1: Write your code here:\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"print(\"Splitting data into training and testing sets...\")\n",
|
| 210 |
+
"X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"print(\"Data split successful.\")\n",
|
| 213 |
+
"print(f\"Shape of X_train: {X_train.shape}\")\n",
|
| 214 |
+
"print(f\"Shape of X_test: {X_test.shape}\")\n",
|
| 215 |
+
"print(f\"Shape of y_train: {y_train.shape}\")\n",
|
| 216 |
+
"print(f\"Shape of y_test: {y_test.shape}\")"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 226 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 227 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 228 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 229 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
|
| 230 |
+
"print(\"Initializing models and K-Fold cross-validation...\")\n",
|
| 231 |
+
"from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
|
| 232 |
+
"# Determine the number of classes for one-hot encoding\n",
|
| 233 |
+
"num_classes = len(np.unique(y_encoded))\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"# 1. Initialize the machine learning models\n",
|
| 236 |
+
"models = {\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42),\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"}\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"# 2. Create a KFold object\n",
|
| 243 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"# 3. Create an empty dictionary to store average losses\n",
|
| 246 |
+
"model_losses = {}\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"print(\"Starting K-Fold Cross-Validation for each model...\")\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"# 4. For each model:\n",
|
| 251 |
+
"for model_name, model in models.items():\n",
|
| 252 |
+
" print(f\"\\nTraining and evaluating {model_name}...\")\n",
|
| 253 |
+
" fold_losses = [] # List to store loss from each fold\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n",
|
| 256 |
+
" # Split X_train and y_train into training and validation sets for the current fold\n",
|
| 257 |
+
" X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n",
|
| 258 |
+
" y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Train the current model\n",
|
| 261 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Generate predictions (probabilities) on the validation set\n",
|
| 264 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" # Convert y_val_fold (true labels) into a one-hot encoded format\n",
|
| 267 |
+
" y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # Calculate categorical cross-entropy loss for the current fold\n",
|
| 270 |
+
" loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n",
|
| 271 |
+
" fold_losses.append(loss)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Calculate the average loss for the model\n",
|
| 274 |
+
" avg_loss = np.mean(fold_losses)\n",
|
| 275 |
+
" model_losses[model_name] = avg_loss\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Print the average cross-validation loss for the current model\n",
|
| 278 |
+
" print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"print(\"\\nAll models trained and evaluated. Stored average losses:\")\n",
|
| 281 |
+
"print(model_losses)"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"source": [
|
| 290 |
+
"# Task 1: Write your code here:"
|
| 291 |
+
],
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"outputs": []
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "code",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"# Task 2: Write your code here:"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"cell_type": "code",
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"source": [
|
| 308 |
+
"# Task Bonus: Write your code here:"
|
| 309 |
+
],
|
| 310 |
+
"execution_count": null,
|
| 311 |
+
"outputs": []
|
| 312 |
+
}
|
| 313 |
+
],
|
| 314 |
+
"metadata": {
|
| 315 |
+
"kernelspec": {
|
| 316 |
+
"display_name": "Python 3",
|
| 317 |
+
"name": "python3"
|
| 318 |
+
},
|
| 319 |
+
"language_info": {
|
| 320 |
+
"name": "python"
|
| 321 |
+
}
|
| 322 |
+
},
|
| 323 |
+
"nbformat": 4,
|
| 324 |
+
"nbformat_minor": 0
|
| 325 |
+
}
|
submissions_extracted/308/Q2.ipynb
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"import torch.nn as nn\n",
|
| 71 |
+
"from torchvision.datasets import MNIST\n",
|
| 72 |
+
"from torch.utils.data import DataLoader\n",
|
| 73 |
+
"from torch.optim import Adam\n",
|
| 74 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 75 |
+
"import torch.nn.functional as F\n",
|
| 76 |
+
"import matplotlib.pyplot as plt\n",
|
| 77 |
+
"# Training dataset\n",
|
| 78 |
+
"train_dataset = MNIST(\n",
|
| 79 |
+
" root='./datasets', # Dataset storage path\n",
|
| 80 |
+
" train=True, # Use training data\n",
|
| 81 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 82 |
+
" download=True # Download if not available\n",
|
| 83 |
+
")\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"# Testing dataset\n",
|
| 86 |
+
"test_dataset = MNIST(\n",
|
| 87 |
+
" root='./datasets', # Dataset storage path\n",
|
| 88 |
+
" train=False, # Use test data\n",
|
| 89 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 90 |
+
" download=True # Download if not available\n",
|
| 91 |
+
")\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 2. Create TensorDataset objects\n",
|
| 101 |
+
"# print one sample from the dataset\n",
|
| 102 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 103 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (C, H, W)\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"'''When you load batches, it becomes:\n",
|
| 108 |
+
"(batch_size, 1, 28, 28)'''\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"print(f\"Label: {sample_label}\")\n"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# 3. Create DataLoaders\n",
|
| 120 |
+
"# DataLoader for training data\n",
|
| 121 |
+
"train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
|
| 122 |
+
"# DataLoader for test data\n",
|
| 123 |
+
"test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
|
| 124 |
+
"\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# 4. Print shape of one batch\n",
|
| 134 |
+
"# Get the first batch from the training DataLoader\n",
|
| 135 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 136 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 137 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# 5. Display sample images\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"# Get one batch of images and labels\n",
|
| 149 |
+
"images, labels = next(iter(train_loader))\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"# Display the first 6 images in the batch\n",
|
| 152 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"for i in range(6):\n",
|
| 155 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 158 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" plt.imshow(img)\n",
|
| 161 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 162 |
+
" plt.axis('off')\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"plt.tight_layout()\n",
|
| 165 |
+
"plt.show()"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"# Task 1: Write your model class here:\n",
|
| 175 |
+
"class NN4Layer(nn.Module):\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 178 |
+
" super(NN4Layer, self).__init__()\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # activation function for non-linearity\n",
|
| 194 |
+
" self.relu = nn.ReLU()\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Defines how input data flows through the network\n",
|
| 197 |
+
" def forward(self, x):\n",
|
| 198 |
+
" # Layer 1: TODO\n",
|
| 199 |
+
" z1 = self.layer1(x)\n",
|
| 200 |
+
" a1 = self.relu(z1)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # Layer 2 TODO\n",
|
| 203 |
+
" z2 = self.layer2(a1)\n",
|
| 204 |
+
" a2 = self.relu(z2)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Layer 3 TODO\n",
|
| 207 |
+
" z3 = self.layer3(a2)\n",
|
| 208 |
+
" a3 = self.relu(z3)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Output layer TODO\n",
|
| 211 |
+
" z4 = self.layer4(a3)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" return z4"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 2: Write your training loop here:\n",
|
| 229 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 230 |
+
" # Set the model to training mode\n",
|
| 231 |
+
" model.train()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" running_loss = 0.0\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 236 |
+
" # Move batch to the selected device\n",
|
| 237 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 238 |
+
" y_batch = y_batch.to(device)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Forward pass\n",
|
| 241 |
+
" # TODO: make predictions\n",
|
| 242 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 243 |
+
" # TODO: compute loss\n",
|
| 244 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # Backward pass & optimization\n",
|
| 247 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 248 |
+
" loss.backward() # Compute gradients\n",
|
| 249 |
+
" optimizer.step() # Update model parameters\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" running_loss += loss.item()\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Average loss over all batches\n",
|
| 254 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" return avg_loss"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 3: Write your validation loop here:\n",
|
| 266 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 267 |
+
" # Set the model to evaluation mode\n",
|
| 268 |
+
" model.eval()\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" running_loss = 0.0\n",
|
| 271 |
+
" correct = 0\n",
|
| 272 |
+
" total = 0\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" with torch.no_grad():\n",
|
| 275 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 276 |
+
" # Move data to device\n",
|
| 277 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 278 |
+
" y_batch = y_batch.to(device)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Forward pass\n",
|
| 281 |
+
" # TODO: make predictions\n",
|
| 282 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 283 |
+
" # TODO: compute loss\n",
|
| 284 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 285 |
+
" running_loss += loss.item()\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 288 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
" # TODO: Multiclass predictions\n",
|
| 291 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" # Accuracy calculation\n",
|
| 294 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 295 |
+
" total += y_batch.size(0)\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 298 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 299 |
+
" accuracy = correct / total\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" return avg_loss, accuracy\n"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 311 |
+
"# Device setup\n",
|
| 312 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Model parameters\n",
|
| 315 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 316 |
+
"input_dim = 1*28*28 # CIFAR-10 images flattened (RGB)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# TODO: choose number of hidden neurons\n",
|
| 319 |
+
"hidden_dim = 64 # Design choice\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"# TODO: what are the number of classes ?\n",
|
| 322 |
+
"output_dim = 10 # CIFAR-10 classes\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 325 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"# TODO: Print the model architecture\n",
|
| 328 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 329 |
+
"print(model)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"# Calculate the total number of trainable parameters\n",
|
| 332 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 333 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n"
|
| 334 |
+
],
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"outputs": []
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"cell_type": "code",
|
| 340 |
+
"metadata": {},
|
| 341 |
+
"source": [
|
| 342 |
+
"# Task 5: Start training for 20 epochs:# TODO: choose number of epochs, increase it if you have gpus :)\n",
|
| 343 |
+
"from torch.optim import AdamW\n",
|
| 344 |
+
"num_epochs = 20\n",
|
| 345 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 346 |
+
"learning_rate = 0.001\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 349 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 350 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 351 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 352 |
+
"# Run Training\n",
|
| 353 |
+
"train_losses = []\n",
|
| 354 |
+
"val_losses = []\n",
|
| 355 |
+
"val_accuracies = []\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"print('Starting Training...')\n",
|
| 358 |
+
"for epoch in range(num_epochs):\n",
|
| 359 |
+
" # Train one epoch\n",
|
| 360 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 361 |
+
"\n",
|
| 362 |
+
" # Validate\n",
|
| 363 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" train_losses.append(train_loss)\n",
|
| 366 |
+
" val_losses.append(val_loss)\n",
|
| 367 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 368 |
+
"\n",
|
| 369 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"print('Training Complete!')"
|
| 372 |
+
],
|
| 373 |
+
"execution_count": null,
|
| 374 |
+
"outputs": []
|
| 375 |
+
},
|
| 376 |
+
{
|
| 377 |
+
"cell_type": "code",
|
| 378 |
+
"metadata": {},
|
| 379 |
+
"source": [
|
| 380 |
+
"# Task 1: Write your code here:\n",
|
| 381 |
+
"# Plotting results\n",
|
| 382 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 385 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 386 |
+
"plt.title('Loss over Epochs')\n",
|
| 387 |
+
"plt.xlabel('Epoch')\n",
|
| 388 |
+
"plt.ylabel('Loss')\n",
|
| 389 |
+
"plt.legend()\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"plt.tight_layout()\n",
|
| 392 |
+
"plt.show()"
|
| 393 |
+
],
|
| 394 |
+
"execution_count": null,
|
| 395 |
+
"outputs": []
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "code",
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"source": [
|
| 401 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 402 |
+
"# Set model to evaluation mode\n",
|
| 403 |
+
"model.eval()\n",
|
| 404 |
+
"# Get one batch from the test DataLoader\n",
|
| 405 |
+
"images, labels = next(iter(test_loader))\n",
|
| 406 |
+
"# Move images to device\n",
|
| 407 |
+
"images = images.to(device)\n",
|
| 408 |
+
"labels = labels.to(device)\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"with torch.no_grad():\n",
|
| 411 |
+
" # Flatten images before passing to the model\n",
|
| 412 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 413 |
+
" predictions = torch.argmax(outputs, dim=1)\n",
|
| 414 |
+
"\n",
|
| 415 |
+
"# Move tensors back to CPU for plotting\n",
|
| 416 |
+
"images = images.cpu()\n",
|
| 417 |
+
"labels = labels.cpu()\n",
|
| 418 |
+
"predictions = predictions.cpu()\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"# Plot first 6 predictions\n",
|
| 421 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 422 |
+
"for i in range(6):\n",
|
| 423 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 424 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 425 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 426 |
+
" plt.axis('off')\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"plt.tight_layout()\n",
|
| 429 |
+
"plt.show()"
|
| 430 |
+
],
|
| 431 |
+
"execution_count": null,
|
| 432 |
+
"outputs": []
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"cell_type": "code",
|
| 436 |
+
"metadata": {},
|
| 437 |
+
"source": [],
|
| 438 |
+
"execution_count": null,
|
| 439 |
+
"outputs": []
|
| 440 |
+
}
|
| 441 |
+
],
|
| 442 |
+
"metadata": {
|
| 443 |
+
"kernelspec": {
|
| 444 |
+
"display_name": "Python 3",
|
| 445 |
+
"name": "python3"
|
| 446 |
+
},
|
| 447 |
+
"language_info": {
|
| 448 |
+
"name": "python"
|
| 449 |
+
}
|
| 450 |
+
},
|
| 451 |
+
"nbformat": 4,
|
| 452 |
+
"nbformat_minor": 0
|
| 453 |
+
}
|
submissions_extracted/308/Q3.ipynb
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"import pandas as pd\n",
|
| 27 |
+
"import numpy as np\n",
|
| 28 |
+
"import matplotlib.pyplot as plt\n",
|
| 29 |
+
"import seaborn as sns\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"import os\n",
|
| 32 |
+
"from tqdm import tqdm\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"%matplotlib inline"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# Task 1: Write your code here:\n",
|
| 44 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"df = pd.read_csv(csv_path)\n"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 2: Write your code here:\n",
|
| 56 |
+
"df.head()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 3: Write your code here:\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"df.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 1: Write your code here:\n",
|
| 86 |
+
"def check_missing_values(df):\n",
|
| 87 |
+
" missing_values = df.isnull().sum()\n",
|
| 88 |
+
" print(\"Missing Values per Column:\")\n",
|
| 89 |
+
" print(missing_values[missing_values > 0])\n",
|
| 90 |
+
" if missing_values.any():\n",
|
| 91 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 92 |
+
" else:\n",
|
| 93 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"check_missing_values(df)"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 2: Write your code here:\n",
|
| 105 |
+
"# 4. Do we have duplicate samples?\n",
|
| 106 |
+
"def check_duplicates(df):\n",
|
| 107 |
+
" duplicates = df.duplicated().sum()\n",
|
| 108 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 109 |
+
" if duplicates > 0:\n",
|
| 110 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 111 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 112 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 113 |
+
" else:\n",
|
| 114 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"check_duplicates(df)"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 3: Write your code here:\n",
|
| 126 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"label_encoders = {}\n",
|
| 129 |
+
"for col in df:\n",
|
| 130 |
+
" le = LabelEncoder()\n",
|
| 131 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 132 |
+
" label_encoders[col] = le\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"df"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 4: Write your code here:\n",
|
| 144 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"scaler = StandardScaler()\n",
|
| 149 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 150 |
+
"df.head()\n"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 5: Write your code here:\n",
|
| 160 |
+
"# 1. Is the target imbalanced?\n",
|
| 161 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 162 |
+
" print(\"Target Distribution:\")\n",
|
| 163 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 164 |
+
" sns.countplot(x=df[target_column])\n",
|
| 165 |
+
" plt.title(\"Target Distribution\")\n",
|
| 166 |
+
" plt.show()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"check_target_imbalance(df, \"Target\")"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 1: Write your code here:\n",
|
| 178 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 179 |
+
"y = df['Target'].astype(float)"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"# sigmoid in NumPy\n",
|
| 189 |
+
"def sigmoid(z):\n",
|
| 190 |
+
" return 1 / (1 + np.exp(-z))"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# BCE in NumPy\n",
|
| 200 |
+
"def binary_cross_entropy(y, y_hat):\n",
|
| 201 |
+
" epsilon = 1e-15 # Very small number to prevent log(0)\n",
|
| 202 |
+
" y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
|
| 205 |
+
" return loss"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 215 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 216 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 217 |
+
" losses = []\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
|
| 220 |
+
" z = np.dot(X, theta)\n",
|
| 221 |
+
" y_hat = sigmoid(z)\n",
|
| 222 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 223 |
+
" theta -= learning_rate * gradient\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" loss = binary_cross_entropy(y, y_hat)\n",
|
| 226 |
+
" losses.append(loss)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" return theta, losses"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 238 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 239 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
|
| 240 |
+
],
|
| 241 |
+
"execution_count": null,
|
| 242 |
+
"outputs": []
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"cell_type": "code",
|
| 246 |
+
"metadata": {},
|
| 247 |
+
"source": [
|
| 248 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 251 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"# Storage for logistic regression results for each fold\n",
|
| 261 |
+
"lr_losses = []\n",
|
| 262 |
+
"lr_accuracy = []\n",
|
| 263 |
+
"lr_precision = []\n",
|
| 264 |
+
"lr_recall = []\n",
|
| 265 |
+
"lr_f1 = []"
|
| 266 |
+
],
|
| 267 |
+
"execution_count": null,
|
| 268 |
+
"outputs": []
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "code",
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"source": [
|
| 274 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 275 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 278 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Train\n",
|
| 281 |
+
" theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" # Validate\n",
|
| 284 |
+
" y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
|
| 285 |
+
" y_pred = (y_pred_proba >= 0.5).astype(int)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # Calculate evaluation metrics\n",
|
| 288 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 289 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 290 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 291 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" # Store results\n",
|
| 294 |
+
" lr_losses.append(losses)\n",
|
| 295 |
+
" lr_accuracy.append(accuracy)\n",
|
| 296 |
+
" lr_precision.append(precision)\n",
|
| 297 |
+
" lr_recall.append(recall)\n",
|
| 298 |
+
" lr_f1.append(f1)"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"print(\"LOGISTIC REGRESSION Performance:\")\n",
|
| 308 |
+
"print(f\" Accuracy: {np.mean(lr_accuracy):.4f}\")\n",
|
| 309 |
+
"print(f\" F1-Score: {np.mean(lr_f1):.4f}\")"
|
| 310 |
+
],
|
| 311 |
+
"execution_count": null,
|
| 312 |
+
"outputs": []
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"cell_type": "code",
|
| 316 |
+
"metadata": {},
|
| 317 |
+
"source": [
|
| 318 |
+
"from catboost import CatBoostClassifier\n",
|
| 319 |
+
"sklearn_models = {\n",
|
| 320 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 321 |
+
" verbose=0,\n",
|
| 322 |
+
" n_estimators=320,\n",
|
| 323 |
+
" max_depth=4\n",
|
| 324 |
+
" )\n",
|
| 325 |
+
"}"
|
| 326 |
+
],
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"outputs": []
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"cell_type": "code",
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"source": [
|
| 334 |
+
"n_splits = 5 # K\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 337 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
|
| 338 |
+
],
|
| 339 |
+
"execution_count": null,
|
| 340 |
+
"outputs": []
|
| 341 |
+
},
|
| 342 |
+
{
|
| 343 |
+
"cell_type": "code",
|
| 344 |
+
"metadata": {},
|
| 345 |
+
"source": [
|
| 346 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 347 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" # 1. Split data\n",
|
| 350 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 351 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" # 2. Train & Validate sklearn models\n",
|
| 354 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 355 |
+
" print(f\"Training {model_name}...\")\n",
|
| 356 |
+
" model.fit(X_train, y_train) # train\n",
|
| 357 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 360 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 361 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 362 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 363 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 366 |
+
" all_results[model_name]['f1'].append(f1)"
|
| 367 |
+
],
|
| 368 |
+
"execution_count": null,
|
| 369 |
+
"outputs": []
|
| 370 |
+
},
|
| 371 |
+
{
|
| 372 |
+
"cell_type": "code",
|
| 373 |
+
"metadata": {},
|
| 374 |
+
"source": [
|
| 375 |
+
"for model_name in all_results:\n",
|
| 376 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 377 |
+
" print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
|
| 378 |
+
" print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
|
| 379 |
+
],
|
| 380 |
+
"execution_count": null,
|
| 381 |
+
"outputs": []
|
| 382 |
+
},
|
| 383 |
+
{
|
| 384 |
+
"cell_type": "code",
|
| 385 |
+
"metadata": {},
|
| 386 |
+
"source": [
|
| 387 |
+
"# Calculate the majority class baseline\n",
|
| 388 |
+
"majority_class = y.value_counts().idxmax()\n",
|
| 389 |
+
"baseline_pred = [majority_class] * len(y)\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"# Evaluate the baseline\n",
|
| 392 |
+
"baseline_accuracy = accuracy_score(y, baseline_pred)\n",
|
| 393 |
+
"baseline_precision = precision_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 394 |
+
"baseline_recall = recall_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 395 |
+
"baseline_f1 = f1_score(y, baseline_pred, average='weighted', zero_division=0)\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"print(f\"Baseline Accuracy (majority class): {baseline_accuracy:.4f}\")\n",
|
| 398 |
+
"print(f\"Baseline F1-Score: {baseline_f1:.4f}\")\n"
|
| 399 |
+
],
|
| 400 |
+
"execution_count": null,
|
| 401 |
+
"outputs": []
|
| 402 |
+
},
|
| 403 |
+
{
|
| 404 |
+
"cell_type": "code",
|
| 405 |
+
"metadata": {},
|
| 406 |
+
"source": [
|
| 407 |
+
"# Task 1: Write your code here:\n",
|
| 408 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 409 |
+
"importances = {}\n",
|
| 410 |
+
"\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"# Create a 1x3 plot\n",
|
| 415 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 416 |
+
"axes = axes.flatten()\n",
|
| 417 |
+
"features = X.columns\n",
|
| 418 |
+
"\n",
|
| 419 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 420 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 421 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 422 |
+
"\n",
|
| 423 |
+
" ax = axes[i]\n",
|
| 424 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 425 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 426 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"plt.tight_layout()\n",
|
| 429 |
+
"plt.show()"
|
| 430 |
+
],
|
| 431 |
+
"execution_count": null,
|
| 432 |
+
"outputs": []
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"cell_type": "code",
|
| 436 |
+
"metadata": {},
|
| 437 |
+
"source": [
|
| 438 |
+
"# Task 2: Write your code here:"
|
| 439 |
+
],
|
| 440 |
+
"execution_count": null,
|
| 441 |
+
"outputs": []
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"cell_type": "code",
|
| 445 |
+
"metadata": {},
|
| 446 |
+
"source": [
|
| 447 |
+
"# Task Bonus: Write your code here:"
|
| 448 |
+
],
|
| 449 |
+
"execution_count": null,
|
| 450 |
+
"outputs": []
|
| 451 |
+
}
|
| 452 |
+
],
|
| 453 |
+
"metadata": {
|
| 454 |
+
"kernelspec": {
|
| 455 |
+
"display_name": "Python 3",
|
| 456 |
+
"name": "python3"
|
| 457 |
+
},
|
| 458 |
+
"language_info": {
|
| 459 |
+
"name": "python"
|
| 460 |
+
}
|
| 461 |
+
},
|
| 462 |
+
"nbformat": 4,
|
| 463 |
+
"nbformat_minor": 0
|
| 464 |
+
}
|
submissions_extracted/309/Q1.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ell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import numpy as np\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import os\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Download latest version\n",
|
| 19 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"print(\"Path to dataset files:\", path)"
|
| 22 |
+
],
|
| 23 |
+
"execution_count": null,
|
| 24 |
+
"outputs": []
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"# Task 1: Write your code here:\n",
|
| 31 |
+
"# Load the dataset\n",
|
| 32 |
+
"cars_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 33 |
+
"df_cars = pd.read_csv(cars_path)\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"print(f\"Dataset shape: {df_cars.shape}\")\n",
|
| 36 |
+
"df_cars.head()"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 2: Write your code here:\n",
|
| 46 |
+
"# Check data types and structure\n",
|
| 47 |
+
"df_cars.info()"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 3: Write your code here:\n",
|
| 57 |
+
"# Analyze missing values\n",
|
| 58 |
+
"missing_percentage = (df_cars.isnull().sum() / len(df_cars)) * 100\n",
|
| 59 |
+
"missing_data = pd.DataFrame({\n",
|
| 60 |
+
" 'Column': missing_percentage.index,\n",
|
| 61 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 62 |
+
"})\n",
|
| 63 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 66 |
+
"missing_data.head(10)"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:# Descriptive statistics for numerical columns\n",
|
| 76 |
+
"df_cars.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"#5. Plot the target distribution (delivery_time)\n",
|
| 86 |
+
"# Task 5: Write your code here:\n",
|
| 87 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 88 |
+
"plt.hist(df_cars['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 89 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 90 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 91 |
+
"plt.ylabel('Frequency')\n",
|
| 92 |
+
"plt.show"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# Task 1: Write your code here:\n",
|
| 102 |
+
"# Drop 'Order_ID' column from the data\n",
|
| 103 |
+
"df_clean =(df_cars['Order_ID'].dropna())\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 2: Write your code here:\n",
|
| 113 |
+
"# Missing values\n",
|
| 114 |
+
"# 2️ Check for missing values\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"def check_missing_values(df):\n",
|
| 117 |
+
" missing_values = df.isnull().sum()\n",
|
| 118 |
+
" # Count number of missing values in each column\n",
|
| 119 |
+
"\n",
|
| 120 |
+
" print(\"Missing Values per Column:\")\n",
|
| 121 |
+
" print(missing_values[missing_values > 0])\n",
|
| 122 |
+
"\n",
|
| 123 |
+
" if missing_values.any():\n",
|
| 124 |
+
" # If any missing values exist\n",
|
| 125 |
+
"\n",
|
| 126 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 127 |
+
"\n",
|
| 128 |
+
" else:\n",
|
| 129 |
+
" # If no missing values exist\n",
|
| 130 |
+
"\n",
|
| 131 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"check_missing_values(df_cars)\n"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"#Check and remove duplicates if any exist\n",
|
| 143 |
+
"def check_duplicates(df):\n",
|
| 144 |
+
" duplicates = df.duplicated().sum()\n",
|
| 145 |
+
" # Count duplicated row\n",
|
| 146 |
+
"\n",
|
| 147 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" if duplicates > 0:\n",
|
| 150 |
+
" # If duplicates exist\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 153 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 154 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 155 |
+
" else:\n",
|
| 156 |
+
" # If no duplicates exist\n",
|
| 157 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"check_duplicates(df_cars)\n"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 169 |
+
"#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
|
| 170 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 171 |
+
"# Encode type columns\n",
|
| 172 |
+
"le = LabelEncoder()\n",
|
| 173 |
+
"df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n",
|
| 174 |
+
"df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n",
|
| 175 |
+
"df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n",
|
| 176 |
+
"df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 4: Write your code here:"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task 5: Write your code here:\n",
|
| 202 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 203 |
+
"print('data before scaling:\\n',df_cars) #show before scaling\n",
|
| 204 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 205 |
+
"data_standard_scaled = standard_scaler.fit_transform(df_cars) # Apply fit_transform\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 208 |
+
],
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"outputs": []
|
| 211 |
+
},
|
| 212 |
+
{
|
| 213 |
+
"cell_type": "code",
|
| 214 |
+
"metadata": {},
|
| 215 |
+
"source": [
|
| 216 |
+
"# Replace 'target_column' with your actual target name\n",
|
| 217 |
+
"df_cars['target_column'].hist()"
|
| 218 |
+
],
|
| 219 |
+
"execution_count": null,
|
| 220 |
+
"outputs": []
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "code",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"# Task 1: Write your code here:\n",
|
| 227 |
+
"X = df_cars.drop(\"target\", axis=1).astype(float)\n",
|
| 228 |
+
"y = df_cars[\"target\"].astype(float)"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 238 |
+
"# Task 1: Write your code here:\n",
|
| 239 |
+
"from sklearn.model_selection import KFold\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"# Use previously generated random data (example: regression data)\n",
|
| 242 |
+
"X, y = X_reg.copy(), y_reg.copy()\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"# Define K-Fold Cross Validation\n",
|
| 245 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"# Iterate through folds\n",
|
| 248 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 249 |
+
" # indexing for each fold\n",
|
| 250 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 251 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 252 |
+
" # print shapes\n",
|
| 253 |
+
" print(f\"Fold {fold}\")\n",
|
| 254 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 255 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 256 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 257 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 258 |
+
" print(\"-\" * 30)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Train RandomForestClassifier\n",
|
| 261 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 262 |
+
" class_weight='balanced', random_state=42)\n",
|
| 263 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 264 |
+
"print(\"Model trained!\")\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"# Get predictions on test set\n",
|
| 268 |
+
"model.eval()\n",
|
| 269 |
+
"with torch.no_grad():\n",
|
| 270 |
+
" # TODO: Get predictions for X_test\n",
|
| 271 |
+
" # [HINT]: Move X_test to device, pass through model, then move back to CPU\n",
|
| 272 |
+
" predictions = model(X_test.to(device)).cpu().numpy()\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# TODO: Calculate evaluation metrics\n",
|
| 275 |
+
"# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n",
|
| 276 |
+
"mae = mean_absolute_error(y_test.numpy(), predictions)\n",
|
| 277 |
+
"mse = mean_squared_error(y_test.numpy(), predictions)\n",
|
| 278 |
+
"rmse = np.sqrt(mse)\n",
|
| 279 |
+
"r2 = r2_score(y_test.numpy(), predictions)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"print(\"Model Evaluation\")\n",
|
| 282 |
+
"print(f\" MAE: ${mae:.2f}\")\n",
|
| 283 |
+
"print(f\" MSE: {mse:.2f}\")\n",
|
| 284 |
+
"print(f\" RMSE: ${rmse:.2f}\")\n",
|
| 285 |
+
"print(f\" R2: {r2:.4f}\")"
|
| 286 |
+
],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [],
|
| 294 |
+
"execution_count": null,
|
| 295 |
+
"outputs": []
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"cell_type": "code",
|
| 299 |
+
"metadata": {},
|
| 300 |
+
"source": [
|
| 301 |
+
"# Task 2: Write your code here:\n"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"# Task Bonus: Write your code here:"
|
| 311 |
+
],
|
| 312 |
+
"execution_count": null,
|
| 313 |
+
"outputs": []
|
| 314 |
+
}
|
| 315 |
+
],
|
| 316 |
+
"metadata": {
|
| 317 |
+
"kernelspec": {
|
| 318 |
+
"display_name": "Python 3",
|
| 319 |
+
"name": "python3"
|
| 320 |
+
},
|
| 321 |
+
"language_info": {
|
| 322 |
+
"name": "python"
|
| 323 |
+
}
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 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import numpy as np\n",
|
| 12 |
+
"import torch\n",
|
| 13 |
+
"import torch.nn as nn\n",
|
| 14 |
+
"from torch.optim import AdamW\n",
|
| 15 |
+
"import matplotlib.pyplot as plt\n",
|
| 16 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 17 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 18 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 19 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"print(f\"PyTorch version: {torch.__version__}\")\n",
|
| 22 |
+
"print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"# Download latest version\n",
|
| 25 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"import os\n",
|
| 37 |
+
"import pandas as pd\n",
|
| 38 |
+
"import numpy as np\n",
|
| 39 |
+
"from PIL import Image\n",
|
| 40 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"# Load Labels\n",
|
| 43 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 44 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"images = []\n",
|
| 47 |
+
"ages = []\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"# Load Images and Resize\n",
|
| 50 |
+
"print(\"Loading images...\")\n",
|
| 51 |
+
"for index, row in labels_df.iterrows():\n",
|
| 52 |
+
" img_name = row.iloc[0]\n",
|
| 53 |
+
" age = row.iloc[1]\n",
|
| 54 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
" if os.path.exists(img_path):\n",
|
| 57 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 58 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 59 |
+
" images.append(img_array)\n",
|
| 60 |
+
" ages.append(age)\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"X = np.array(images)\n",
|
| 63 |
+
"y = np.array(ages)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 66 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"# Split Data\n",
|
| 69 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 72 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 73 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 74 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"# Training dataset\n",
|
| 86 |
+
"train_dataset = CIFAR10(\n",
|
| 87 |
+
" root='./datasets', # Directory to store dataset\n",
|
| 88 |
+
" # مسار حفظ البيانات\n",
|
| 89 |
+
" train=True, # Use training data\n",
|
| 90 |
+
" # نستخدم بيانات التدريب\n",
|
| 91 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 92 |
+
" # تحويل الصور إلى Tensor\n",
|
| 93 |
+
" download=True # Download if not already downloaded\n",
|
| 94 |
+
" # تحميل البيانات إذا غير موجودة\n",
|
| 95 |
+
")\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"# Testing dataset\n",
|
| 98 |
+
"test_dataset = CIFAR10(\n",
|
| 99 |
+
" root='./datasets', # Same dataset directory\n",
|
| 100 |
+
" # نفس مسار البيانات\n",
|
| 101 |
+
" train=False, # Use test data\n",
|
| 102 |
+
" # نستخدم بيانات الاختبار\n",
|
| 103 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 104 |
+
" # تحويل الصور إلى Tensor\n",
|
| 105 |
+
" download=True # Download if needed\n",
|
| 106 |
+
" # تحميلها إذا لزم\n",
|
| 107 |
+
")\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"# Get one sample image and its label from training data\n",
|
| 110 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"# Print the shape of the image tensor\n",
|
| 113 |
+
"# طباعة شكل الصورة بعد التحويل إلى Tensor\n",
|
| 114 |
+
"print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"# Print the label (class index)\n",
|
| 117 |
+
"# طباعة رقم الفئة (التصنيف)\n",
|
| 118 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# DataLoader for training data\n",
|
| 121 |
+
"#\n",
|
| 122 |
+
"# إنشاء DataLoader لبيانات التدريب\n",
|
| 123 |
+
"train_loader = DataLoader(\n",
|
| 124 |
+
" train_dataset, # Training dataset\n",
|
| 125 |
+
" # بيانات التدريب\n",
|
| 126 |
+
" batch_size=32, # Number of samples per batch\n",
|
| 127 |
+
" # عدد الصور في كل دفعة\n",
|
| 128 |
+
" shuffle=True, # Shuffle data each epoch\n",
|
| 129 |
+
" # خلط البيانات كل مرة (مهم للتدريب)\n",
|
| 130 |
+
" num_workers=2 # Number of subprocesses for data loading\n",
|
| 131 |
+
" # عدد العمليات لتحميل البيانات\n",
|
| 132 |
+
")\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"# DataLoader for test data\n",
|
| 135 |
+
"# إنشاء DataLoader لبيانات الاختبار\n",
|
| 136 |
+
"test_loader = DataLoader(\n",
|
| 137 |
+
" test_dataset, # Test dataset\n",
|
| 138 |
+
" # بيانات الاختبار\n",
|
| 139 |
+
" batch_size=32, # Same batch size\n",
|
| 140 |
+
" # نفس حجم الدفعة\n",
|
| 141 |
+
" shuffle=False, # No shuffling during evaluation\n",
|
| 142 |
+
" # لا نخلط البيانات أثناء التقييم\n",
|
| 143 |
+
" num_workers=2 # Data loading workers\n",
|
| 144 |
+
" # عمليات تحميل البيانات\n",
|
| 145 |
+
")\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"# Get the first batch from the training DataLoader\n",
|
| 148 |
+
"# أخذ أول batch من بيانات التدريب (للفحص فقط)\n",
|
| 149 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"# Print input batch shape\n",
|
| 152 |
+
"# طباعة شكل بيانات الإدخال\n",
|
| 153 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"# Print labels batch shape\n",
|
| 156 |
+
"# طباعة شكل التسميات\n",
|
| 157 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# 2. Create TensorDataset objects\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Create TensorDatasets for training and testing\n",
|
| 170 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 171 |
+
"test_dataset = TensorDataset(X_test, y_test)"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# 3. Create DataLoaders\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 183 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 184 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# 4. Print shape of one batch\n",
|
| 194 |
+
"# Print dataset sizes\n",
|
| 195 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 196 |
+
"print(\"Test dataset:\", len(test_dataset))\n"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# 5. Display sample images\n",
|
| 206 |
+
"# Get the first batch from the training DataLoader\n",
|
| 207 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 208 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 209 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 1: Write your model class here:\n",
|
| 219 |
+
"class NN3Layer(nn.Module):\n",
|
| 220 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 221 |
+
" super(NN3Layer, self).__init__()\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 224 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 227 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Output layer: hidden layer -> single continuous value\n",
|
| 230 |
+
" self.layer3 = nn.Linear(hidden_dim, 1)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # ReLU activation for non-linearity in hidden layers\n",
|
| 233 |
+
" self.relu = nn.ReLU()\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Defines how input data flows through the network\n",
|
| 236 |
+
" def forward(self, x):\n",
|
| 237 |
+
" # First hidden layer\n",
|
| 238 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Second hidden layer\n",
|
| 241 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Output layer (regression output)\n",
|
| 244 |
+
" output = self.layer3(a2)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" return output"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 2: Write your training loop here:\n",
|
| 256 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 257 |
+
" # Set the model to training mode\n",
|
| 258 |
+
" model.train()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" running_loss = 0.0\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 263 |
+
" # Move batch to the selected device\n",
|
| 264 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 265 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Forward pass (continuous output)\n",
|
| 268 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 269 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # Backward pass & optimization\n",
|
| 272 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 273 |
+
" loss.backward() # Compute gradients\n",
|
| 274 |
+
" optimizer.step() # Update model parameters\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" running_loss += loss.item()\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # Average loss over all batches\n",
|
| 279 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" return avg_loss"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"source": [
|
| 290 |
+
"# Task 3: Write your validation loop here:\n",
|
| 291 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 292 |
+
" # Set the model to evaluation mode\n",
|
| 293 |
+
" model.eval()\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" running_loss = 0.0\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" with torch.no_grad():\n",
|
| 298 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 299 |
+
" # Move data to device\n",
|
| 300 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 301 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" # Forward pass (continuous output)\n",
|
| 304 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 305 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" running_loss += loss.item()\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" # Average loss over all batches\n",
|
| 310 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" return avg_loss"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 322 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 323 |
+
" # Set the model to evaluation mode\n",
|
| 324 |
+
" model.eval()\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" running_loss = 0.0\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" with torch.no_grad():\n",
|
| 329 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 330 |
+
" # Move data to device\n",
|
| 331 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 332 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" # Forward pass (continuous output)\n",
|
| 335 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 336 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" running_loss += loss.item()\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" # Average loss over all batches\n",
|
| 341 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" return avg_loss\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" # Model parameters\n",
|
| 346 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 347 |
+
"hidden_dim = 64 # Design choice\n",
|
| 348 |
+
"\n",
|
| 349 |
+
"# Instantiate regression model\n",
|
| 350 |
+
"model = NN3Layer(input_dim, hidden_dim).to(device)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"# Print the model architecture\n",
|
| 353 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 354 |
+
"print(model)\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"# Calculate the total number of trainable parameters\n",
|
| 357 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 358 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"\n"
|
| 361 |
+
],
|
| 362 |
+
"execution_count": null,
|
| 363 |
+
"outputs": []
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"cell_type": "code",
|
| 367 |
+
"metadata": {},
|
| 368 |
+
"source": [
|
| 369 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 370 |
+
"# Hyperparameters (feel free to experiment!)\n",
|
| 371 |
+
"num_epochs = 20\n",
|
| 372 |
+
"learning_rate = 0.001\n",
|
| 373 |
+
"# Define criterion (loss function)\n",
|
| 374 |
+
"criterion = nn.MSELoss()\n",
|
| 375 |
+
"# Define optimizer\n",
|
| 376 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"# Run Training\n",
|
| 379 |
+
"train_losses = []\n",
|
| 380 |
+
"val_losses = []\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"print('Starting Training...')\n",
|
| 383 |
+
"for epoch in range(num_epochs):\n",
|
| 384 |
+
" # Train one epoch\n",
|
| 385 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 386 |
+
"\n",
|
| 387 |
+
" # Validate\n",
|
| 388 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" train_losses.append(train_loss)\n",
|
| 391 |
+
" val_losses.append(val_loss)\n",
|
| 392 |
+
"\n",
|
| 393 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 394 |
+
" print(\n",
|
| 395 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 396 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 397 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 398 |
+
" )\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"print('Training Complete!')"
|
| 401 |
+
],
|
| 402 |
+
"execution_count": null,
|
| 403 |
+
"outputs": []
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
"cell_type": "code",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"# Task 1: Write your code here:\n",
|
| 410 |
+
"# Plotting results\n",
|
| 411 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 414 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 415 |
+
"plt.title('Loss over Epochs')\n",
|
| 416 |
+
"plt.xlabel('Epoch')\n",
|
| 417 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 418 |
+
"plt.legend()\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"plt.tight_layout()\n",
|
| 421 |
+
"plt.show()"
|
| 422 |
+
],
|
| 423 |
+
"execution_count": null,
|
| 424 |
+
"outputs": []
|
| 425 |
+
},
|
| 426 |
+
{
|
| 427 |
+
"cell_type": "code",
|
| 428 |
+
"metadata": {},
|
| 429 |
+
"source": [
|
| 430 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 431 |
+
"# Scatter plot: Predicted vs Actual\n",
|
| 432 |
+
"plt.figure(figsize=(8, 6))\n",
|
| 433 |
+
"\n",
|
| 434 |
+
"# Plot: Predicted vs Actual scatter\n",
|
| 435 |
+
"plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"# Add perfect prediction line\n",
|
| 438 |
+
"min_val = min(y_test.min(), predictions.min())\n",
|
| 439 |
+
"max_val = max(y_test.max(), predictions.max())\n",
|
| 440 |
+
"plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n",
|
| 441 |
+
"\n",
|
| 442 |
+
"plt.xlabel('Actual Price ($)', fontsize=12)\n",
|
| 443 |
+
"plt.ylabel('Predicted Price ($)', fontsize=12)\n",
|
| 444 |
+
"plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n",
|
| 445 |
+
"plt.legend()\n",
|
| 446 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 447 |
+
"\n",
|
| 448 |
+
"plt.tight_layout()\n",
|
| 449 |
+
"plt.show()"
|
| 450 |
+
],
|
| 451 |
+
"execution_count": null,
|
| 452 |
+
"outputs": []
|
| 453 |
+
}
|
| 454 |
+
],
|
| 455 |
+
"metadata": {
|
| 456 |
+
"kernelspec": {
|
| 457 |
+
"display_name": "Python 3",
|
| 458 |
+
"name": "python3"
|
| 459 |
+
},
|
| 460 |
+
"language_info": {
|
| 461 |
+
"name": "python"
|
| 462 |
+
}
|
| 463 |
+
},
|
| 464 |
+
"nbformat": 4,
|
| 465 |
+
"nbformat_minor": 0
|
| 466 |
+
}
|
submissions_extracted/309/Q3.ipynb
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"# Download latest version\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 18 |
+
"print(\"Path to dataset files:\", path)"
|
| 19 |
+
],
|
| 20 |
+
"execution_count": null,
|
| 21 |
+
"outputs": []
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"source": [
|
| 27 |
+
"# Task 1: Write your code here:\n",
|
| 28 |
+
"pokemon_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 29 |
+
"df_pokemon = pd.read_csv(pokemon_path)\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"print(f\"Shape: {df_pokemon.shape}\")\n"
|
| 32 |
+
],
|
| 33 |
+
"execution_count": null,
|
| 34 |
+
"outputs": []
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"# Task 2: Write your code here:\n",
|
| 41 |
+
"df_pokemon.head()"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 3: Write your code here:\n",
|
| 51 |
+
"df_pokemon.info()"
|
| 52 |
+
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": []
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
+
"metadata": {},
|
| 59 |
+
"source": [
|
| 60 |
+
"print(\"Missing values:\")\n",
|
| 61 |
+
"print(df_pokemon.isnull().sum())"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 4: Write your code here:\n",
|
| 78 |
+
"# Descriptive statistics for numerical columns\n",
|
| 79 |
+
"df_pokemon.describe()"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Task 1: Write your code here:\n",
|
| 89 |
+
"# Missing values\n",
|
| 90 |
+
"print(\"Missing values:\")\n",
|
| 91 |
+
"print(df_pokemon.isnull().sum())\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"cols=['P_2 ', 'D_39 ', 'B_1 ', 'B_2 ', 'R_1']\n",
|
| 102 |
+
"df_clean = df_pokemon[cols].copy()\n",
|
| 103 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 104 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 105 |
+
"for col in ['P_2', 'B_2 ']:\n",
|
| 106 |
+
" df_pokemon[col] = df_pokemon[col].fillna('unknown')\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# Fill cylinders with mode - discrete feature, mode is most representative\n",
|
| 109 |
+
"df_pokemon['cylinders'] = df_pokemon['cylinders'].fillna(df_pokemon['cylinders'].mode()[0])\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"print(\"Missing values remaining:\", df_pokemon.isnull().sum().sum())"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 2: Write your code here:\n",
|
| 121 |
+
"# 4️ Check for duplicate samples\n",
|
| 122 |
+
"# فحص وجود عينات مكررة في البيانات\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"def check_duplicates(df):\n",
|
| 125 |
+
" duplicates = df.duplicated().sum()\n",
|
| 126 |
+
" # Count duplicated rows\n",
|
| 127 |
+
" # حساب عدد الصفوف المكررة\n",
|
| 128 |
+
"\n",
|
| 129 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 130 |
+
"\n",
|
| 131 |
+
" if duplicates > 0:\n",
|
| 132 |
+
" # If duplicates exist\n",
|
| 133 |
+
" # إذا وُجدت عينات مكررة\n",
|
| 134 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 135 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 136 |
+
" # حذف العينات المكررة\n",
|
| 137 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 138 |
+
" else:\n",
|
| 139 |
+
" # If no duplicates exist\n",
|
| 140 |
+
" # إذا لا توجد عينات مكررة\n",
|
| 141 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"check_duplicates(df_pokemon)"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 3: Write your code here:\n",
|
| 153 |
+
"from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"print('data before encoding:\\n', df_pokemon) #show before encoding\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"label_encoder = LabelEncoder() # Instantiate LabelEncoder\n",
|
| 158 |
+
"data_label_encoded = label_encoder.fit_transform(df_pokemon[\"Animal\"]) # Apply fit_transform to the column\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"print('\\nData after encoding:\\n', data_label_encoded)"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 4: Write your code here:\n",
|
| 170 |
+
"# Scale features - fit on train, transform both\n",
|
| 171 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 172 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 173 |
+
"# EN: StandardScaler transforms features to have mean=0 and std=1\n",
|
| 174 |
+
"numerical_cols = df_pokemon.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"status\")\n",
|
| 175 |
+
"# EN: Select all numeric columns EXCEPT the target column \"status\"\n",
|
| 176 |
+
"# IMPORTANT: We do NOT scale the target (label)\n",
|
| 177 |
+
"# مهم: لا نقوم بعمل scaling للـ target لأنه يمثل الفئة (0/1) وليس feature\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"scaler = StandardScaler()\n",
|
| 181 |
+
"# EN: Create scaler object\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"df_pokemon[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 185 |
+
"# EN: Fit scaler on numeric features and transform them\n",
|
| 186 |
+
"# AR: تعلم الإحصائيات من البيانات (mean/std) ثم تطبيق التحويل على الأعمدة الرقمية\n",
|
| 187 |
+
"# Result: features become standardized\n",
|
| 188 |
+
"# النتيجة: الخصائص تصبح على نفس المقياس\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"df_pokemon.head()\n",
|
| 192 |
+
"# EN: Show first rows after scaling\n",
|
| 193 |
+
"\n"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 5: Write your code here:\n"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 1: Write your code here:\n",
|
| 212 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# Use previously generated random data (example: classification data)\n",
|
| 215 |
+
"X, y= X_clf.copy(), y_clf.copy()\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"# split ratio (80% train, 20% test)\n",
|
| 218 |
+
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 219 |
+
" X, y,\n",
|
| 220 |
+
" test_size=0.2, # 20% for test, remaining 80% for train\n",
|
| 221 |
+
" random_state=42, # reproducible output\n",
|
| 222 |
+
" shuffle=True, # representative splits\n",
|
| 223 |
+
" stratify=y # preserve class distribution\n",
|
| 224 |
+
")\n",
|
| 225 |
+
"# Print shapes\n",
|
| 226 |
+
"print(\"X_train shape:\", X_train.shape)\n",
|
| 227 |
+
"print(\"X_test shape:\", X_test.shape)\n",
|
| 228 |
+
"print(\"y_train shape:\", y_train.shape)\n",
|
| 229 |
+
"print(\"y_test shape:\", y_test.shape)"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 241 |
+
"from sklearn.model_selection import KFold\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Use previously generated random data (example: regression data)\n",
|
| 244 |
+
"X, y = X_reg.copy(), y_reg.copy()\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"# Define K-Fold Cross Validation\n",
|
| 247 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"# Iterate through folds\n",
|
| 250 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 251 |
+
" # indexing for each fold\n",
|
| 252 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 253 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 254 |
+
" # print shapes\n",
|
| 255 |
+
" print(f\"Fold {fold}\")\n",
|
| 256 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 257 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 258 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 259 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 260 |
+
" print(\"-\" * 30)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" from catboost import CatBoostClassifier\n",
|
| 263 |
+
" #: CatBoost boosting classifier (robust)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 267 |
+
" verbose=0,\n",
|
| 268 |
+
" # EN: suppress log\n",
|
| 269 |
+
" n_estimators=320,\n",
|
| 270 |
+
" # EN: number of boosting iterations\n",
|
| 271 |
+
" max_depth=4\n",
|
| 272 |
+
" # EN: tree depth\n",
|
| 273 |
+
" # AR: عمق الشجرة\n",
|
| 274 |
+
" )\n",
|
| 275 |
+
" all_results = {}\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"for name in sklearn_models:\n",
|
| 278 |
+
" # EN: Initialize lists to store metrics across folds\n",
|
| 279 |
+
" # AR: تهيئة قوائم لتخزين نتائج كل fold\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" all_results[name] = {\n",
|
| 282 |
+
" 'accuracy': [], # EN: overall correctness |\n",
|
| 283 |
+
" 'precision': [], # EN: correctness of positive predictions |\n",
|
| 284 |
+
" 'recall': [], # EN: ability to find positives |\n",
|
| 285 |
+
" 'f1': [] # EN: balance precision & recall |\n",
|
| 286 |
+
" }\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"## Print average evaluation metrics for each model\n",
|
| 290 |
+
"# طباعة متوسط مقاييس التقييم لكل نموذج بعد K-Fold Cross-Validation\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"for model_name in all_results:\n",
|
| 293 |
+
" # Loop through each trained model\n",
|
| 294 |
+
" # المرور على كل نموذج تم تدريبه وتقييمه\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 297 |
+
" # Print model name\n",
|
| 298 |
+
" # طباعة اسم النموذج\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" print(f\" accuracy : {np.mean(all_results[model_name]['mse']):.4f}\")\n",
|
| 302 |
+
" # EN: Average Mean Squared Error across all folds\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"\n"
|
| 307 |
+
],
|
| 308 |
+
"execution_count": null,
|
| 309 |
+
"outputs": []
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"cell_type": "code",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"# Task 1: Write your code here:\n",
|
| 316 |
+
"# Plot for Linear Regression Predictions vs. Ground Truth\n",
|
| 317 |
+
"plt.figure(figsize=(6, 4))\n",
|
| 318 |
+
"plt.scatter(y_test, y_pred, alpha=0.7)\n",
|
| 319 |
+
"plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n",
|
| 320 |
+
"plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
|
| 321 |
+
"plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n",
|
| 322 |
+
"plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n",
|
| 323 |
+
"plt.grid(True)\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"plt.tight_layout()\n",
|
| 326 |
+
"plt.show()"
|
| 327 |
+
],
|
| 328 |
+
"execution_count": null,
|
| 329 |
+
"outputs": []
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "code",
|
| 333 |
+
"metadata": {},
|
| 334 |
+
"source": [
|
| 335 |
+
"# Task 2: Write your code here:\n",
|
| 336 |
+
"print(\"golden feature\"+ )\n"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"# Task Bonus: Write your code here:"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
}
|
| 350 |
+
],
|
| 351 |
+
"metadata": {
|
| 352 |
+
"kernelspec": {
|
| 353 |
+
"display_name": "Python 3",
|
| 354 |
+
"name": "python3"
|
| 355 |
+
},
|
| 356 |
+
"language_info": {
|
| 357 |
+
"name": "python"
|
| 358 |
+
}
|
| 359 |
+
},
|
| 360 |
+
"nbformat": 4,
|
| 361 |
+
"nbformat_minor": 0
|
| 362 |
+
}
|
submissions_extracted/31/Q1.ipynb
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"# Task 1: Write your code here:\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"data = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"data\n"
|
| 27 |
+
],
|
| 28 |
+
"execution_count": null,
|
| 29 |
+
"outputs": []
|
| 30 |
+
},
|
| 31 |
+
{
|
| 32 |
+
"cell_type": "code",
|
| 33 |
+
"metadata": {},
|
| 34 |
+
"source": [
|
| 35 |
+
"# Task 2: Write your code here:\n",
|
| 36 |
+
"head = data.head()"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 3: Write your code here:\n",
|
| 46 |
+
"data.info(10)"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 4: Write your code here:\n",
|
| 56 |
+
"data.describe()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 5: Write your code here:\n",
|
| 66 |
+
"import matplotlib.pyplot as plt\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"plt.show(data.X_axis , data.Y_axis)\n",
|
| 69 |
+
"\n"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 1: Write your code here:"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 2: Write your code here:"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 3: Write your code here:"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 4: Write your code here:"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 5: Write your code here:"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 6: Write your code here:"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# Task 1: Write your code here:\n",
|
| 133 |
+
"from sklearn import linear_regression"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 2,3,4,5: Write your code here:\n"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 1: Write your code here:"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 2: Write your code here:"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task Bonus: Write your code here:"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
}
|
| 174 |
+
],
|
| 175 |
+
"metadata": {
|
| 176 |
+
"kernelspec": {
|
| 177 |
+
"display_name": "Python 3",
|
| 178 |
+
"name": "python3"
|
| 179 |
+
},
|
| 180 |
+
"language_info": {
|
| 181 |
+
"name": "python"
|
| 182 |
+
}
|
| 183 |
+
},
|
| 184 |
+
"nbformat": 4,
|
| 185 |
+
"nbformat_minor": 0
|
| 186 |
+
}
|
submissions_extracted/31/Q2.ipynb
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch as tr\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"X_tensor = X.ternsor()\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"Y_tensor = Y.tensor()\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"\n"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 2. Create TensorDataset objects\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"\n"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 3. Create DataLoaders\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# 4. Print shape of one batch\n",
|
| 108 |
+
"\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# 5. Display sample images\n",
|
| 118 |
+
"\n"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 1: Write your model class here:"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 2: Write your training loop here:"
|
| 137 |
+
],
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"outputs": []
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"cell_type": "code",
|
| 143 |
+
"metadata": {},
|
| 144 |
+
"source": [
|
| 145 |
+
"# Task 3: Write your validation loop here:"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 5: Start training for 20 epochs:"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# Task 1: Write your code here:"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
}
|
| 186 |
+
],
|
| 187 |
+
"metadata": {
|
| 188 |
+
"kernelspec": {
|
| 189 |
+
"display_name": "Python 3",
|
| 190 |
+
"name": "python3"
|
| 191 |
+
},
|
| 192 |
+
"language_info": {
|
| 193 |
+
"name": "python"
|
| 194 |
+
}
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"# Task 1: Write your code here:\n",
|
| 27 |
+
"import pandas as pd\n",
|
| 28 |
+
"data = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"data"
|
| 31 |
+
],
|
| 32 |
+
"execution_count": null,
|
| 33 |
+
"outputs": []
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"cell_type": "code",
|
| 37 |
+
"metadata": {},
|
| 38 |
+
"source": [
|
| 39 |
+
"# Task 2: Write your code here:\n",
|
| 40 |
+
"data.head()"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 3: Write your code here:\n",
|
| 50 |
+
"data.info(200)"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 4: Write your code here:\n",
|
| 60 |
+
"data.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 1: Write your code here:"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 2: Write your code here:"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 3: Write your code here:"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 4: Write your code here:"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 5: Write your code here:"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 1: Write your code here:\n",
|
| 115 |
+
"from sklearn import k-fold\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 1: Write your code here:"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 2: Write your code here:"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task Bonus: Write your code here:"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
}
|
| 156 |
+
],
|
| 157 |
+
"metadata": {
|
| 158 |
+
"kernelspec": {
|
| 159 |
+
"display_name": "Python 3",
|
| 160 |
+
"name": "python3"
|
| 161 |
+
},
|
| 162 |
+
"language_info": {
|
| 163 |
+
"name": "python"
|
| 164 |
+
}
|
| 165 |
+
},
|
| 166 |
+
"nbformat": 4,
|
| 167 |
+
"nbformat_minor": 0
|
| 168 |
+
}
|