Intro to AI Stage 2 practical exam: 1038 dual-graded students, rubric, solutions (part 4)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- submissions_extracted/45/Q2.ipynb +273 -0
- submissions_extracted/45/Q3.ipynb +213 -0
- submissions_extracted/450/Q1.ipynb +329 -0
- submissions_extracted/450/Q2.ipynb +402 -0
- submissions_extracted/451/Q1.ipynb +449 -0
- submissions_extracted/451/Q2.ipynb +439 -0
- submissions_extracted/451/Q3.ipynb +441 -0
- submissions_extracted/452/Q1.ipynb +351 -0
- submissions_extracted/452/Q2.ipynb +403 -0
- submissions_extracted/452/Q3.ipynb +218 -0
- submissions_extracted/453/Q1.ipynb +338 -0
- submissions_extracted/453/Q2.ipynb +401 -0
- submissions_extracted/453/Q3.ipynb +284 -0
- submissions_extracted/454/Q1.ipynb +352 -0
- submissions_extracted/454/Q2.ipynb +374 -0
- submissions_extracted/454/Q3.ipynb +301 -0
- submissions_extracted/455/Q1.ipynb +429 -0
- submissions_extracted/455/Q2.ipynb +434 -0
- submissions_extracted/455/Q3.ipynb +341 -0
- submissions_extracted/456/Q1.ipynb +203 -0
- submissions_extracted/456/Q2.ipynb +431 -0
- submissions_extracted/456/Q3.ipynb +175 -0
- submissions_extracted/457/Q1.ipynb +338 -0
- submissions_extracted/457/Q2.ipynb +381 -0
- submissions_extracted/457/Q3.ipynb +194 -0
- submissions_extracted/458/Q1.ipynb +275 -0
- submissions_extracted/458/Q2.ipynb +372 -0
- submissions_extracted/459/Q1.ipynb +273 -0
- submissions_extracted/459/Q2.ipynb +332 -0
- submissions_extracted/459/Q3.ipynb +270 -0
- submissions_extracted/46/Q1.ipynb +206 -0
- submissions_extracted/46/Q2.ipynb +316 -0
- submissions_extracted/46/Q3.ipynb +177 -0
- submissions_extracted/460/Q1.ipynb +441 -0
- submissions_extracted/460/Q2.ipynb +439 -0
- submissions_extracted/460/Q3.ipynb +429 -0
- submissions_extracted/461/Q1.ipynb +229 -0
- submissions_extracted/461/Q2.ipynb +209 -0
- submissions_extracted/461/Q3.ipynb +183 -0
- submissions_extracted/462/Q1.ipynb +334 -0
- submissions_extracted/462/Q2.ipynb +312 -0
- submissions_extracted/462/Q3.ipynb +278 -0
- submissions_extracted/463/Q1.ipynb +224 -0
- submissions_extracted/463/Q2.ipynb +379 -0
- submissions_extracted/463/Q3.ipynb +212 -0
- submissions_extracted/464/Q1.ipynb +284 -0
- submissions_extracted/464/Q2.ipynb +382 -0
- submissions_extracted/464/Q3.ipynb +289 -0
- submissions_extracted/465/Q1.ipynb +266 -0
- submissions_extracted/465/Q2.ipynb +393 -0
submissions_extracted/45/Q2.ipynb
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"\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 |
+
"\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 |
+
"\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"\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}\")\n",
|
| 60 |
+
"import numpy as np\n",
|
| 61 |
+
"import torch\n",
|
| 62 |
+
"import torch.nn as nn\n",
|
| 63 |
+
"import torch.optim as optim\n",
|
| 64 |
+
"from torch.utils.data import DataLoader, TensorDataset"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"\n",
|
| 74 |
+
"X_tensor = torch.tensor(X, dtype=torch.float32)\n",
|
| 75 |
+
"y_tensor = torch.tensor(y, dtype=torch.long)\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"dataset = TensorDataset(X_tensor, y_tensor)\n",
|
| 79 |
+
"loader = DataLoader(dataset, batch_size=32, shuffle=True)\n",
|
| 80 |
+
"\n"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# 2. Create TensorDataset objects\n",
|
| 90 |
+
"X_tensor = torch.tensor(X, dtype=torch.float32)\n",
|
| 91 |
+
"y_tensor = torch.tensor(y, dtype=torch.long)\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 3. Create DataLoaders\n",
|
| 101 |
+
"dataset = TensorDataset(X_tensor, y_tensor)\n",
|
| 102 |
+
"loader = DataLoader(dataset, batch_size=32, shuffle=True)\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}\")"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# 5. Display sample images\n",
|
| 126 |
+
"\n"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 1: Write your model class here:\n",
|
| 136 |
+
"class HAR_Net(nn.Module):\n",
|
| 137 |
+
" def __init__(self, num_classes):\n",
|
| 138 |
+
" super(HAR_Net, self).__init__()\n",
|
| 139 |
+
"\n",
|
| 140 |
+
" # Layer 1: Convolution\n",
|
| 141 |
+
" self.conv1 = nn.Conv2d(\n",
|
| 142 |
+
" in_channels=X.shape[1], # عدد القنوات (WiFi channels)\n",
|
| 143 |
+
" out_channels=16,\n",
|
| 144 |
+
" kernel_size=3,\n",
|
| 145 |
+
" padding=1\n",
|
| 146 |
+
" )\n",
|
| 147 |
+
"\n",
|
| 148 |
+
" # Layer 2: Activation\n",
|
| 149 |
+
" self.relu = nn.ReLU()\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" # Layer 3: Pooling\n",
|
| 152 |
+
" self.pool = nn.MaxPool2d(2)\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" # Layer 4: Fully Connected\n",
|
| 155 |
+
" self.fc1 = nn.Linear(16 * (X.shape[2]//2) * (X.shape[3]//2), 64)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # Layer 5: Output Layer\n",
|
| 158 |
+
" self.fc2 = nn.Linear(64, num_classes)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" def forward(self, x):\n",
|
| 161 |
+
" x = self.conv1(x)\n",
|
| 162 |
+
" x = self.relu(x)\n",
|
| 163 |
+
" x = self.pool(x)\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" x = x.view(x.size(0), -1)\n",
|
| 166 |
+
" x = self.relu(self.fc1(x))\n",
|
| 167 |
+
" x = self.fc2(x)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" return x"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 2: Write your training loop here:\n"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 3: Write your validation loop here:"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 197 |
+
"num_classes = len(unique_labels)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"model = HAR_Net(num_classes)\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 202 |
+
"optimizer = optim.Adam(model.parameters(), lr=0.001)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"print(model)"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"epochs = 20\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"for epoch in range(epochs):\n",
|
| 218 |
+
" total_loss = 0\n",
|
| 219 |
+
" correct = 0\n",
|
| 220 |
+
" total = 0\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" for X_batch, y_batch in loader:\n",
|
| 223 |
+
" optimizer.zero_grad()\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" outputs = model(X_batch)\n",
|
| 226 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" loss.backward()\n",
|
| 229 |
+
" optimizer.step()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" total_loss += loss.item()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" _, predicted = torch.max(outputs, 1)\n",
|
| 234 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 235 |
+
" total += y_batch.size(0)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" accuracy = correct / total\n",
|
| 238 |
+
" print(f\"Epoch [{epoch+1}/{epochs}] | Loss: {total_loss:.4f} | Accuracy: {accuracy:.4f}\")"
|
| 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 (Bonus): Write your code here:"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
}
|
| 261 |
+
],
|
| 262 |
+
"metadata": {
|
| 263 |
+
"kernelspec": {
|
| 264 |
+
"display_name": "Python 3",
|
| 265 |
+
"name": "python3"
|
| 266 |
+
},
|
| 267 |
+
"language_info": {
|
| 268 |
+
"name": "python"
|
| 269 |
+
}
|
| 270 |
+
},
|
| 271 |
+
"nbformat": 4,
|
| 272 |
+
"nbformat_minor": 0
|
| 273 |
+
}
|
submissions_extracted/45/Q3.ipynb
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"import pandas as pd\n",
|
| 16 |
+
"import numpy as np\n",
|
| 17 |
+
"import matplotlib.pyplot as plt\n",
|
| 18 |
+
"import seaborn as sns\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
| 21 |
+
"from sklearn.model_selection import KFold\n",
|
| 22 |
+
"from sklearn.metrics import f1_score\n",
|
| 23 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 24 |
+
"from sklearn.dummy import DummyClassifier\n",
|
| 25 |
+
"from sklearn.ensemble import VotingClassifier, RandomForestClassifier\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 |
+
"df = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")"
|
| 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()"
|
| 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 = df.isnull().sum()\n",
|
| 77 |
+
"print(\"\\nMissing Values:\")\n",
|
| 78 |
+
"print(missing[missing > 0])"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 2: Write your code here:\n",
|
| 88 |
+
"def check_duplicates(df):\n",
|
| 89 |
+
" duplicates = df.duplicated().sum()\n",
|
| 90 |
+
" print(f\"Duplicate Samples: {duplicates}\")\n",
|
| 91 |
+
"\n",
|
| 92 |
+
" if duplicates > 0:\n",
|
| 93 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 94 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"check_duplicates(df)"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# Task 3: Write your code here:\n",
|
| 106 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 107 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"label_encoders = {}\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"for col in categorical_cols:\n",
|
| 114 |
+
" le = LabelEncoder()\n",
|
| 115 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 116 |
+
" label_encoders[col] = le\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"df.head()"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 4: Write your code here:\n",
|
| 128 |
+
"df.describe()\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"numerical_cols = (\n",
|
| 134 |
+
" df.select_dtypes(include=[\"int64\", \"float64\"])\n",
|
| 135 |
+
" .columns\n",
|
| 136 |
+
" .drop(\"P_2\")\n",
|
| 137 |
+
")\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"scaler = StandardScaler()\n",
|
| 140 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"df.head()"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 5: Write your code here:"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 1: Write your code here:"
|
| 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:"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 1: Write your code here:"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 2: Write your code here:"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task Bonus: Write your code here:"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
}
|
| 201 |
+
],
|
| 202 |
+
"metadata": {
|
| 203 |
+
"kernelspec": {
|
| 204 |
+
"display_name": "Python 3",
|
| 205 |
+
"name": "python3"
|
| 206 |
+
},
|
| 207 |
+
"language_info": {
|
| 208 |
+
"name": "python"
|
| 209 |
+
}
|
| 210 |
+
},
|
| 211 |
+
"nbformat": 4,
|
| 212 |
+
"nbformat_minor": 0
|
| 213 |
+
}
|
submissions_extracted/450/Q1.ipynb
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"#libraries\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 16 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 17 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 18 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"import warnings\n",
|
| 21 |
+
"warnings.filterwarnings('ignore')\n",
|
| 22 |
+
"\n"
|
| 23 |
+
],
|
| 24 |
+
"execution_count": null,
|
| 25 |
+
"outputs": []
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"import kagglehub\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"print(\"Path to dataset files:\", path)"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 1: Write your code here: 1. Read the dataset `Q1_data.csv` using `read_csv()`\n",
|
| 45 |
+
"dataset_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 46 |
+
"df_delivery = pd.read_csv(dataset_path)\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"print(f\"Dataset shape: {df_delivery.shape}\")\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 2: Write your code here: 2. Inspect the first few rows using `head()`\n",
|
| 58 |
+
"df_delivery.head()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 3: Write your code here:Display dataset information using info()\n",
|
| 68 |
+
"df_delivery.info()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 4: Write your code here:Show statistical description using describe()\n",
|
| 78 |
+
"df_delivery.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:Plot the target distribution (delivery_time)\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"df = pd.DataFrame(df_delivery)\n",
|
| 90 |
+
"plt.hist(df['Delivery_Time'], bins=4, color='blue')\n",
|
| 91 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 92 |
+
"plt.xlabel('Delivery Time')\n",
|
| 93 |
+
"plt.ylabel('Frequency')\n",
|
| 94 |
+
"plt.show()"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 1: Write your code here:\n",
|
| 104 |
+
"df_delivery.drop(['Order_ID'],axis =1)"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [],
|
| 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 |
+
"df.isna().sum()"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"#drop all of em\n",
|
| 131 |
+
"df_delivery.dropna(inplace=True)\n",
|
| 132 |
+
"\n"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"df_delivery.fillna(0, inplace=True)\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 4: Write your code here:\n",
|
| 151 |
+
"df_delivery.duplicated()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"df_delivery.drop_duplicates()"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 5: Write your code here: Encode categorical variables**\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"df_delivery = pd.get_dummies(df_delivery, columns=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type'], dtype=int) #makes sense to encode these because they're redundant\n"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# Task 6: Write your code here:\n",
|
| 188 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"scaler = StandardScaler()\n",
|
| 191 |
+
"X_train_scaled = scaler.fit_transform(df_delivery)\n"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"df_delivery.columns"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 1: Write your code here:\n",
|
| 210 |
+
"# Define features (X) and target (y)\n",
|
| 211 |
+
"feature_cols = ['Order_ID', 'Distance_km', 'Preparation_Time_min',\n",
|
| 212 |
+
" 'Courier_Experience_yrs', 'Delivery_Time', 'Weather_Clear',\n",
|
| 213 |
+
" 'Weather_Foggy', 'Weather_Rainy', 'Weather_Snowy', 'Weather_Windy',\n",
|
| 214 |
+
" 'Traffic_Level_High', 'Traffic_Level_Low', 'Traffic_Level_Medium',\n",
|
| 215 |
+
" 'Time_of_Day_Afternoon', 'Time_of_Day_Evening', 'Time_of_Day_Morning',\n",
|
| 216 |
+
" 'Time_of_Day_Night', 'Vehicle_Type_Bike', 'Vehicle_Type_Car',\n",
|
| 217 |
+
" 'Vehicle_Type_Scooter']\n",
|
| 218 |
+
"X = df_delivery[feature_cols]\n",
|
| 219 |
+
"y = df_delivery['Delivery_Time']\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 222 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.5, random_state=42)\n",
|
| 223 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=23, n_jobs=-1)\n",
|
| 233 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 234 |
+
"print(\"Model trained!\")"
|
| 235 |
+
],
|
| 236 |
+
"execution_count": null,
|
| 237 |
+
"outputs": []
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"cell_type": "code",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"source": [
|
| 243 |
+
"X.isnull().sum()"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"y.isnull().sum() #JUST CHECKING AN ERROR PLEASE WORK DAMN"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"mae_scores = []\n",
|
| 266 |
+
"rmse_scores = []\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"for train_idx, val_idx in kfold.split(X_train_scaled):\n",
|
| 269 |
+
" X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
|
| 270 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" # Train and predict\n",
|
| 273 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 274 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" # Calculate metrics\n",
|
| 277 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 278 |
+
" rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 281 |
+
"rmse_scores = np.array(rmse_scores)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 284 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
|
| 285 |
+
"print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
|
| 286 |
+
],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [
|
| 294 |
+
"# Task 1: Write your code here:"
|
| 295 |
+
],
|
| 296 |
+
"execution_count": null,
|
| 297 |
+
"outputs": []
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"cell_type": "code",
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"source": [
|
| 303 |
+
"# Task 2: Write your code here:"
|
| 304 |
+
],
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"outputs": []
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"cell_type": "code",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"# Task Bonus: Write your code here:"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
}
|
| 317 |
+
],
|
| 318 |
+
"metadata": {
|
| 319 |
+
"kernelspec": {
|
| 320 |
+
"display_name": "Python 3",
|
| 321 |
+
"name": "python3"
|
| 322 |
+
},
|
| 323 |
+
"language_info": {
|
| 324 |
+
"name": "python"
|
| 325 |
+
}
|
| 326 |
+
},
|
| 327 |
+
"nbformat": 4,
|
| 328 |
+
"nbformat_minor": 0
|
| 329 |
+
}
|
submissions_extracted/450/Q2.ipynb
ADDED
|
@@ -0,0 +1,402 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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",
|
| 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 |
+
"\n"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"\n",
|
| 86 |
+
"# transform to tensors\n",
|
| 87 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 88 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 89 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 90 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 93 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 94 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 95 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"# Access a single sample from the dataset\n",
|
| 98 |
+
"# This helps verify the shape of one data sample\n",
|
| 99 |
+
"first_sample, _ = train_dataset[0]\n",
|
| 100 |
+
"print(f\"Shape of one sample: {first_sample.shape}\")"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# 3. Create DataLoaders\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"from torch.utils.data import DataLoader\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"# DataLoader for training data\n",
|
| 114 |
+
"train_loader = DataLoader(\n",
|
| 115 |
+
" train_dataset,\n",
|
| 116 |
+
" batch_size=32,\n",
|
| 117 |
+
" shuffle=True,\n",
|
| 118 |
+
" num_workers=2\n",
|
| 119 |
+
")\n",
|
| 120 |
+
"# DataLoader for test/validation data\n",
|
| 121 |
+
"test_loader = DataLoader(\n",
|
| 122 |
+
" test_dataset,\n",
|
| 123 |
+
" batch_size=32,\n",
|
| 124 |
+
" shuffle=False,\n",
|
| 125 |
+
" num_workers=2\n",
|
| 126 |
+
")\n",
|
| 127 |
+
"# Get the first batch from the training DataLoader\n",
|
| 128 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 129 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 130 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 131 |
+
"\n"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"# 4. Print shape of one batch\n",
|
| 141 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 144 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"\n"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# 5. Display sample images\n",
|
| 156 |
+
"import matplotlib.pyplot as plt\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"plt.imshow(sample_image.permute(1, 2, 0))\n"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 1: Write your model class here:\n",
|
| 168 |
+
"class NN1Layer(nn.Module):\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" def __init__(self, input_dim):\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" super(NN1Layer, self).__init__()\n",
|
| 173 |
+
" # input_dim = num of features, Output for binary classification is 1\n",
|
| 174 |
+
" self.layer_1 = nn.Linear(input_dim, 1)\n",
|
| 175 |
+
" elf.layer_2 = nn.Linear(input_dim, 1)\n",
|
| 176 |
+
" elf.layer_3 = nn.Linear(input_dim, 1)\n",
|
| 177 |
+
" elf.layer_4 = nn.Linear(input_dim, 1)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # output activation function\n",
|
| 180 |
+
" self.sigmoid = nn.Sigmoid()\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # forward pass\n",
|
| 183 |
+
" def forward(self, x):\n",
|
| 184 |
+
" z = self.layer_1(x)\n",
|
| 185 |
+
" a = self.sigmoid(z)\n",
|
| 186 |
+
" return a"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "code",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": [],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 2: Write your training loop here:\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 205 |
+
" # Set the model to training mode\n",
|
| 206 |
+
" model.train()\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" running_loss = 0.0\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 211 |
+
" # Move batch to the selected device\n",
|
| 212 |
+
" X_batch = X_batch.to(device)\n",
|
| 213 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Forward pass\n",
|
| 216 |
+
" outputs = model(X_batch)\n",
|
| 217 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" # Backward pass & optimization\n",
|
| 220 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 221 |
+
" loss.backward() # Compute gradients\n",
|
| 222 |
+
" optimizer.step() # Update model parameters\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" running_loss += loss.item()\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Average loss over all batches\n",
|
| 227 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" return avg_loss"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Task 3: Write your validation loop here:\n",
|
| 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(): # Disable gradient computation\n",
|
| 248 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 249 |
+
" # Move batch to the selected device\n",
|
| 250 |
+
" X_batch = X_batch.to(device)\n",
|
| 251 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Forward pass\n",
|
| 254 |
+
" outputs = model(X_batch)\n",
|
| 255 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 256 |
+
" running_loss += loss.item()\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" # Binary predictions\n",
|
| 259 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" # Accuracy calculation\n",
|
| 262 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 263 |
+
" total += y_batch.size(0)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 266 |
+
" accuracy = correct / total\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" return avg_loss, accuracy\n"
|
| 269 |
+
],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"# Task 4: Define device, model, loss, optimize\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"\n",
|
| 280 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 281 |
+
" # Set the model to training mode\n",
|
| 282 |
+
" model.train()\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" running_loss = 0.0\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 287 |
+
" # Move batch to the selected device\n",
|
| 288 |
+
" X_batch = X_batch.to(device)\n",
|
| 289 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" # Forward pass\n",
|
| 292 |
+
" outputs = model(X_batch)\n",
|
| 293 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" # Backward pass & optimization\n",
|
| 296 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 297 |
+
" loss.backward() # Compute gradients\n",
|
| 298 |
+
" optimizer.step() # Update model parameters\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" running_loss += loss.item()\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" # Average loss over all batches\n",
|
| 303 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" return avg_loss"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# 1️⃣ Flatten - Convert any shape to (batch_size, features)\n",
|
| 315 |
+
"x = torch.randn(32, 3, 28, 28)\n",
|
| 316 |
+
"x_flat = x.flatten(start_dim=1)\n",
|
| 317 |
+
"print(\"Flatten:\", x_flat.shape) # (32, 2352)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"# 2️⃣ Squeeze - Remove dimensions with size 1\n",
|
| 320 |
+
"x = torch.randn(1, 3, 28, 28)\n",
|
| 321 |
+
"x_sq = x.squeeze()\n",
|
| 322 |
+
"print(\"Squeeze:\", x_sq.shape) # (3, 28, 28)\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# 3️⃣ Unsqueeze - Add a new dimension of size 1\n",
|
| 325 |
+
"x = torch.randn(3, 28, 28)\n",
|
| 326 |
+
"x_unsq = x.unsqueeze(0)\n",
|
| 327 |
+
"print(\"Unsqueeze:\", x_unsq.shape) # (1, 3, 28, 28)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# 4️⃣ View - Reshape freely while keeping same number of elements\n",
|
| 330 |
+
"x = torch.randn(32, 28, 28, 3)\n",
|
| 331 |
+
"x_view = x.view(32, -1) # Flatten all except batch\n",
|
| 332 |
+
"print(\"View:\", x_view.shape) # (32, 28*28*3)\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"#I used flatten here to fix the below error because it seems the propotions of the matrices are not good but for some reasons it doesn't work"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"# Task 5: Start training for 20 epochs:\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 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 365 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"print('Training Complete!')"
|
| 368 |
+
],
|
| 369 |
+
"execution_count": null,
|
| 370 |
+
"outputs": []
|
| 371 |
+
},
|
| 372 |
+
{
|
| 373 |
+
"cell_type": "code",
|
| 374 |
+
"metadata": {},
|
| 375 |
+
"source": [
|
| 376 |
+
"# Task 1: Write your code here:"
|
| 377 |
+
],
|
| 378 |
+
"execution_count": null,
|
| 379 |
+
"outputs": []
|
| 380 |
+
},
|
| 381 |
+
{
|
| 382 |
+
"cell_type": "code",
|
| 383 |
+
"metadata": {},
|
| 384 |
+
"source": [
|
| 385 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 386 |
+
],
|
| 387 |
+
"execution_count": null,
|
| 388 |
+
"outputs": []
|
| 389 |
+
}
|
| 390 |
+
],
|
| 391 |
+
"metadata": {
|
| 392 |
+
"kernelspec": {
|
| 393 |
+
"display_name": "Python 3",
|
| 394 |
+
"name": "python3"
|
| 395 |
+
},
|
| 396 |
+
"language_info": {
|
| 397 |
+
"name": "python"
|
| 398 |
+
}
|
| 399 |
+
},
|
| 400 |
+
"nbformat": 4,
|
| 401 |
+
"nbformat_minor": 0
|
| 402 |
+
}
|
submissions_extracted/451/Q1.ipynb
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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, StratifiedKFold, cross_val_score\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 16 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"import warnings"
|
| 19 |
+
],
|
| 20 |
+
"execution_count": null,
|
| 21 |
+
"outputs": []
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"source": [
|
| 27 |
+
"import kagglehub\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"# Download latest version\n",
|
| 30 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 31 |
+
"print(\"Path:\", path)"
|
| 32 |
+
],
|
| 33 |
+
"execution_count": null,
|
| 34 |
+
"outputs": []
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"# Task 1: Write your code here:\n",
|
| 41 |
+
"#read_csv()\n",
|
| 42 |
+
"p_path = os.path.join(path, 'q1-exam-data')\n"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 2: Write your code here:\n",
|
| 52 |
+
"p_path.head()\n",
|
| 53 |
+
"#head()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 3: Write your code here:\n",
|
| 63 |
+
"p_path.info()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 4: Write your code here:\n",
|
| 73 |
+
"p_path.describe()"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 5: Write your code here:\n",
|
| 83 |
+
"p_path.delivery_time"
|
| 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 |
+
"#Drop Order_ID\n",
|
| 94 |
+
"stat_cols = ['Order_ID']\n"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"\n",
|
| 104 |
+
"# Drop rows with missing stat values\n",
|
| 105 |
+
"df_clean =p_path.dropna(subset=stat_cols).copy()\n",
|
| 106 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# Task 2: Write your code here:\n",
|
| 116 |
+
"df_clean['type2'] = df_clean['type2'].fillna('none')\n",
|
| 117 |
+
"print(\"Missing values:\")\n",
|
| 118 |
+
"print(path.isnull().sum())"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 3: Write your code here:\n",
|
| 128 |
+
"print(\"Separating target variable and features\")\n",
|
| 129 |
+
"X = df.drop('class', axis=1)\n",
|
| 130 |
+
"y = df['class']\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"print(\"Applying Label Encoding to target variable 'y'\")\n",
|
| 133 |
+
"label_encoder = LabelEncoder()\n",
|
| 134 |
+
"y_encoded = label_encoder.fit_transform(y)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"print(\"Applying One-Hot Encoding to feature DataFrame 'X'\")\n",
|
| 137 |
+
"onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n",
|
| 138 |
+
"X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"print(\"Verification of encoded data shapes:\")\n",
|
| 141 |
+
"print(f\"Shape of X_encoded: {X_encoded.shape}\")\n",
|
| 142 |
+
"print(f\"Shape of y_encoded: {y_encoded.shape}\")\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"print(\"First 5 rows of X_encoded:\")\n",
|
| 145 |
+
"display(X_encoded.head())\n",
|
| 146 |
+
"print(\"First 5 elements of y_encoded:\")\n",
|
| 147 |
+
"print(y_encoded[:5])"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 4: Write your code here:\n",
|
| 157 |
+
"print(\"Checking for duplicate rows\")\n",
|
| 158 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 159 |
+
"if duplicate_rows > 0:\n",
|
| 160 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them\")\n",
|
| 161 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 162 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 163 |
+
"else:\n",
|
| 164 |
+
" print(\"No duplicate rows found.\")"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 5: Write your code here:\n",
|
| 174 |
+
"df_clean['age_x_miles_per_year'] = df_clean['miles_per_year'] * df_clean['age']\n"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task 6: Write your code here:\n",
|
| 184 |
+
"df_clean['cylinders'] = df_clean['cylinders'].fillna(df_clean['cylinders'].mode()[0])\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "code",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": [
|
| 195 |
+
"import numpy as np\n",
|
| 196 |
+
"import pandas as pd\n",
|
| 197 |
+
"import matplotlib.pyplot as plt\n",
|
| 198 |
+
"import os\n",
|
| 199 |
+
"import kagglehub\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 202 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 203 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 204 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"import warnings"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 1: Write your code here:\n",
|
| 216 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"mae_scores = []\n",
|
| 219 |
+
"rmse_scores = []\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"for train_idx, val_idx in kfold.split(X_train_scaled):\n",
|
| 222 |
+
" X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
|
| 223 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Train and predict\n",
|
| 226 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 227 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Calculate metrics\n",
|
| 230 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 231 |
+
" rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 234 |
+
"rmse_scores = np.array(rmse_scores)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 237 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
|
| 238 |
+
"print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"y_pred = model.predict(X_test_scaled)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 250 |
+
"rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"print(f\"MAE: ${mae:,.2f}\")\n",
|
| 253 |
+
"print(f\"RMSE: ${rmse:,.2f}\")"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n",
|
| 265 |
+
"X_train.head(4)\n",
|
| 266 |
+
"scaler = StandardScaler()\n",
|
| 267 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 268 |
+
"X_test_scaled = scaler.transform(X_test)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
|
| 271 |
+
"pd.DataFrame(X_train_scaled, columns=X_train.columns).head(4)\n",
|
| 272 |
+
"cm = confusion_matrix(y_test, y_pred)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# 5. For each model:\n",
|
| 275 |
+
"for model_name, model in models.items():\n",
|
| 276 |
+
" print(f\"\\nTraining and evaluating {model_name}...\")\n",
|
| 277 |
+
" fold_losses = []\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n",
|
| 280 |
+
" X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n",
|
| 281 |
+
" y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n",
|
| 282 |
+
"\n",
|
| 283 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 286 |
+
" y_val_one_hot = one_hot_encode(y_val_fold, num_classes)\n",
|
| 287 |
+
" loss = categorical_cross_entropy(y_val_one_hot, y_pred_proba)\n",
|
| 288 |
+
" fold_losses.append(loss)\n",
|
| 289 |
+
"\n",
|
| 290 |
+
" avg_loss = np.mean(fold_losses)\n",
|
| 291 |
+
" model_losses[model_name] = avg_loss\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"print(\"\\nAll models trained and evaluated. Stored average losses:\")\n",
|
| 296 |
+
"print(model_losses)"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"# Task 1: Write your code here:\n",
|
| 306 |
+
"model = RandomForestClassifier(n_estimators=101, max_depth=10,\n",
|
| 307 |
+
" class_weight='balanced', random_state=42)\n",
|
| 308 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 309 |
+
"print(\"Model trained!\")"
|
| 310 |
+
],
|
| 311 |
+
"execution_count": null,
|
| 312 |
+
"outputs": []
|
| 313 |
+
},
|
| 314 |
+
{
|
| 315 |
+
"cell_type": "code",
|
| 316 |
+
"metadata": {},
|
| 317 |
+
"source": [
|
| 318 |
+
"# Task 2: Write your code here:\n",
|
| 319 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 320 |
+
"plt.hist(p_path['attack'].dropna(), bins=30, edgecolor='black')\n",
|
| 321 |
+
"plt.title('Attack Distribution')\n",
|
| 322 |
+
"plt.xlabel('Attack')\n",
|
| 323 |
+
"plt.ylabel('Frequency')\n",
|
| 324 |
+
"plt.show()"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"cell_type": "code",
|
| 331 |
+
"metadata": {},
|
| 332 |
+
"source": [
|
| 333 |
+
"# Task Bonus: Write your code here:\n",
|
| 334 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 335 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 336 |
+
"print(\"Model trained!\")\n",
|
| 337 |
+
"from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"print(\"Regression Metrics\\n\" + \"-\"*30)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# Use previously generated random classification data\n",
|
| 342 |
+
"X, y = X_reg.copy(), y_reg.copy()\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"# Split ratio (80% train, 20% test)\n",
|
| 345 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y,test_size=0.2,random_state=42,shuffle=True)\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"# Train a regression model\n",
|
| 348 |
+
"reg_model = LinearRegression()\n",
|
| 349 |
+
"reg_model.fit(X_train, y_train)\n",
|
| 350 |
+
"y_pred = reg_model.predict(X_test)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"# Calculate metrics\n",
|
| 353 |
+
"mse = mean_squared_error(y_test, y_pred)\n",
|
| 354 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 355 |
+
"rmse = np.sqrt(mse)\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"print(\"MSE :\", mse)\n",
|
| 358 |
+
"print(\"MAE :\", mae)\n",
|
| 359 |
+
"print(\"RMSE:\", rmse)"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"print(\"Evaluating:\")\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"# Dictionary to store performance metrics\n",
|
| 371 |
+
"model_performance = {}\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"# Iterate through each trained model\n",
|
| 374 |
+
"for model_name, model in models.items():\n",
|
| 375 |
+
" print(f\"\\nEvaluating {model_name}...\")\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" # Make predictions on the test set (hard labels)\n",
|
| 378 |
+
" y_pred = model.predict(X_test)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
" # Calculate evaluation metrics\n",
|
| 381 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 382 |
+
" precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 383 |
+
" recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 384 |
+
" f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 385 |
+
"\n",
|
| 386 |
+
" # Store metrics\n",
|
| 387 |
+
" model_performance[model_name] = {\n",
|
| 388 |
+
" 'Accuracy': accuracy,\n",
|
| 389 |
+
" 'Precision': precision,\n",
|
| 390 |
+
" 'Recall': recall,\n",
|
| 391 |
+
" 'F1-Score': f1\n",
|
| 392 |
+
" }\n",
|
| 393 |
+
"\n",
|
| 394 |
+
" # Print metrics\n",
|
| 395 |
+
" print(f\" Accuracy: {accuracy:.4f}\")\n",
|
| 396 |
+
" print(f\" Precision: {precision:.4f}\")\n",
|
| 397 |
+
" print(f\" Recall: {recall:.4f}\")\n",
|
| 398 |
+
" print(f\" F1-Score: {f1:.4f}\")\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" # Generate and visualize Confusion Matrix\n",
|
| 401 |
+
" cm = confusion_matrix(y_test, y_pred)\n",
|
| 402 |
+
" plt.figure(figsize=(6, 5))\n",
|
| 403 |
+
" sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,\n",
|
| 404 |
+
" xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)\n",
|
| 405 |
+
" plt.title(f'Confusion Matrix for {model_name}')\n",
|
| 406 |
+
" plt.xlabel('Predicted Label')\n",
|
| 407 |
+
" plt.ylabel('True Label')\n",
|
| 408 |
+
" plt.show()\n",
|
| 409 |
+
"\n",
|
| 410 |
+
"print(\"\\nAll models evaluated.\")"
|
| 411 |
+
],
|
| 412 |
+
"execution_count": null,
|
| 413 |
+
"outputs": []
|
| 414 |
+
},
|
| 415 |
+
{
|
| 416 |
+
"cell_type": "code",
|
| 417 |
+
"metadata": {},
|
| 418 |
+
"source": [
|
| 419 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 420 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 421 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 422 |
+
" losses = []\n",
|
| 423 |
+
"\n",
|
| 424 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
|
| 425 |
+
" y_hat = np.dot(X, theta)\n",
|
| 426 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 427 |
+
" theta -= learning_rate * gradient\n",
|
| 428 |
+
"\n",
|
| 429 |
+
" loss = mean_squared_error(y, y_hat)\n",
|
| 430 |
+
" losses.append(loss)\n",
|
| 431 |
+
"\n",
|
| 432 |
+
" return theta, losses"
|
| 433 |
+
],
|
| 434 |
+
"execution_count": null,
|
| 435 |
+
"outputs": []
|
| 436 |
+
}
|
| 437 |
+
],
|
| 438 |
+
"metadata": {
|
| 439 |
+
"kernelspec": {
|
| 440 |
+
"display_name": "Python 3",
|
| 441 |
+
"name": "python3"
|
| 442 |
+
},
|
| 443 |
+
"language_info": {
|
| 444 |
+
"name": "python"
|
| 445 |
+
}
|
| 446 |
+
},
|
| 447 |
+
"nbformat": 4,
|
| 448 |
+
"nbformat_minor": 0
|
| 449 |
+
}
|
submissions_extracted/451/Q2.ipynb
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"from torchvision.datasets import CIFAR10\n",
|
| 69 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 70 |
+
"from torch.utils.data import DataLoader\n",
|
| 71 |
+
"import matplotlib.pyplot as plt\n",
|
| 72 |
+
"import torch.nn as nn\n",
|
| 73 |
+
"import torch.nn.functional as F\n",
|
| 74 |
+
"import torch\n",
|
| 75 |
+
"from torch.optim import AdamW"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 85 |
+
"x = torch.tensor([1.0, 2.0, 3.0])\n",
|
| 86 |
+
"y = torch.randn(3)\n",
|
| 87 |
+
"print(\"x:\", x)\n",
|
| 88 |
+
"print(\"y:\", y)\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"a = torch.tensor([1.0, 2.0, 3.0])\n",
|
| 92 |
+
"b = torch.tensor([4.0, 5.0, 6.0])\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"print(\"Addition:\", a + b)\n",
|
| 95 |
+
"print(\"Multiplication:\", a * b)\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"A = torch.randn(2, 3)\n",
|
| 98 |
+
"B = torch.randn(3, 2)\n",
|
| 99 |
+
"C = A @ B\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"print(\"Matrix multiplication result shape:\", C.shape)"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# 2. Create TensorDataset objects\n",
|
| 111 |
+
"train_dataset = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n",
|
| 112 |
+
"test_dataset = CIFAR10(root='./datasets', train=False, transform=to_tensor, download=True)\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 115 |
+
"print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n",
|
| 116 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 117 |
+
"\n"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# 3. Create DataLoaders\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
|
| 129 |
+
"test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
|
| 130 |
+
"\n"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# 4. Print shape of one batch\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 142 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 143 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# 5. Display sample images\n",
|
| 153 |
+
"images, labels = next(iter(train_loader))\n",
|
| 154 |
+
"\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 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" plt.imshow(img)\n",
|
| 163 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 164 |
+
" plt.axis('off')\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"plt.tight_layout()\n",
|
| 167 |
+
"plt.show()\n"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 1: Write your model class here:\n",
|
| 177 |
+
"class NN5Layer(nn.Module):\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 180 |
+
" super(NN5Layer, self).__init__()\n",
|
| 181 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 182 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 183 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 184 |
+
" self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" self.relu = nn.ReLU()\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" def forward(self, x):\n",
|
| 189 |
+
" # Layer 1: TODO\n",
|
| 190 |
+
" z1 = self.layer1(x)\n",
|
| 191 |
+
" a1 = self.relu(z1)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # Layer 2 TODO\n",
|
| 194 |
+
" z2 = self.layer2(a1)\n",
|
| 195 |
+
" a2 = self.relu(z2)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Layer 3 TODO\n",
|
| 198 |
+
" z3 = self.layer3(a2)\n",
|
| 199 |
+
" a3 = self.relu(z3)\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # Output layer TODO\n",
|
| 203 |
+
" z4 = self.layer5(a3)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" return z4"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 2: Write your training loop here:\n",
|
| 215 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 216 |
+
" model.train()\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" running_loss = 0.0\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 221 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 222 |
+
" y_batch = y_batch.to(device)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" outputs = model(X_batch)\n",
|
| 225 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" optimizer.zero_grad()\n",
|
| 228 |
+
" loss.backward()\n",
|
| 229 |
+
" optimizer.step()\n",
|
| 230 |
+
" running_loss += loss.item()\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" return avg_loss"
|
| 235 |
+
],
|
| 236 |
+
"execution_count": null,
|
| 237 |
+
"outputs": []
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"cell_type": "code",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"source": [
|
| 243 |
+
"# Task 3: Write your validation loop here:\n",
|
| 244 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 245 |
+
" # Set the model to evaluation mode\n",
|
| 246 |
+
" model.eval()\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" running_loss = 0.03\n",
|
| 249 |
+
" correct = 20\n",
|
| 250 |
+
" total = 20\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" with torch.no_grad():\n",
|
| 253 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 254 |
+
" # Move data to device\n",
|
| 255 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 256 |
+
" y_batch = y_batch.to(device)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" # Forward pass\n",
|
| 259 |
+
" # TODO: make predictions\n",
|
| 260 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 261 |
+
" # TODO: compute loss\n",
|
| 262 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 263 |
+
" running_loss += loss.item()\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 266 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # TODO: Multiclass predictions\n",
|
| 269 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # Accuracy calculation\n",
|
| 272 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 273 |
+
" total += y_batch.size(0)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 276 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 277 |
+
" accuracy = correct / total\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" return avg_loss, accuracy"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": []
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"source": [
|
| 288 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 289 |
+
"# Device s\n",
|
| 290 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"# Model\n",
|
| 293 |
+
"input_dim = 3 * 32 * 32\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"hidden_dim = 64\n",
|
| 296 |
+
"output_dim = 10\n",
|
| 297 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 298 |
+
"model = NN5Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# TODO: Print the model architecture\n",
|
| 301 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 302 |
+
"print(model)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 305 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 315 |
+
"num_epochs = 20\n",
|
| 316 |
+
"learning_rate = 0.001\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 319 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 320 |
+
],
|
| 321 |
+
"execution_count": null,
|
| 322 |
+
"outputs": []
|
| 323 |
+
},
|
| 324 |
+
{
|
| 325 |
+
"cell_type": "code",
|
| 326 |
+
"metadata": {},
|
| 327 |
+
"source": [
|
| 328 |
+
"# Task 1: Write your code here:\n",
|
| 329 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 330 |
+
" model.train()\n",
|
| 331 |
+
"\n",
|
| 332 |
+
" running_loss = 0.06\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 335 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 336 |
+
" y_batch = y_batch.to(device)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" outputs = model(X_batch)\n",
|
| 339 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
" optimizer.zero_grad()\n",
|
| 342 |
+
" loss.backward()\n",
|
| 343 |
+
" optimizer.step()\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" running_loss += loss.item()\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 348 |
+
"\n",
|
| 349 |
+
" return avg_loss"
|
| 350 |
+
],
|
| 351 |
+
"execution_count": null,
|
| 352 |
+
"outputs": []
|
| 353 |
+
},
|
| 354 |
+
{
|
| 355 |
+
"cell_type": "code",
|
| 356 |
+
"metadata": {},
|
| 357 |
+
"source": [
|
| 358 |
+
"#validation\n",
|
| 359 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 360 |
+
" model.eval()\n",
|
| 361 |
+
"\n",
|
| 362 |
+
" running_loss = 0.02\n",
|
| 363 |
+
" correct = 0.01\n",
|
| 364 |
+
" total = 20\n",
|
| 365 |
+
"\n",
|
| 366 |
+
" with torch.no_grad():\n",
|
| 367 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 368 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 369 |
+
" y_batch = y_batch.to(device)\n",
|
| 370 |
+
"\n",
|
| 371 |
+
" outputs = model(X_batch)\n",
|
| 372 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 373 |
+
" running_loss += loss.item()\n",
|
| 374 |
+
"\n",
|
| 375 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 376 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 377 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 378 |
+
" total += y_batch.size(20)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 381 |
+
" accuracy = correct / total\n",
|
| 382 |
+
"\n",
|
| 383 |
+
" return avg_loss, accuracy"
|
| 384 |
+
],
|
| 385 |
+
"execution_count": null,
|
| 386 |
+
"outputs": []
|
| 387 |
+
},
|
| 388 |
+
{
|
| 389 |
+
"cell_type": "code",
|
| 390 |
+
"metadata": {},
|
| 391 |
+
"source": [
|
| 392 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 393 |
+
"model.eval()\n",
|
| 394 |
+
"images, labels = next(iter(test_loader))\n",
|
| 395 |
+
"images = images.to(device)\n",
|
| 396 |
+
"labels = labels.to(device)"
|
| 397 |
+
],
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"outputs": []
|
| 400 |
+
},
|
| 401 |
+
{
|
| 402 |
+
"cell_type": "code",
|
| 403 |
+
"metadata": {},
|
| 404 |
+
"source": [
|
| 405 |
+
"with torch.no_grad():\n",
|
| 406 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 407 |
+
" predictions = torch.argmax(outputs, dim=1)\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"images = images.cpu()\n",
|
| 410 |
+
"labels = labels.cpu()\n",
|
| 411 |
+
"predictions = predictions.cpu()\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"# Plot first 6 predictions\n",
|
| 414 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 415 |
+
"for i in range(6):\n",
|
| 416 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 417 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 418 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 419 |
+
" plt.axis('off')\n",
|
| 420 |
+
"\n",
|
| 421 |
+
"plt.tight_layout()\n",
|
| 422 |
+
"plt.show()"
|
| 423 |
+
],
|
| 424 |
+
"execution_count": null,
|
| 425 |
+
"outputs": []
|
| 426 |
+
}
|
| 427 |
+
],
|
| 428 |
+
"metadata": {
|
| 429 |
+
"kernelspec": {
|
| 430 |
+
"display_name": "Python 3",
|
| 431 |
+
"name": "python3"
|
| 432 |
+
},
|
| 433 |
+
"language_info": {
|
| 434 |
+
"name": "python"
|
| 435 |
+
}
|
| 436 |
+
},
|
| 437 |
+
"nbformat": 4,
|
| 438 |
+
"nbformat_minor": 0
|
| 439 |
+
}
|
submissions_extracted/451/Q3.ipynb
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"from sklearn.model_selection import train_test_split, KFold, cross_val_score\n",
|
| 13 |
+
"from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
|
| 14 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
|
| 15 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 16 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 17 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 18 |
+
"from sklearn.svm import SVC"
|
| 19 |
+
],
|
| 20 |
+
"execution_count": null,
|
| 21 |
+
"outputs": []
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"metadata": {},
|
| 26 |
+
"source": [
|
| 27 |
+
"import kagglehub\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"# Download latest version\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(\"Path to dataset files:\", path)"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 1: Write your code here:\n",
|
| 47 |
+
"import os\n",
|
| 48 |
+
"csv_file_path = os.path.join(path, 'q3-exam-data')"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"df = pd.read_csv(csv_file_path)\n",
|
| 58 |
+
"df.head()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 2: Write your code here:\n",
|
| 68 |
+
"df.head()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 3: Write your code here:\n",
|
| 78 |
+
"df.info()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 4: Write your code here:\n",
|
| 88 |
+
"print(\"\\nDataFrame Description:\")\n",
|
| 89 |
+
"df.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 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 100 |
+
"print(df.isnull().sum())"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# Task 2: Write your code here:\n",
|
| 110 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 111 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 112 |
+
"if duplicate_rows > 0:\n",
|
| 113 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 114 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 115 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 116 |
+
"else:\n",
|
| 117 |
+
" print(\"No duplicate rows found.\")\n",
|
| 118 |
+
""
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 3: Write your code here:\n",
|
| 128 |
+
"print(\"\\nValue counts for the target variable 'class':\")\n",
|
| 129 |
+
"class_distribution = df['class'].value_counts()\n",
|
| 130 |
+
"print(class_distribution)"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 4: Write your code here:\n",
|
| 140 |
+
"df_clean[''] = - df_clean['']\n",
|
| 141 |
+
"df_clean[''] = df_clean[''] / (df_clean[''])\n",
|
| 142 |
+
"df_clean[''] = df_clean[''] * df_clean['']\n",
|
| 143 |
+
"\n"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 5: Write your code here:\n",
|
| 153 |
+
"print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n",
|
| 154 |
+
"X_train.head(3)"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 1: Write your code here:\n",
|
| 164 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 165 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # Get the train & test split for this fold\n",
|
| 168 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 169 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # Train & Validate Models\n",
|
| 172 |
+
" for model_name, model in models.items():\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" print(f\"Training {model_name}...\")\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Fit the model on train data\n",
|
| 177 |
+
" model.fit(X_train, y_train)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Use the model to predict the test data\n",
|
| 180 |
+
" y_pred = model.predict(X_test)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # Calculate evaluation metrics\n",
|
| 183 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 184 |
+
" f1 = f1_score(y_test, y_pred, average='macro')\n",
|
| 185 |
+
""
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"for model_name in results:\n",
|
| 197 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 198 |
+
" # Print the average of each evaluation metric across folds\n",
|
| 199 |
+
" print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n",
|
| 200 |
+
" print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")\n",
|
| 201 |
+
"baseline_pred = np.full_like(y, y.mean())\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"# Evaluate the baseline\n",
|
| 204 |
+
"baseline_mse = sklearn_mse(y, baseline_pred)\n",
|
| 205 |
+
"baseline_rmse = np.sqrt(baseline_mse)\n",
|
| 206 |
+
"baseline_r2 = r2_score(y, baseline_pred)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"print(f\"Baseline MSE (using mean target): {baseline_mse:.4f}\")\n",
|
| 209 |
+
"print(f\"Baseline RMSE (using mean target): {baseline_rmse:.4f}\")\n",
|
| 210 |
+
"print(f\"Baseline R2 (using mean target): {baseline_r2:.4f}\")\n",
|
| 211 |
+
"print(\"Linear Regression Results\")\n",
|
| 212 |
+
"print(f\" Average MSE: {np.mean(lr_mse):.4f}\")\n",
|
| 213 |
+
"print(f\" Average RMSE: {np.mean(lr_rmse):.4f}\")\n",
|
| 214 |
+
"print(f\" Average R2: {np.mean(lr_r2):.4f}\")"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 1: Write your code here:\n",
|
| 224 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 225 |
+
"importances = {}\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
|
| 228 |
+
"importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n",
|
| 229 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"# Create a 1x3 plot\n",
|
| 232 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 233 |
+
"axes = axes.flatten()\n",
|
| 234 |
+
"features = X.columns\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 237 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 238 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" ax = axes[i]\n",
|
| 241 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 242 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 243 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"plt.tight_layout()\n",
|
| 246 |
+
"plt.show()\n"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 2: Write your code here:\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"plt.tight_layout()\n",
|
| 258 |
+
"plt.show()"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"import pandas as pd\n",
|
| 268 |
+
"import numpy as np\n",
|
| 269 |
+
"import matplotlib.pyplot as plt\n",
|
| 270 |
+
"import seaborn as sns\n",
|
| 271 |
+
"import kagglehub\n",
|
| 272 |
+
"import os\n",
|
| 273 |
+
"from tqdm import tqdm\n",
|
| 274 |
+
"# Import models\n",
|
| 275 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 276 |
+
"from sklearn.svm import SVC\n",
|
| 277 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 278 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 279 |
+
"from xgboost import XGBClassifier\n"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": []
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"source": [
|
| 288 |
+
"from catboost import CatBoostClassifier"
|
| 289 |
+
],
|
| 290 |
+
"execution_count": null,
|
| 291 |
+
"outputs": []
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"cell_type": "code",
|
| 295 |
+
"metadata": {},
|
| 296 |
+
"source": [
|
| 297 |
+
"# Task Bonus: Write your code here:\n",
|
| 298 |
+
"sklearn_models = {\n",
|
| 299 |
+
" \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
|
| 300 |
+
" n_neighbors=3, # Number of neighbors to consider\n",
|
| 301 |
+
" ),\n",
|
| 302 |
+
" \"Support Vector Machine\": SVC(\n",
|
| 303 |
+
" kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
|
| 304 |
+
" C=0.75 # Regularization parameter\n",
|
| 305 |
+
" ),\n",
|
| 306 |
+
" \"Decision Tree\": DecisionTreeClassifier(\n",
|
| 307 |
+
" max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
|
| 308 |
+
" ),\n",
|
| 309 |
+
" \"Random Forest\": RandomForestClassifier(\n",
|
| 310 |
+
" n_estimators=320, # Number of trees\n",
|
| 311 |
+
" max_depth=4\n",
|
| 312 |
+
" ),\n",
|
| 313 |
+
" \"XGBoost\": XGBClassifier(\n",
|
| 314 |
+
" verbosity=0,\n",
|
| 315 |
+
" n_estimators=300, # Number of boosting rounds\n",
|
| 316 |
+
" max_depth=5,\n",
|
| 317 |
+
" learning_rate=0.05 # Step size shrinkage\n",
|
| 318 |
+
" ),\n",
|
| 319 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 320 |
+
" verbose=0,\n",
|
| 321 |
+
" n_estimators=320,\n",
|
| 322 |
+
" max_depth=4\n",
|
| 323 |
+
" )\n",
|
| 324 |
+
"}\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"all_results = {}\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"for name in sklearn_models:\n",
|
| 329 |
+
" all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
|
| 330 |
+
"\n",
|
| 331 |
+
""
|
| 332 |
+
],
|
| 333 |
+
"execution_count": null,
|
| 334 |
+
"outputs": []
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"cell_type": "code",
|
| 338 |
+
"metadata": {},
|
| 339 |
+
"source": [
|
| 340 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 341 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" # 1. Split data\n",
|
| 344 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 345 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" # 2. Train & Validate sklearn models\n",
|
| 348 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 349 |
+
" print(f\"Training {model_name}...\")\n",
|
| 350 |
+
" model.fit(X_train, y_train) # train\n",
|
| 351 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 354 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 355 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 356 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 357 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 360 |
+
" all_results[model_name]['precision'].append(precision)\n",
|
| 361 |
+
" all_results[model_name]['recall'].append(recall)\n",
|
| 362 |
+
" all_results[model_name]['f1'].append(f1)"
|
| 363 |
+
],
|
| 364 |
+
"execution_count": null,
|
| 365 |
+
"outputs": []
|
| 366 |
+
},
|
| 367 |
+
{
|
| 368 |
+
"cell_type": "code",
|
| 369 |
+
"metadata": {},
|
| 370 |
+
"source": [
|
| 371 |
+
"class NN5Layer(nn.Module):\n",
|
| 372 |
+
"\n",
|
| 373 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 374 |
+
" super(NN5Layer, self).__init__()\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 377 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 378 |
+
"\n",
|
| 379 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 380 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 383 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 384 |
+
"\n",
|
| 385 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 386 |
+
" self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n",
|
| 389 |
+
" self.layer5 = nn.Linear(hidden_dim, output_dim)\n",
|
| 390 |
+
"\n",
|
| 391 |
+
" # activation function for non-linearity\n",
|
| 392 |
+
" self.relu = nn.ReLU()\n",
|
| 393 |
+
"\n",
|
| 394 |
+
" # Defines how input data flows through the network\n",
|
| 395 |
+
" def forward(self, x):\n",
|
| 396 |
+
" # Layer 1: TODO\n",
|
| 397 |
+
" z1 = self.layer1(x)\n",
|
| 398 |
+
" a1 = self.relu(z1)\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" # Layer 2 TODO\n",
|
| 401 |
+
" z2 = self.layer2(a1)\n",
|
| 402 |
+
" a2 = self.relu(z2)\n",
|
| 403 |
+
"\n",
|
| 404 |
+
" # Layer 3 TODO\n",
|
| 405 |
+
" z3 = self.layer3(a2)\n",
|
| 406 |
+
" a3 = self.relu(z3)\n",
|
| 407 |
+
"\n",
|
| 408 |
+
" # Layer 4 TODO\n",
|
| 409 |
+
" z4 = self.layer4(a3)\n",
|
| 410 |
+
" a4 = self.relu(z4)\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" # Output layer TODO\n",
|
| 413 |
+
" z5 = self.layer5(a4)\n",
|
| 414 |
+
"\n",
|
| 415 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 416 |
+
"\n",
|
| 417 |
+
" return z5"
|
| 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/452/Q1.ipynb
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"import numpy as np\n",
|
| 29 |
+
"import pandas as pd\n",
|
| 30 |
+
"import matplotlib.pyplot as plt\n",
|
| 31 |
+
"import os\n",
|
| 32 |
+
"import kagglehub\n",
|
| 33 |
+
"import seaborn as sns\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score, KFold\n",
|
| 37 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 38 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 39 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, ConfusionMatrixDisplay\n",
|
| 40 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 41 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 42 |
+
"from sklearn.decomposition import PCA\n",
|
| 43 |
+
"from sklearn.manifold import TSNE\n",
|
| 44 |
+
"from sklearn.cluster import KMeans\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 47 |
+
"from sklearn.svm import SVR\n",
|
| 48 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 49 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 50 |
+
"from lightgbm import LGBMRegressor\n",
|
| 51 |
+
"# from catboost import CatBoostRegressor\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"import torch\n",
|
| 54 |
+
"from torch.utils.data import TensorDataset\n",
|
| 55 |
+
"from torch.utils.data import DataLoader\n",
|
| 56 |
+
"import torch.nn as nn\n",
|
| 57 |
+
"from torch.optim import AdamW\n",
|
| 58 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 59 |
+
"import torch.nn.functional as F\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"\n"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"# Task 1: Write your code here:\n",
|
| 71 |
+
"df= pd.read_csv(path+'/Q1_data.csv')\n",
|
| 72 |
+
"df"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 2: Write your code here:\n",
|
| 82 |
+
"df.head()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 3: Write your code here:\n",
|
| 92 |
+
"df.info()"
|
| 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 |
+
"df.describe()"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 5: Write your code here:\n",
|
| 112 |
+
"# Plot the target distribution (delivery_time)\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"df.head()"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 1: Write your code here:\n",
|
| 131 |
+
"df.drop('Order_ID', axis= 1, inplace= True)\n",
|
| 132 |
+
"df"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# Task 2: Write your code here:\n",
|
| 142 |
+
"#filling num cols\n",
|
| 143 |
+
"num_col= df.select_dtypes(np.number).columns\n",
|
| 144 |
+
"df[num_col]= df[num_col].apply(lambda x: x.fillna(x.mean))\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"#filling cat col\n",
|
| 147 |
+
"cat_col= df.select_dtypes(include= ['object']).columns\n",
|
| 148 |
+
"df[cat_col]= df[cat_col].apply(lambda x: x.fillna('none'))\n",
|
| 149 |
+
"df.isnull().sum()"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 3: Write your code here:\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# def check_duplicates(df):\n",
|
| 161 |
+
"# duplicates = df.duplicated().sum()\n",
|
| 162 |
+
"# print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 163 |
+
"# if duplicates > 0:\n",
|
| 164 |
+
"# print(\"Dropping Duplicates...\")\n",
|
| 165 |
+
"# df.drop_duplicates(inplace=True)\n",
|
| 166 |
+
"# print(\"Duplicates Dropped.\")\n",
|
| 167 |
+
"# else:\n",
|
| 168 |
+
"# print(\"No Duplicate Samples Found.\")\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"# df= check_duplicates(df)"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# df['Delivery_Time']= df['Delivery_Time'].tofloat()\n",
|
| 180 |
+
"# df['Courier_Experience_yrs']= df['Courier_Experience_yrs'].astype('float32')\n",
|
| 181 |
+
"# df.select_dtypes(include= ['object']).columns"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 191 |
+
"categorical_cols"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"# Task 4: Write your code here:\n",
|
| 201 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 202 |
+
"categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"label_encoders = {}\n",
|
| 205 |
+
"for col in categorical_cols:\n",
|
| 206 |
+
" le = LabelEncoder()\n",
|
| 207 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 208 |
+
" label_encoders[col] = le\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"df"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"X= df.drop('Delivery_Time', axis =1)\n",
|
| 220 |
+
"y= df['Delivery_Time']\n",
|
| 221 |
+
"out = pd.Series\n",
|
| 222 |
+
"for i in range(y.shape[0]):\n",
|
| 223 |
+
" out= y[i]\n",
|
| 224 |
+
"print(type(out))"
|
| 225 |
+
],
|
| 226 |
+
"execution_count": null,
|
| 227 |
+
"outputs": []
|
| 228 |
+
},
|
| 229 |
+
{
|
| 230 |
+
"cell_type": "code",
|
| 231 |
+
"metadata": {},
|
| 232 |
+
"source": [
|
| 233 |
+
"# Task 5: Write your code here:\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"#split first\n",
|
| 238 |
+
"X_train ,X_test, y_train, y_test= train_test_split(X, y, random_state= 42, test_size=0.2)\n",
|
| 239 |
+
"scaler = StandardScaler()\n",
|
| 240 |
+
"# X_train_scaled = scaler.fit_transform(X_train[X_train.select_dtypes(include= np.number)])\n",
|
| 241 |
+
"# X_test_scaled = scaler.transform(X_test)\n",
|
| 242 |
+
"\n"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "code",
|
| 249 |
+
"metadata": {},
|
| 250 |
+
"source": [
|
| 251 |
+
"# Task 6: Write your code here:\n"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"# X_train['Preparation_Time_min']= X_train['Preparation_Time_min'].astype('float32')"
|
| 261 |
+
],
|
| 262 |
+
"execution_count": null,
|
| 263 |
+
"outputs": []
|
| 264 |
+
},
|
| 265 |
+
{
|
| 266 |
+
"cell_type": "code",
|
| 267 |
+
"metadata": {},
|
| 268 |
+
"source": [
|
| 269 |
+
"# Task 1: Write your code here:\n",
|
| 270 |
+
"X= df.drop('Delivery_Time', axis =1)\n",
|
| 271 |
+
"y= df['Delivery_Time']\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"n_splits= 5\n",
|
| 275 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"\n"
|
| 278 |
+
],
|
| 279 |
+
"execution_count": null,
|
| 280 |
+
"outputs": []
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"cell_type": "code",
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"source": [
|
| 286 |
+
"X.info()"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
" # Task 2,3,4,5: Write your code here:\n",
|
| 296 |
+
"model = Ridge(alpha=1.0, max_iter=10000)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 299 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 300 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 301 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" model.fit(X_train, y_train)\n",
|
| 304 |
+
" y_pred = model.predict(X_test)\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" print(f\"Accuracy: {mean_absolute_error(y_test, y_pred):.4f}\")\n",
|
| 307 |
+
"\n"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task 1: Write your code here:"
|
| 317 |
+
],
|
| 318 |
+
"execution_count": null,
|
| 319 |
+
"outputs": []
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"cell_type": "code",
|
| 323 |
+
"metadata": {},
|
| 324 |
+
"source": [
|
| 325 |
+
"# Task 2: Write your code here:"
|
| 326 |
+
],
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"outputs": []
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"cell_type": "code",
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"source": [
|
| 334 |
+
"# Task Bonus: Write your code here:"
|
| 335 |
+
],
|
| 336 |
+
"execution_count": null,
|
| 337 |
+
"outputs": []
|
| 338 |
+
}
|
| 339 |
+
],
|
| 340 |
+
"metadata": {
|
| 341 |
+
"kernelspec": {
|
| 342 |
+
"display_name": "Python 3",
|
| 343 |
+
"name": "python3"
|
| 344 |
+
},
|
| 345 |
+
"language_info": {
|
| 346 |
+
"name": "python"
|
| 347 |
+
}
|
| 348 |
+
},
|
| 349 |
+
"nbformat": 4,
|
| 350 |
+
"nbformat_minor": 0
|
| 351 |
+
}
|
submissions_extracted/452/Q2.ipynb
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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11 |
+
"import os\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"import seaborn as sns\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score, KFold\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, ConfusionMatrixDisplay\n",
|
| 20 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 21 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 22 |
+
"from sklearn.decomposition import PCA\n",
|
| 23 |
+
"from sklearn.manifold import TSNE\n",
|
| 24 |
+
"from sklearn.cluster import KMeans\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"import torch\n",
|
| 28 |
+
"from torch.utils.data import TensorDataset\n",
|
| 29 |
+
"from torch.utils.data import DataLoader\n",
|
| 30 |
+
"import torch.nn as nn\n",
|
| 31 |
+
"from torch.optim import AdamW\n",
|
| 32 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 33 |
+
"import torch.nn.functional as F\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"\n"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"import kagglehub\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"# Download latest version\n",
|
| 47 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"print(\"Path to dataset files:\", path)"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"import os\n",
|
| 59 |
+
"import pandas as pd\n",
|
| 60 |
+
"import numpy as np\n",
|
| 61 |
+
"from PIL import Image\n",
|
| 62 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"# Load Labels\n",
|
| 65 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 66 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 67 |
+
"\n",
|
| 68 |
+
"images = []\n",
|
| 69 |
+
"ages = []\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"# Load Images and Resize\n",
|
| 72 |
+
"print(\"Loading images...\")\n",
|
| 73 |
+
"for index, row in labels_df.iterrows():\n",
|
| 74 |
+
" img_name = row.iloc[0]\n",
|
| 75 |
+
" age = row.iloc[1]\n",
|
| 76 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 77 |
+
"\n",
|
| 78 |
+
" if os.path.exists(img_path):\n",
|
| 79 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 80 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 81 |
+
" images.append(img_array)\n",
|
| 82 |
+
" ages.append(age)\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"X = np.array(images)\n",
|
| 85 |
+
"y = np.array(ages)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 88 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"# Split Data\n",
|
| 91 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 94 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 95 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 96 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 108 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 109 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 110 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# 2. Create TensorDataset objects\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"train_dataset = TensorDataset(X_train, y_train) # <Replace None with your code>\n",
|
| 124 |
+
"test_dataset = TensorDataset(X_test, y_test) # <Replace None with your code>\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# 3. Create DataLoaders\n",
|
| 134 |
+
"train_loader = DataLoader(train_dataset, batch_size= 32, shuffle= True)\n",
|
| 135 |
+
"test_loader = DataLoader(test_dataset, batch_size= 32, shuffle= False)\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"\n"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# 4. Print shape of one batch\n",
|
| 147 |
+
"for X_batch, y_batch in train_loader:\n",
|
| 148 |
+
" print(X_batch.shape)\n"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# 5. Display sample images\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"\n"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"class NN4Layer(nn.Module):\n",
|
| 169 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 170 |
+
" super(NN4Layer, self).__init__()\n",
|
| 171 |
+
" # TODO: Define the first linear layer: input_dim -> hidden_dim\n",
|
| 172 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim) # <Replace None with your code>\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" # TODO: Define the second linear layer: hidden_dim -> hidden_dim\n",
|
| 175 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim) # <Replace None with your code>\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # TODO: Define the output layer: hidden_dim -> 1 (single value for regression)\n",
|
| 178 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim) # <Replace None with your code>\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # TODO: Define ReLU activation\n",
|
| 183 |
+
" self.relu = nn.ReLU() # <Replace None with your code>\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" def forward(self, x):\n",
|
| 186 |
+
" # TODO: First hidden layer with ReLU\n",
|
| 187 |
+
" a1 = self.relu(self.layer1(x)) # <Replace None with your code>\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # TODO: Second hidden layer with ReLU\n",
|
| 190 |
+
" a2 = self.relu(self.layer2(a1)) # <Replace None with your code>\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" output = self.layer4(a3)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" return output"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"# pay extra special for to device and view of batches\n",
|
| 208 |
+
"# when y is only one columns reshape\n",
|
| 209 |
+
"# when x is an image reshape (flatten)\n",
|
| 210 |
+
"# this is for x: X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 211 |
+
"# this is for y: y_batch = y_batch.view(-1,1).to(device)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 216 |
+
" # TODO: Set the model to training mode\n",
|
| 217 |
+
" # <YOUR CODE HERE>\n",
|
| 218 |
+
" model.train()\n",
|
| 219 |
+
" running_loss = 0.0\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 222 |
+
" # TODO: Move batch to the selected device\n",
|
| 223 |
+
" X_batch = X_batch = X_batch.view(X_batch.size(0), -1).to(device) # <Replace None with your code>\n",
|
| 224 |
+
" y_batch = y_batch.view(-1,1).to(device) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # TODO: Forward pass - get model predictions\n",
|
| 227 |
+
" outputs = model(X_batch) # <Replace None with your code>\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # TODO: Compute loss using criterion\n",
|
| 230 |
+
" loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # TODO: Backward pass & optimization\n",
|
| 233 |
+
" # Step 1: Clear previous gradients\n",
|
| 234 |
+
" # <YOUR CODE HERE>\n",
|
| 235 |
+
" optimizer.zero_grad()\n",
|
| 236 |
+
" # Step 2: Compute gradients (backward pass)\n",
|
| 237 |
+
" # <YOUR CODE HERE>\n",
|
| 238 |
+
" loss.backward()\n",
|
| 239 |
+
" # Step 3: Update model parameters\n",
|
| 240 |
+
" # <YOUR CODE HERE>\n",
|
| 241 |
+
" optimizer.step()\n",
|
| 242 |
+
" running_loss += loss.item()\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" # Calculate average loss over all batches\n",
|
| 245 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" return avg_loss"
|
| 248 |
+
],
|
| 249 |
+
"execution_count": null,
|
| 250 |
+
"outputs": []
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"# Task 3: Write your validation loop here:\n",
|
| 257 |
+
"# pay extra special for to device and view of batches\n",
|
| 258 |
+
"# when y is only one columns reshape\n",
|
| 259 |
+
"# when x is an image reshape (flatten)\n",
|
| 260 |
+
"# this is for x: X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 261 |
+
"# this is for y: y_batch = y_batch.view(-1,1).to(device)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 266 |
+
" # TODO: Set the model to evaluation mode\n",
|
| 267 |
+
" # <YOUR CODE HERE>\n",
|
| 268 |
+
" model.eval()\n",
|
| 269 |
+
" running_loss = 0.0\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # TODO: Disable gradient computation using torch.no_grad()\n",
|
| 272 |
+
" with torch.no_grad():\n",
|
| 273 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 274 |
+
" # TODO: Move data to device\n",
|
| 275 |
+
" X_batch = X_batch = X_batch.view(X_batch.size(0), -1).to(device) # <Replace None with your code>\n",
|
| 276 |
+
" y_batch = y_batch.view(-1,1).to(device) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # TODO: Forward pass - get model predictions\n",
|
| 279 |
+
" outputs = model(X_batch) # <Replace None with your code>\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" # TODO: Compute loss using criterion\n",
|
| 282 |
+
" loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" running_loss += loss.item()\n",
|
| 285 |
+
"\n",
|
| 286 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" return avg_loss"
|
| 290 |
+
],
|
| 291 |
+
"execution_count": null,
|
| 292 |
+
"outputs": []
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"cell_type": "code",
|
| 296 |
+
"metadata": {},
|
| 297 |
+
"source": [
|
| 298 |
+
"device = torch.device(\"cuda\" + \":0\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"s, c, x, y= X_batch.shape # if its an image\n",
|
| 301 |
+
"# Model parameters\n",
|
| 302 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 303 |
+
"input_dim = c*x*y# <YOUR CODE HERE>\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# TODO: choose number of hidden neurons\n",
|
| 306 |
+
"hidden_dim = 20# <YOUR CODE HERE>\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# TODO: what are the number of classes ?\n",
|
| 309 |
+
"output_dim = 1# <YOUR CODE HERE>\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 312 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)# <YOUR CODE HERE>.to(device)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# TODO: Print the model architecture\n",
|
| 315 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 316 |
+
"print(model)# <YOUR CODE HERE>)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# Calculate the total number of trainable parameters\n",
|
| 319 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 320 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"num_epochs = 20# <YOUR CODE HERE>\n",
|
| 323 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 324 |
+
"learning_rate = 0.0001# <YOUR CODE HERE>\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 327 |
+
"criterion = nn.MSELoss()# <YOUR CODE HERE>\n",
|
| 328 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 329 |
+
"optimizer = AdamW(model.parameters(), learning_rate)# <YOUR CODE HERE>, # <YOUR CODE HERE>)"
|
| 330 |
+
],
|
| 331 |
+
"execution_count": null,
|
| 332 |
+
"outputs": []
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"cell_type": "code",
|
| 336 |
+
"metadata": {},
|
| 337 |
+
"source": [
|
| 338 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 339 |
+
"train_losses = []\n",
|
| 340 |
+
"val_losses = []\n",
|
| 341 |
+
"val_accuracies = []\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"print('Starting Training...')\n",
|
| 344 |
+
"for epoch in range(num_epochs):\n",
|
| 345 |
+
" # Train one epoch\n",
|
| 346 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" # Validate\n",
|
| 349 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" train_losses.append(train_loss)\n",
|
| 352 |
+
" val_losses.append(val_loss)\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"\n",
|
| 355 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"print('Training Complete!')\n"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
},
|
| 362 |
+
{
|
| 363 |
+
"cell_type": "code",
|
| 364 |
+
"metadata": {},
|
| 365 |
+
"source": [
|
| 366 |
+
"# Task 1: Write your code here:\n",
|
| 367 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 370 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 371 |
+
"plt.title('Loss over Epochs')\n",
|
| 372 |
+
"plt.xlabel('Epoch')\n",
|
| 373 |
+
"plt.ylabel('Loss')\n",
|
| 374 |
+
"plt.legend()\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"plt.tight_layout()\n",
|
| 377 |
+
"plt.show()"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
},
|
| 382 |
+
{
|
| 383 |
+
"cell_type": "code",
|
| 384 |
+
"metadata": {},
|
| 385 |
+
"source": [
|
| 386 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 387 |
+
],
|
| 388 |
+
"execution_count": null,
|
| 389 |
+
"outputs": []
|
| 390 |
+
}
|
| 391 |
+
],
|
| 392 |
+
"metadata": {
|
| 393 |
+
"kernelspec": {
|
| 394 |
+
"display_name": "Python 3",
|
| 395 |
+
"name": "python3"
|
| 396 |
+
},
|
| 397 |
+
"language_info": {
|
| 398 |
+
"name": "python"
|
| 399 |
+
}
|
| 400 |
+
},
|
| 401 |
+
"nbformat": 4,
|
| 402 |
+
"nbformat_minor": 0
|
| 403 |
+
}
|
submissions_extracted/452/Q3.ipynb
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"import seaborn as sns\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score, KFold\n",
|
| 18 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 19 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 20 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, ConfusionMatrixDisplay\n",
|
| 21 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 22 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 23 |
+
"from sklearn.decomposition import PCA\n",
|
| 24 |
+
"from sklearn.manifold import TSNE\n",
|
| 25 |
+
"from sklearn.cluster import KMeans\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"import torch\n",
|
| 29 |
+
"from torch.utils.data import TensorDataset\n",
|
| 30 |
+
"from torch.utils.data import DataLoader\n",
|
| 31 |
+
"import torch.nn as nn\n",
|
| 32 |
+
"from torch.optim import AdamW\n",
|
| 33 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 34 |
+
"import torch.nn.functional as F\n"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"import kagglehub\n",
|
| 44 |
+
"\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"# Download latest version\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"print(\"Path to dataset files:\", path)"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 1: Write your code here:\n",
|
| 63 |
+
"df= pd.read_csv(path+'/Q3_data.csv')\n"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 2: Write your code here:\n",
|
| 73 |
+
"df.head()"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 3: Write your code here:\n",
|
| 83 |
+
"df.info()"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 4: Write your code here:\n",
|
| 93 |
+
"df.describe()"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 1: Write your code here:\n",
|
| 103 |
+
"df= df.apply(lambda x: x.fillna(x.mean))\n",
|
| 104 |
+
"df.isnull().sum()"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 2: Write your code here:"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# Task 3: Write your code here:"
|
| 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 |
+
"# scale= StandardScaler()\n",
|
| 133 |
+
"# df= scale.fitsform(df_tran)"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 5: Write your code here:"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 1: Write your code here:\n",
|
| 152 |
+
"n_splits= 5\n",
|
| 153 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 154 |
+
"\n"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 164 |
+
"model = RandomForestClassifier(n_estimators= 100, max_depth= 15,class_weight= 'balanced', random_state= 42)\n",
|
| 165 |
+
"X= df\n",
|
| 166 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 167 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 168 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" model.fit(X_train, y_train)\n",
|
| 171 |
+
" y_pred = model.predict(X_test)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" print(f\"Accuracy: {mean_absolute_error(y_test, y_pred):.4f}\")\n",
|
| 174 |
+
" print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))"
|
| 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/453/Q1.ipynb
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
"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 |
+
"\n",
|
| 20 |
+
"# Download latest version\n",
|
| 21 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-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 |
+
"# Task 1: Write your code here:\n",
|
| 33 |
+
"#Read the dataset Q1_data.csv using read_csv()\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"food_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 36 |
+
"df_food = pd.read_csv(food_path)"
|
| 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 |
+
"#Inspect the first few rows using head()\n",
|
| 47 |
+
"df_food.head()"
|
| 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 |
+
"#Display dataset information using info()\n",
|
| 58 |
+
"df_food.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 |
+
"#Show statistical description using describe()\n",
|
| 69 |
+
"df_food.describe()"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 5: Write your code here:\n",
|
| 79 |
+
"# Plot the target distribution (delivery_time)\n",
|
| 80 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 81 |
+
"plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 82 |
+
"plt.title('Price Distribution')\n",
|
| 83 |
+
"plt.xlabel('Time')\n",
|
| 84 |
+
"plt.ylabel('Frequency')\n",
|
| 85 |
+
"plt.show()"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 1: Write your code here:\n",
|
| 95 |
+
"#Drop the 'Order_ID' column from the data\n",
|
| 96 |
+
"aim = 'Order_ID'\n",
|
| 97 |
+
"df_food = df_food.drop(aim, axis=1)"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 2: Write your code here:\n",
|
| 107 |
+
"#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"# Analyze missing values\n",
|
| 110 |
+
"missing_percentage = (df_food.isnull().sum() / len(df_food)) * 100\n",
|
| 111 |
+
"missing_data = pd.DataFrame({\n",
|
| 112 |
+
" 'Column': missing_percentage.index,\n",
|
| 113 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 114 |
+
"})\n",
|
| 115 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 118 |
+
"missing_data.head(10)\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Since we have missing values we need to deal with them below-->\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"df_clean = df_food.copy()\n",
|
| 123 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 124 |
+
"df_clean = df_clean.dropna(subset=['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n",
|
| 125 |
+
"print(f\"After dropping missing: {df_clean.shape}\")\n"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 3: Write your code here:\n",
|
| 135 |
+
"#Check and remove duplicates if any exist\n",
|
| 136 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 137 |
+
"duplicate_rows = df_clean.duplicated().sum()\n",
|
| 138 |
+
"if duplicate_rows > 0:\n",
|
| 139 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 140 |
+
" df_clean.drop_duplicates(inplace=True)\n",
|
| 141 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 142 |
+
"else:\n",
|
| 143 |
+
" print(\"No duplicate rows found.\")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 146 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 147 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"# Fill cylinders with mode - discrete feature, mode is most representative\n",
|
| 150 |
+
"df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mode()[0])\n",
|
| 151 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
|
| 154 |
+
],
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"outputs": []
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"source": [
|
| 162 |
+
"# Task 4: Write your code here:\n",
|
| 163 |
+
"#Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
|
| 164 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 165 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# They are: Weather\tTraffic_Level\tTime_of_Day\tVehicle_Type\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"label_encoder = LabelEncoder() # Instantiate LabelEncoder\n",
|
| 171 |
+
"df_clean[\"Weather\"] = label_encoder.fit_transform(df_clean[\"Weather\"])\n",
|
| 172 |
+
"df_clean[\"Traffic_Level\"] = label_encoder.fit_transform(df_clean[\"Traffic_Level\"])\n",
|
| 173 |
+
"df_clean[\"Time_of_Day\"] = label_encoder.fit_transform(df_clean[\"Time_of_Day\"])\n",
|
| 174 |
+
"df_clean[\"Vehicle_Type\"] = label_encoder.fit_transform(df_clean[\"Vehicle_Type\"])\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"print('\\nData after encoding:\\n', df_clean[\"Weather\"]) #show after encoding"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 5: Write your code here:\n",
|
| 187 |
+
"#Apply feature scaling for all features (Use StandardScaler)\n",
|
| 188 |
+
"feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
|
| 189 |
+
"scaler = StandardScaler()\n",
|
| 190 |
+
"df_clean_scaled = scaler.fit_transform(df_clean[feature_cols])\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"print(f\"\\nScaled ranges - Min: {df_clean_scaled.min():.2f}, Max: {df_clean_scaled.max():.2f}\")"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task 6: Write your code here:\n",
|
| 202 |
+
"#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"# From above we have this that it is imbalnced:\n",
|
| 205 |
+
"# Plot the target distribution (delivery_time)\n",
|
| 206 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 207 |
+
"plt.hist(df_clean['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 208 |
+
"plt.title('Price Distribution')\n",
|
| 209 |
+
"plt.xlabel('Time')\n",
|
| 210 |
+
"plt.ylabel('Frequency')\n",
|
| 211 |
+
"plt.show()"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# Task 1: Write your code here:\n",
|
| 221 |
+
"#1. Split the dataset into features (X) and target (y)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"# Define features (X) and target (y)\n",
|
| 224 |
+
"X = pd.DataFrame(df_clean_scaled.copy())\n",
|
| 225 |
+
"y = pd.DataFrame(df_clean['Delivery_Time'].copy())"
|
| 226 |
+
],
|
| 227 |
+
"execution_count": null,
|
| 228 |
+
"outputs": []
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 235 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 236 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"models = {\n",
|
| 240 |
+
"\"Random Forest Regressor\": RandomForestRegressor(\n",
|
| 241 |
+
"n_estimators=200, # Number of trees in the forest\n",
|
| 242 |
+
"max_depth=10, # Maximum depth of trees\n",
|
| 243 |
+
"min_samples_split=2, # Minimum samples to split\n",
|
| 244 |
+
"min_samples_leaf=1, # Minimum samples at leaf\n",
|
| 245 |
+
"n_jobs=-1, # Use all CPU cores (-1 = all cores)\n",
|
| 246 |
+
"random_state=42 # Seed\n",
|
| 247 |
+
")\n",
|
| 248 |
+
"}\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 252 |
+
"results = {name: {'mse': [], 'mae': [], 'rmse': [], 'r2': []} for name in models}\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 255 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 256 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" for model_name, model in models.items():\n",
|
| 259 |
+
" # Train\n",
|
| 260 |
+
" model.fit(X_train, y_train)\n",
|
| 261 |
+
" # Predict\n",
|
| 262 |
+
" y_pred = model.predict(X_test)\n",
|
| 263 |
+
" # Evaluate\n",
|
| 264 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 265 |
+
" # Store results\n",
|
| 266 |
+
" results[model_name]['mae'].append(mae)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"# Print average results\n",
|
| 270 |
+
"for model_name in results:\n",
|
| 271 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 272 |
+
" print(f\" MAE: {np.mean(results[model_name]['mae']):.4f}\")"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task 1: Write your code here:\n",
|
| 282 |
+
"# Feature importance\n",
|
| 283 |
+
"feature_importance = pd.DataFrame({\n",
|
| 284 |
+
" 'feature': feature_cols,\n",
|
| 285 |
+
" 'importance': model.feature_importances_\n",
|
| 286 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 289 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 290 |
+
"plt.xlabel('Importance')\n",
|
| 291 |
+
"plt.title('Feature Importance')\n",
|
| 292 |
+
"plt.gca().invert_yaxis()\n",
|
| 293 |
+
"plt.show()\n"
|
| 294 |
+
],
|
| 295 |
+
"execution_count": null,
|
| 296 |
+
"outputs": []
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "code",
|
| 300 |
+
"metadata": {},
|
| 301 |
+
"source": [
|
| 302 |
+
"# Task 2: Write your code here:\n",
|
| 303 |
+
"plt.figure(figsize=(10, 8))\n",
|
| 304 |
+
"plt.scatter(y_test, y_pred, alpha=0.7)\n",
|
| 305 |
+
"plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n",
|
| 306 |
+
"plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
|
| 307 |
+
"plt.ylabel(\"Predicted y_pred\")\n",
|
| 308 |
+
"plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n",
|
| 309 |
+
"plt.grid(True)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"plt.tight_layout()\n",
|
| 312 |
+
"plt.show()"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"# Task Bonus: Write your code here:"
|
| 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/453/Q2.ipynb
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"from torchvision.datasets import CIFAR10\n",
|
| 10 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 11 |
+
"from torch.utils.data import DataLoader\n",
|
| 12 |
+
"import matplotlib.pyplot as plt\n",
|
| 13 |
+
"import torch.nn as nn\n",
|
| 14 |
+
"import torch.nn.functional as F\n",
|
| 15 |
+
"import torch\n",
|
| 16 |
+
"from torch.optim import AdamW\n",
|
| 17 |
+
"# Download latest version\n",
|
| 18 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"print(\"Path to dataset files:\", path)"
|
| 21 |
+
],
|
| 22 |
+
"execution_count": null,
|
| 23 |
+
"outputs": []
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"import os\n",
|
| 30 |
+
"import pandas as pd\n",
|
| 31 |
+
"import numpy as np\n",
|
| 32 |
+
"from PIL import Image\n",
|
| 33 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Load Labels\n",
|
| 36 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 37 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"images = []\n",
|
| 40 |
+
"ages = []\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"# Load Images and Resize\n",
|
| 43 |
+
"print(\"Loading images...\")\n",
|
| 44 |
+
"for index, row in labels_df.iterrows():\n",
|
| 45 |
+
" img_name = row.iloc[0]\n",
|
| 46 |
+
" age = row.iloc[1]\n",
|
| 47 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
" if os.path.exists(img_path):\n",
|
| 50 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 51 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 52 |
+
" images.append(img_array)\n",
|
| 53 |
+
" ages.append(age)\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"X = np.array(images)\n",
|
| 56 |
+
"y = np.array(ages)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 59 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"# Split Data\n",
|
| 62 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 65 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 66 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 67 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 77 |
+
"import torch\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 80 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 81 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 82 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# 2. Create TensorDataset objects\n",
|
| 92 |
+
"from torch.utils.data import Dataset, TensorDataset, DataLoader\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 95 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# 3. Create DataLoaders\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 107 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# 4. Print shape of one batch\n",
|
| 117 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 118 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Get the first batch from the training DataLoader\n",
|
| 121 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 122 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 123 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# 5. Display sample images\n",
|
| 133 |
+
"# Get one batch of images and labels\n",
|
| 134 |
+
"images, labels = next(iter(train_loader))\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"# Display the first 6 images in the batch\n",
|
| 137 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"for i in range(6):\n",
|
| 140 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 143 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 144 |
+
"\n",
|
| 145 |
+
" plt.imshow(img)\n",
|
| 146 |
+
" plt.title(f\"age: {labels[i].item()}\")\n",
|
| 147 |
+
" plt.axis('off')\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"plt.tight_layout()\n",
|
| 150 |
+
"plt.show()\n"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 1: Write your model class here:\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 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 167 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 170 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 173 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 176 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim) #output_dim\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" # activation function for non-linearity\n",
|
| 179 |
+
" self.relu = nn.ReLU()\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Defines how input data flows through the network\n",
|
| 182 |
+
" def forward(self, x):\n",
|
| 183 |
+
" # Layer 1: TODO\n",
|
| 184 |
+
" z1 = self.layer1(x)\n",
|
| 185 |
+
" a1 = self.relu(z1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Layer 2 TODO\n",
|
| 188 |
+
" z2 = self.layer2(a1)\n",
|
| 189 |
+
" a2 = self.relu(z2)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" # Layer 3 TODO\n",
|
| 192 |
+
" z3 = self.layer3(a2)\n",
|
| 193 |
+
" a3 = self.relu(z3)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Output layer TODO\n",
|
| 196 |
+
" z4 = self.layer4(a3)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" return z4"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 2: Write your training loop here:\n",
|
| 210 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 211 |
+
" # Set the model to training mode\n",
|
| 212 |
+
" model.train()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" running_loss = 0.0\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 217 |
+
" # Move batch to the selected device\n",
|
| 218 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 219 |
+
" y_batch = y_batch.to(device)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Forward pass\n",
|
| 222 |
+
" # TODO: make predictions\n",
|
| 223 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 224 |
+
" # TODO: compute loss\n",
|
| 225 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Backward pass & optimization\n",
|
| 228 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 229 |
+
" loss.backward() # Compute gradients\n",
|
| 230 |
+
" optimizer.step() # Update model parameters\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" running_loss += loss.item()\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Average loss over all batches\n",
|
| 235 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" return avg_loss"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 3: Write your validation loop here:\n",
|
| 247 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 248 |
+
" # Set the model to evaluation mode\n",
|
| 249 |
+
" model.eval()\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" running_loss = 0.0\n",
|
| 252 |
+
" correct = 0\n",
|
| 253 |
+
" total = 0\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" with torch.no_grad():\n",
|
| 256 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 257 |
+
" # Move data to device\n",
|
| 258 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 259 |
+
" y_batch = y_batch.to(device)\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" # Forward pass\n",
|
| 262 |
+
" # TODO: make predictions\n",
|
| 263 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 264 |
+
" # TODO: compute loss\n",
|
| 265 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 266 |
+
" running_loss += loss.item()\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 269 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # TODO: Multiclass predictions\n",
|
| 272 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" # Accuracy calculation\n",
|
| 275 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 276 |
+
" total += y_batch.size(0)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 279 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 280 |
+
" accuracy = correct / total\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" return avg_loss, accuracy\n"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 292 |
+
"# Device setup\n",
|
| 293 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"# Model parameters\n",
|
| 296 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 297 |
+
"input_dim = 3 * 36 * 36\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"# TODO: choose number of hidden neurons\n",
|
| 300 |
+
"hidden_dim = 128 # Design choice\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"# it is not a class so not sure what to set the output dim to\n",
|
| 303 |
+
"output_dim = 1\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 306 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# TODO: Print the model architecture\n",
|
| 309 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 310 |
+
"print(model)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"# Calculate the total number of trainable parameters\n",
|
| 313 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 314 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"# TODO: choose number of epochs, increase it if you have gpus :)\n",
|
| 326 |
+
"num_epochs = 20\n",
|
| 327 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 328 |
+
"learning_rate = 0.001\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 331 |
+
"criterion = nn.MSELoss()\n",
|
| 332 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 333 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"# Run Training\n",
|
| 336 |
+
"train_losses = []\n",
|
| 337 |
+
"val_losses = []\n",
|
| 338 |
+
"val_accuracies = []\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"print('Starting Training...')\n",
|
| 341 |
+
"for epoch in range(num_epochs):\n",
|
| 342 |
+
" # Train one epoch\n",
|
| 343 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" # Validate\n",
|
| 346 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" train_losses.append(train_loss)\n",
|
| 349 |
+
" val_losses.append(val_loss)\n",
|
| 350 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 351 |
+
"\n",
|
| 352 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"print('Training Complete!')"
|
| 355 |
+
],
|
| 356 |
+
"execution_count": null,
|
| 357 |
+
"outputs": []
|
| 358 |
+
},
|
| 359 |
+
{
|
| 360 |
+
"cell_type": "code",
|
| 361 |
+
"metadata": {},
|
| 362 |
+
"source": [
|
| 363 |
+
"# Task 1: Write your code here:\n",
|
| 364 |
+
"# Plotting results\n",
|
| 365 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 368 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 369 |
+
"plt.title('Loss over Epochs')\n",
|
| 370 |
+
"plt.xlabel('Epoch')\n",
|
| 371 |
+
"plt.ylabel('Loss')\n",
|
| 372 |
+
"plt.legend()\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"plt.tight_layout()\n",
|
| 375 |
+
"plt.show()\n"
|
| 376 |
+
],
|
| 377 |
+
"execution_count": null,
|
| 378 |
+
"outputs": []
|
| 379 |
+
},
|
| 380 |
+
{
|
| 381 |
+
"cell_type": "code",
|
| 382 |
+
"metadata": {},
|
| 383 |
+
"source": [
|
| 384 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 385 |
+
],
|
| 386 |
+
"execution_count": null,
|
| 387 |
+
"outputs": []
|
| 388 |
+
}
|
| 389 |
+
],
|
| 390 |
+
"metadata": {
|
| 391 |
+
"kernelspec": {
|
| 392 |
+
"display_name": "Python 3",
|
| 393 |
+
"name": "python3"
|
| 394 |
+
},
|
| 395 |
+
"language_info": {
|
| 396 |
+
"name": "python"
|
| 397 |
+
}
|
| 398 |
+
},
|
| 399 |
+
"nbformat": 4,
|
| 400 |
+
"nbformat_minor": 0
|
| 401 |
+
}
|
submissions_extracted/453/Q3.ipynb
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 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 |
+
"\n",
|
| 20 |
+
"# Download latest version\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\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 |
+
"amx_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 35 |
+
"df_amx = pd.read_csv(amx_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_amx.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_amx.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_amx.describe()"
|
| 66 |
+
],
|
| 67 |
+
"execution_count": null,
|
| 68 |
+
"outputs": []
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"cell_type": "code",
|
| 72 |
+
"metadata": {},
|
| 73 |
+
"source": [
|
| 74 |
+
"# Task 1: Write your code here:\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"df_clean = df_amx.copy()\n",
|
| 77 |
+
"features = df_amx.copy().drop(columns='Target')\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# Analyze missing values\n",
|
| 80 |
+
"missing_percentage = (df_amx.isnull().sum() / len(df_amx)) * 100\n",
|
| 81 |
+
"missing_data = pd.DataFrame({\n",
|
| 82 |
+
" 'Column': missing_percentage.index,\n",
|
| 83 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 84 |
+
"})\n",
|
| 85 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 88 |
+
"missing_data.head(10)\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"# The missing values in many col are greater than 95 > so we need to drop them\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# Task 2: Write your code here:\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"#Check and remove duplicates if any exist\n",
|
| 104 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 105 |
+
"duplicate_rows = features.duplicated().sum()\n",
|
| 106 |
+
"if duplicate_rows > 0:\n",
|
| 107 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 108 |
+
" df_clean.drop_duplicates(inplace=True)\n",
|
| 109 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 110 |
+
"else:\n",
|
| 111 |
+
" print(\"No duplicate rows found.\")\n"
|
| 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 |
+
"\n",
|
| 122 |
+
"# We don't have any catgorical and the target is already label encoded as binary"
|
| 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 |
+
"\n",
|
| 133 |
+
"#Apply feature scaling for all features (Use StandardScaler)\n",
|
| 134 |
+
"feature_cols = features.columns\n",
|
| 135 |
+
"scaler = StandardScaler()\n",
|
| 136 |
+
"df_clean_scaled = scaler.fit_transform(df_clean[feature_cols])\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"print(f\"\\nScaled ranges - Min: {df_clean_scaled.min():.2f}, Max: {df_clean_scaled.max():.2f}\")"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 5: Write your code here:\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"# Plot the target distribution (Target)\n",
|
| 150 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 151 |
+
"plt.hist(df_clean['Target'].dropna(), bins=50, edgecolor='black')\n",
|
| 152 |
+
"plt.title('Price Distribution')\n",
|
| 153 |
+
"plt.xlabel('Time')\n",
|
| 154 |
+
"plt.ylabel('Frequency')\n",
|
| 155 |
+
"plt.show()\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# it is"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 1: Write your code here:\n",
|
| 167 |
+
"#1. Split the dataset into features (X) and target (y)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Define features (X) and target (y)\n",
|
| 170 |
+
"X = df_clean_scaled.copy()\n",
|
| 171 |
+
"y = df_clean['Target'].copy()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 174 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 175 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 185 |
+
"from catboost import CatBoostClassifier\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"models = {\n",
|
| 188 |
+
"\"CatBoost\": CatBoostClassifier(\n",
|
| 189 |
+
"n_estimators=200, # Number of boosting rounds\n",
|
| 190 |
+
"max_depth=4, # Maximum tree depth\n",
|
| 191 |
+
"verbose=0 # Suppress output\n",
|
| 192 |
+
")\n",
|
| 193 |
+
"}\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 197 |
+
"results = {name: {'mse': [], 'mae': [], 'rmse': [], 'r2': []} for name in models}\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"for train_idx, test_idx in kf.split(X):\n",
|
| 200 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 201 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" for model_name, model in models.items():\n",
|
| 204 |
+
" # Train\n",
|
| 205 |
+
" model.fit(X_train, y_train)\n",
|
| 206 |
+
" # Predict\n",
|
| 207 |
+
" y_pred = model.predict(X_test)\n",
|
| 208 |
+
" # Evaluate\n",
|
| 209 |
+
" mse = mean_squared_error(y_test, y_pred)\n",
|
| 210 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 211 |
+
" rmse = np.sqrt(mse)\n",
|
| 212 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 213 |
+
" # Store results\n",
|
| 214 |
+
" results[model_name]['mse'].append(mse)\n",
|
| 215 |
+
" results[model_name]['mae'].append(mae)\n",
|
| 216 |
+
" results[model_name]['rmse'].append(rmse)\n",
|
| 217 |
+
" results[model_name]['r2'].append(r2)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"# Print average results\n",
|
| 221 |
+
"for model_name in results:\n",
|
| 222 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 223 |
+
" print(f\" MSE: {np.mean(results[model_name]['mse']):.4f}\")\n",
|
| 224 |
+
" print(f\" MAE: {np.mean(results[model_name]['mae']):.4f}\")\n",
|
| 225 |
+
" print(f\" RMSE: {np.mean(results[model_name]['rmse']):.4f}\")\n",
|
| 226 |
+
" print(f\" R2: {np.mean(results[model_name]['r2']):.4f}\")"
|
| 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 |
+
"\n",
|
| 237 |
+
"feature_importance = pd.DataFrame({\n",
|
| 238 |
+
" 'feature': feature_cols,\n",
|
| 239 |
+
" 'importance': model.feature_importances_\n",
|
| 240 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 243 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 244 |
+
"plt.xlabel('Importance')\n",
|
| 245 |
+
"plt.title('Feature Importance')\n",
|
| 246 |
+
"plt.gca().invert_yaxis()\n",
|
| 247 |
+
"plt.show()\n"
|
| 248 |
+
],
|
| 249 |
+
"execution_count": null,
|
| 250 |
+
"outputs": []
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"# Task 2: Write your code here:\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"print(\"\")"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"# Task Bonus: Write your code here:"
|
| 268 |
+
],
|
| 269 |
+
"execution_count": null,
|
| 270 |
+
"outputs": []
|
| 271 |
+
}
|
| 272 |
+
],
|
| 273 |
+
"metadata": {
|
| 274 |
+
"kernelspec": {
|
| 275 |
+
"display_name": "Python 3",
|
| 276 |
+
"name": "python3"
|
| 277 |
+
},
|
| 278 |
+
"language_info": {
|
| 279 |
+
"name": "python"
|
| 280 |
+
}
|
| 281 |
+
},
|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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 #to read files\n",
|
| 9 |
+
"import os\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 12 |
+
"# Download latest version\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"print(\"Path to dataset files:\", path)"
|
| 16 |
+
],
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"outputs": []
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "code",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"# Task 1: Write your code here:\n",
|
| 25 |
+
"# Load the CSV file\n",
|
| 26 |
+
"df = pd.read_csv(os.path.join(path, \"Q1_data.csv\"))"
|
| 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 |
+
"df.head() #display first 5 rows"
|
| 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 |
+
"df.info()"
|
| 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 |
+
"df.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 |
+
"def check_target_distribution(df, target_column):\n",
|
| 67 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 68 |
+
"\n",
|
| 69 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 70 |
+
" plt.xlabel(target_column)\n",
|
| 71 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 72 |
+
" plt.grid(False)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
" plt.show()\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 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 |
+
"df2 = df.copy()\n",
|
| 87 |
+
"df2 = df2.drop('Order_ID',axis=1)"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"df2"
|
| 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 |
+
"def check_missing_values(df2):\n",
|
| 107 |
+
" missing_values = df2.isnull().sum()\n",
|
| 108 |
+
" print(\"Missing Values per Column:\")\n",
|
| 109 |
+
" print(missing_values[missing_values > 0])\n",
|
| 110 |
+
" if missing_values.any():\n",
|
| 111 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 112 |
+
" else:\n",
|
| 113 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"check_missing_values(df2)\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"df_dropna = df2.dropna()\n"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"check_missing_values(df_dropna)"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 3: Write your code here:\n",
|
| 137 |
+
"def check_duplicates(df):\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" #TODO: get duplicated data using pandas\n",
|
| 140 |
+
" duplicates = df.duplicated().sum()\n",
|
| 141 |
+
"\n",
|
| 142 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 143 |
+
" if duplicates > 0:\n",
|
| 144 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 145 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 146 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 147 |
+
" else:\n",
|
| 148 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"check_duplicates(df_dropna)"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"df_dropna"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task 4: Write your code here:\n",
|
| 169 |
+
"categorical_cols = df_dropna.select_dtypes(include=[\"object\"]).columns\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"\n"
|
| 174 |
+
],
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"outputs": []
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"label_encoders = {}\n",
|
| 185 |
+
"for col in categorical_cols:\n",
|
| 186 |
+
" le = LabelEncoder()\n",
|
| 187 |
+
" df_dropna[col] = le.fit_transform(df_dropna[col])\n",
|
| 188 |
+
" label_encoders[col] = le\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"df_dropna"
|
| 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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"features = df_dropna.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"scaler = StandardScaler()\n",
|
| 205 |
+
"df_dropna[features] = scaler.fit_transform(df_dropna[features])\n",
|
| 206 |
+
"df_dropna.head()"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 6: Write your code here:\n",
|
| 216 |
+
"import seaborn as sns\n",
|
| 217 |
+
"def check_target_imbalance(df_dropna, target_column):\n",
|
| 218 |
+
" print(\"Target Distribution:\")\n",
|
| 219 |
+
" print(df_dropna[target_column].value_counts(normalize=True))\n",
|
| 220 |
+
" sns.countplot(x=df_dropna[target_column])\n",
|
| 221 |
+
" plt.title(\"Target Distribution\")\n",
|
| 222 |
+
" plt.show()\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"check_target_imbalance(df_dropna, \"Delivery_Time\")\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"#i believe the target is impalanced"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"from sklearn.model_selection import KFold\n",
|
| 236 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 237 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 238 |
+
"import numpy as np"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 1: Write your code here:\n",
|
| 248 |
+
"X = df_dropna.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 249 |
+
"y = df_dropna['Delivery_Time'].astype(float)"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 259 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 260 |
+
"#model.fit(X_train, y_train) # train\n",
|
| 261 |
+
"#y_pred = model.predict(X_test) # validate\n",
|
| 262 |
+
"rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n",
|
| 263 |
+
"lr_mae = []\n",
|
| 264 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 265 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 268 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 271 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Train\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" rf.fit(X_train, y_train)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" # Validate\n",
|
| 278 |
+
" y_pred = rf.predict(X_test.values)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Calculate evaluation metrics\n",
|
| 281 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 282 |
+
" # Store results\n",
|
| 283 |
+
" lr_mae.append(mae)\n",
|
| 284 |
+
"average_losses = np.mean(lr_mae, axis=0)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 287 |
+
"plt.plot(average_losses, label='Average Loss')\n",
|
| 288 |
+
"plt.xlabel('Iteration')\n",
|
| 289 |
+
"plt.ylabel('MSE Loss')\n",
|
| 290 |
+
"plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
|
| 291 |
+
"plt.legend()\n",
|
| 292 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 293 |
+
"plt.show()"
|
| 294 |
+
],
|
| 295 |
+
"execution_count": null,
|
| 296 |
+
"outputs": []
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "code",
|
| 300 |
+
"metadata": {},
|
| 301 |
+
"source": [
|
| 302 |
+
"# Task 1: Write your code here:\n",
|
| 303 |
+
"RandomForestRegressor_model = rf\n",
|
| 304 |
+
"RandomForestRegressor_importance = list(zip(X.columns, RandomForestRegressor_model.feature_importances_))\n",
|
| 305 |
+
"sorted_catboost_importance = sorted(RandomForestRegressor_importance, key=lambda x: x[1], reverse=True)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"# Extract features and their importances\n",
|
| 308 |
+
"features, importances = zip(*RandomForestRegressor_importance)\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"# Plot feature importances\n",
|
| 311 |
+
"plt.figure(figsize=(18, 14))\n",
|
| 312 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 313 |
+
"plt.xlabel('Importance Score')\n",
|
| 314 |
+
"plt.ylabel('Features')\n",
|
| 315 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 316 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 317 |
+
"plt.show()"
|
| 318 |
+
],
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"outputs": []
|
| 321 |
+
},
|
| 322 |
+
{
|
| 323 |
+
"cell_type": "code",
|
| 324 |
+
"metadata": {},
|
| 325 |
+
"source": [
|
| 326 |
+
"# Task 2: Write your code here:\n"
|
| 327 |
+
],
|
| 328 |
+
"execution_count": null,
|
| 329 |
+
"outputs": []
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "code",
|
| 333 |
+
"metadata": {},
|
| 334 |
+
"source": [
|
| 335 |
+
"# Task Bonus: Write your code here:"
|
| 336 |
+
],
|
| 337 |
+
"execution_count": null,
|
| 338 |
+
"outputs": []
|
| 339 |
+
}
|
| 340 |
+
],
|
| 341 |
+
"metadata": {
|
| 342 |
+
"kernelspec": {
|
| 343 |
+
"display_name": "Python 3",
|
| 344 |
+
"name": "python3"
|
| 345 |
+
},
|
| 346 |
+
"language_info": {
|
| 347 |
+
"name": "python"
|
| 348 |
+
}
|
| 349 |
+
},
|
| 350 |
+
"nbformat": 4,
|
| 351 |
+
"nbformat_minor": 0
|
| 352 |
+
}
|
submissions_extracted/454/Q2.ipynb
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"import torch.nn as nn\n",
|
| 70 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 71 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 72 |
+
"import torch.nn.functional as F\n",
|
| 73 |
+
"import matplotlib.pyplot as plt"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 83 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 84 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 87 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 88 |
+
"\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# 2. Create TensorDataset objects\n",
|
| 98 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 99 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 100 |
+
"\n"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# 3. Create DataLoaders\n",
|
| 110 |
+
"train_loader = DataLoader(\n",
|
| 111 |
+
" train_dataset,\n",
|
| 112 |
+
" batch_size=32,\n",
|
| 113 |
+
" shuffle=True,\n",
|
| 114 |
+
" num_workers=2\n",
|
| 115 |
+
")\n",
|
| 116 |
+
"# DataLoader for test/validation data\n",
|
| 117 |
+
"test_loader = DataLoader(\n",
|
| 118 |
+
" test_dataset,\n",
|
| 119 |
+
" batch_size=32,\n",
|
| 120 |
+
" shuffle=False,\n",
|
| 121 |
+
" num_workers=2\n",
|
| 122 |
+
")\n",
|
| 123 |
+
"\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 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 135 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 136 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 137 |
+
],
|
| 138 |
+
"execution_count": null,
|
| 139 |
+
"outputs": []
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"cell_type": "code",
|
| 143 |
+
"metadata": {},
|
| 144 |
+
"source": [
|
| 145 |
+
"# 5. Display sample images\n",
|
| 146 |
+
"images, labels = next(iter(train_loader))\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"# Display the first 6 images in the batch\n",
|
| 149 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"for i in range(6):\n",
|
| 152 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 155 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" plt.imshow(img)\n",
|
| 158 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 159 |
+
" plt.axis('off')\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"plt.tight_layout()\n",
|
| 162 |
+
"plt.show()"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"class NN4Layer(nn.Module):\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 174 |
+
" super(NN4Layer, self).__init__()\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" self.relu = nn.ReLU()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" def forward(self, x):\n",
|
| 190 |
+
" # First hidden layer\n",
|
| 191 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # Second hidden layer\n",
|
| 194 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 195 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 196 |
+
" output = self.layer4(a3)\n",
|
| 197 |
+
" return output"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task 2: Write your training loop here:\n",
|
| 207 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 208 |
+
" # Set the model to training mode\n",
|
| 209 |
+
" model.train()\n",
|
| 210 |
+
" model.to(device)\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" running_loss = 0.0\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 215 |
+
" # Move batch to the selected device\n",
|
| 216 |
+
" X_batch = X_batch.to(device)\n",
|
| 217 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" # Forward pass\n",
|
| 220 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 221 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" # Backward pass & optimization\n",
|
| 224 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 225 |
+
" loss.backward() # Compute gradients\n",
|
| 226 |
+
" optimizer.step() # Update model parameters\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" running_loss += loss.item()\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" # Average loss over all batches\n",
|
| 231 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" return avg_loss"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 3: Write your validation loop here:\n",
|
| 243 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 244 |
+
" # Set the model to evaluation mode\n",
|
| 245 |
+
" model.eval()\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" running_loss = 0.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)\n",
|
| 253 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Forward pass (continuous output)\n",
|
| 256 |
+
" outputs = model(X_batch)\n",
|
| 257 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" running_loss += loss.item()\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" # Average loss over all batches\n",
|
| 262 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" return avg_loss"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
},
|
| 269 |
+
{
|
| 270 |
+
"cell_type": "code",
|
| 271 |
+
"metadata": {},
|
| 272 |
+
"source": [
|
| 273 |
+
"from torch.optim import AdamW"
|
| 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 = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 284 |
+
"input_dim = 3 * 36 * 36 # Number of tabular features\n",
|
| 285 |
+
"hidden_dim = 64 # Design choice\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Instantiate regression model\n",
|
| 288 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 289 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 290 |
+
"print(model)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"num_epochs = 20\n",
|
| 293 |
+
"learning_rate = 0.001\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 296 |
+
"criterion = nn.MSELoss()\n",
|
| 297 |
+
"# Define optimizer\n",
|
| 298 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 308 |
+
"train_losses = []\n",
|
| 309 |
+
"val_losses = []\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 = validate(model, criterion, test_loader, device)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" train_losses.append(train_loss)\n",
|
| 319 |
+
" val_losses.append(val_loss)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 322 |
+
" print(\n",
|
| 323 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 324 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 325 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 326 |
+
" )\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"print('Training Complete!')"
|
| 329 |
+
],
|
| 330 |
+
"execution_count": null,
|
| 331 |
+
"outputs": []
|
| 332 |
+
},
|
| 333 |
+
{
|
| 334 |
+
"cell_type": "code",
|
| 335 |
+
"metadata": {},
|
| 336 |
+
"source": [
|
| 337 |
+
"# Task 1: Write your code here:\n",
|
| 338 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 341 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 342 |
+
"plt.title('Loss over Epochs')\n",
|
| 343 |
+
"plt.xlabel('Epoch')\n",
|
| 344 |
+
"plt.ylabel('Loss')\n",
|
| 345 |
+
"plt.legend()\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"plt.tight_layout()\n",
|
| 348 |
+
"plt.show()"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 358 |
+
],
|
| 359 |
+
"execution_count": null,
|
| 360 |
+
"outputs": []
|
| 361 |
+
}
|
| 362 |
+
],
|
| 363 |
+
"metadata": {
|
| 364 |
+
"kernelspec": {
|
| 365 |
+
"display_name": "Python 3",
|
| 366 |
+
"name": "python3"
|
| 367 |
+
},
|
| 368 |
+
"language_info": {
|
| 369 |
+
"name": "python"
|
| 370 |
+
}
|
| 371 |
+
},
|
| 372 |
+
"nbformat": 4,
|
| 373 |
+
"nbformat_minor": 0
|
| 374 |
+
}
|
submissions_extracted/454/Q3.ipynb
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 #to read files\n",
|
| 27 |
+
"import os\n",
|
| 28 |
+
"import matplotlib.pyplot as plt"
|
| 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 |
+
"df = pd.read_csv(os.path.join(path, \"Q3_data.csv\"))"
|
| 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(df2):\n",
|
| 79 |
+
" missing_values = df2.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)\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"df_clean=df.dropna()\n"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"df_clean"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"check_missing_values(df)"
|
| 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 |
+
"def check_duplicates(df):\n",
|
| 118 |
+
" duplicates = df.duplicated().sum()\n",
|
| 119 |
+
"\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(df)\n",
|
| 129 |
+
"#none was found"
|
| 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 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 142 |
+
"#none was found"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"df"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 4: Write your code here:\n",
|
| 161 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"# Pick only the numerical columns, NOT the target\n",
|
| 164 |
+
"numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"scaler = StandardScaler()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"# scale the `numerical_cols`\n",
|
| 169 |
+
"#df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"df[numerical_cols]"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 5: Write your code here:\n",
|
| 181 |
+
"import seaborn as sns\n",
|
| 182 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 183 |
+
" print(\"Target Distribution:\")\n",
|
| 184 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 185 |
+
" sns.countplot(x=df[target_column])\n",
|
| 186 |
+
" plt.title(\"Target Distribution\")\n",
|
| 187 |
+
" plt.show()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"check_target_imbalance(df, \"Target\")"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"# Task 1: Write your code here:\n",
|
| 199 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 200 |
+
"y = df['Target'].astype(float)"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"from IPython.display import clear_output\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 221 |
+
"from catboost import CatBoostClassifier"
|
| 222 |
+
],
|
| 223 |
+
"execution_count": null,
|
| 224 |
+
"outputs": []
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 231 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 232 |
+
"model = CatBoostClassifier(verbose=0)\n",
|
| 233 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 234 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 235 |
+
"for train_index, test_index in skf.split(X, y):\n",
|
| 236 |
+
" # Split data into training and testing sets\n",
|
| 237 |
+
" X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
|
| 238 |
+
" y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 239 |
+
" # Train the model\n",
|
| 240 |
+
" model.fit(X_Train, y_Train)\n",
|
| 241 |
+
" # Predict on the test set\n",
|
| 242 |
+
" y_pred = model.predict(X_Test)"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "code",
|
| 249 |
+
"metadata": {},
|
| 250 |
+
"source": [
|
| 251 |
+
"# Task 1: Write your code here:\n",
|
| 252 |
+
"catboost_model = model\n",
|
| 253 |
+
"catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n",
|
| 254 |
+
"sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"# Extract features and their importances\n",
|
| 257 |
+
"features, importances = zip(*sorted_catboost_importance)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"# Plot feature importances\n",
|
| 260 |
+
"plt.figure(figsize=(18, 14))\n",
|
| 261 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 262 |
+
"plt.xlabel('Importance Score')\n",
|
| 263 |
+
"plt.ylabel('Features')\n",
|
| 264 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 265 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 266 |
+
"plt.show()"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task 2: Write your code here:"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task Bonus: Write your code here:"
|
| 285 |
+
],
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"outputs": []
|
| 288 |
+
}
|
| 289 |
+
],
|
| 290 |
+
"metadata": {
|
| 291 |
+
"kernelspec": {
|
| 292 |
+
"display_name": "Python 3",
|
| 293 |
+
"name": "python3"
|
| 294 |
+
},
|
| 295 |
+
"language_info": {
|
| 296 |
+
"name": "python"
|
| 297 |
+
}
|
| 298 |
+
},
|
| 299 |
+
"nbformat": 4,
|
| 300 |
+
"nbformat_minor": 0
|
| 301 |
+
}
|
submissions_extracted/455/Q1.ipynb
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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agglehub\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 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"import matplotlib.pyplot as plt\n",
|
| 25 |
+
"import seaborn as sns"
|
| 26 |
+
],
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"source": [
|
| 34 |
+
"# Task 1: Write your code here:\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# first lets's see how many files are on the dir of the path\n",
|
| 37 |
+
"#os.listdir(path)\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"csv_path = os.path.join(path, os.listdir(path)[0])\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"df = pd.read_csv(csv_path)\n"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 2: Write your code here:\n",
|
| 51 |
+
"df.head()"
|
| 52 |
+
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": []
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
+
"metadata": {},
|
| 59 |
+
"source": [
|
| 60 |
+
"# Task 3: Write your code here:\n",
|
| 61 |
+
"df.info()\n"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"# Task 4: Write your code here:\n",
|
| 71 |
+
"df.describe()"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Task 5: Write your code here:\n",
|
| 81 |
+
"def check_target_distribution(df, target_column):\n",
|
| 82 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 83 |
+
"\n",
|
| 84 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 85 |
+
" plt.xlabel(target_column)\n",
|
| 86 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 87 |
+
" plt.grid(False)\n",
|
| 88 |
+
"\n",
|
| 89 |
+
" plt.show()\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 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 |
+
"df = df.drop(columns=\"Order_ID\", axis=1)\n",
|
| 102 |
+
"df.head()"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 2: Write your code here:\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)"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"Delivery_Time = [\"Weather\", \"Traffic_Level\" , \"Time_of_Day\" , \"Courier_Experience_yrs\" , \"Delivery_Time\"]\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"df_clean = df.dropna(subset = Delivery_Time).copy()\n",
|
| 133 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")\n",
|
| 134 |
+
"check_missing_values(df_clean)"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 3: Write your code here:\n",
|
| 144 |
+
"def check_duplicates(df):\n",
|
| 145 |
+
" duplicates = df.duplicated().sum()\n",
|
| 146 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 147 |
+
" if duplicates > 0:\n",
|
| 148 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 149 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 150 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 151 |
+
" else:\n",
|
| 152 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"check_duplicates(df_clean)"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"def encode_categorical_columns(df):\n",
|
| 164 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 165 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"label_encoders = encode_categorical_columns(df_clean)"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 4: Write your code here:\n",
|
| 177 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 180 |
+
"for col in categorical_cols:\n",
|
| 181 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 182 |
+
" le = LabelEncoder()\n",
|
| 183 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 184 |
+
"\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"df_clean"
|
| 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\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"scaler = StandardScaler()\n",
|
| 208 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 209 |
+
"df_clean.head()"
|
| 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 |
+
"\n",
|
| 220 |
+
"#Since we are not training a logistic regression model and it's not classification so we will not do this step an we will use kfold"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 1: Write your code here:\n",
|
| 237 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 238 |
+
"y = df_clean['Delivery_Time'].astype(float)"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Mean Squared Error in NumPy\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 |
+
"from tqdm import tqdm\n",
|
| 259 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 260 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 261 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 262 |
+
" losses = []\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
|
| 265 |
+
" y_hat = np.dot(X, theta)\n",
|
| 266 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 267 |
+
" theta -= learning_rate * gradient\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" loss = mean_squared_error(y, y_hat)\n",
|
| 270 |
+
" losses.append(loss)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" return theta, losses"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"from sklearn.model_selection import KFold\n",
|
| 284 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 289 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Storage for linear regression results for each fold\n",
|
| 292 |
+
"lr_losses = []\n",
|
| 293 |
+
"lr_mae = []\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 297 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 300 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" # Train\n",
|
| 303 |
+
" theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" # Validate\n",
|
| 306 |
+
" y_pred = np.dot(X_test.values, theta)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" # Calculate evaluation metrics\n",
|
| 309 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" # Store results\n",
|
| 313 |
+
" lr_losses.append(losses)\n",
|
| 314 |
+
" lr_mae.append(mae)\n"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"print(\"Linear Regression Results\")\n",
|
| 324 |
+
"print(f\" Average MAE: {np.mean(lr_mae):.4f}\")\n"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"cell_type": "code",
|
| 331 |
+
"metadata": {},
|
| 332 |
+
"source": [
|
| 333 |
+
"coeffs = {}\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
|
| 336 |
+
"coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
|
| 339 |
+
"axes = axes.flatten()\n",
|
| 340 |
+
"features = X.columns\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 343 |
+
" # Sort features by absolute coefficient value\n",
|
| 344 |
+
" absolute_coef = np.abs(coef)\n",
|
| 345 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" ax = axes[i]\n",
|
| 348 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 349 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 350 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"plt.tight_layout()\n",
|
| 353 |
+
"plt.show()"
|
| 354 |
+
],
|
| 355 |
+
"execution_count": null,
|
| 356 |
+
"outputs": []
|
| 357 |
+
},
|
| 358 |
+
{
|
| 359 |
+
"cell_type": "code",
|
| 360 |
+
"metadata": {},
|
| 361 |
+
"source": [
|
| 362 |
+
"# Task 2: Write your code here:\n"
|
| 363 |
+
],
|
| 364 |
+
"execution_count": null,
|
| 365 |
+
"outputs": []
|
| 366 |
+
},
|
| 367 |
+
{
|
| 368 |
+
"cell_type": "code",
|
| 369 |
+
"metadata": {},
|
| 370 |
+
"source": [
|
| 371 |
+
"# Task Bonus: Write your code here:\n",
|
| 372 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 373 |
+
"from sklearn.svm import SVR\n",
|
| 374 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 375 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 376 |
+
"from lightgbm import LGBMRegressor\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"models = {\n",
|
| 379 |
+
" \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
|
| 380 |
+
" \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
|
| 381 |
+
"}\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"# Storage for results\n",
|
| 384 |
+
"all_results = {}\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"for name in models:\n",
|
| 387 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 390 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 391 |
+
"\n",
|
| 392 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 393 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 394 |
+
"\n",
|
| 395 |
+
" for model_name, model in models.items():\n",
|
| 396 |
+
" print(f\"Training {model_name}...\")\n",
|
| 397 |
+
"\n",
|
| 398 |
+
" # Train\n",
|
| 399 |
+
" model.fit(X_train, y_train)\n",
|
| 400 |
+
"\n",
|
| 401 |
+
" # Predict\n",
|
| 402 |
+
" y_pred = model.predict(X_test)\n",
|
| 403 |
+
"\n",
|
| 404 |
+
" # Calculate metrics\n",
|
| 405 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 406 |
+
" rmse = np.sqrt(mse)\n",
|
| 407 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 408 |
+
"\n",
|
| 409 |
+
" # Store results\n",
|
| 410 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 411 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 412 |
+
" all_results[model_name][\"r2\"].append(r2)"
|
| 413 |
+
],
|
| 414 |
+
"execution_count": null,
|
| 415 |
+
"outputs": []
|
| 416 |
+
}
|
| 417 |
+
],
|
| 418 |
+
"metadata": {
|
| 419 |
+
"kernelspec": {
|
| 420 |
+
"display_name": "Python 3",
|
| 421 |
+
"name": "python3"
|
| 422 |
+
},
|
| 423 |
+
"language_info": {
|
| 424 |
+
"name": "python"
|
| 425 |
+
}
|
| 426 |
+
},
|
| 427 |
+
"nbformat": 4,
|
| 428 |
+
"nbformat_minor": 0
|
| 429 |
+
}
|
submissions_extracted/455/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 |
+
"from torch.utils.data import TensorDataset\n",
|
| 69 |
+
"from torch.utils.data import DataLoader\n",
|
| 70 |
+
"import torch"
|
| 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 |
+
"\n",
|
| 81 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 82 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 83 |
+
"y_train = torch.tensor(y_train, dtype=torch.long)\n",
|
| 84 |
+
"y_test = torch.tensor(y_test, dtype=torch.long)\n",
|
| 85 |
+
"\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 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 96 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (3, 36, 36)\n",
|
| 111 |
+
"print(f\"Label: {sample_label}\")"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# 3. Create DataLoaders\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"from torch.utils.data import DataLoader\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# DataLoader for training data\n",
|
| 125 |
+
"train_loader = DataLoader(\n",
|
| 126 |
+
" train_dataset,\n",
|
| 127 |
+
" batch_size=32,\n",
|
| 128 |
+
" shuffle=True,\n",
|
| 129 |
+
" num_workers=2\n",
|
| 130 |
+
")\n",
|
| 131 |
+
"# DataLoader for test/validation data\n",
|
| 132 |
+
"test_loader = DataLoader(\n",
|
| 133 |
+
" test_dataset,\n",
|
| 134 |
+
" batch_size=32,\n",
|
| 135 |
+
" shuffle=False,\n",
|
| 136 |
+
" num_workers=2\n",
|
| 137 |
+
")\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"\n"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# 4. Print shape of one batch\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"# Get the first batch from the training DataLoader\n",
|
| 152 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 153 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 154 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# 5. Display sample images\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"import matplotlib.pyplot as plt\n",
|
| 166 |
+
"# Get one batch of images and labels\n",
|
| 167 |
+
"images, labels = next(iter(train_loader))\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Display the first 6 images in the batch\n",
|
| 170 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"for i in range(6):\n",
|
| 173 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 176 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" plt.imshow(img)\n",
|
| 179 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 180 |
+
" plt.axis('off')\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"plt.tight_layout()\n",
|
| 183 |
+
"plt.show()\n"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 1: Write your model class here:\n",
|
| 193 |
+
"import torch.nn as nn\n",
|
| 194 |
+
"import torch.nn.functional as F\n",
|
| 195 |
+
"import torch\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"class NN4Layer(nn.Module):\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 200 |
+
" super(NN4Layer, self).__init__()\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" # activation function for non-linearity\n",
|
| 213 |
+
" self.relu = nn.ReLU()\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Defines how input data flows through the network\n",
|
| 216 |
+
" def forward(self, x):\n",
|
| 217 |
+
" # Layer 1: TODO\n",
|
| 218 |
+
" z1 = self.layer1(x)\n",
|
| 219 |
+
" a1 = self.relu(z1)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Layer 2 TODO\n",
|
| 222 |
+
" z2 = self.layer2(a1)\n",
|
| 223 |
+
" a2 = self.relu(z2)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Layer 3 TODO\n",
|
| 226 |
+
" z3 = self.layer3(a2)\n",
|
| 227 |
+
" a3 = self.relu(z3)\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Layer 4 and output\n",
|
| 230 |
+
" z4 = self.layer4(a3)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" return z4"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 2: Write your training loop here:\n",
|
| 243 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 244 |
+
" # Set the model to training mode\n",
|
| 245 |
+
" model.train()\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" running_loss = 0.0\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 250 |
+
" # Move batch to the selected device\n",
|
| 251 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 252 |
+
" y_batch = y_batch.to(device)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" # Forward pass\n",
|
| 255 |
+
" # make predictions\n",
|
| 256 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 257 |
+
" # compute loss\n",
|
| 258 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Backward pass & optimization\n",
|
| 261 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 262 |
+
" loss.backward() # Compute gradients\n",
|
| 263 |
+
" optimizer.step() # Update model parameters\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" running_loss += loss.item()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Average loss over all batches\n",
|
| 268 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" return avg_loss"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"# Task 3: Write your validation loop here:\n",
|
| 280 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 281 |
+
" # Set the model to evaluation mode\n",
|
| 282 |
+
" model.eval()\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" running_loss = 0.0\n",
|
| 285 |
+
" correct = 0\n",
|
| 286 |
+
" total = 0\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" with torch.no_grad():\n",
|
| 289 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 290 |
+
" # Move data to device\n",
|
| 291 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 292 |
+
" y_batch = y_batch.to(device)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
" # Forward pass\n",
|
| 295 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 296 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 297 |
+
" running_loss += loss.item()\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" # Apply Softmax to get probabilities\n",
|
| 300 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" # Multiclass predictions\n",
|
| 303 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" # Accuracy calculation\n",
|
| 306 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 307 |
+
" total += y_batch.size(0)\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 310 |
+
" # how do we calculate accuracy?\n",
|
| 311 |
+
" accuracy = correct / total\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" return avg_loss, accuracy"
|
| 314 |
+
],
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"outputs": []
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "code",
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"source": [
|
| 322 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 323 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"input_dim = 3 * 36 * 36\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"#choose number of hidden neurons and this is a design choice\n",
|
| 328 |
+
"hidden_dim = 64\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"#this is same as the labels we have\n",
|
| 331 |
+
"output_dim = 14\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 336 |
+
"print(model)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 339 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n"
|
| 340 |
+
],
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"outputs": []
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"cell_type": "code",
|
| 346 |
+
"metadata": {},
|
| 347 |
+
"source": [
|
| 348 |
+
"from torch.optim import AdamW\n",
|
| 349 |
+
"\n",
|
| 350 |
+
"num_epochs = 20\n",
|
| 351 |
+
"#chosing the learning rate this is a hyperparameter that i can play with\n",
|
| 352 |
+
"learning_rate = 0.001\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"# here the crossentropy loss does has softmax built in that's why i didn't put it on the NN class\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 357 |
+
"# chosing an optmizer , AdamW is a the best one or at least we start with it\n",
|
| 358 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 359 |
+
],
|
| 360 |
+
"execution_count": null,
|
| 361 |
+
"outputs": []
|
| 362 |
+
},
|
| 363 |
+
{
|
| 364 |
+
"cell_type": "code",
|
| 365 |
+
"metadata": {},
|
| 366 |
+
"source": [
|
| 367 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 368 |
+
"# Run Training\n",
|
| 369 |
+
"train_losses = []\n",
|
| 370 |
+
"val_losses = []\n",
|
| 371 |
+
"val_accuracies = []\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"print('Starting Training...')\n",
|
| 374 |
+
"for epoch in range(num_epochs):\n",
|
| 375 |
+
" # Train one epoch\n",
|
| 376 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 377 |
+
"\n",
|
| 378 |
+
" # Validate\n",
|
| 379 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 380 |
+
"\n",
|
| 381 |
+
" train_losses.append(train_loss)\n",
|
| 382 |
+
" val_losses.append(val_loss)\n",
|
| 383 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 384 |
+
"\n",
|
| 385 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"print('Training Complete!')"
|
| 388 |
+
],
|
| 389 |
+
"execution_count": null,
|
| 390 |
+
"outputs": []
|
| 391 |
+
},
|
| 392 |
+
{
|
| 393 |
+
"cell_type": "code",
|
| 394 |
+
"metadata": {},
|
| 395 |
+
"source": [
|
| 396 |
+
"# Task 1: Write your code here:\n",
|
| 397 |
+
"# Plotting results\n",
|
| 398 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 401 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 402 |
+
"plt.title('Loss over Epochs')\n",
|
| 403 |
+
"plt.xlabel('Epoch')\n",
|
| 404 |
+
"plt.ylabel('Loss')\n",
|
| 405 |
+
"plt.legend()\n",
|
| 406 |
+
"\n",
|
| 407 |
+
"plt.tight_layout()\n",
|
| 408 |
+
"plt.show()"
|
| 409 |
+
],
|
| 410 |
+
"execution_count": null,
|
| 411 |
+
"outputs": []
|
| 412 |
+
},
|
| 413 |
+
{
|
| 414 |
+
"cell_type": "code",
|
| 415 |
+
"metadata": {},
|
| 416 |
+
"source": [
|
| 417 |
+
"# Task 2 (Bonus): Write your code here:\n"
|
| 418 |
+
],
|
| 419 |
+
"execution_count": null,
|
| 420 |
+
"outputs": []
|
| 421 |
+
}
|
| 422 |
+
],
|
| 423 |
+
"metadata": {
|
| 424 |
+
"kernelspec": {
|
| 425 |
+
"display_name": "Python 3",
|
| 426 |
+
"name": "python3"
|
| 427 |
+
},
|
| 428 |
+
"language_info": {
|
| 429 |
+
"name": "python"
|
| 430 |
+
}
|
| 431 |
+
},
|
| 432 |
+
"nbformat": 4,
|
| 433 |
+
"nbformat_minor": 0
|
| 434 |
+
}
|
submissions_extracted/455/Q3.ipynb
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
{
|
| 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 numpy as np\n",
|
| 29 |
+
"import matplotlib.pyplot as plt\n",
|
| 30 |
+
"import seaborn as sns\n",
|
| 31 |
+
"import kagglehub\n",
|
| 32 |
+
"import os\n",
|
| 33 |
+
"from tqdm import tqdm\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"df = pd.read_csv(csv_path)\n",
|
| 38 |
+
"\n"
|
| 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 |
+
"\n",
|
| 69 |
+
"df.describe()\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:\n",
|
| 79 |
+
"def check_missing_values(df):\n",
|
| 80 |
+
" missing_values = df.isnull().sum()\n",
|
| 81 |
+
" print(\"Missing Values per Column:\")\n",
|
| 82 |
+
" print(missing_values[missing_values > 0])\n",
|
| 83 |
+
" if missing_values.any():\n",
|
| 84 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 85 |
+
" else:\n",
|
| 86 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"check_missing_values(df)"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"#this columns does have a lot of missing values so im gonna just drop it\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"df = df.drop(columns=['D_142'])"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"categorical_cols = df.columns\n",
|
| 109 |
+
"print(list(categorical_cols))\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"for col in list(list(categorical_cols)):\n",
|
| 113 |
+
" df = df[col].fillna(df[col].mode()[0])\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"print(\"handeld all the messing values\")\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"df.head()\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 |
+
"# Task 2: Write your code here:\n",
|
| 136 |
+
"def check_duplicates(df):\n",
|
| 137 |
+
" duplicates = df.duplicated().sum()\n",
|
| 138 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 139 |
+
" if duplicates > 0:\n",
|
| 140 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 141 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 142 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 143 |
+
" else:\n",
|
| 144 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"df_clean = df.copy()\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"check_duplicates(df_clean)"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 3: Write your code here:\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"#we don't need to encode anything all types are either float or int"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"df_clean.head()"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 4: Write your code here:\n",
|
| 178 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"scaler = StandardScaler()\n",
|
| 183 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 184 |
+
"df.head()\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 5: Write your code here:\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 196 |
+
" print(\"Target Distribution:\")\n",
|
| 197 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 198 |
+
" sns.countplot(x=df[target_column])\n",
|
| 199 |
+
" plt.title(\"Target Distribution\")\n",
|
| 200 |
+
" plt.show()\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"check_target_imbalance(df, \"Target\")"
|
| 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 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 213 |
+
"y = df['Target'].astype(float)\n",
|
| 214 |
+
"\n"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 224 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 227 |
+
"from sklearn.svm import SVC\n",
|
| 228 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 229 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 230 |
+
"from xgboost import XGBClassifier\n",
|
| 231 |
+
"from catboost import CatBoostClassifier\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 234 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"sklearn_models = {\n",
|
| 237 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 238 |
+
" verbose=0,\n",
|
| 239 |
+
" n_estimators=320,\n",
|
| 240 |
+
" max_depth=4\n",
|
| 241 |
+
" )\n",
|
| 242 |
+
"}\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"all_results = {}\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"for name in sklearn_models:\n",
|
| 247 |
+
" all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"n_splits = 5 # K\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 252 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 256 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" # 1. Split data\n",
|
| 259 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 260 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # 2. Train & Validate sklearn models\n",
|
| 263 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 264 |
+
" print(f\"Training {model_name}...\")\n",
|
| 265 |
+
" model.fit(X_train, y_train) # train\n",
|
| 266 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 269 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 270 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 271 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 272 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 275 |
+
" all_results[model_name]['precision'].append(precision)\n",
|
| 276 |
+
" all_results[model_name]['recall'].append(recall)\n",
|
| 277 |
+
" all_results[model_name]['f1'].append(f1)"
|
| 278 |
+
],
|
| 279 |
+
"execution_count": null,
|
| 280 |
+
"outputs": []
|
| 281 |
+
},
|
| 282 |
+
{
|
| 283 |
+
"cell_type": "code",
|
| 284 |
+
"metadata": {},
|
| 285 |
+
"source": [
|
| 286 |
+
"# Task 1: Write your code here:\n",
|
| 287 |
+
"importances = {}\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Create a 1x3 plot\n",
|
| 292 |
+
"fig, axes = plt.subplots(1, 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:"
|
| 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"
|
| 337 |
+
}
|
| 338 |
+
},
|
| 339 |
+
"nbformat": 4,
|
| 340 |
+
"nbformat_minor": 0
|
| 341 |
+
}
|
submissions_extracted/456/Q1.ipynb
ADDED
|
@@ -0,0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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 |
+
"from tqdm import tqdm\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"%matplotlib inline\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 |
+
"id_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 32 |
+
"df_id = pd.read_csv(id_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_id.head()"
|
| 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_id.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_id.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: Plot the target distribution (delivery_time)\n",
|
| 72 |
+
"# Target distribution\n",
|
| 73 |
+
"print(f\"Legendary: {df_id['Delivery_Time'].sum()}\")\n",
|
| 74 |
+
"print(f\"Normal: {(df_id['Delivery_Time'] == 0).sum()}\")"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"def check_missing_values(df):\n",
|
| 84 |
+
" missing_values = df.isnull().sum()\n",
|
| 85 |
+
" print(\"Missing Values per Column:\")\n",
|
| 86 |
+
" print(missing_values[missing_values > 0])\n",
|
| 87 |
+
" if missing_values.any():\n",
|
| 88 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 89 |
+
" else:\n",
|
| 90 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"check_missing_values(df)"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# Task 2: Write your code here:\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"df_clean = df_id.dropna(subset=cols).copy()\n",
|
| 105 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")\n"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 3: Write your code here:\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 4: Write your code here:"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# Task 5: Write your code here:"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# Task 6: 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,3,4,5: Write your code here:"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task 1: Write your code here:"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 2: Write your code here:"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task Bonus: Write your code here:"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
}
|
| 191 |
+
],
|
| 192 |
+
"metadata": {
|
| 193 |
+
"kernelspec": {
|
| 194 |
+
"display_name": "Python 3",
|
| 195 |
+
"name": "python3"
|
| 196 |
+
},
|
| 197 |
+
"language_info": {
|
| 198 |
+
"name": "python"
|
| 199 |
+
}
|
| 200 |
+
},
|
| 201 |
+
"nbformat": 4,
|
| 202 |
+
"nbformat_minor": 0
|
| 203 |
+
}
|
submissions_extracted/456/Q2.ipynb
ADDED
|
@@ -0,0 +1,431 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 torchvision.datasets import MNIST\n",
|
| 29 |
+
"from torch.utils.data import DataLoader\n",
|
| 30 |
+
"from torch.optim import Adam\n",
|
| 31 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 32 |
+
"import torch.nn.functional as F\n",
|
| 33 |
+
"import matplotlib.pyplot as plt\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Load Labels\n",
|
| 36 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 37 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"images = []\n",
|
| 40 |
+
"ages = []\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"# Load Images and Resize\n",
|
| 43 |
+
"print(\"Loading images...\")\n",
|
| 44 |
+
"for index, row in labels_df.iterrows():\n",
|
| 45 |
+
" img_name = row.iloc[0]\n",
|
| 46 |
+
" age = row.iloc[1]\n",
|
| 47 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
" if os.path.exists(img_path):\n",
|
| 50 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 51 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 52 |
+
" images.append(img_array)\n",
|
| 53 |
+
" ages.append(age)\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"X = np.array(images)\n",
|
| 56 |
+
"y = np.array(ages)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 59 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"# Split Data\n",
|
| 62 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 65 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 66 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 67 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"import torch\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"# Create a float32 tensor\n",
|
| 79 |
+
"x = torch.tensor([1.2, 2.3, 3.4], dtype=torch.float32)\n",
|
| 80 |
+
"print(x.dtype) # Output: torch.float32\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"# Convert to float16\n",
|
| 83 |
+
"x_half = x.to(torch.float16)\n",
|
| 84 |
+
"print(x_half.dtype) # Output: torch.float16"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"# 2. Create TensorDataset objects\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 96 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 97 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 98 |
+
"from torch.utils.data import TensorDataset\n",
|
| 99 |
+
"from torch.utils.data import DataLoader\n",
|
| 100 |
+
"import torch\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"# load data\n",
|
| 103 |
+
"data = load_breast_cancer()\n",
|
| 104 |
+
"X = data.data\n",
|
| 105 |
+
"y = data.target\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"# Split the dataset into training and testing sets\n",
|
| 108 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"# Standardize the data\n",
|
| 111 |
+
"scaler = StandardScaler()\n",
|
| 112 |
+
"X_train = scaler.fit_transform(X_train)\n",
|
| 113 |
+
"X_test = scaler.transform(X_test)\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"# transform to tensors\n",
|
| 116 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 117 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 118 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 119 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 122 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 123 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 124 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# Access a single sample from the dataset\n",
|
| 127 |
+
"# This helps verify the shape of one data sample\n",
|
| 128 |
+
"first_sample, _ = train_dataset[0]\n",
|
| 129 |
+
"print(f\"Shape of one sample: {first_sample.shape}\")\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# 3. Create DataLoaders\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"from torch.utils.data import DataLoader\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"# DataLoader for training data\n",
|
| 144 |
+
"train_loader = DataLoader(\n",
|
| 145 |
+
" train_dataset,\n",
|
| 146 |
+
" batch_size=32,\n",
|
| 147 |
+
" shuffle=True,\n",
|
| 148 |
+
" num_workers=2\n",
|
| 149 |
+
")\n",
|
| 150 |
+
"# DataLoader for test/validation data\n",
|
| 151 |
+
"test_loader = DataLoader(\n",
|
| 152 |
+
" test_dataset,\n",
|
| 153 |
+
" batch_size=32,\n",
|
| 154 |
+
" shuffle=False,\n",
|
| 155 |
+
" num_workers=2\n",
|
| 156 |
+
")\n",
|
| 157 |
+
"# Get the first batch from the training DataLoader\n",
|
| 158 |
+
"X_batch, y_batch = next(iter(train_loader))\n"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# 4. Print shape of one batch\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 170 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# 5. Display sample images\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# print one sample from the dataset\n",
|
| 183 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 184 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 187 |
+
"print(f\"Label: {sample_label}\")"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"class NN3Layer(nn.Module):\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 199 |
+
" super(NN3Layer, self).__init__()\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 202 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 205 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 206 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 209 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # ReLU activation for non-linearity\n",
|
| 212 |
+
" self.relu = nn.ReLU()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Defines how input data flows through the network\n",
|
| 215 |
+
" def forward(self, x):\n",
|
| 216 |
+
" # First hidden layer\n",
|
| 217 |
+
" z1 = self.layer1(x)\n",
|
| 218 |
+
" a1 = self.relu(z1)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Second hidden layer\n",
|
| 221 |
+
" z2 = self.layer2(a1)\n",
|
| 222 |
+
" a2 = self.relu(z2)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" # Output layer (raw scores / logits)\n",
|
| 225 |
+
" output = self.layer3(a2) # there is something missing here, remember? :)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" return output\n",
|
| 228 |
+
"\n"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 2: Write your training loop here:\n",
|
| 238 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 239 |
+
" # Set the model to training mode\n",
|
| 240 |
+
" model.train()\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" running_loss = 0.0\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 245 |
+
" # Move batch to the selected device\n",
|
| 246 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 247 |
+
" y_batch = y_batch.to(device)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # Forward pass\n",
|
| 250 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 251 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Backward pass & optimization\n",
|
| 254 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 255 |
+
" loss.backward() # Compute gradients\n",
|
| 256 |
+
" optimizer.step() # Update model parameters\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" running_loss += loss.item()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Average loss over all batches\n",
|
| 261 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" return avg_loss"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"# Task 3: Write your validation loop here:\n",
|
| 273 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 274 |
+
" # Set the model to evaluation mode\n",
|
| 275 |
+
" model.eval()\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" running_loss = 0.0\n",
|
| 278 |
+
" correct = 0\n",
|
| 279 |
+
" total = 0\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" with torch.no_grad():\n",
|
| 282 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 283 |
+
" # Move data to device\n",
|
| 284 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 285 |
+
" y_batch = y_batch.to(device)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" # Forward pass\n",
|
| 288 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 289 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 290 |
+
" running_loss += loss.item()\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # Apply Softmax to get probabilities\n",
|
| 293 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" # Multiclass predictions\n",
|
| 296 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
" # Accuracy calculation\n",
|
| 299 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 300 |
+
" total += y_batch.size(0)\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 303 |
+
" accuracy = correct / total\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" return avg_loss, accuracy"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 315 |
+
"# Device setup\n",
|
| 316 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# Model parameters\n",
|
| 319 |
+
"input_dim = 28 * 28 # MNIST images flattened\n",
|
| 320 |
+
"hidden_dim = 14 # Design choice\n",
|
| 321 |
+
"output_dim = 10 # Digits 0–9\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"# Instantiate model\n",
|
| 324 |
+
"model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"# Print the model architecture\n",
|
| 327 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 328 |
+
"print(model)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"# Calculate the total number of trainable parameters\n",
|
| 331 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 332 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
},
|
| 337 |
+
{
|
| 338 |
+
"cell_type": "code",
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"source": [
|
| 341 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 342 |
+
"num_epochs = 20\n",
|
| 343 |
+
"learning_rate = 0.001\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 346 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 347 |
+
"# Define optimizer\n",
|
| 348 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"\n",
|
| 358 |
+
"# Task 1: Write your code here:\n",
|
| 359 |
+
"train_losses = []\n",
|
| 360 |
+
"val_losses = []\n",
|
| 361 |
+
"val_accuracies = []\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"print('Starting Training...')\n",
|
| 364 |
+
"for epoch in range(num_epochs):\n",
|
| 365 |
+
" # Train one epoch\n",
|
| 366 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 367 |
+
"\n",
|
| 368 |
+
" # Validate\n",
|
| 369 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 370 |
+
"\n",
|
| 371 |
+
" train_losses.append(train_loss)\n",
|
| 372 |
+
" val_losses.append(val_loss)\n",
|
| 373 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 374 |
+
"\n",
|
| 375 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 376 |
+
"\n",
|
| 377 |
+
"print('Training Complete!')"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
},
|
| 382 |
+
{
|
| 383 |
+
"cell_type": "code",
|
| 384 |
+
"metadata": {},
|
| 385 |
+
"source": [
|
| 386 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 387 |
+
"# Set model to evaluation mode\n",
|
| 388 |
+
"model.eval()\n",
|
| 389 |
+
"# Get one batch from the test DataLoader\n",
|
| 390 |
+
"images, labels = next(iter(test_loader))\n",
|
| 391 |
+
"# Move images to device\n",
|
| 392 |
+
"images = images.to(device)\n",
|
| 393 |
+
"labels = labels.to(device)\n",
|
| 394 |
+
"\n",
|
| 395 |
+
"with torch.no_grad():\n",
|
| 396 |
+
" # Flatten images before passing to the model\n",
|
| 397 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 398 |
+
" predictions = torch.argmax(outputs, dim=1)\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"# Move tensors back to CPU for plotting\n",
|
| 401 |
+
"images = images.cpu()\n",
|
| 402 |
+
"labels = labels.cpu()\n",
|
| 403 |
+
"predictions = predictions.cpu()\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"# Plot first 6 predictions\n",
|
| 406 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 407 |
+
"for i in range(6):\n",
|
| 408 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 409 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 410 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 411 |
+
" plt.axis('off')\n",
|
| 412 |
+
"\n",
|
| 413 |
+
"plt.tight_layout()\n",
|
| 414 |
+
"plt.show()"
|
| 415 |
+
],
|
| 416 |
+
"execution_count": null,
|
| 417 |
+
"outputs": []
|
| 418 |
+
}
|
| 419 |
+
],
|
| 420 |
+
"metadata": {
|
| 421 |
+
"kernelspec": {
|
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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 |
+
"from tqdm import tqdm\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 |
+
"id_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 34 |
+
"df_id = pd.read_csv(id_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_id.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_id.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_id.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 |
+
"\n",
|
| 75 |
+
"\n"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# Task 2: Write your code here:"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"# Task 3: Write your code here:"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 4: Write your code here:"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 5: Write your code here:"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 1: Write your code here:\n",
|
| 121 |
+
"X = df.drop(\"status\", axis=1).astype(float)\n",
|
| 122 |
+
"y = df['status'].astype(float)"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"# Task 1: Write your code here:"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 2: Write your code here:"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task Bonus: Write your code here:"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
}
|
| 163 |
+
],
|
| 164 |
+
"metadata": {
|
| 165 |
+
"kernelspec": {
|
| 166 |
+
"display_name": "Python 3",
|
| 167 |
+
"name": "python3"
|
| 168 |
+
},
|
| 169 |
+
"language_info": {
|
| 170 |
+
"name": "python"
|
| 171 |
+
}
|
| 172 |
+
},
|
| 173 |
+
"nbformat": 4,
|
| 174 |
+
"nbformat_minor": 0
|
| 175 |
+
}
|
submissions_extracted/457/Q1.ipynb
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 kagglehub\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"from tqdm import tqdm\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n"
|
| 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)\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 5: Write your code here:\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:\n",
|
| 100 |
+
"df = df.drop('Order_ID', axis=1)\n",
|
| 101 |
+
"df.head()"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# Task 2: Write your code here:\n",
|
| 111 |
+
"print(df.isnull().sum())\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
|
| 114 |
+
"df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
|
| 115 |
+
"df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
|
| 116 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna('None')\n",
|
| 117 |
+
"df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"print(\"\\n---------------------------------------\\n\")\n",
|
| 120 |
+
"print(df.isnull().sum())\n",
|
| 121 |
+
"\n"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 3: Write your code here:\n",
|
| 131 |
+
"def check_duplicates(df):\n",
|
| 132 |
+
" duplicates = df.duplicated().sum()\n",
|
| 133 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 134 |
+
" if duplicates > 0:\n",
|
| 135 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 136 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 137 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 138 |
+
" else:\n",
|
| 139 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"check_duplicates(df)"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"check_duplicates(df) # run again to check if there are any duplicates remaining"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 160 |
+
"# Task 4: Write your code here:\n",
|
| 161 |
+
"print(len(df['Time_of_Day'].unique()))\n",
|
| 162 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"for col in categorical_cols:\n",
|
| 168 |
+
" le = LabelEncoder()\n",
|
| 169 |
+
" df[col] = le.fit_transform(df[col].astype(str))\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"df.head()"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 5: Write your code here:\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"print(df['Distance_km'])\n",
|
| 185 |
+
"scaler = StandardScaler()\n",
|
| 186 |
+
"#df['Distance_km'] = float(df['Distance_km'])\n",
|
| 187 |
+
"features = df.columns.drop(\"Delivery_Time\")\n",
|
| 188 |
+
"df[features] = scaler.fit_transform(features)"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 6: Write your code here:\n",
|
| 198 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 199 |
+
" print(\"Target Distribution:\")\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 202 |
+
" plt.show()\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"check_target_imbalance(df, \"Delivery_Time\")"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"# there is a slight imbalance, some values are much lower than others"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 1: Write your code here:\n",
|
| 223 |
+
"X = df[df.columns.drop(\"Delivery_Time\")]\n",
|
| 224 |
+
"y = df['Delivery_Time']\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"y"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"lr_losses = []\n",
|
| 236 |
+
"lr_mse = []\n",
|
| 237 |
+
"lr_rmse = []\n",
|
| 238 |
+
"lr_r2 = []"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 248 |
+
"from sklearn.model_selection import KFold\n",
|
| 249 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 252 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 253 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 254 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 255 |
+
"model = RandomForestRegressor(n_estimators=200)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"lr_losses = []\n",
|
| 258 |
+
"lr_mse = []\n",
|
| 259 |
+
"lr_rmse = []\n",
|
| 260 |
+
"lr_r2 = []\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 263 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 266 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # Train\n",
|
| 271 |
+
" model.fit(X_train, y_train)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Predict\n",
|
| 274 |
+
" y_pred = model.predict(X_test)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" # Calculate metrics\n",
|
| 277 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 278 |
+
" rmse = np.sqrt(mse)\n",
|
| 279 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" # Store results\n",
|
| 282 |
+
" # Store results\n",
|
| 283 |
+
" lr_mse.append(mse)\n",
|
| 284 |
+
" lr_rmse.append(rmse)\n",
|
| 285 |
+
" lr_r2.append(r2)\n",
|
| 286 |
+
" print(\"MSE\")\n",
|
| 287 |
+
" print(pd.array(lr_mse))\n",
|
| 288 |
+
" print(\"RMSE\")\n",
|
| 289 |
+
" print(pd.array(lr_rmse))\n",
|
| 290 |
+
" print(\"R2\")\n",
|
| 291 |
+
" print(pd.array(lr_r2))\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"\n"
|
| 295 |
+
],
|
| 296 |
+
"execution_count": null,
|
| 297 |
+
"outputs": []
|
| 298 |
+
},
|
| 299 |
+
{
|
| 300 |
+
"cell_type": "code",
|
| 301 |
+
"metadata": {},
|
| 302 |
+
"source": [
|
| 303 |
+
"# Task 1: Write your code here:"
|
| 304 |
+
],
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"outputs": []
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"cell_type": "code",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"# Task 2: Write your code here:"
|
| 313 |
+
],
|
| 314 |
+
"execution_count": null,
|
| 315 |
+
"outputs": []
|
| 316 |
+
},
|
| 317 |
+
{
|
| 318 |
+
"cell_type": "code",
|
| 319 |
+
"metadata": {},
|
| 320 |
+
"source": [
|
| 321 |
+
"# Task Bonus: Write your code here:"
|
| 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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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 |
+
"import torch\n",
|
| 28 |
+
"import torch.nn as nn\n",
|
| 29 |
+
"from torch.optim import AdamW\n",
|
| 30 |
+
"import matplotlib.pyplot as plt\n",
|
| 31 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 32 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 33 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Load Labels\n",
|
| 36 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 37 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"images = []\n",
|
| 40 |
+
"ages = []\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"# Load Images and Resize\n",
|
| 43 |
+
"print(\"Loading images...\")\n",
|
| 44 |
+
"for index, row in labels_df.iterrows():\n",
|
| 45 |
+
" img_name = row.iloc[0]\n",
|
| 46 |
+
" age = row.iloc[1]\n",
|
| 47 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
" if os.path.exists(img_path):\n",
|
| 50 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 51 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 52 |
+
" images.append(img_array)\n",
|
| 53 |
+
" ages.append(age)\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"X = np.array(images)\n",
|
| 56 |
+
"y = np.array(ages)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 59 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 60 |
+
"\n",
|
| 61 |
+
"# Split Data\n",
|
| 62 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 65 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 66 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 67 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 79 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 80 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 81 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# 2. Create TensorDataset objects\n",
|
| 91 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 92 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 93 |
+
"\n"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# 3. Create DataLoaders\n",
|
| 103 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 104 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 105 |
+
"\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 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 116 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 117 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# 5. Display sample images\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"images, labels = next(iter(train_loader))\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"# Display the first 6 images in the batch\n",
|
| 131 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"for i in range(6):\n",
|
| 134 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 137 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
" plt.imshow(img)\n",
|
| 140 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 141 |
+
" plt.axis('off')\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"plt.tight_layout()\n",
|
| 144 |
+
"plt.show()\n"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 1: Write your model class here:\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 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 160 |
+
" self.layer1 = nn.Linear(input_dim,hidden_dim)# <YOUR CODE HERE>\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 163 |
+
" self.layer2 = nn.Linear(hidden_dim, 256)# <YOUR CODE HERE>\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 166 |
+
" self.layer3 = nn.Linear(256, 128)# <YOUR CODE HERE>\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 169 |
+
" self.layer4 = nn.Linear(128, output_dim)# <YOUR CODE HERE\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # activation function 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 |
+
" # Layer 1: TODO\n",
|
| 177 |
+
" z1 = self.layer1(x)#YOUR CODE HERE)\n",
|
| 178 |
+
" a1 = self.relu(z1)#YOUR CODE HERE)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Layer 2 TODO\n",
|
| 181 |
+
" z2 = self.layer2(a1)# <YOUR CODE HERE>)\n",
|
| 182 |
+
" a2 = self.relu(z2)# <YOUR CODE HERE>)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" # Layer 3 TODO\n",
|
| 185 |
+
" z3 = self.layer3(a2)# <YOUR CODE HERE>)\n",
|
| 186 |
+
" a3 = self.relu(z3)# <YOUR CODE HERE>)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" # Layer 4 TODO\n",
|
| 189 |
+
" z4 = self.layer4(a3)# <YOUR CODE HERE>)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" return z4"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"# Task 2: Write your training loop here:\n",
|
| 204 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 205 |
+
" # Set the model to training mode\n",
|
| 206 |
+
" model.train()\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" running_loss = 0.0\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 211 |
+
" # Move batch to the selected device\n",
|
| 212 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 213 |
+
" y_batch = y_batch.to(device)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # Forward pass\n",
|
| 216 |
+
" # TODO: make predictions\n",
|
| 217 |
+
" outputs = model.forward(X_batch.flatten(start_dim=1))# <YOUR CODE HERE>\n",
|
| 218 |
+
" # TODO: compute loss\n",
|
| 219 |
+
" loss = criterion(outputs, y_batch)# <YOUR CODE HERE>\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"
|
| 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.view(X_batch.size(0), -1).to(device)\n",
|
| 253 |
+
" y_batch = y_batch.to(device)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Forward pass\n",
|
| 256 |
+
" # TODO: make predictions\n",
|
| 257 |
+
" outputs = model.forward(X_batch)# <YOUR CODE HERE>\n",
|
| 258 |
+
" # TODO: compute loss\n",
|
| 259 |
+
" loss = criterion(outputs,y_batch)# <YOUR CODE HERE>\n",
|
| 260 |
+
" running_loss += loss.item()\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 263 |
+
" probabilities = F.softmax(outputs)# <YOUR CODE HERE>, dim=1)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # TODO: Multiclass predictions\n",
|
| 266 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # Accuracy calculation\n",
|
| 269 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 270 |
+
" total += y_batch.size(0)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 273 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 274 |
+
" accuracy = correct / total # <YOUR CODE HERE>\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" return avg_loss, accuracy\n"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Device setup\n",
|
| 288 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"# Model parameters\n",
|
| 291 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 292 |
+
"input_dim = 3*36*36 # <YOUR CODE HERE>\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"# TODO: choose number of hidden neurons\n",
|
| 295 |
+
"hidden_dim = 512# <YOUR CODE HERE>\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"# TODO: what are the number of classes ?\n",
|
| 298 |
+
"output_dim = 10 # <YOUR CODE HERE>\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 301 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"criterion = nn.MSELoss()\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"optimizer = AdamW(model.parameters(), lr=0.001)# <YOUR CODE HERE>, # <YOUR CODE HERE>)\n"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 315 |
+
"# Run Training\n",
|
| 316 |
+
"num_epochs = 20\n",
|
| 317 |
+
"train_losses = []\n",
|
| 318 |
+
"val_losses = []\n",
|
| 319 |
+
"val_accuracies = []\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"print('Starting Training...')\n",
|
| 322 |
+
"for epoch in range(num_epochs):\n",
|
| 323 |
+
" # Train one epoch\n",
|
| 324 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" # Validate\n",
|
| 327 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
" train_losses.append(train_loss)\n",
|
| 330 |
+
" val_losses.append(val_loss)\n",
|
| 331 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"print('Training Complete!')"
|
| 336 |
+
],
|
| 337 |
+
"execution_count": null,
|
| 338 |
+
"outputs": []
|
| 339 |
+
},
|
| 340 |
+
{
|
| 341 |
+
"cell_type": "code",
|
| 342 |
+
"metadata": {},
|
| 343 |
+
"source": [
|
| 344 |
+
"# Task 1: Write your code here:\n",
|
| 345 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 348 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 349 |
+
"plt.title('Loss over Epochs')\n",
|
| 350 |
+
"plt.xlabel('Epoch')\n",
|
| 351 |
+
"plt.ylabel('Loss')\n",
|
| 352 |
+
"plt.legend()\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"plt.tight_layout()\n",
|
| 355 |
+
"plt.show()"
|
| 356 |
+
],
|
| 357 |
+
"execution_count": null,
|
| 358 |
+
"outputs": []
|
| 359 |
+
},
|
| 360 |
+
{
|
| 361 |
+
"cell_type": "code",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"source": [
|
| 364 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 365 |
+
],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
}
|
| 369 |
+
],
|
| 370 |
+
"metadata": {
|
| 371 |
+
"kernelspec": {
|
| 372 |
+
"display_name": "Python 3",
|
| 373 |
+
"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 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 |
+
"from tqdm import tqdm\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 16 |
+
"import os\n",
|
| 17 |
+
"import pandas as pd\n",
|
| 18 |
+
"import numpy as np\n",
|
| 19 |
+
"from PIL import Image\n",
|
| 20 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"import torch\n",
|
| 23 |
+
"import torch.nn as nn\n",
|
| 24 |
+
"from torch.optim import AdamW\n",
|
| 25 |
+
"import matplotlib.pyplot as plt\n",
|
| 26 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 27 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 28 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Download latest version\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"print(\"Path to dataset files:\", path)"
|
| 36 |
+
],
|
| 37 |
+
"execution_count": null,
|
| 38 |
+
"outputs": []
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"cell_type": "code",
|
| 42 |
+
"metadata": {},
|
| 43 |
+
"source": [
|
| 44 |
+
"# Task 1: Write your code here:\n",
|
| 45 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"df = pd.read_csv(csv_path)"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"# Task 2: Write your code here:\n",
|
| 57 |
+
"df.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.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 |
+
"df.describe()"
|
| 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 |
+
"print(df.isnull().sum())\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"df = df.dropna()\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"print(df.isnull().sum())\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 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"# NO NEED FOR ENCODING!!"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 3: Write your code here:"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 4: Write your code here:"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# Task 5: Write your code here:"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# Task 1: Write your code here:"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 1: Write your code here:"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task 2: Write your code here:"
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task Bonus: Write your code here:"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
}
|
| 182 |
+
],
|
| 183 |
+
"metadata": {
|
| 184 |
+
"kernelspec": {
|
| 185 |
+
"display_name": "Python 3",
|
| 186 |
+
"name": "python3"
|
| 187 |
+
},
|
| 188 |
+
"language_info": {
|
| 189 |
+
"name": "python"
|
| 190 |
+
}
|
| 191 |
+
},
|
| 192 |
+
"nbformat": 4,
|
| 193 |
+
"nbformat_minor": 0
|
| 194 |
+
}
|
submissions_extracted/458/Q1.ipynb
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"# Download latest version\n",
|
| 11 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"print(\"Path to dataset files:\", path)"
|
| 14 |
+
],
|
| 15 |
+
"execution_count": null,
|
| 16 |
+
"outputs": []
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"cell_type": "code",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"# Task 1: Write your code here:\n",
|
| 23 |
+
"# Load CSV file\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"food_delivery= os.path.join(path, 'Q1_data.csv')\n",
|
| 26 |
+
"df_food_delivery = pd.read_csv(food_delivery)\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 |
+
"df_food_delivery.head(10)\n",
|
| 37 |
+
"#it will read the first 10 lines from the dataframe"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"# Task 3: Write your code here:\n",
|
| 47 |
+
"df_food_delivery.info()\n",
|
| 48 |
+
"#it will check the data types and structure"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 4: Write your code here:\n",
|
| 58 |
+
"df_food_delivery.describe()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 5: Write your code here:\n",
|
| 68 |
+
"# Define target\n",
|
| 69 |
+
"target = \"Delivery_Time\"\n",
|
| 70 |
+
"X = df_food_delivery.drop(columns=[target])\n",
|
| 71 |
+
"y=df_food_delivery[target]\n",
|
| 72 |
+
"# here i drouped the column delivery_time since it is the target so i do not want it to appear in the dataframe"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 1: Write your code here:\n",
|
| 82 |
+
"df_food_delivery.drop(columns=['Order_ID'])"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 2: Write your code here:\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"df_food_delivery.isnull().sum()"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# Task 3: Write your code here:\n",
|
| 103 |
+
"df_food_delivery.duplicated()\n",
|
| 104 |
+
"df_food_delivery.drop_duplicates()"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 4: Write your code here:\n",
|
| 114 |
+
"#import OneHotEncoder\n",
|
| 115 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# we know that OneHotEncoder is usually for X features and not y'\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"print('data before encoding:\\n', df_food_delivery ) #show before encoding\n",
|
| 120 |
+
"# Instantiate OneHotEncoder\n",
|
| 121 |
+
"#'sparse_output=False mean its a normal NumPy array'\n",
|
| 122 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False)\n",
|
| 123 |
+
"data_onehot_encoded = onehot_encoder.fit_transform(df_food_delivery)\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 5: Write your code here:\n",
|
| 135 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 136 |
+
"#'StandardScaler used to Converts each feature to: mean = 0 std = 1'\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 139 |
+
"data_standard_scaled = standard_scaler.fit_transform(df_food_delivery) # Apply fit_transform\n",
|
| 140 |
+
"print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 6: Write your code here:\n",
|
| 150 |
+
"import numpy as np # for random data generation\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"np.random.seed(42) # for reproducbility\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
|
| 155 |
+
"y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with nois"
|
| 156 |
+
],
|
| 157 |
+
"execution_count": null,
|
| 158 |
+
"outputs": []
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"cell_type": "code",
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"source": [
|
| 164 |
+
"# Task 1: Write your code here:\n",
|
| 165 |
+
"# Define features (X) and target (y)\n",
|
| 166 |
+
"feature_cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\n",
|
| 167 |
+
" 'Preparation_Time_min\t', 'Courier_Experience_yrs' ]\n",
|
| 168 |
+
"X = df_food_delivery[feature_cols]\n",
|
| 169 |
+
"y = df_food_delivery['Delivery_Time']"
|
| 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 |
+
"from sklearn.model_selection import KFold\n",
|
| 180 |
+
"# Define K-Fold Cross Validation\n",
|
| 181 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42) #shuffle=true is to make sure the data is not in the same order they were and now it is random\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"# Iterate through folds\n",
|
| 184 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 185 |
+
" # indexing for each fold\n",
|
| 186 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 187 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 188 |
+
" # print shapes\n",
|
| 189 |
+
" print(f\"Fold {fold}\")\n",
|
| 190 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 191 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 192 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 193 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 194 |
+
" print(\"-\" * 30)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 197 |
+
"# Train RandomForestClassifier\n",
|
| 198 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 199 |
+
" class_weight='balanced', random_state=42)\n",
|
| 200 |
+
"model.fit(X_train, y_train)\n",
|
| 201 |
+
"print(\"Model trained!\")\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 205 |
+
"y_pred = model.predict(X_test) #here er put x test inside the model to make a prediction and the result of the prediction will be store in y_pred\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 208 |
+
" print(\"MAE :\", mae)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"print(avg=kf/n_splits=5)\n"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# Task 1: Write your code here:\n",
|
| 221 |
+
"# Feature importance\n",
|
| 222 |
+
"import matplotlib.pyplot as plt\n",
|
| 223 |
+
"importance = df_food_delivery({\n",
|
| 224 |
+
" 'feature': feature_cols,\n",
|
| 225 |
+
" 'importance': model.x\n",
|
| 226 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 229 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 230 |
+
"plt.xlabel('Importance')\n",
|
| 231 |
+
"plt.title('Feature Importance')\n",
|
| 232 |
+
"plt.gca().invert_yaxis()\n",
|
| 233 |
+
"plt.show()"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 2: Write your code here:\n",
|
| 243 |
+
"import matplotlib.pyplot as plt\n",
|
| 244 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 245 |
+
"plt.hist(df_food_delivery['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='blue')\n",
|
| 246 |
+
"plt.title('delivery time Distrbution')\n",
|
| 247 |
+
"plt.xlabel('Preparation_Time_min')\n",
|
| 248 |
+
"plt.ylabel('predicted delivery time ')\n",
|
| 249 |
+
"plt.show()"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"# Task Bonus: Write your code here:"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
}
|
| 263 |
+
],
|
| 264 |
+
"metadata": {
|
| 265 |
+
"kernelspec": {
|
| 266 |
+
"display_name": "Python 3",
|
| 267 |
+
"name": "python3"
|
| 268 |
+
},
|
| 269 |
+
"language_info": {
|
| 270 |
+
"name": "python"
|
| 271 |
+
}
|
| 272 |
+
},
|
| 273 |
+
"nbformat": 4,
|
| 274 |
+
"nbformat_minor": 0
|
| 275 |
+
}
|
submissions_extracted/458/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 |
+
"\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(X_train ,dtype=torch.float32)\n",
|
| 73 |
+
"y = torch.tensor(X_test ,dtype=torch.float32)\n",
|
| 74 |
+
"z = torch.tensor(y_train ,dtype=torch.float32)\n",
|
| 75 |
+
"a = torch.tensor(y_test ,dtype=torch.float32)\n",
|
| 76 |
+
"#float32 since it is regression mode\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 sklearn.model_selection import train_test_split\n",
|
| 88 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 89 |
+
"from torch.utils.data import TensorDataset\n",
|
| 90 |
+
"from torch.utils.data import DataLoader\n",
|
| 91 |
+
"import torch\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 95 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 96 |
+
"test_dataset = TensorDataset(y,a)\n",
|
| 97 |
+
"train_dataset = TensorDataset(x, z)\n",
|
| 98 |
+
"\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# 3. Create DataLoaders\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"from torch.utils.data import DataLoader\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"# DataLoader for training data\n",
|
| 112 |
+
"train_loader = DataLoader(\n",
|
| 113 |
+
" train_dataset,\n",
|
| 114 |
+
" batch_size=32,\n",
|
| 115 |
+
" shuffle=True,\n",
|
| 116 |
+
" num_workers=2\n",
|
| 117 |
+
")\n",
|
| 118 |
+
"#shuffle=True, sice it is training\n",
|
| 119 |
+
"\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 |
+
"#shuffle=False, sice it is testing\n"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# 4. Print shape of one batch\n",
|
| 138 |
+
"# Get the first batch from the training DataLoader\n",
|
| 139 |
+
"X_batch= next(iter(train_loader))\n",
|
| 140 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"\n"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# 5. Display sample images\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 model class here:\n",
|
| 162 |
+
"import torch\n",
|
| 163 |
+
"import torch.nn as nn\n",
|
| 164 |
+
"class NN4Layer(nn.Module):\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" def __init__(self, input_dim , hidden_dim1,hidden_dim2,hidden_dim3,hidden_dim4):\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" super(NN4Layer, self).__init__()\n",
|
| 169 |
+
" #input_dim = num of features, hidden_dim = num of neurons\n",
|
| 170 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim1)\n",
|
| 171 |
+
" self.layer2 = nn.Linear(hidden_dim1,hidden_dim2 )\n",
|
| 172 |
+
" self.layer3 = nn.Linear(hidden_dim2, hidden_dim3)\n",
|
| 173 |
+
" # hidden_dim = num of neurons, Output for binary classification is 1\n",
|
| 174 |
+
" self.layer4 = nn.Linear(hidden_dim3, 1)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # non-linearity activation function\n",
|
| 178 |
+
" self.relu = nn.ReLU()\n",
|
| 179 |
+
" # output activation function\n",
|
| 180 |
+
" self.sigmoid = nn.Sigmoid()\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # forward pass\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" def forward(self, x):\n",
|
| 185 |
+
" z1 = self.layer1(x)\n",
|
| 186 |
+
" a1 = self.relu(z1)\n",
|
| 187 |
+
" z2 = self.layer2(a1)\n",
|
| 188 |
+
" a2 = self.sigmoid(z2)\n",
|
| 189 |
+
" z3 = self.layer3(a2)\n",
|
| 190 |
+
" a3 = self.sigmoid(z3)\n",
|
| 191 |
+
" z4 = self.layer4(a3)\n",
|
| 192 |
+
" a5 = self.sigmoid(z4)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" return a5\n",
|
| 195 |
+
"\n",
|
| 196 |
+
""
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 2: Write your training loop here:\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)\n",
|
| 215 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Forward pass\n",
|
| 218 |
+
" outputs = model(X_batch)\n",
|
| 219 |
+
" loss = criterion(outputs, y_batch) #'criterion is a loss function'\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"
|
| 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(): # Disable gradient computation\n",
|
| 250 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 251 |
+
" # Move batch to the selected device\n",
|
| 252 |
+
" X_batch = X_batch.to(device)\n",
|
| 253 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Forward pass\n",
|
| 256 |
+
" outputs = model(X_batch)\n",
|
| 257 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 258 |
+
" running_loss += loss.item()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Binary predictions\n",
|
| 261 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Accuracy calculation\n",
|
| 264 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 265 |
+
" total += y_batch.size(0)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 268 |
+
" accuracy = correct / total\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" return avg_loss, accuracy"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 280 |
+
],
|
| 281 |
+
"execution_count": null,
|
| 282 |
+
"outputs": []
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"cell_type": "code",
|
| 286 |
+
"metadata": {},
|
| 287 |
+
"source": [
|
| 288 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 289 |
+
"# Device configuration\n",
|
| 290 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 291 |
+
"print(f\"Using device: {device}\")\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"num_epochs = 20 #'iteration for the whole data in training or testing'\n",
|
| 294 |
+
"learning_rate = 0.001\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Model, Criterion, Optimizer\n",
|
| 297 |
+
"input_dim = X_train.shape[1] #'1 mean num of features , if its 0 mean num of samples '\n",
|
| 298 |
+
"hidden_dim = 10\n",
|
| 299 |
+
"model =NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 300 |
+
"criterion = nn.BCELoss()\n",
|
| 301 |
+
"optimizer = Adam(model.parameters(), lr=learning_rate)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"# Run Training\n",
|
| 305 |
+
"train_losses = []\n",
|
| 306 |
+
"val_losses = [] #'val loss for each epoch'\n",
|
| 307 |
+
"val_accuracies = []\n",
|
| 308 |
+
"\n",
|
| 309 |
+
"print('Starting Training...')\n",
|
| 310 |
+
"for epoch in range(num_epochs):\n",
|
| 311 |
+
" # Train one epoch\n",
|
| 312 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
" # Validate\n",
|
| 315 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" train_losses.append(train_loss)\n",
|
| 318 |
+
" val_losses.append(val_loss)\n",
|
| 319 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" if (epoch + 1) % 5 == 0: #'for every 5 epoch it will print the loss'\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!')"
|
| 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 |
+
"# Plotting results\n",
|
| 335 |
+
"import matplotlib.pyplot as plt\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/459/Q1.ipynb
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")"
|
| 24 |
+
],
|
| 25 |
+
"execution_count": null,
|
| 26 |
+
"outputs": []
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"# Task 2: Write your code here:\n",
|
| 33 |
+
"df.head()"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 3: Write your code here:\n",
|
| 43 |
+
"df.info()"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 4: Write your code here:\n",
|
| 53 |
+
"df.describe()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 5: Write your code here:\n",
|
| 63 |
+
"import matplotlib.pyplot as plt\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 66 |
+
"plt.hist(df['Delivery_Time'], bins=50, edgecolor='black')\n",
|
| 67 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 68 |
+
"plt.xlabel('Delivery')\n",
|
| 69 |
+
"plt.ylabel('Frequency')\n",
|
| 70 |
+
"plt.show()"
|
| 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 |
+
"df = df.drop('Order_ID', axis=1)"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 2: Write your code here:\n",
|
| 90 |
+
"df.dropna(inplace=True)"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 3: Write your code here:\n",
|
| 100 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 101 |
+
"if duplicate_rows > 0:\n",
|
| 102 |
+
" print(f\"Found {duplicate_rows} duplicate rows.\")\n",
|
| 103 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 104 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 105 |
+
"else:\n",
|
| 106 |
+
" print(\"No duplicate rows found.\")\n",
|
| 107 |
+
"\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"# Task 4: Write your code here:\n",
|
| 117 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 118 |
+
"categorical_cols = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n",
|
| 119 |
+
"for col in categorical_cols:\n",
|
| 120 |
+
" le = LabelEncoder()\n",
|
| 121 |
+
" df[col] = le.fit_transform(df[col])"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 5: Write your code here:\n",
|
| 131 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # NO TARGET SCALING\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"scaler = StandardScaler()\n",
|
| 136 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 137 |
+
"df.head()"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# Task 6: Write your code here:\n",
|
| 147 |
+
"import seaborn as sns\n",
|
| 148 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 149 |
+
" print(\"Target Distribution:\")\n",
|
| 150 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 151 |
+
" sns.countplot(x=df[target_column])\n",
|
| 152 |
+
" plt.title(\"Target Distribution\")\n",
|
| 153 |
+
" plt.show()\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"check_target_imbalance(df, \"Delivery_Time\")\n",
|
| 156 |
+
"#Target is balanced"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 1: Write your code here:\n",
|
| 166 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 167 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 168 |
+
"y = df['Delivery_Time']\n",
|
| 169 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"\n",
|
| 179 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 182 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 183 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 184 |
+
"import numpy as np\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"n_splits = 5 # K\n",
|
| 187 |
+
"mae_scores = []\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 190 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 193 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # 1. Split data\n",
|
| 196 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 197 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" # 2. Train & Validate sklearn models\n",
|
| 200 |
+
" model = RandomForestClassifier()\n",
|
| 201 |
+
" model.fit(X_train, y_train) # train\n",
|
| 202 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 203 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"print(np.mean(mae_scores))"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 1: Write your code here:\n",
|
| 215 |
+
"importances = {}\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"importances['Random Forest'] = model.feature_importances_\n",
|
| 218 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 219 |
+
"axes = axes.flatten()\n",
|
| 220 |
+
"features = X.columns\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 223 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" ax = axes[i]\n",
|
| 226 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 227 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 228 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"plt.show()"
|
| 231 |
+
],
|
| 232 |
+
"execution_count": null,
|
| 233 |
+
"outputs": []
|
| 234 |
+
},
|
| 235 |
+
{
|
| 236 |
+
"cell_type": "code",
|
| 237 |
+
"metadata": {},
|
| 238 |
+
"source": [
|
| 239 |
+
"# Task 5: Write your code here:\n",
|
| 240 |
+
"import matplotlib.pyplot as plt\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 243 |
+
"plt.hist(y_pred, bins=50, edgecolor='black')\n",
|
| 244 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 245 |
+
"plt.xlabel('Delivery')\n",
|
| 246 |
+
"plt.ylabel('Frequency')\n",
|
| 247 |
+
"plt.show()"
|
| 248 |
+
],
|
| 249 |
+
"execution_count": null,
|
| 250 |
+
"outputs": []
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"# Task Bonus: Write your code here:"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
}
|
| 261 |
+
],
|
| 262 |
+
"metadata": {
|
| 263 |
+
"kernelspec": {
|
| 264 |
+
"display_name": "Python 3",
|
| 265 |
+
"name": "python3"
|
| 266 |
+
},
|
| 267 |
+
"language_info": {
|
| 268 |
+
"name": "python"
|
| 269 |
+
}
|
| 270 |
+
},
|
| 271 |
+
"nbformat": 4,
|
| 272 |
+
"nbformat_minor": 0
|
| 273 |
+
}
|
submissions_extracted/459/Q2.ipynb
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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.tensor(X_train)\n",
|
| 71 |
+
"X_test = torch.tensor(X_test)\n",
|
| 72 |
+
"y_train = torch.tensor(y_train)\n",
|
| 73 |
+
"y_train = torch.tensor(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 |
+
"\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# 3. Create DataLoaders\n",
|
| 98 |
+
"from torch.utils.data import DataLoader\n",
|
| 99 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 100 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 101 |
+
"\n"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# 4. Print shape of one batch\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 113 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 114 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# 5. Display sample images\n",
|
| 124 |
+
"\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 1: Write your model class here:\n",
|
| 134 |
+
"import torch.nn as nn\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"class NN4Layer(nn.Module):\n",
|
| 137 |
+
"\n",
|
| 138 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 139 |
+
" super(NN4Layer, self).__init__()\n",
|
| 140 |
+
"\n",
|
| 141 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 142 |
+
"\n",
|
| 143 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 144 |
+
"\n",
|
| 145 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 146 |
+
"\n",
|
| 147 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 148 |
+
"\n",
|
| 149 |
+
" self.relu = nn.ReLU()\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" def forward(self, x):\n",
|
| 152 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" output = self.layer4(a3)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" return output\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 2: Write your training loop here:\n",
|
| 170 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 171 |
+
" model.train()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" running_loss = 0.0\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 176 |
+
" X_batch = X_batch.to(device)\n",
|
| 177 |
+
" y_batch = y_batch.to(device)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" outputs = model(X_batch)\n",
|
| 180 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" optimizer.zero_grad()\n",
|
| 183 |
+
" loss.backward()\n",
|
| 184 |
+
" optimizer.step()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" running_loss += loss.item()\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" return avg_loss\n"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 3: Write your validation loop here:\n",
|
| 200 |
+
"import torch.nn.functional as F\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 203 |
+
" model.eval()\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" running_loss = 0.0\n",
|
| 206 |
+
" correct = 0\n",
|
| 207 |
+
" total = 0\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" with torch.no_grad():\n",
|
| 210 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 211 |
+
" X_batch = X_batch.to(device)\n",
|
| 212 |
+
" y_batch = y_batch.to(device)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" outputs = model(X_batch)\n",
|
| 215 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 216 |
+
" running_loss += loss.item()\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 223 |
+
" total += y_batch.size(0)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 226 |
+
" accuracy = correct / total\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" return avg_loss, accuracy"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 238 |
+
"from torch.optim import AdamW\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"input_dim = X_train.shape[1]\n",
|
| 243 |
+
"hidden_dim = 14\n",
|
| 244 |
+
"output_dim = 4\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 249 |
+
"print(model)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 252 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"num_epochs = 20\n",
|
| 255 |
+
"learning_rate = 0.001\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 258 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 268 |
+
"train_losses = []\n",
|
| 269 |
+
"val_losses = []\n",
|
| 270 |
+
"val_accuracies = []\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"print('Starting Training...')\n",
|
| 273 |
+
"for epoch in range(num_epochs):\n",
|
| 274 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" train_losses.append(train_loss)\n",
|
| 279 |
+
" val_losses.append(val_loss)\n",
|
| 280 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"print('Training Complete!')"
|
| 285 |
+
],
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"outputs": []
|
| 288 |
+
},
|
| 289 |
+
{
|
| 290 |
+
"cell_type": "code",
|
| 291 |
+
"metadata": {},
|
| 292 |
+
"source": [
|
| 293 |
+
"# Task 1: Write your code here:\n",
|
| 294 |
+
"import matplotlib.pyplot as plt\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 299 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 300 |
+
"plt.title('Loss over Epochs')\n",
|
| 301 |
+
"plt.xlabel('Epoch')\n",
|
| 302 |
+
"plt.ylabel('Loss')\n",
|
| 303 |
+
"plt.legend()\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 (Bonus): Write your code here:"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
}
|
| 320 |
+
],
|
| 321 |
+
"metadata": {
|
| 322 |
+
"kernelspec": {
|
| 323 |
+
"display_name": "Python 3",
|
| 324 |
+
"name": "python3"
|
| 325 |
+
},
|
| 326 |
+
"language_info": {
|
| 327 |
+
"name": "python"
|
| 328 |
+
}
|
| 329 |
+
},
|
| 330 |
+
"nbformat": 4,
|
| 331 |
+
"nbformat_minor": 0
|
| 332 |
+
}
|
submissions_extracted/459/Q3.ipynb
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"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.display import clear_output\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"clear_output()"
|
| 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 |
+
"import pandas as pd\n",
|
| 41 |
+
"df = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 2: Write your code here:\n",
|
| 51 |
+
"df.head()"
|
| 52 |
+
],
|
| 53 |
+
"execution_count": null,
|
| 54 |
+
"outputs": []
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"cell_type": "code",
|
| 58 |
+
"metadata": {},
|
| 59 |
+
"source": [
|
| 60 |
+
"# Task 3: Write your code here:\n",
|
| 61 |
+
"df.info()"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"# Task 4: Write your code here:\n",
|
| 71 |
+
"df.describe()"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Task 1: Write your code here:\n",
|
| 81 |
+
"for col in df.columns:\n",
|
| 82 |
+
" df[col].fillna(df[col].mode()[0])"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 2: Write your code here:\n",
|
| 92 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 93 |
+
"if duplicate_rows > 0:\n",
|
| 94 |
+
" print(f\"Found {duplicate_rows} duplicate rows.\")\n",
|
| 95 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 96 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 97 |
+
"else:\n",
|
| 98 |
+
" print(\"No duplicate rows found.\")\n",
|
| 99 |
+
"\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 3: Write your code here:\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"# No encoding needed, all features are non-categorical variables"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# Task 4: Write your code here:\n",
|
| 120 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 121 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") ### DON'T SCALE THE TARGET\n",
|
| 122 |
+
"scaler = StandardScaler()\n",
|
| 123 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 124 |
+
"df\n"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 5: Write your code here:\n",
|
| 134 |
+
"import seaborn as sns\n",
|
| 135 |
+
"import matplotlib.pyplot as plt\n",
|
| 136 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 137 |
+
" print(\"Target Distribution:\")\n",
|
| 138 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 139 |
+
" sns.countplot(x=df[target_column])\n",
|
| 140 |
+
" plt.title(\"Target Distribution\")\n",
|
| 141 |
+
" plt.show()\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"check_target_imbalance(df, \"Target\")\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Target is imbalanced!"
|
| 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\n",
|
| 156 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 157 |
+
"y = df['Target']\n",
|
| 158 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 170 |
+
"from catboost import CatBoostClassifier\n",
|
| 171 |
+
"from sklearn.metrics import mean_absolute_error, accuracy_score, f1_score\n",
|
| 172 |
+
"import numpy as np\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"n_splits = 5 # K\n",
|
| 175 |
+
"mae_scores = []\n",
|
| 176 |
+
"lr_accuracy = []\n",
|
| 177 |
+
"lr_f1 = []\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 180 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 183 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # 1. Split data\n",
|
| 186 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 187 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # 2. Train & Validate sklearn models\n",
|
| 190 |
+
" model = CatBoostClassifier()\n",
|
| 191 |
+
" model.fit(X_train, y_train) # train\n",
|
| 192 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Calculate evaluation metrics\n",
|
| 195 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 196 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" # Store results\n",
|
| 199 |
+
" lr_accuracy.append(accuracy)\n",
|
| 200 |
+
" lr_f1.append(f1)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 203 |
+
"print()\n",
|
| 204 |
+
"print(f\"Accuracy: {np.mean(lr_accuracy)}\")\n",
|
| 205 |
+
"print(f\"Accuracy: {np.mean(lr_f1)}\")\n",
|
| 206 |
+
"print(f\"Accuracy: {np.mean(mae_scores)}\")"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 1: Write your code here:\n",
|
| 216 |
+
"importances = {}\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"importances['CatBoost Classifier'] = model.feature_importances_\n",
|
| 219 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 20))\n",
|
| 220 |
+
"axes = axes.flatten()\n",
|
| 221 |
+
"features = X.columns\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 224 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" ax = axes[i]\n",
|
| 227 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 228 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 229 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"plt.show()"
|
| 232 |
+
],
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"outputs": []
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"metadata": {},
|
| 239 |
+
"source": [
|
| 240 |
+
"# Task 2: Write your code here:\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"#Golden_Feature: P_2\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"print(df['P_2'].describe())"
|
| 245 |
+
],
|
| 246 |
+
"execution_count": null,
|
| 247 |
+
"outputs": []
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "code",
|
| 251 |
+
"metadata": {},
|
| 252 |
+
"source": [
|
| 253 |
+
"# Task Bonus: Write your code here:"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
}
|
| 258 |
+
],
|
| 259 |
+
"metadata": {
|
| 260 |
+
"kernelspec": {
|
| 261 |
+
"display_name": "Python 3",
|
| 262 |
+
"name": "python3"
|
| 263 |
+
},
|
| 264 |
+
"language_info": {
|
| 265 |
+
"name": "python"
|
| 266 |
+
}
|
| 267 |
+
},
|
| 268 |
+
"nbformat": 4,
|
| 269 |
+
"nbformat_minor": 0
|
| 270 |
+
}
|
submissions_extracted/46/Q1.ipynb
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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')\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 |
+
"cars_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 35 |
+
"df_delivery = pd.read_csv(cars_path)\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(f\"Dataset shape: {df_delivery.shape}\")"
|
| 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 |
+
"df_delivery.head()"
|
| 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 |
+
"df_delivery.info()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"# Task 4: Write your code here:\n",
|
| 67 |
+
"df_delivery.describe()"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 5: Write your code here:\n",
|
| 77 |
+
"# Price distribution (target variable)\n",
|
| 78 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 79 |
+
"plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 80 |
+
"plt.title('Delivery 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 |
+
"\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"# Drop rows where target (price) or key features are missing - can't predict without them\n",
|
| 96 |
+
"print(f\"Before: {df_delivery.shape}\")\n",
|
| 97 |
+
"df_delivery = df_delivery.drop(columns=['Order_ID'])\n",
|
| 98 |
+
"print(f\"After dropping missing : {df_delivery.shape}\")"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# Task 2: Write your code here:\n",
|
| 108 |
+
"print(\"Missing values remaining:\", df_delivery.isnull().sum().sum())"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# Task 3: Write your code here:"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 4: Write your code here:"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 5: Write your code here:"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 6: 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:"
|
| 154 |
+
],
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"outputs": []
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"source": [
|
| 162 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"# Task 1: Write your code here:"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 2: Write your code here:"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Task Bonus: Write your code here:"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
}
|
| 194 |
+
],
|
| 195 |
+
"metadata": {
|
| 196 |
+
"kernelspec": {
|
| 197 |
+
"display_name": "Python 3",
|
| 198 |
+
"name": "python3"
|
| 199 |
+
},
|
| 200 |
+
"language_info": {
|
| 201 |
+
"name": "python"
|
| 202 |
+
}
|
| 203 |
+
},
|
| 204 |
+
"nbformat": 4,
|
| 205 |
+
"nbformat_minor": 0
|
| 206 |
+
}
|
submissions_extracted/46/Q2.ipynb
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"print(\"Path to dataset files:\", path)"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"import os\n",
|
| 24 |
+
"import pandas as pd\n",
|
| 25 |
+
"import numpy as np\n",
|
| 26 |
+
"from PIL import Image\n",
|
| 27 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Load Labels\n",
|
| 31 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 32 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"images = []\n",
|
| 35 |
+
"ages = []\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"# Load Images and Resize\n",
|
| 38 |
+
"print(\"Loading images...\")\n",
|
| 39 |
+
"for index, row in labels_df.iterrows():\n",
|
| 40 |
+
" img_name = row.iloc[0]\n",
|
| 41 |
+
" age = row.iloc[1]\n",
|
| 42 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 43 |
+
"\n",
|
| 44 |
+
" if os.path.exists(img_path):\n",
|
| 45 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 46 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 47 |
+
" images.append(img_array)\n",
|
| 48 |
+
" ages.append(age)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"X = np.array(images)\n",
|
| 51 |
+
"y = np.array(ages)\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 54 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"# Split Data\n",
|
| 57 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 60 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 61 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 62 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 72 |
+
"import torch\n",
|
| 73 |
+
"import torch.nn as nn\n",
|
| 74 |
+
"from torch.optim import AdamW\n",
|
| 75 |
+
"import matplotlib.pyplot as plt\n",
|
| 76 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 77 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 78 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 79 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"# TODO: Transform to PyTorch tensors with dtype=torch.float32\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.float32)\n",
|
| 85 |
+
"y_test = torch.tensor(y_test.values, 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 |
+
"# Create TensorDatasets for training and testing\n",
|
| 97 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 98 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"\n"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# 3. Create DataLoaders\n",
|
| 110 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 111 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 112 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\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 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 124 |
+
"print(\"Test dataset:\", len(test_dataset))\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 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 146 |
+
" super(NN3Layer, self).__init__()\n",
|
| 147 |
+
"\n",
|
| 148 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 149 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 152 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" # Therd linear layer: hidden layer -> hidden layer\n",
|
| 155 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 156 |
+
"\n",
|
| 157 |
+
" # Output layer: hidden layer -> single continuous value\n",
|
| 158 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" # ReLU activation for non-linearity in hidden layers\n",
|
| 161 |
+
" self.relu = nn.ReLU()\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" # Defines how input data flows through the network\n",
|
| 164 |
+
" def forward(self, x):\n",
|
| 165 |
+
" # First hidden layer\n",
|
| 166 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # Second hidden layer\n",
|
| 169 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 170 |
+
" #Therd hidden layer\n",
|
| 171 |
+
" a3 = self.relu(self.layer2(a2))\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # Output layer (regression output)\n",
|
| 174 |
+
" output = self.layer3(a3)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" return output"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"# Task 2: Write your training loop here:\n",
|
| 186 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 187 |
+
" # Set the model to training mode\n",
|
| 188 |
+
" model.train()\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" running_loss = 0.0\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 193 |
+
" # Move batch to the selected device\n",
|
| 194 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 195 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Forward pass (continuous output)\n",
|
| 198 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 199 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" # Backward pass & optimization\n",
|
| 202 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 203 |
+
" loss.backward() # Compute gradients\n",
|
| 204 |
+
" optimizer.step() # Update model parameters\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" running_loss += loss.item()\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Average loss over all batches\n",
|
| 209 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" return avg_loss"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# Task 3: Write your validation loop here:\n",
|
| 221 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 222 |
+
" # Set the model to evaluation mode\n",
|
| 223 |
+
" model.eval()\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" running_loss = 0.0\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" with torch.no_grad():\n",
|
| 228 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 229 |
+
" # Move data to device\n",
|
| 230 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 231 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Forward pass (continuous output)\n",
|
| 234 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 235 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" running_loss += loss.item()\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # Average loss over all batches\n",
|
| 240 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" return avg_loss"
|
| 243 |
+
],
|
| 244 |
+
"execution_count": null,
|
| 245 |
+
"outputs": []
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"cell_type": "code",
|
| 249 |
+
"metadata": {},
|
| 250 |
+
"source": [
|
| 251 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 252 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 253 |
+
"# Model parameters\n",
|
| 254 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 255 |
+
"hidden_dim = 64 # Design choice\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# Instantiate regression model\n",
|
| 258 |
+
"model = NN3Layer(input_dim, hidden_dim).to(device)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"# Print the model architecture\n",
|
| 261 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 262 |
+
"print(model)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"# Calculate the total number of trainable parameters\n",
|
| 265 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 266 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 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 |
+
"num_epochs = 20\n",
|
| 277 |
+
"learning_rate = 0.001\n",
|
| 278 |
+
"# Define criterion (loss function)\n",
|
| 279 |
+
"criterion = nn.MSELoss()\n",
|
| 280 |
+
"# Define optimizer\n",
|
| 281 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 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 (Bonus): Write your code here:"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
}
|
| 304 |
+
],
|
| 305 |
+
"metadata": {
|
| 306 |
+
"kernelspec": {
|
| 307 |
+
"display_name": "Python 3",
|
| 308 |
+
"name": "python3"
|
| 309 |
+
},
|
| 310 |
+
"language_info": {
|
| 311 |
+
"name": "python"
|
| 312 |
+
}
|
| 313 |
+
},
|
| 314 |
+
"nbformat": 4,
|
| 315 |
+
"nbformat_minor": 0
|
| 316 |
+
}
|
submissions_extracted/46/Q3.ipynb
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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')\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)"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 1: Write your code here:\n",
|
| 37 |
+
"cars_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 38 |
+
"df_describe = pd.read_csv(cars_path)\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(f\"Dataset shape: {df_describe.shape}\")"
|
| 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_describe.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_describe.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.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:"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Task 2: Write your code here:"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# Task 3: Write your code here:"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 4: Write your code here:"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# Task 5: Write your code here:"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 1: Write your code here:"
|
| 125 |
+
],
|
| 126 |
+
"execution_count": null,
|
| 127 |
+
"outputs": []
|
| 128 |
+
},
|
| 129 |
+
{
|
| 130 |
+
"cell_type": "code",
|
| 131 |
+
"metadata": {},
|
| 132 |
+
"source": [
|
| 133 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 1: Write your code here:"
|
| 143 |
+
],
|
| 144 |
+
"execution_count": null,
|
| 145 |
+
"outputs": []
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"cell_type": "code",
|
| 149 |
+
"metadata": {},
|
| 150 |
+
"source": [
|
| 151 |
+
"# Task 2: Write your code here:"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task Bonus: Write your code here:"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
}
|
| 165 |
+
],
|
| 166 |
+
"metadata": {
|
| 167 |
+
"kernelspec": {
|
| 168 |
+
"display_name": "Python 3",
|
| 169 |
+
"name": "python3"
|
| 170 |
+
},
|
| 171 |
+
"language_info": {
|
| 172 |
+
"name": "python"
|
| 173 |
+
}
|
| 174 |
+
},
|
| 175 |
+
"nbformat": 4,
|
| 176 |
+
"nbformat_minor": 0
|
| 177 |
+
}
|
submissions_extracted/460/Q1.ipynb
ADDED
|
@@ -0,0 +1,441 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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')\n",
|
| 20 |
+
"\n"
|
| 21 |
+
],
|
| 22 |
+
"execution_count": null,
|
| 23 |
+
"outputs": []
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"import kagglehub\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"# Download latest version\n",
|
| 32 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(\"Path to dataset files:\", path)"
|
| 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 |
+
"\n",
|
| 45 |
+
"# Load the dataset\n",
|
| 46 |
+
"time_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 47 |
+
"data = pd.read_csv(time_path)\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"print(f\"Dataset shape: {data.shape}\")\n"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 2: Write your code here:\n",
|
| 59 |
+
"data.head()"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 3: Write your code here:\n",
|
| 69 |
+
"data.info()"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 4: Write your code here:\n",
|
| 79 |
+
"data.describe()"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Task 5: Write your code here:\n",
|
| 89 |
+
"# Price distribution (target variable)\n",
|
| 90 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 91 |
+
"plt.hist(data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 92 |
+
"plt.title('delivery_time Distribution')\n",
|
| 93 |
+
"plt.xlabel('delivery_time')\n",
|
| 94 |
+
"plt.ylabel('Frequency')\n",
|
| 95 |
+
"plt.show()"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 1: Write your code here:\n",
|
| 105 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 106 |
+
"cols = ['Order_ID']\n",
|
| 107 |
+
"df_clean = data[cols].copy()\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"df_clean = data.dropna(subset=['Order_ID'])\n",
|
| 112 |
+
"print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 2: Write your code here:\n",
|
| 122 |
+
"# 2. Do we have missing values?\n",
|
| 123 |
+
"def check_missing_values(df):\n",
|
| 124 |
+
" missing_values = df.isnull().sum()\n",
|
| 125 |
+
" print(\"Missing Values per Column:\")\n",
|
| 126 |
+
" print(missing_values[missing_values > 0])\n",
|
| 127 |
+
" if missing_values.any():\n",
|
| 128 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 129 |
+
" else:\n",
|
| 130 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"check_missing_values(df_clean)\n"
|
| 133 |
+
],
|
| 134 |
+
"execution_count": null,
|
| 135 |
+
"outputs": []
|
| 136 |
+
},
|
| 137 |
+
{
|
| 138 |
+
"cell_type": "code",
|
| 139 |
+
"metadata": {},
|
| 140 |
+
"source": [
|
| 141 |
+
"# تعويض الأرقام بالمتوسط (للتوزيع الطبيعي)\n",
|
| 142 |
+
"df_clean['Weather'] = df_clean['Weather'].fillna(df_clean['Weather'].mean())\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# تعويض الأرقام بالوسيط (إذا فيه قيم شاذة Outliers)\n",
|
| 145 |
+
"df_clean['Traffic_Level'] = df_clean['Traffic_Level'].fillna(df_clean['Traffic_Level'].median())\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"# تعويض النصوص بالقيمة الأكثر تكراراً (Mode) - انتبه للـ [0]\n",
|
| 148 |
+
"df_clean['Time_of_Day'] = df_clean['Time_of_Day'].fillna(df_clean['Time_of_Day'].mode()[0])\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 3: Write your code here:\n",
|
| 162 |
+
"# Do we have duplicate samples?\n",
|
| 163 |
+
"def check_duplicates(df):\n",
|
| 164 |
+
" duplicates = df.duplicated().sum()\n",
|
| 165 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 166 |
+
" if duplicates > 0:\n",
|
| 167 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 168 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 169 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 170 |
+
" else:\n",
|
| 171 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"check_duplicates(df_clean)"
|
| 174 |
+
],
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"outputs": []
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"# Task 4: Write your code here:\n",
|
| 183 |
+
"# Do we have categorical columns?\n",
|
| 184 |
+
"def encode_categorical_columns(df):\n",
|
| 185 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 186 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"label_encoders = encode_categorical_columns(df_clean)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 193 |
+
"for col in categorical_cols:\n",
|
| 194 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 195 |
+
" le = LabelEncoder()\n",
|
| 196 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 197 |
+
"df_clean"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task 5: Write your code here:\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"features = data.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"scaler = StandardScaler()\n",
|
| 213 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 214 |
+
"df_clean.head()"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 6: Write your code here:\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"# not needed becu it is regression\n",
|
| 227 |
+
"import seaborn as sns\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"# Is the target imbalanced?\n",
|
| 230 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 231 |
+
" print(\"Target Distribution:\")\n",
|
| 232 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 233 |
+
" sns.countplot(x=df[target_column])\n",
|
| 234 |
+
" plt.title(\"Target Distribution\")\n",
|
| 235 |
+
" plt.show()\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"check_target_imbalance(df_clean, \"Delivery_Time\")"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 1: Write your code here:\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 249 |
+
"y = df_clean['Delivery_Time'].astype(float)"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 259 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 260 |
+
],
|
| 261 |
+
"execution_count": null,
|
| 262 |
+
"outputs": []
|
| 263 |
+
},
|
| 264 |
+
{
|
| 265 |
+
"cell_type": "code",
|
| 266 |
+
"metadata": {},
|
| 267 |
+
"source": [
|
| 268 |
+
"# Train Random Forest Regressor\n",
|
| 269 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42)\n",
|
| 272 |
+
"model.fit(X_train, y_train)\n",
|
| 273 |
+
"print(\"Model trained!\")"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Predict and evaluate\n",
|
| 283 |
+
"y_pred = model.predict(X_test)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"mae = mean_absolute_error(y_test, y_pred)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"print(f\"MAE: ${mae:,.2f}\")\n"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"average_losses = np.mean(mae, axis=0)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 299 |
+
"plt.plot(average_losses, label='Average Loss')\n",
|
| 300 |
+
"plt.xlabel('Iteration')\n",
|
| 301 |
+
"plt.ylabel('MSE Loss')\n",
|
| 302 |
+
"plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
|
| 303 |
+
"plt.legend()\n",
|
| 304 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 305 |
+
"plt.show()"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Feature importance\n",
|
| 315 |
+
"feature_importance = pd.DataFrame({\n",
|
| 316 |
+
" 'feature': X,\n",
|
| 317 |
+
" 'importance': model.feature_importances_\n",
|
| 318 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 321 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 322 |
+
"plt.xlabel('Importance')\n",
|
| 323 |
+
"plt.title('Feature Importance')\n",
|
| 324 |
+
"plt.gca().invert_yaxis()\n",
|
| 325 |
+
"plt.show()"
|
| 326 |
+
],
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"outputs": []
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"cell_type": "code",
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"source": [
|
| 334 |
+
"# Task 2: Write your code here:\n",
|
| 335 |
+
"y_pred.hist()"
|
| 336 |
+
],
|
| 337 |
+
"execution_count": null,
|
| 338 |
+
"outputs": []
|
| 339 |
+
},
|
| 340 |
+
{
|
| 341 |
+
"cell_type": "code",
|
| 342 |
+
"metadata": {},
|
| 343 |
+
"source": [
|
| 344 |
+
"# Task Bonus: Write your code here:"
|
| 345 |
+
],
|
| 346 |
+
"execution_count": null,
|
| 347 |
+
"outputs": []
|
| 348 |
+
},
|
| 349 |
+
{
|
| 350 |
+
"cell_type": "code",
|
| 351 |
+
"metadata": {},
|
| 352 |
+
"source": [
|
| 353 |
+
"# Calculate the majority class baseline\n",
|
| 354 |
+
"majority_class = y.value_counts().idxmax()\n",
|
| 355 |
+
"baseline_pred = [majority_class] * len(y)\n",
|
| 356 |
+
"\n",
|
| 357 |
+
"# Evaluate the baseline\n",
|
| 358 |
+
"baseline_f1 = f1_score(y, baseline_pred, average='weighted')\n",
|
| 359 |
+
"print(f\"Baseline F1-Score (majority class): {baseline_f1:.4f}\")\n"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"# Define classification models\n",
|
| 369 |
+
"models = {\n",
|
| 370 |
+
" \"Logistic Regression\": LogisticRegression(max_iter=10000),\n",
|
| 371 |
+
" \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n",
|
| 372 |
+
" \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n",
|
| 373 |
+
"}\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"models[\"Ensemble\"] = VotingClassifier(estimators=[\n",
|
| 376 |
+
" ('lr', models[\"CatBoost Classifier\"]), ('rf', models[\"Logistic Regression\"]), ('gnb', models[\"Random Forest Classifier\"])], voting=\"soft\")\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"for model_name, model in models.items():\n",
|
| 379 |
+
" scores_accuracy = []\n",
|
| 380 |
+
" scores_precision = []\n",
|
| 381 |
+
" scores_recall = []\n",
|
| 382 |
+
" scores_f1 = []\n",
|
| 383 |
+
"\n",
|
| 384 |
+
" # Stratified 5-Fold Cross-Validation\n",
|
| 385 |
+
" skf = KFold(n_splits=5)\n",
|
| 386 |
+
" for train_index, test_index in skf.split(X, y):\n",
|
| 387 |
+
" # Split data into training and testing sets\n",
|
| 388 |
+
" X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
|
| 389 |
+
" y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 390 |
+
" # Train the model\n",
|
| 391 |
+
" model.fit(X_Train, y_Train)\n",
|
| 392 |
+
" # Predict on the test set\n",
|
| 393 |
+
" y_pred = model.predict(X_Test)\n",
|
| 394 |
+
"\n",
|
| 395 |
+
" # Calculate metrics\n",
|
| 396 |
+
" scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
|
| 397 |
+
"\n",
|
| 398 |
+
" # Print the results\n",
|
| 399 |
+
" print(f\"{model_name} F1-Score: {np.mean(scores_f1):.4f}\")\n",
|
| 400 |
+
" print(\"\\n\")\n"
|
| 401 |
+
],
|
| 402 |
+
"execution_count": null,
|
| 403 |
+
"outputs": []
|
| 404 |
+
},
|
| 405 |
+
{
|
| 406 |
+
"cell_type": "code",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"# Retrieve CatBoost feature importances and sort them\n",
|
| 410 |
+
"catboost_model = models[\"CatBoost Classifier\"]\n",
|
| 411 |
+
"catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n",
|
| 412 |
+
"sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"# Extract features and their importances\n",
|
| 415 |
+
"features, importances = zip(*sorted_catboost_importance)\n",
|
| 416 |
+
"\n",
|
| 417 |
+
"# Plot feature importances\n",
|
| 418 |
+
"plt.figure(figsize=(18, 14))\n",
|
| 419 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 420 |
+
"plt.xlabel('Importance Score')\n",
|
| 421 |
+
"plt.ylabel('Features')\n",
|
| 422 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 423 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 424 |
+
"plt.show()\n"
|
| 425 |
+
],
|
| 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/460/Q2.ipynb
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"from torchvision.datasets import CIFAR10\n",
|
| 8 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 9 |
+
"from torch.utils.data import DataLoader\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"import torch.nn as nn\n",
|
| 12 |
+
"import torch.nn.functional as F\n",
|
| 13 |
+
"import torch\n",
|
| 14 |
+
"from torch.optim import AdamW"
|
| 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/q2-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 |
+
"import os\n",
|
| 38 |
+
"import pandas as pd\n",
|
| 39 |
+
"import numpy as np\n",
|
| 40 |
+
"from PIL import Image\n",
|
| 41 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"# Load Labels\n",
|
| 44 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 45 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"images = []\n",
|
| 48 |
+
"ages = []\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Load Images and Resize\n",
|
| 51 |
+
"print(\"Loading images...\")\n",
|
| 52 |
+
"for index, row in labels_df.iterrows():\n",
|
| 53 |
+
" img_name = row.iloc[0]\n",
|
| 54 |
+
" age = row.iloc[1]\n",
|
| 55 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 56 |
+
"\n",
|
| 57 |
+
" if os.path.exists(img_path):\n",
|
| 58 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 59 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 60 |
+
" images.append(img_array)\n",
|
| 61 |
+
" ages.append(age)\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"X = np.array(images)\n",
|
| 64 |
+
"y = np.array(ages)\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 67 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"# Split Data\n",
|
| 70 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 73 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 74 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 75 |
+
"print(f\"y_test shape: {y_test.shape}\")\n"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 85 |
+
"import torch\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"# transform to tensors\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)\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# # 2. Create TensorDataset objects\n",
|
| 102 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 103 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 108 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"# Access a single sample from the dataset\n",
|
| 111 |
+
"# This helps verify the shape of one data sample\n",
|
| 112 |
+
"first_sample, _ = train_dataset[0]\n",
|
| 113 |
+
"print(f\"Shape of one sample: {first_sample.shape}\")"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# 3. Create DataLoaders\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"from torch.utils.data import DataLoader\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"# DataLoader for training data\n",
|
| 128 |
+
"train_loader = DataLoader(\n",
|
| 129 |
+
" train_dataset,\n",
|
| 130 |
+
" batch_size=32,\n",
|
| 131 |
+
" shuffle=True,\n",
|
| 132 |
+
" num_workers=2\n",
|
| 133 |
+
")\n",
|
| 134 |
+
"# DataLoader for test/validation data\n",
|
| 135 |
+
"test_loader = DataLoader(\n",
|
| 136 |
+
" test_dataset,\n",
|
| 137 |
+
" batch_size=32,\n",
|
| 138 |
+
" shuffle=False,\n",
|
| 139 |
+
" num_workers=2\n",
|
| 140 |
+
")\n"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# 4. Print shape of one batch\n",
|
| 150 |
+
"# Get the first batch from the training DataLoader\n",
|
| 151 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 152 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 153 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n",
|
| 154 |
+
"\n"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# 5 Display a few images: Use matplotlib to display a few images.\n",
|
| 164 |
+
"# Get one batch of images and labels\n",
|
| 165 |
+
"import matplotlib.pyplot as plt\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"images, labels = next(iter(train_loader))\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Display the first 6 images in the batch\n",
|
| 170 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"for i in range(6):\n",
|
| 173 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 176 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" plt.imshow(img)\n",
|
| 179 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 180 |
+
" plt.axis('off')\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"plt.tight_layout()\n",
|
| 183 |
+
"plt.show()"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 1: Write your model class here:\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"class NN4Layer(nn.Module):\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 197 |
+
" super(NN4Layer, self).__init__()\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 200 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 203 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 206 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 209 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # activation function for non-linearity\n",
|
| 212 |
+
" self.relu = nn.ReLU()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Task 2: Write your training loop here:\n",
|
| 215 |
+
"\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Defines how input data flows through the network\n",
|
| 218 |
+
" def forward(self, x):\n",
|
| 219 |
+
" # Layer 1: TODO\n",
|
| 220 |
+
" z1 = self.layer1(x)\n",
|
| 221 |
+
" a1 = self.relu(z1)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" # Layer 2 TODO\n",
|
| 224 |
+
" z2 = self.layer2(a1)\n",
|
| 225 |
+
" a2 = self.relu(z2)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Layer 3 TODO\n",
|
| 228 |
+
" z3 = self.layer3(a2)\n",
|
| 229 |
+
" a3 = self.relu(z3)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Layer 4 TODO\n",
|
| 232 |
+
" z4 = self.layer4(a3)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" return z4"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 247 |
+
" # Set the model to training mode\n",
|
| 248 |
+
" model.train()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" running_loss = 0.0\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 253 |
+
" # Move batch to the selected device\n",
|
| 254 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 255 |
+
" y_batch = y_batch.to(device)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" # Forward pass\n",
|
| 258 |
+
" # TODO: make predictions\n",
|
| 259 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 260 |
+
" # TODO: compute loss\n",
|
| 261 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Backward pass & optimization\n",
|
| 264 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 265 |
+
" loss.backward() # Compute gradients\n",
|
| 266 |
+
" optimizer.step() # Update model parameters\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" running_loss += loss.item()\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" # Average loss over all batches\n",
|
| 271 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" return avg_loss"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 3: Write your validation loop here:\n",
|
| 283 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 284 |
+
" # Set the model to evaluation mode\n",
|
| 285 |
+
" model.eval()\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" running_loss = 0.0\n",
|
| 288 |
+
" correct = 0\n",
|
| 289 |
+
" total = 0\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" with torch.no_grad():\n",
|
| 292 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 293 |
+
" # Move data to device\n",
|
| 294 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 295 |
+
" y_batch = y_batch.to(device)\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" # Forward pass\n",
|
| 298 |
+
" # TODO: make predictions\n",
|
| 299 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 300 |
+
" # TODO: compute loss\n",
|
| 301 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 302 |
+
" running_loss += loss.item()\n",
|
| 303 |
+
"\n",
|
| 304 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 305 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
" # TODO: Multiclass predictions\n",
|
| 308 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 309 |
+
"\n",
|
| 310 |
+
" # Accuracy calculation\n",
|
| 311 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 312 |
+
" total += y_batch.size(0)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 315 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 316 |
+
" accuracy = correct / total\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" return avg_loss, accuracy\n"
|
| 319 |
+
],
|
| 320 |
+
"execution_count": null,
|
| 321 |
+
"outputs": []
|
| 322 |
+
},
|
| 323 |
+
{
|
| 324 |
+
"cell_type": "code",
|
| 325 |
+
"metadata": {},
|
| 326 |
+
"source": [
|
| 327 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 328 |
+
"# Device setup\n",
|
| 329 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"# Model parameters\n",
|
| 332 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 333 |
+
"input_dim = 3 * 36 * 36 # images flattened (RGB)\n",
|
| 334 |
+
"# TODO: choose number of hidden neurons\n",
|
| 335 |
+
"hidden_dim = 32 # Design choice\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 339 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# TODO: Print the model architecture\n",
|
| 342 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 343 |
+
"print(model)\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"# Calculate the total number of trainable parameters\n",
|
| 346 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 347 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n"
|
| 348 |
+
],
|
| 349 |
+
"execution_count": null,
|
| 350 |
+
"outputs": []
|
| 351 |
+
},
|
| 352 |
+
{
|
| 353 |
+
"cell_type": "code",
|
| 354 |
+
"metadata": {},
|
| 355 |
+
"source": [
|
| 356 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 357 |
+
"num_epochs = 20\n",
|
| 358 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 359 |
+
"learning_rate = 0.001\n",
|
| 360 |
+
"\n",
|
| 361 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 362 |
+
"criterion = nn.MSELoss()\n",
|
| 363 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 364 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 365 |
+
],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
},
|
| 369 |
+
{
|
| 370 |
+
"cell_type": "code",
|
| 371 |
+
"metadata": {},
|
| 372 |
+
"source": [
|
| 373 |
+
"# Run Training\n",
|
| 374 |
+
"train_losses = []\n",
|
| 375 |
+
"val_losses = []\n",
|
| 376 |
+
"val_accuracies = []\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"print('Starting Training...')\n",
|
| 379 |
+
"for epoch in range(num_epochs):\n",
|
| 380 |
+
" # Train one epoch\n",
|
| 381 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 382 |
+
"\n",
|
| 383 |
+
" # Validate\n",
|
| 384 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 385 |
+
"\n",
|
| 386 |
+
" train_losses.append(train_loss)\n",
|
| 387 |
+
" val_losses.append(val_loss)\n",
|
| 388 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"print('Training Complete!')"
|
| 393 |
+
],
|
| 394 |
+
"execution_count": null,
|
| 395 |
+
"outputs": []
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "code",
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"source": [
|
| 401 |
+
"# Task 1: Write your code here:\n",
|
| 402 |
+
"# Plotting results\n",
|
| 403 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 404 |
+
"\n",
|
| 405 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 406 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 407 |
+
"plt.title('Loss over Epochs')\n",
|
| 408 |
+
"plt.xlabel('Epoch')\n",
|
| 409 |
+
"plt.ylabel('Loss')\n",
|
| 410 |
+
"plt.legend()\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"plt.tight_layout()\n",
|
| 413 |
+
"plt.show()"
|
| 414 |
+
],
|
| 415 |
+
"execution_count": null,
|
| 416 |
+
"outputs": []
|
| 417 |
+
},
|
| 418 |
+
{
|
| 419 |
+
"cell_type": "code",
|
| 420 |
+
"metadata": {},
|
| 421 |
+
"source": [
|
| 422 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 423 |
+
],
|
| 424 |
+
"execution_count": null,
|
| 425 |
+
"outputs": []
|
| 426 |
+
}
|
| 427 |
+
],
|
| 428 |
+
"metadata": {
|
| 429 |
+
"kernelspec": {
|
| 430 |
+
"display_name": "Python 3",
|
| 431 |
+
"name": "python3"
|
| 432 |
+
},
|
| 433 |
+
"language_info": {
|
| 434 |
+
"name": "python"
|
| 435 |
+
}
|
| 436 |
+
},
|
| 437 |
+
"nbformat": 4,
|
| 438 |
+
"nbformat_minor": 0
|
| 439 |
+
}
|
submissions_extracted/460/Q3.ipynb
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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otlib.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')\n",
|
| 20 |
+
"\n"
|
| 21 |
+
],
|
| 22 |
+
"execution_count": null,
|
| 23 |
+
"outputs": []
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"cell_type": "code",
|
| 27 |
+
"metadata": {},
|
| 28 |
+
"source": [
|
| 29 |
+
"import kagglehub\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"# Download latest version\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"print(\"Path to dataset files:\", path)"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 1: Write your code here:\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"# Load the dataset\n",
|
| 59 |
+
"data_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 60 |
+
"df_data = pd.read_csv(data_path)\n"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 2: Write your code here:\n",
|
| 70 |
+
"\n",
|
| 71 |
+
"df_data.head()"
|
| 72 |
+
],
|
| 73 |
+
"execution_count": null,
|
| 74 |
+
"outputs": []
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
"cell_type": "code",
|
| 78 |
+
"metadata": {},
|
| 79 |
+
"source": [
|
| 80 |
+
"# Task 3: Write your code here:\n",
|
| 81 |
+
"df_data.info()"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Task 4: Write your code here:\n",
|
| 91 |
+
"\n",
|
| 92 |
+
"df_data.describe()"
|
| 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 |
+
"# 2. Do we have missing values?\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_data)"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Check missing values\n",
|
| 122 |
+
"missing_values = df_data.isnull().sum()\n",
|
| 123 |
+
"print(\"Columns with missing values:\")\n",
|
| 124 |
+
"print(missing_values[missing_values > 0])\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# Fill missing values with mean for each column\n",
|
| 127 |
+
"data = df_data.fillna(df_data.mean())"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 2: Write your code here:\n",
|
| 137 |
+
"# 4. Do we have duplicate samples?\n",
|
| 138 |
+
"def check_duplicates(df):\n",
|
| 139 |
+
" duplicates = df.duplicated().sum()\n",
|
| 140 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 141 |
+
" if duplicates > 0:\n",
|
| 142 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 143 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 144 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 145 |
+
" else:\n",
|
| 146 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"check_duplicates(df_data)"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 3: Write your code here:\n",
|
| 158 |
+
"# Encode categorical columns - converts text to integers\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"# 3. Do we have categorical columns?\n",
|
| 161 |
+
"def encode_categorical_columns(df):\n",
|
| 162 |
+
" categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 163 |
+
" print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"label_encoders = encode_categorical_columns(df_data)"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n",
|
| 177 |
+
"for col in categorical_cols:\n",
|
| 178 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 179 |
+
" le = LabelEncoder()\n",
|
| 180 |
+
" df_data[col] = le.fit_transform(df_data[col])\n",
|
| 181 |
+
"df_data"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 4: Write your code here:\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"# Task 5: Write your code here:\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"features = data.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"scaler = StandardScaler()\n",
|
| 199 |
+
"df_data[features] = scaler.fit_transform(df_data[features])\n",
|
| 200 |
+
"df_data.head()"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Is the target imbalanced?\n",
|
| 210 |
+
"import pandas as pd\n",
|
| 211 |
+
"import numpy as np\n",
|
| 212 |
+
"import matplotlib.pyplot as plt\n",
|
| 213 |
+
"import seaborn as sns\n",
|
| 214 |
+
"import kagglehub\n",
|
| 215 |
+
"import os\n",
|
| 216 |
+
"from tqdm import tqdm\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"%matplotlib inline\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_data, \"Target\")"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"# Task 5: Write your code here:\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"# Price distribution (target variable)\n",
|
| 238 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 239 |
+
"plt.hist(df_data['Target'].dropna(), bins=50, edgecolor='black')\n",
|
| 240 |
+
"plt.title('Target Distribution')\n",
|
| 241 |
+
"plt.xlabel('Target')\n",
|
| 242 |
+
"plt.ylabel('Frequency')\n",
|
| 243 |
+
"plt.show()\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"# not balanced target"
|
| 246 |
+
],
|
| 247 |
+
"execution_count": null,
|
| 248 |
+
"outputs": []
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"# Task 1: Write your code here:\n",
|
| 255 |
+
"# Modeling\n",
|
| 256 |
+
"X = df_data.drop(\"Target\",axis=1)\n",
|
| 257 |
+
"y = df_data['Target']"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"cell_type": "code",
|
| 264 |
+
"metadata": {},
|
| 265 |
+
"source": [
|
| 266 |
+
"import numpy as np # for random data generation\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"np.random.seed(42) # for reproducbility\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
|
| 271 |
+
"y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5 # continous labels with noise\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)}) # features\n",
|
| 275 |
+
"y_clf = (X_clf[\"Feature_1\"] > 0).astype(int) # labels as class 0 or 1\n"
|
| 276 |
+
],
|
| 277 |
+
"execution_count": null,
|
| 278 |
+
"outputs": []
|
| 279 |
+
},
|
| 280 |
+
{
|
| 281 |
+
"cell_type": "code",
|
| 282 |
+
"metadata": {},
|
| 283 |
+
"source": [
|
| 284 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 285 |
+
"\n"
|
| 286 |
+
],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [
|
| 294 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Use previously generated random classification data\n",
|
| 297 |
+
"X, y = X_clf.copy(), y_clf.copy()\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"# Show full dataset class distribution\n",
|
| 300 |
+
"full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
|
| 301 |
+
"print(\"Full Dataset Class Distribution\")\n",
|
| 302 |
+
"print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
|
| 303 |
+
"print(\"-\" * 40)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Define Stratified K-Fold\n",
|
| 306 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 311 |
+
" # indexing for each fold\n",
|
| 312 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 313 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 314 |
+
"\n",
|
| 315 |
+
" print(f\"Fold {fold}\")\n",
|
| 316 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 317 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 318 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 319 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" # showing class distribution\n",
|
| 322 |
+
" train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
|
| 323 |
+
" test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
|
| 324 |
+
"\n",
|
| 325 |
+
" print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
|
| 326 |
+
" print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" print(\"-\" * 40)\n"
|
| 329 |
+
],
|
| 330 |
+
"execution_count": null,
|
| 331 |
+
"outputs": []
|
| 332 |
+
},
|
| 333 |
+
{
|
| 334 |
+
"cell_type": "code",
|
| 335 |
+
"metadata": {},
|
| 336 |
+
"source": [
|
| 337 |
+
"from catboost import CatBoostClassifier\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"# Initialize and train model\n",
|
| 340 |
+
"model = CatBoostClassifier(random_state=42, verbose=-1)\n",
|
| 341 |
+
"model.fit(X_train, y_train)\n"
|
| 342 |
+
],
|
| 343 |
+
"execution_count": null,
|
| 344 |
+
"outputs": []
|
| 345 |
+
},
|
| 346 |
+
{
|
| 347 |
+
"cell_type": "code",
|
| 348 |
+
"metadata": {},
|
| 349 |
+
"source": [
|
| 350 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 351 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" # 1. Split data\n",
|
| 354 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 355 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" # 2. Train & Validate sklearn models\n",
|
| 358 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 359 |
+
" print(f\"Training {model_name}...\")\n",
|
| 360 |
+
" model.fit(X_train, y_train) # train\n",
|
| 361 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 362 |
+
"\n",
|
| 363 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 364 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 365 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 366 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 367 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 368 |
+
"\n",
|
| 369 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 370 |
+
" all_results[model_name]['precision'].append(precision)\n",
|
| 371 |
+
" all_results[model_name]['recall'].append(recall)\n",
|
| 372 |
+
" all_results[model_name]['f1'].append(f1)"
|
| 373 |
+
],
|
| 374 |
+
"execution_count": null,
|
| 375 |
+
"outputs": []
|
| 376 |
+
},
|
| 377 |
+
{
|
| 378 |
+
"cell_type": "code",
|
| 379 |
+
"metadata": {},
|
| 380 |
+
"source": [
|
| 381 |
+
"# Task 1: Write your code here:\n",
|
| 382 |
+
"# Plot feature importance\n",
|
| 383 |
+
"importance = pd.DataFrame({\n",
|
| 384 |
+
" 'feature': features,\n",
|
| 385 |
+
" 'importance': model.feature_importances_\n",
|
| 386 |
+
"})\n",
|
| 387 |
+
"importance = importance.sort_values('importance', ascending=True).tail(10)\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 390 |
+
"plt.barh(importance['feature'], importance['importance'])\n",
|
| 391 |
+
"plt.title('Top 10 Feature Importance')\n",
|
| 392 |
+
"plt.xlabel('Importance')\n",
|
| 393 |
+
"plt.tight_layout()\n",
|
| 394 |
+
"plt.show()"
|
| 395 |
+
],
|
| 396 |
+
"execution_count": null,
|
| 397 |
+
"outputs": []
|
| 398 |
+
},
|
| 399 |
+
{
|
| 400 |
+
"cell_type": "code",
|
| 401 |
+
"metadata": {},
|
| 402 |
+
"source": [
|
| 403 |
+
"# Task 2: Write your code here:"
|
| 404 |
+
],
|
| 405 |
+
"execution_count": null,
|
| 406 |
+
"outputs": []
|
| 407 |
+
},
|
| 408 |
+
{
|
| 409 |
+
"cell_type": "code",
|
| 410 |
+
"metadata": {},
|
| 411 |
+
"source": [
|
| 412 |
+
"# Task Bonus: Write your code here:"
|
| 413 |
+
],
|
| 414 |
+
"execution_count": null,
|
| 415 |
+
"outputs": []
|
| 416 |
+
}
|
| 417 |
+
],
|
| 418 |
+
"metadata": {
|
| 419 |
+
"kernelspec": {
|
| 420 |
+
"display_name": "Python 3",
|
| 421 |
+
"name": "python3"
|
| 422 |
+
},
|
| 423 |
+
"language_info": {
|
| 424 |
+
"name": "python"
|
| 425 |
+
}
|
| 426 |
+
},
|
| 427 |
+
"nbformat": 4,
|
| 428 |
+
"nbformat_minor": 0
|
| 429 |
+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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 |
+
"import pandas as pd\n",
|
| 22 |
+
"import numpy as np\n",
|
| 23 |
+
"import matplotlib.pyplot as plt\n",
|
| 24 |
+
"import seaborn as sns\n",
|
| 25 |
+
"import os"
|
| 26 |
+
],
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"source": [
|
| 34 |
+
"import os\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"print(os.listdir(path))"
|
| 37 |
+
],
|
| 38 |
+
"execution_count": null,
|
| 39 |
+
"outputs": []
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"cell_type": "code",
|
| 43 |
+
"metadata": {},
|
| 44 |
+
"source": [
|
| 45 |
+
"# Task 1: Write your code here:\n",
|
| 46 |
+
"csv_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 47 |
+
"df= pd.read_csv(csv_path)\n",
|
| 48 |
+
"df.head()\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"# Task 2: Write your code here:\n",
|
| 58 |
+
"df.head()"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 3: Write your code here:\n",
|
| 68 |
+
"df.info()"
|
| 69 |
+
],
|
| 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 |
+
"df.describe()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"df.columns"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 5: Write your code here:\n",
|
| 97 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 98 |
+
"plt.hist(df[\"Delivery_Time\"].dropna(), bins=30, edgecolor='black', color='orange')\n",
|
| 99 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 100 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 101 |
+
"plt.ylabel('Frequency')\n",
|
| 102 |
+
"plt.show()"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 1: Write your code here:\n",
|
| 112 |
+
"df=df.drop(\"Order_ID\",axis=1)"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 2: Write your code here:\n",
|
| 122 |
+
"missing_values = df.isnull().sum()\n",
|
| 123 |
+
"print(missing_values)\n",
|
| 124 |
+
"df_clean= df.dropna()\n",
|
| 125 |
+
"df_clean"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 3: Write your code here:\n",
|
| 135 |
+
"print(\"Duplicates before:\", df.duplicated().sum())\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"df_clean.drop_duplicates(inplace=True)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"print(\"Duplicates after:\", df_clean.duplicated().sum())"
|
| 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 |
+
"x = df_clean.drop(columns=['Order_ID'])\n"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 5: Write your code here:"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 6: Write your code here:"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 1: Write your code here:"
|
| 177 |
+
],
|
| 178 |
+
"execution_count": null,
|
| 179 |
+
"outputs": []
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"cell_type": "code",
|
| 183 |
+
"metadata": {},
|
| 184 |
+
"source": [
|
| 185 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 186 |
+
],
|
| 187 |
+
"execution_count": null,
|
| 188 |
+
"outputs": []
|
| 189 |
+
},
|
| 190 |
+
{
|
| 191 |
+
"cell_type": "code",
|
| 192 |
+
"metadata": {},
|
| 193 |
+
"source": [
|
| 194 |
+
"# Task 1: Write your code here:"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [
|
| 203 |
+
"# Task 2: Write your code here:"
|
| 204 |
+
],
|
| 205 |
+
"execution_count": null,
|
| 206 |
+
"outputs": []
|
| 207 |
+
},
|
| 208 |
+
{
|
| 209 |
+
"cell_type": "code",
|
| 210 |
+
"metadata": {},
|
| 211 |
+
"source": [
|
| 212 |
+
"# Task Bonus: Write your code here:"
|
| 213 |
+
],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
}
|
| 217 |
+
],
|
| 218 |
+
"metadata": {
|
| 219 |
+
"kernelspec": {
|
| 220 |
+
"display_name": "Python 3",
|
| 221 |
+
"name": "python3"
|
| 222 |
+
},
|
| 223 |
+
"language_info": {
|
| 224 |
+
"name": "python"
|
| 225 |
+
}
|
| 226 |
+
},
|
| 227 |
+
"nbformat": 4,
|
| 228 |
+
"nbformat_minor": 0
|
| 229 |
+
}
|
submissions_extracted/461/Q2.ipynb
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
],
|
| 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 |
+
"X_train_t = torch.from_numpy(X_train).float()\n",
|
| 79 |
+
"X_test_t = torch.from_numpy(X_test).float()\n",
|
| 80 |
+
"\n",
|
| 81 |
+
"y_train_t = torch.from_numpy(y_train)\n",
|
| 82 |
+
"y_test_t = torch.from_numpy(y_test)\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"if y_train_t.dtype != torch.long and (y_train_t.ndim == 1):\n",
|
| 85 |
+
" y_train_t = y_train_t.long()\n",
|
| 86 |
+
" y_test_t = y_test_t.long()\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_t, y_train_t)\n",
|
| 97 |
+
"test_dataset = TensorDataset(X_test_t, y_test_t)\n",
|
| 98 |
+
"\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# 3. Create DataLoaders\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"\n"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# 4. Print shape of one batch\n",
|
| 119 |
+
"\n"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# 5. Display sample images\n",
|
| 129 |
+
"\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 1: Write your model class here:"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 2: Write your training loop here:"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 3: Write your validation loop here:"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"# Task 5: Start training for 20 epochs:"
|
| 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 (Bonus): Write your code here:"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
}
|
| 197 |
+
],
|
| 198 |
+
"metadata": {
|
| 199 |
+
"kernelspec": {
|
| 200 |
+
"display_name": "Python 3",
|
| 201 |
+
"name": "python3"
|
| 202 |
+
},
|
| 203 |
+
"language_info": {
|
| 204 |
+
"name": "python"
|
| 205 |
+
}
|
| 206 |
+
},
|
| 207 |
+
"nbformat": 4,
|
| 208 |
+
"nbformat_minor": 0
|
| 209 |
+
}
|
submissions_extracted/461/Q3.ipynb
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 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"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"import matplotlib.pyplot as plt\n",
|
| 39 |
+
"\n"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 1: Write your code here:\n",
|
| 49 |
+
"df=pd.read_csv(path)"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 2: Write your code here:"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 3: Write your code here:"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 4: Write your code here:"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 1: Write your code here:"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 2: Write your code here:"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 3: Write your code here:"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# Task 4: Write your code here:"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# Task 5: Write your code here:"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# Task 1: Write your code here:"
|
| 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:"
|
| 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: Write your code here:"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task Bonus: Write your code here:"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
}
|
| 171 |
+
],
|
| 172 |
+
"metadata": {
|
| 173 |
+
"kernelspec": {
|
| 174 |
+
"display_name": "Python 3",
|
| 175 |
+
"name": "python3"
|
| 176 |
+
},
|
| 177 |
+
"language_info": {
|
| 178 |
+
"name": "python"
|
| 179 |
+
}
|
| 180 |
+
},
|
| 181 |
+
"nbformat": 4,
|
| 182 |
+
"nbformat_minor": 0
|
| 183 |
+
}
|
submissions_extracted/462/Q1.ipynb
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
"# 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 |
+
"\n",
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"df = pd.read_csv(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n"
|
| 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 |
+
"df.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 |
+
"df.info()\n"
|
| 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 |
+
"df.describe()\n"
|
| 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\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"plt.figure(figsize=(6,4))\n",
|
| 68 |
+
"plt.hist(df['Delivery_Time'], bins=20, edgecolor='black')\n",
|
| 69 |
+
"plt.xlabel('Delivery Time')\n",
|
| 70 |
+
"plt.ylabel('Frequency')\n",
|
| 71 |
+
"plt.title('Distribution of Delivery Time')\n",
|
| 72 |
+
"plt.show()\n",
|
| 73 |
+
"\n"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 1: Write your code here:\n",
|
| 83 |
+
"df = df.drop(columns=['Order_ID'])\n"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 2: Write your code here:\n",
|
| 93 |
+
"df = df.fillna(df.mode().iloc[0])\n",
|
| 94 |
+
"df.isnull().sum()"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 3: Write your code here:\n",
|
| 104 |
+
"df.duplicated().sum()"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"df = df.drop_duplicates()"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"encoder = OneHotEncoder(drop='first', sparse_output=False)\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"df = pd.concat(\n",
|
| 127 |
+
" [df.drop(columns=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']),\n",
|
| 128 |
+
" pd.DataFrame(\n",
|
| 129 |
+
" encoder.fit_transform(df[['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']]),\n",
|
| 130 |
+
" columns=encoder.get_feature_names_out(['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']),\n",
|
| 131 |
+
" index=df.index\n",
|
| 132 |
+
" )],\n",
|
| 133 |
+
" axis=1\n",
|
| 134 |
+
")\n"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# see all columns\n",
|
| 144 |
+
"print(df.columns)\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"# see first rows\n",
|
| 147 |
+
"df.head()\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"# shape before / after\n",
|
| 150 |
+
"df.shape\n"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"scaler = StandardScaler()\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"X = df.drop(columns=['Delivery_Time'])\n",
|
| 164 |
+
"y = df['Delivery_Time']\n",
|
| 165 |
+
"\n",
|
| 166 |
+
"X_scaled = scaler.fit_transform(X)\n"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 6: Write your code here:"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"\n",
|
| 185 |
+
"# Task 1: Split the dataset into features (X) and target (y)\n",
|
| 186 |
+
"X = df.drop(columns=['Delivery_Time'])\n",
|
| 187 |
+
"y = df['Delivery_Time']\n"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 197 |
+
"from sklearn.model_selection import KFold\n",
|
| 198 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 199 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 200 |
+
"import numpy as np\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"# Task 2: Use KFold for cross-validation\n",
|
| 203 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"mae_scores = []\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"# Tasks 3 & 4: Train RandomForest and evaluate using MAE\n",
|
| 208 |
+
"for train_idx, val_idx in kf.split(X):\n",
|
| 209 |
+
" X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
|
| 210 |
+
" y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" model = RandomForestRegressor(\n",
|
| 213 |
+
" n_estimators=100,\n",
|
| 214 |
+
" random_state=42\n",
|
| 215 |
+
" )\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" model.fit(X_train, y_train)\n",
|
| 218 |
+
" y_pred = model.predict(X_val)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" mae = mean_absolute_error(y_val, y_pred)\n",
|
| 221 |
+
" mae_scores.append(mae)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"# Task 5: Print average MAE across all folds\n",
|
| 224 |
+
"print(\"Average MAE across all folds:\", np.mean(mae_scores))\n",
|
| 225 |
+
"print(\"Average Accuracy:\", np.mean(scores) * 100, \"%\")\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"\n"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"import matplotlib.pyplot as plt\n",
|
| 237 |
+
"import pandas as pd\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"# Train model on full dataset\n",
|
| 240 |
+
"rf_model = RandomForestRegressor(n_estimators=200, random_state=42)\n",
|
| 241 |
+
"rf_model.fit(X, y)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"importances = rf_model.feature_importances_\n",
|
| 244 |
+
"feature_names = X.columns\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"importance_df = pd.DataFrame({\n",
|
| 247 |
+
" 'Feature': feature_names,\n",
|
| 248 |
+
" 'Importance': importances\n",
|
| 249 |
+
"}).sort_values(by='Importance', ascending=False)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"plt.figure(figsize=(10,6))\n",
|
| 252 |
+
"plt.barh(importance_df['Feature'], importance_df['Importance'])\n",
|
| 253 |
+
"plt.gca().invert_yaxis()\n",
|
| 254 |
+
"plt.title('Feature Importance - Random Forest')\n",
|
| 255 |
+
"plt.xlabel('Importance')\n",
|
| 256 |
+
"plt.show()\n"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 2: Write your code here:\n",
|
| 266 |
+
"y_pred_full = rf_model.predict(X)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"plt.figure(figsize=(6,4))\n",
|
| 269 |
+
"plt.hist(y_pred_full, bins=20, edgecolor='black')\n",
|
| 270 |
+
"plt.xlabel('Predicted Delivery Time')\n",
|
| 271 |
+
"plt.ylabel('Frequency')\n",
|
| 272 |
+
"plt.title('Predicted Delivery Time Distribution')\n",
|
| 273 |
+
"plt.show()\n"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"!pip install catboost"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task Bonus: Write your code here:\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"from catboost import CatBoostRegressor\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 296 |
+
"mae_scores = []\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"for train_idx, val_idx in kf.split(X):\n",
|
| 299 |
+
" X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
|
| 300 |
+
" y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" rf = RandomForestRegressor(random_state=42)\n",
|
| 303 |
+
" cb = CatBoostRegressor(verbose=0, random_state=42)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" rf.fit(X_train, y_train)\n",
|
| 306 |
+
" cb.fit(X_train, y_train)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" preds = (rf.predict(X_val) + cb.predict(X_val)) / 2\n",
|
| 309 |
+
" mae_scores.append(mean_absolute_error(y_val, preds))\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"# Results\n",
|
| 312 |
+
"avg_mae = np.mean(mae_scores)\n",
|
| 313 |
+
"mean_delivery_time = y.mean()\n",
|
| 314 |
+
"accuracy_percent = (1 - avg_mae / mean_delivery_time) * 100\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"print(\"Ensemble MAE:\", avg_mae)\n",
|
| 317 |
+
"print(\"Ensemble Accuracy (%):\", round(accuracy_percent, 2))"
|
| 318 |
+
],
|
| 319 |
+
"execution_count": null,
|
| 320 |
+
"outputs": []
|
| 321 |
+
}
|
| 322 |
+
],
|
| 323 |
+
"metadata": {
|
| 324 |
+
"kernelspec": {
|
| 325 |
+
"display_name": "Python 3",
|
| 326 |
+
"name": "python3"
|
| 327 |
+
},
|
| 328 |
+
"language_info": {
|
| 329 |
+
"name": "python"
|
| 330 |
+
}
|
| 331 |
+
},
|
| 332 |
+
"nbformat": 4,
|
| 333 |
+
"nbformat_minor": 0
|
| 334 |
+
}
|
submissions_extracted/462/Q2.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 |
+
"# 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_t = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 72 |
+
"X_test_t = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"y_train_t = torch.tensor(y_train, dtype=torch.float32).unsqueeze(1)\n",
|
| 75 |
+
"y_test_t = torch.tensor(y_test, dtype=torch.float32).unsqueeze(1)\n",
|
| 76 |
+
"\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 |
+
"# Task 2: Create dataset\n",
|
| 88 |
+
"from torch.utils.data import TensorDataset\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"train_dataset = TensorDataset(X_train_t, y_train_t)\n",
|
| 91 |
+
"test_dataset = TensorDataset(X_test_t, y_test_t)"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 3. Create DataLoaders\n",
|
| 101 |
+
"from torch.utils.data import DataLoader\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 104 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 105 |
+
"\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 |
+
"xb, yb = next(iter(train_loader))\n",
|
| 116 |
+
"print(\"X batch:\", xb.shape)\n",
|
| 117 |
+
"print(\"y batch:\", yb.shape)\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"\n"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# 5. Display sample images\n",
|
| 129 |
+
"import matplotlib.pyplot as plt\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"xb, yb = next(iter(train_loader))\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"plt.figure(figsize=(10, 4))\n",
|
| 134 |
+
"for i in range(6):\n",
|
| 135 |
+
" img = xb[i].permute(1, 2, 0).numpy()\n",
|
| 136 |
+
" plt.subplot(2, 3, i+1)\n",
|
| 137 |
+
" plt.imshow(img)\n",
|
| 138 |
+
" plt.title(f\"Age: {yb[i].item():.0f}\")\n",
|
| 139 |
+
" plt.axis(\"off\")\n",
|
| 140 |
+
"plt.tight_layout()\n",
|
| 141 |
+
"plt.show()\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"\n"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"\n",
|
| 153 |
+
"# Task 1: Write your model class here:\n",
|
| 154 |
+
"import torch\n",
|
| 155 |
+
"import torch.nn as nn\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"class AgeRegressor(nn.Module):\n",
|
| 158 |
+
" def __init__(self):\n",
|
| 159 |
+
" super().__init__()\n",
|
| 160 |
+
" self.model = nn.Sequential(\n",
|
| 161 |
+
" nn.Flatten(),\n",
|
| 162 |
+
" nn.LazyLinear(512),\n",
|
| 163 |
+
" nn.ReLU(),\n",
|
| 164 |
+
" nn.Linear(512, 128),\n",
|
| 165 |
+
" nn.ReLU(),\n",
|
| 166 |
+
" nn.Linear(128, 32),\n",
|
| 167 |
+
" nn.ReLU(),\n",
|
| 168 |
+
" nn.Linear(32, 1)\n",
|
| 169 |
+
" )\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" def forward(self, x):\n",
|
| 172 |
+
" return self.model(x)\n"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 2: Write your training loop here:\n",
|
| 182 |
+
"def train_one_epoch(model, loader, loss_fn, optimizer, device):\n",
|
| 183 |
+
" model.train()\n",
|
| 184 |
+
" loss = 0\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" for X, y in loader:\n",
|
| 187 |
+
" X, y = X.to(device), y.to(device)\n",
|
| 188 |
+
" optimizer.zero_grad()\n",
|
| 189 |
+
" output = model(X)\n",
|
| 190 |
+
" l = loss_fn(output, y)\n",
|
| 191 |
+
" l.backward()\n",
|
| 192 |
+
" optimizer.step()\n",
|
| 193 |
+
" loss += l.item()\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return loss / len(loader)"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 3: Write your validation loop here:\n",
|
| 205 |
+
"def validate(model, loader, loss_fn, device):\n",
|
| 206 |
+
" model.eval()\n",
|
| 207 |
+
" loss = 0\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" for X, y in loader:\n",
|
| 210 |
+
" X, y = X.to(device), y.to(device)\n",
|
| 211 |
+
" output = model(X)\n",
|
| 212 |
+
" loss += loss_fn(output, y).item()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" return loss / len(loader)\n",
|
| 215 |
+
"\n"
|
| 216 |
+
],
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"outputs": []
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 224 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 225 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 226 |
+
"model = AgeRegressor().to(device)\n",
|
| 227 |
+
"loss_fn = nn.MSELoss()\n",
|
| 228 |
+
"optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"# Create loss lists\n",
|
| 240 |
+
"train_losses = []\n",
|
| 241 |
+
"val_losses = []\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"# Train model\n",
|
| 244 |
+
"for epoch in range(20):\n",
|
| 245 |
+
" train_loss = train_one_epoch(model, train_loader, loss_fn, optimizer, device)\n",
|
| 246 |
+
" val_loss = validate(model, test_loader, loss_fn, device)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" train_losses.append(train_loss)\n",
|
| 249 |
+
" val_losses.append(val_loss)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" print(epoch + 1)\n",
|
| 252 |
+
"\n"
|
| 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 |
+
"import matplotlib.pyplot as plt\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"plt.plot(train_losses)\n",
|
| 265 |
+
"plt.plot(val_losses)\n",
|
| 266 |
+
"plt.xlabel(\"Epoch\")\n",
|
| 267 |
+
"plt.ylabel(\"Loss\")\n",
|
| 268 |
+
"plt.legend([\"Train\", \"Val\"])\n",
|
| 269 |
+
"plt.show()\n"
|
| 270 |
+
],
|
| 271 |
+
"execution_count": null,
|
| 272 |
+
"outputs": []
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"metadata": {},
|
| 277 |
+
"source": [
|
| 278 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 279 |
+
"import matplotlib.pyplot as plt\n",
|
| 280 |
+
"import torch\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"model.eval()\n",
|
| 283 |
+
"X, y = next(iter(test_loader))\n",
|
| 284 |
+
"X = X.to(device)\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"with torch.no_grad():\n",
|
| 287 |
+
" pred = model(X).cpu()\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"for i in range(6):\n",
|
| 290 |
+
" plt.subplot(2, 3, i+1)\n",
|
| 291 |
+
" plt.imshow(X[i].cpu().permute(1, 2, 0))\n",
|
| 292 |
+
" plt.title(f\"P:{pred[i].item():.1f} T:{y[i].item():.0f}\")\n",
|
| 293 |
+
" plt.axis(\"off\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"plt.show()\n"
|
| 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/462/Q3.ipynb
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import os\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"print(\"Path to dataset files:\", path)\n"
|
| 14 |
+
],
|
| 15 |
+
"execution_count": null,
|
| 16 |
+
"outputs": []
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"cell_type": "code",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"# Task 1: Write your code here:\n",
|
| 23 |
+
"df = pd.read_csv(os.path.join(path, \"Q3_data.csv\"))"
|
| 24 |
+
],
|
| 25 |
+
"execution_count": null,
|
| 26 |
+
"outputs": []
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
"cell_type": "code",
|
| 30 |
+
"metadata": {},
|
| 31 |
+
"source": [
|
| 32 |
+
"# Task 2: Write your code here:\n",
|
| 33 |
+
"df.head()"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 3: Write your code here:\n",
|
| 43 |
+
"df.info()"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 4: Write your code here:\n",
|
| 53 |
+
"df.describe()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 1: Write your code here:\n",
|
| 63 |
+
"# Show missing values before\n",
|
| 64 |
+
"print(df.isnull().sum())\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"# Fill missing values\n",
|
| 67 |
+
"df.fillna(df.mean(), inplace=True)\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"# Show after\n",
|
| 70 |
+
"print(df.isnull().sum())\n"
|
| 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 |
+
"\n",
|
| 81 |
+
"# Show number of duplicates before\n",
|
| 82 |
+
"print(\"Duplicates before:\", df.duplicated().sum())\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"# Remove duplicates\n",
|
| 85 |
+
"df.drop_duplicates(inplace=True)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"# Show after\n",
|
| 88 |
+
"print(\"Duplicates after:\", df.duplicated().sum())\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# Task 3: Write your code here:\n",
|
| 98 |
+
"# Show data types before encoding\n",
|
| 99 |
+
"print(df.dtypes)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"# Encode categorical variables\n",
|
| 102 |
+
"df = pd.get_dummies(df, drop_first=True)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"# Show data types after encoding\n",
|
| 105 |
+
"print(df.dtypes)\n"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 4: Write your code here:\n",
|
| 115 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# Show data before scaling\n",
|
| 118 |
+
"print(df.head())\n",
|
| 119 |
+
"\n",
|
| 120 |
+
"# Apply scaling\n",
|
| 121 |
+
"scaler = StandardScaler()\n",
|
| 122 |
+
"df_scaled = scaler.fit_transform(df)\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# Show data after scaling\n",
|
| 125 |
+
"print(df_scaled[:5])\n"
|
| 126 |
+
],
|
| 127 |
+
"execution_count": null,
|
| 128 |
+
"outputs": []
|
| 129 |
+
},
|
| 130 |
+
{
|
| 131 |
+
"cell_type": "code",
|
| 132 |
+
"metadata": {},
|
| 133 |
+
"source": [
|
| 134 |
+
"# Task 5: Write your code here:\n",
|
| 135 |
+
"# Target distribution\n",
|
| 136 |
+
"y = df.iloc[:, -1]\n",
|
| 137 |
+
"print(f\"Class 1: {(y == 1).sum()}\")\n",
|
| 138 |
+
"print(f\"Class 0: {(y == 0).sum()}\")"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"!pip install catboost"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 1: Write your code here:\n",
|
| 157 |
+
"X = df.drop(df.columns[-1], axis=1)\n",
|
| 158 |
+
"y = df.iloc[:, -1]"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 168 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 169 |
+
"from sklearn.metrics import accuracy_score\n",
|
| 170 |
+
"from catboost import CatBoostClassifier\n",
|
| 171 |
+
"import numpy as np\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"scores = []\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"for train_idx, test_idx in skf.split(X, y):\n",
|
| 178 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 179 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" model = CatBoostClassifier(verbose=0)\n",
|
| 182 |
+
" model.fit(X_train, y_train)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" y_pred = model.predict(X_test)\n",
|
| 185 |
+
" acc = accuracy_score(y_test, y_pred)\n",
|
| 186 |
+
" scores.append(acc)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"print(\"Average Accuracy:\", np.mean(scores) * 100, \"%\")\n"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 1: Write your code here:\n",
|
| 198 |
+
"import matplotlib.pyplot as plt\n",
|
| 199 |
+
"import numpy as np\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"importances = model.get_feature_importance()\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"# Get top 10 features\n",
|
| 204 |
+
"idx = np.argsort(importances)[-10:]\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"plt.barh(X.columns[idx], importances[idx])\n",
|
| 207 |
+
"plt.xlabel(\"Importance\")\n",
|
| 208 |
+
"plt.ylabel(\"Features\")\n",
|
| 209 |
+
"plt.show()\n",
|
| 210 |
+
"\n"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"# Task 2: Write your code here:\n",
|
| 220 |
+
"golden_feature = X.columns[importances.argmax()]\n",
|
| 221 |
+
"print(\"Golden Feature:\", golden_feature)"
|
| 222 |
+
],
|
| 223 |
+
"execution_count": null,
|
| 224 |
+
"outputs": []
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"# Task Bonus: Write your code here:\n",
|
| 231 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 232 |
+
"from sklearn.metrics import accuracy_score\n",
|
| 233 |
+
"from catboost import CatBoostClassifier\n",
|
| 234 |
+
"import numpy as np\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"# Use only the golden feature\n",
|
| 237 |
+
"X_golden = X[[golden_feature]]\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"scores_golden = []\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"for train_idx, test_idx in skf.split(X_golden, y):\n",
|
| 244 |
+
" X_train, X_test = X_golden.iloc[train_idx], X_golden.iloc[test_idx]\n",
|
| 245 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" model = CatBoostClassifier(verbose=0)\n",
|
| 248 |
+
" model.fit(X_train, y_train)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" y_pred = model.predict(X_test)\n",
|
| 251 |
+
" acc = accuracy_score(y_test, y_pred)\n",
|
| 252 |
+
" scores_golden.append(acc)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"print(\"Golden Feature Accuracy:\", np.mean(scores_golden) * 100, \"%\")\n"
|
| 255 |
+
],
|
| 256 |
+
"execution_count": null,
|
| 257 |
+
"outputs": []
|
| 258 |
+
},
|
| 259 |
+
{
|
| 260 |
+
"cell_type": "code",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"source": [],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
}
|
| 266 |
+
],
|
| 267 |
+
"metadata": {
|
| 268 |
+
"kernelspec": {
|
| 269 |
+
"display_name": "Python 3",
|
| 270 |
+
"name": "python3"
|
| 271 |
+
},
|
| 272 |
+
"language_info": {
|
| 273 |
+
"name": "python"
|
| 274 |
+
}
|
| 275 |
+
},
|
| 276 |
+
"nbformat": 4,
|
| 277 |
+
"nbformat_minor": 0
|
| 278 |
+
}
|
submissions_extracted/463/Q1.ipynb
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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\n",
|
| 12 |
+
"import kagglehub\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"import seaborn as sns\n",
|
| 18 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse\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 |
+
"\n",
|
| 32 |
+
"#Read the file\n",
|
| 33 |
+
"path = os.path.join(path, 'Q1_data.csv')\n",
|
| 34 |
+
"Q1_data = pd.read_csv(path)\n"
|
| 35 |
+
],
|
| 36 |
+
"execution_count": null,
|
| 37 |
+
"outputs": []
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"metadata": {},
|
| 42 |
+
"source": [
|
| 43 |
+
"# display some of data\n",
|
| 44 |
+
"Q1_data.head()"
|
| 45 |
+
],
|
| 46 |
+
"execution_count": null,
|
| 47 |
+
"outputs": []
|
| 48 |
+
},
|
| 49 |
+
{
|
| 50 |
+
"cell_type": "code",
|
| 51 |
+
"metadata": {},
|
| 52 |
+
"source": [
|
| 53 |
+
"#information about data\n",
|
| 54 |
+
"Q1_data.info()"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"Q1_data.describe()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 73 |
+
"plt.hist(Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 74 |
+
"plt.show()"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"data=Q1_data.dropna(subset=[\"Order_ID\"])"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"Q1_data['Delivery_Time'] =Q1_data['Delivery_Time'].fillna(Q1_data['Delivery_Time'].mean())"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 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(Q1_data)"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"categorical_cols = Q1_data.select_dtypes(include=[\"object\"]).columns\n",
|
| 123 |
+
"for col in categorical_cols:\n",
|
| 124 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 125 |
+
" le = LabelEncoder()\n",
|
| 126 |
+
" Q1_data[col] = le.fit_transform(Q1_data[col])\n",
|
| 127 |
+
"data_onehot_encoded = onehot_encoder.fit_transform(Q1_data)"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"features = Q1_data.columns.drop(\"Delivery_Time\") #scale all just leave the target\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"scaler = StandardScaler()\n",
|
| 139 |
+
"Q1_data[features] = scaler.fit_transform(Q1_data[features])\n",
|
| 140 |
+
"Q1_data.head()"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"sns.countplot(x=Q1_data[\"Delivery_Time\"])\n",
|
| 150 |
+
"plt.title(\"Target Distribution\")\n",
|
| 151 |
+
"plt.show()"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"X=Q1_data.drop[\"Delivery_Time\"]\n",
|
| 161 |
+
"y=Q1_data[\"Delivery_Time\"]\n",
|
| 162 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)"
|
| 163 |
+
],
|
| 164 |
+
"execution_count": null,
|
| 165 |
+
"outputs": []
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"cell_type": "code",
|
| 169 |
+
"metadata": {},
|
| 170 |
+
"source": [
|
| 171 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 172 |
+
"print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
|
| 173 |
+
"mse_scores = []\n",
|
| 174 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 175 |
+
" # indexing for each fold\n",
|
| 176 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 177 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 180 |
+
"model.fit(X_train, y_train)"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"plt.hist(Q1_data['Delivery_Time'], bins=20)\n",
|
| 197 |
+
"plt.title(\" predicted delivery time \")\n",
|
| 198 |
+
"plt.show()"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"# Task Bonus: Write your code here:"
|
| 208 |
+
],
|
| 209 |
+
"execution_count": null,
|
| 210 |
+
"outputs": []
|
| 211 |
+
}
|
| 212 |
+
],
|
| 213 |
+
"metadata": {
|
| 214 |
+
"kernelspec": {
|
| 215 |
+
"display_name": "Python 3",
|
| 216 |
+
"name": "python3"
|
| 217 |
+
},
|
| 218 |
+
"language_info": {
|
| 219 |
+
"name": "python"
|
| 220 |
+
}
|
| 221 |
+
},
|
| 222 |
+
"nbformat": 4,
|
| 223 |
+
"nbformat_minor": 0
|
| 224 |
+
}
|
submissions_extracted/463/Q2.ipynb
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 CIFAR10\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 |
+
"import torch.nn.functional as F\n",
|
| 14 |
+
"import torch\n",
|
| 15 |
+
"from torch.optim import AdamW\n",
|
| 16 |
+
"# Download latest version\n",
|
| 17 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"print(\"Path to dataset files:\", path)"
|
| 20 |
+
],
|
| 21 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"import os\n",
|
| 29 |
+
"import pandas as pd\n",
|
| 30 |
+
"import numpy as np\n",
|
| 31 |
+
"from PIL import Image\n",
|
| 32 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Labels\n",
|
| 35 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 36 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"images = []\n",
|
| 39 |
+
"ages = []\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"# Load Images and Resize\n",
|
| 42 |
+
"print(\"Loading images...\")\n",
|
| 43 |
+
"for index, row in labels_df.iterrows():\n",
|
| 44 |
+
" img_name = row.iloc[0]\n",
|
| 45 |
+
" age = row.iloc[1]\n",
|
| 46 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 47 |
+
"\n",
|
| 48 |
+
" if os.path.exists(img_path):\n",
|
| 49 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 50 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 51 |
+
" images.append(img_array)\n",
|
| 52 |
+
" ages.append(age)\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"X = np.array(images)\n",
|
| 55 |
+
"y = np.array(ages)\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 58 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 59 |
+
"\n",
|
| 60 |
+
"# Split Data\n",
|
| 61 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 62 |
+
"\n",
|
| 63 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 64 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 65 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 66 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"train_dataset = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n",
|
| 76 |
+
"# Testing dataset\n",
|
| 77 |
+
"test_dataset = CIFAR10(root='./datasets', train=False, transform=to_tensor, download=True)\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# Print one sample from the dataset\n",
|
| 80 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 81 |
+
"print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n",
|
| 82 |
+
"print(f\"Label: {sample_label}\")"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# 2. Create TensorDataset objects\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"\n"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"# 3. Create DataLoaders\n",
|
| 103 |
+
"train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
|
| 104 |
+
"# DataLoader for test data\n",
|
| 105 |
+
"test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"# Get the first batch from the training DataLoader\n",
|
| 108 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 109 |
+
"\n"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# 4. Print shape of one batch\n",
|
| 119 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 120 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# 5. Display sample images\n",
|
| 130 |
+
"images, labels = next(iter(train_loader))\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"# Display the first 6 images in the batch\n",
|
| 133 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"for i in range(6):\n",
|
| 136 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 137 |
+
"\n",
|
| 138 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 139 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 140 |
+
"\n",
|
| 141 |
+
" plt.imshow(img)\n",
|
| 142 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 143 |
+
" plt.axis('off')\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"plt.tight_layout()\n",
|
| 146 |
+
"plt.show()\n"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# Task 1: Write your model class here:\n",
|
| 156 |
+
"class NN3Layer(nn.Module):\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 159 |
+
" super(NN3Layer, self).__init__()\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 162 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 165 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 168 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 169 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 170 |
+
" # ReLU activation for non-linearity\n",
|
| 171 |
+
" self.relu = nn.ReLU()\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # Defines how input data flows through the network\n",
|
| 174 |
+
" def forward(self, x):\n",
|
| 175 |
+
" # First hidden layer\n",
|
| 176 |
+
" z1 = self.layer1(x)\n",
|
| 177 |
+
" a1 = self.relu(z1)\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Second hidden layer\n",
|
| 180 |
+
" z2 = self.layer2(a1)\n",
|
| 181 |
+
" a2 = self.relu(z2)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" z3= self.layer2(a2)\n",
|
| 184 |
+
" a3 = self.relu(z3)\n",
|
| 185 |
+
" # Output layer (raw scores / logits)\n",
|
| 186 |
+
" output = self.layer3(a3) # there is something missing here, remember? :)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" return output"
|
| 189 |
+
],
|
| 190 |
+
"execution_count": null,
|
| 191 |
+
"outputs": []
|
| 192 |
+
},
|
| 193 |
+
{
|
| 194 |
+
"cell_type": "code",
|
| 195 |
+
"metadata": {},
|
| 196 |
+
"source": [
|
| 197 |
+
"# Task 2: Write your training loop here:\n",
|
| 198 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 199 |
+
" # Set the model to training mode\n",
|
| 200 |
+
" model.train()\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" running_loss = 0.0\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 205 |
+
" # Move batch to the selected device\n",
|
| 206 |
+
" X_batch = X.Flatten(1).to(device)\n",
|
| 207 |
+
" y_batch = y_batch.to(device)\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" # Forward pass\n",
|
| 210 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 211 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Backward pass & optimization\n",
|
| 214 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 215 |
+
" loss.backward() # Compute gradients\n",
|
| 216 |
+
" optimizer.step() # Update model parameters\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" running_loss += loss.item()\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Average loss over all batches\n",
|
| 221 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" return avg_loss"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 3: Write your validation loop here:\n",
|
| 233 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 234 |
+
" # Set the model to evaluation mode\n",
|
| 235 |
+
" model.eval()\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" running_loss = 0.0\n",
|
| 238 |
+
" correct = 0\n",
|
| 239 |
+
" total = 0\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" with torch.no_grad():\n",
|
| 242 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 243 |
+
" # Move data to device\n",
|
| 244 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 245 |
+
" y_batch = y_batch.to(device)\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" # Forward pass\n",
|
| 248 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 249 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 250 |
+
" running_loss += loss.item()\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # Apply Softmax to get probabilities\n",
|
| 253 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Multiclass predictions\n",
|
| 256 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" # Accuracy calculation\n",
|
| 259 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 260 |
+
" total += y_batch.size(0)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 263 |
+
" accuracy = correct / total\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" return avg_loss, accuracy"
|
| 266 |
+
],
|
| 267 |
+
"execution_count": null,
|
| 268 |
+
"outputs": []
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "code",
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"source": [
|
| 274 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 275 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"# Model parameters\n",
|
| 278 |
+
"input_dim = 32*32 # MNIST images flattened\n",
|
| 279 |
+
"hidden_dim = 14 # Design\n",
|
| 280 |
+
"output_dim = 10\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"# Instantiate model\n",
|
| 283 |
+
"model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# Print the model architecture\n",
|
| 286 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 287 |
+
"print(model)\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"# Calculate the total number of trainable parameters\n",
|
| 290 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 291 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [
|
| 300 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 301 |
+
"num_epochs = 20\n",
|
| 302 |
+
"learning_rate = 0.001\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 305 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 306 |
+
"# Define optimizer\n",
|
| 307 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 308 |
+
"# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
|
| 309 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 310 |
+
"# Define optimizer\n",
|
| 311 |
+
"train_losses = []\n",
|
| 312 |
+
"val_losses = []\n",
|
| 313 |
+
"val_accuracies = []\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"print('Starting Training...')\n",
|
| 316 |
+
"for epoch in range(num_epochs):\n",
|
| 317 |
+
" # Train one epoch\n",
|
| 318 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 319 |
+
" # Validate\n",
|
| 320 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 321 |
+
" train_losses.append(train_loss)\n",
|
| 322 |
+
" val_losses.append(val_loss)\n",
|
| 323 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 324 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"print('Training Complete!')"
|
| 327 |
+
],
|
| 328 |
+
"execution_count": null,
|
| 329 |
+
"outputs": []
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "code",
|
| 333 |
+
"metadata": {},
|
| 334 |
+
"source": [
|
| 335 |
+
"# Task 1: Write your code here:\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 |
+
"cell_type": "code",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"source": [],
|
| 364 |
+
"execution_count": null,
|
| 365 |
+
"outputs": []
|
| 366 |
+
}
|
| 367 |
+
],
|
| 368 |
+
"metadata": {
|
| 369 |
+
"kernelspec": {
|
| 370 |
+
"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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 numpy as np\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import os\n",
|
| 13 |
+
"import kagglehub\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split, KFold,StratifiedKFold\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
|
| 16 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 17 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 18 |
+
"import seaborn as sns\n",
|
| 19 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"# Download latest version\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)\n"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 1: Write your code here:\n",
|
| 37 |
+
"path = os.path.join(path, 'Q3_data.csv')\n",
|
| 38 |
+
"Q3_data = pd.read_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 |
+
"Q3_data.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 |
+
"Q3_data.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 |
+
"Q3_data.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 |
+
"#cheak the missvalue\n",
|
| 79 |
+
"Q3_data.isnull().sum()\n",
|
| 80 |
+
"Q3_data['Target'] =Q3_data['Target'].fillna(Q3_data['Target'].mean())"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 2: Write your code here:\n",
|
| 90 |
+
"def check_duplicates(df):\n",
|
| 91 |
+
" duplicates = df.duplicated().sum()\n",
|
| 92 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 93 |
+
" if duplicates > 0:\n",
|
| 94 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 95 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 96 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 97 |
+
" else:\n",
|
| 98 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 99 |
+
"check_duplicates(Q3_data)"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 3: Write your code here:\n",
|
| 109 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"categorical_cols = Q3_data.select_dtypes(include=[\"object\"]).columns\n",
|
| 112 |
+
"for col in categorical_cols:\n",
|
| 113 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 114 |
+
" le = LabelEncoder()\n",
|
| 115 |
+
" Q3_data[col] = le.fit_transform(Q3_data[col])\n",
|
| 116 |
+
"data_onehot_encoded = onehot_encoder.fit_transform(Q3_data)"
|
| 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 |
+
"features = Q3_data.columns.drop(\"Target\")\n",
|
| 127 |
+
"scaler = StandardScaler()\n",
|
| 128 |
+
"Q3_data[features] = scaler.fit_transform(Q3_data[features])\n",
|
| 129 |
+
"Q3_data.head()"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 5: Write your code here:\n",
|
| 139 |
+
"sns.countplot(x=Q3_data[\"Target\"])\n",
|
| 140 |
+
"plt.title(\"Target Distribution\")\n",
|
| 141 |
+
"plt.show()"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"X=Q3_data.drop[\"Target\"]\n",
|
| 151 |
+
"y=Q3_data[\"Target\"]"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 161 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 162 |
+
"print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
|
| 163 |
+
"mse_scores = []\n",
|
| 164 |
+
"for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
|
| 165 |
+
" # indexing for each fold\n",
|
| 166 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 167 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 168 |
+
""
|
| 169 |
+
],
|
| 170 |
+
"execution_count": null,
|
| 171 |
+
"outputs": []
|
| 172 |
+
},
|
| 173 |
+
{
|
| 174 |
+
"cell_type": "code",
|
| 175 |
+
"metadata": {},
|
| 176 |
+
"source": [
|
| 177 |
+
"# Task 1: Write your code here:"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"# Task 2: Write your code here:"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "code",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": [
|
| 195 |
+
"# Task Bonus: Write your code here:"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
}
|
| 200 |
+
],
|
| 201 |
+
"metadata": {
|
| 202 |
+
"kernelspec": {
|
| 203 |
+
"display_name": "Python 3",
|
| 204 |
+
"name": "python3"
|
| 205 |
+
},
|
| 206 |
+
"language_info": {
|
| 207 |
+
"name": "python"
|
| 208 |
+
}
|
| 209 |
+
},
|
| 210 |
+
"nbformat": 4,
|
| 211 |
+
"nbformat_minor": 0
|
| 212 |
+
}
|
submissions_extracted/464/Q1.ipynb
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"import os\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"df_path = os.path.join(path,\"Q1_data.csv\")\n",
|
| 26 |
+
"df = pd.read_csv(df_path)"
|
| 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 |
+
"df.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 |
+
"df.info()"
|
| 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 |
+
"df.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.figure(figsize=(10, 5))\n",
|
| 69 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 70 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 71 |
+
"plt.xlabel('Delivery Time')\n",
|
| 72 |
+
"plt.ylabel('Frequency')\n",
|
| 73 |
+
"plt.show()"
|
| 74 |
+
],
|
| 75 |
+
"execution_count": null,
|
| 76 |
+
"outputs": []
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"metadata": {},
|
| 81 |
+
"source": [
|
| 82 |
+
"# Task 1: Write your code here:\n",
|
| 83 |
+
"df = df.drop(columns=[\"Order_ID\"])"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# Task 2: Write your code here:\n",
|
| 93 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100 # get the percentage of missing values in each column\n",
|
| 94 |
+
"missing_data = pd.DataFrame({\n",
|
| 95 |
+
" 'Column': missing_percentage.index,\n",
|
| 96 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 97 |
+
"})\n",
|
| 98 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False) # remove columns wih no missing values\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 101 |
+
"missing_data.head(10)"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"#Task 2 continue\n",
|
| 111 |
+
"# Remove nulls form the target values and because we should not fill it with any thing\n",
|
| 112 |
+
"# Remove nulls form the all missing columns and because its too small missing ro\n",
|
| 113 |
+
"df_clean = df.dropna(subset=[\"Delivery_Time\",\"Weather\",\"Traffic_Level\",\"Time_of_Day\",\"Courier_Experience_yrs\"])"
|
| 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 |
+
"def check_duplicates(df):\n",
|
| 124 |
+
" duplicates = df.duplicated().sum()\n",
|
| 125 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 126 |
+
" if duplicates > 0:\n",
|
| 127 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 128 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 129 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 130 |
+
" else:\n",
|
| 131 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"check_duplicates(df_clean)"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [
|
| 142 |
+
"# Task 4: Write your code here:\n",
|
| 143 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 144 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"#initlizing\n",
|
| 147 |
+
"for col in categorical_cols:\n",
|
| 148 |
+
" le = LabelEncoder()\n",
|
| 149 |
+
" df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"df_clean.info()"
|
| 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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"scaler = StandardScaler()\n",
|
| 164 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # will include every col except the target\n",
|
| 165 |
+
"df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
|
| 166 |
+
"df_clean"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 6: Write your code here:plt.figure(figsize=(10, 5))\n",
|
| 176 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 177 |
+
"plt.hist(df_clean['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 178 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 179 |
+
"plt.xlabel('Delivery Time')\n",
|
| 180 |
+
"plt.ylabel('Frequency')\n",
|
| 181 |
+
"plt.show()"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 1: Write your code here:\n",
|
| 191 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 192 |
+
"X = df_clean.drop(\"Delivery_Time\",axis=1)\n",
|
| 193 |
+
"y = df_clean['Delivery_Time']\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"X.head()"
|
| 197 |
+
],
|
| 198 |
+
"execution_count": null,
|
| 199 |
+
"outputs": []
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"cell_type": "code",
|
| 203 |
+
"metadata": {},
|
| 204 |
+
"source": [
|
| 205 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 206 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 207 |
+
"from sklearn.model_selection import KFold\n",
|
| 208 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 209 |
+
"import numpy as np\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 212 |
+
"mae_scores = []\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# we use KFold because its regressing problem\n",
|
| 215 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 216 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 217 |
+
" # indexing for each fold\n",
|
| 218 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 219 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" model.fit(X_train, y_train)\n",
|
| 222 |
+
" y_pred = model.predict(X_test)\n",
|
| 223 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 224 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 225 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 226 |
+
"print(f\"MAE: {mae_scores.mean():,.2f}\")"
|
| 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 |
+
"# Feature importance\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"feature_cols = [\"Distance_km\",\t\"Weather\",\t\"Traffic_Level\",\t\"Time_of_Day\",\t\"Vehicle_Type\",\t\"Preparation_Time_min\",\t\"Courier_Experience_yrs\"]\n",
|
| 239 |
+
"feature_importance = pd.DataFrame({\n",
|
| 240 |
+
" 'feature': feature_cols,\n",
|
| 241 |
+
" 'importance': model.feature_importances_\n",
|
| 242 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 245 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 246 |
+
"plt.xlabel('Importance')\n",
|
| 247 |
+
"plt.title('Feature Importance')\n",
|
| 248 |
+
"plt.gca().invert_yaxis()\n",
|
| 249 |
+
"plt.show()"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"# Task 2: Write your code here:"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"# Task Bonus: Write your code here:"
|
| 268 |
+
],
|
| 269 |
+
"execution_count": null,
|
| 270 |
+
"outputs": []
|
| 271 |
+
}
|
| 272 |
+
],
|
| 273 |
+
"metadata": {
|
| 274 |
+
"kernelspec": {
|
| 275 |
+
"display_name": "Python 3",
|
| 276 |
+
"name": "python3"
|
| 277 |
+
},
|
| 278 |
+
"language_info": {
|
| 279 |
+
"name": "python"
|
| 280 |
+
}
|
| 281 |
+
},
|
| 282 |
+
"nbformat": 4,
|
| 283 |
+
"nbformat_minor": 0
|
| 284 |
+
}
|
submissions_extracted/464/Q2.ipynb
ADDED
|
@@ -0,0 +1,382 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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.tensor(X_train, dtype=torch.float32)\n",
|
| 71 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 72 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 73 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\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 DataLoader, TensorDataset\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"\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 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 101 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 104 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# 4. Print shape of one batch\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 |
+
"import matplotlib.pyplot as plt\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"# Get one batch of images and labels\n",
|
| 132 |
+
"images, labels = next(iter(train_loader))\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"# Display the first 6 images in the batch\n",
|
| 135 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"for i in range(6):\n",
|
| 138 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 139 |
+
"\n",
|
| 140 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 141 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 142 |
+
"\n",
|
| 143 |
+
" plt.imshow(img)\n",
|
| 144 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 145 |
+
" plt.axis('off')\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"plt.tight_layout()\n",
|
| 148 |
+
"plt.show()"
|
| 149 |
+
],
|
| 150 |
+
"execution_count": null,
|
| 151 |
+
"outputs": []
|
| 152 |
+
},
|
| 153 |
+
{
|
| 154 |
+
"cell_type": "code",
|
| 155 |
+
"metadata": {},
|
| 156 |
+
"source": [
|
| 157 |
+
"# Task 1: Write your model class here:\n",
|
| 158 |
+
"import torch.nn as nn\n",
|
| 159 |
+
"class NN4Layer(nn.Module):\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 162 |
+
" super(NN4Layer, self).__init__()\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 165 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 168 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 171 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 174 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # activation function for non-linearity\n",
|
| 178 |
+
" self.relu = nn.ReLU()\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Defines how input data flows through the network\n",
|
| 182 |
+
" def forward(self, x):\n",
|
| 183 |
+
" # Layer 1: TODO\n",
|
| 184 |
+
" z1 = self.layer1(x)\n",
|
| 185 |
+
" a1 = self.relu(z1)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Layer 2 TODO\n",
|
| 188 |
+
" z2 = self.layer2(a1)\n",
|
| 189 |
+
" a2 = self.relu(z2)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" # Layer 3 TODO\n",
|
| 192 |
+
" z3 = self.layer3(a2)\n",
|
| 193 |
+
" a3 = self.relu(z3)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Output layer\n",
|
| 196 |
+
" z4 = self.layer4(a3)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" return z4"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"# Task 2: Write your training loop here:\n",
|
| 209 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 210 |
+
" # Set the model to training mode\n",
|
| 211 |
+
" model.train()\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" running_loss = 0.0\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 216 |
+
" # Move batch to the selected device\n",
|
| 217 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 218 |
+
" y_batch = y_batch.to(device)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" # Forward pass\n",
|
| 221 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 222 |
+
" # compute loss\n",
|
| 223 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" # Backward pass & optimization\n",
|
| 226 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 227 |
+
" loss.backward() # Compute gradients\n",
|
| 228 |
+
" optimizer.step() # Update model parameters\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" running_loss += loss.item()\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # Average loss over all batches\n",
|
| 233 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" return avg_loss"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 244 |
+
"# Task 3: Write your validation loop here:\n",
|
| 245 |
+
"import torch.nn.functional as F\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 248 |
+
" # Set the model to evaluation mode\n",
|
| 249 |
+
" model.eval()\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" running_loss = 0.0\n",
|
| 252 |
+
" correct = 0\n",
|
| 253 |
+
" total = 0\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" with torch.no_grad():\n",
|
| 256 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 257 |
+
" # Move data to device\n",
|
| 258 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 259 |
+
" y_batch = y_batch.to(device)\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" # Forward pass\n",
|
| 262 |
+
" # make predictions\n",
|
| 263 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 264 |
+
" # compute loss\n",
|
| 265 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 266 |
+
" running_loss += loss.item()\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # Apply Softmax to get probabilities\n",
|
| 269 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # Multiclass predictions\n",
|
| 272 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" # Accuracy calculation\n",
|
| 275 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 276 |
+
" total += y_batch.size(0)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 279 |
+
" # how do we calculate accuracy?\n",
|
| 280 |
+
" accuracy = correct / total\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" return avg_loss, accuracy\n"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 292 |
+
"from torch.optim import AdamW\n",
|
| 293 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 294 |
+
"input_dim = 3 * 36 * 36\n",
|
| 295 |
+
"hidden_dim = 64\n",
|
| 296 |
+
"output_dim = 1\n",
|
| 297 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 298 |
+
"num_epochs = 20\n",
|
| 299 |
+
"learning_rate = 0.001\n",
|
| 300 |
+
"\n",
|
| 301 |
+
"# Define criterion (loss function)\n",
|
| 302 |
+
"criterion = nn.MSELoss()\n",
|
| 303 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 304 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 307 |
+
"print(model)"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# Run Training\n",
|
| 319 |
+
"train_losses = []\n",
|
| 320 |
+
"val_losses = []\n",
|
| 321 |
+
"val_accuracies = []\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"print('Starting Training...')\n",
|
| 324 |
+
"for epoch in range(num_epochs):\n",
|
| 325 |
+
" # Train one epoch\n",
|
| 326 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 327 |
+
"\n",
|
| 328 |
+
" # Validate\n",
|
| 329 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" train_losses.append(train_loss)\n",
|
| 332 |
+
" val_losses.append(val_loss)\n",
|
| 333 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"print('Training Complete!')"
|
| 338 |
+
],
|
| 339 |
+
"execution_count": null,
|
| 340 |
+
"outputs": []
|
| 341 |
+
},
|
| 342 |
+
{
|
| 343 |
+
"cell_type": "code",
|
| 344 |
+
"metadata": {},
|
| 345 |
+
"source": [
|
| 346 |
+
"# Task 1: Write your code here:plt.figure(figsize=(7, 5))\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 349 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 350 |
+
"plt.title('Loss over Epochs')\n",
|
| 351 |
+
"plt.xlabel('Epoch')\n",
|
| 352 |
+
"plt.ylabel('Loss')\n",
|
| 353 |
+
"plt.legend()\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"plt.tight_layout()\n",
|
| 356 |
+
"plt.show()"
|
| 357 |
+
],
|
| 358 |
+
"execution_count": null,
|
| 359 |
+
"outputs": []
|
| 360 |
+
},
|
| 361 |
+
{
|
| 362 |
+
"cell_type": "code",
|
| 363 |
+
"metadata": {},
|
| 364 |
+
"source": [
|
| 365 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 366 |
+
],
|
| 367 |
+
"execution_count": null,
|
| 368 |
+
"outputs": []
|
| 369 |
+
}
|
| 370 |
+
],
|
| 371 |
+
"metadata": {
|
| 372 |
+
"kernelspec": {
|
| 373 |
+
"display_name": "Python 3",
|
| 374 |
+
"name": "python3"
|
| 375 |
+
},
|
| 376 |
+
"language_info": {
|
| 377 |
+
"name": "python"
|
| 378 |
+
}
|
| 379 |
+
},
|
| 380 |
+
"nbformat": 4,
|
| 381 |
+
"nbformat_minor": 0
|
| 382 |
+
}
|
submissions_extracted/464/Q3.ipynb
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"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 os\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"df_path = os.path.join(path,\"Q3_data.csv\")\n",
|
| 30 |
+
"df = pd.read_csv(df_path)\n"
|
| 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 |
+
"df.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 |
+
"df.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 |
+
"df.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 |
+
"missing_percentage = (df.isnull().sum() / len(df)) * 100 # get the percentage of missing values in each column\n",
|
| 71 |
+
"missing_data = pd.DataFrame({\n",
|
| 72 |
+
" 'Column': missing_percentage.index,\n",
|
| 73 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 74 |
+
"})\n",
|
| 75 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False) # remove columns wih no missing values\n",
|
| 76 |
+
"\n",
|
| 77 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 78 |
+
"missing_data.head(10)"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"#Task 1 continue\n",
|
| 88 |
+
"df.dropna(subset=[\"D_87\",\"D_88\",\"B_39\",\"D_110\",\"D_111\",\"D_108\",\"B_42\",\"D_73\",\"D_135\",\"D_136\",\"D_42\",\"D_142\"])\n",
|
| 89 |
+
"df"
|
| 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 |
+
"def check_duplicates(df):\n",
|
| 100 |
+
" duplicates = df.duplicated().sum()\n",
|
| 101 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 102 |
+
" if duplicates > 0:\n",
|
| 103 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 104 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 105 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 106 |
+
" else:\n",
|
| 107 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"check_duplicates(df)\n"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"df"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 3: Write your code here:\n",
|
| 128 |
+
"# no need for encoding\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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"scaler = StandardScaler()\n",
|
| 141 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # will include every col except the target\n",
|
| 142 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 143 |
+
"df"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"# Task 5: Write your code here:\n",
|
| 153 |
+
"import matplotlib.pyplot as plt\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 156 |
+
"plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n",
|
| 157 |
+
"plt.title('Target Distribution')\n",
|
| 158 |
+
"plt.xlabel('Target')\n",
|
| 159 |
+
"plt.ylabel('Frequency')\n",
|
| 160 |
+
"plt.show()"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"!pip install catboost"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 1: Write your code here:\n",
|
| 179 |
+
"from catboost import CatBoostClassifier\n",
|
| 180 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 181 |
+
"from sklearn.metrics import accuracy_score,f1_score\n",
|
| 182 |
+
"X = df.drop(\"Target\",axis=1)\n",
|
| 183 |
+
"y = df['Target']\n"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 193 |
+
"import numpy as np\n",
|
| 194 |
+
"n_splits =5\n",
|
| 195 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 196 |
+
"model = CatBoostClassifier(\n",
|
| 197 |
+
" verbose=0,\n",
|
| 198 |
+
" n_estimators=320,\n",
|
| 199 |
+
" max_depth=4\n",
|
| 200 |
+
" )\n",
|
| 201 |
+
"accuercy_list = []\n",
|
| 202 |
+
"f1_list = []\n",
|
| 203 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 204 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # 1. Split data\n",
|
| 207 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 208 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # 2. Train & Validate sklearn models\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" model.fit(X_train, y_train) # train\n",
|
| 213 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 216 |
+
" accuercy_list.append(accuracy_score(y_test, y_pred))\n",
|
| 217 |
+
" f1_list.append(f1_score(y_test, y_pred, zero_division=0))\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"accuercy_list = np.array(accuercy_list)\n",
|
| 220 |
+
"f1_list = np.array(f1_list)\n",
|
| 221 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 222 |
+
"print(f\"MAE: {accuercy_list.mean():,.2f}\")\n"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"print(f\"accuercy: {accuercy_list.mean():,.2f}\")\n",
|
| 232 |
+
"print(f\"F1: {f1_list.mean():,.2f}\")\n"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task 1: Write your code here:\n",
|
| 242 |
+
"feature_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
|
| 243 |
+
"feature_importance = pd.DataFrame({\n",
|
| 244 |
+
" 'feature': feature_cols,\n",
|
| 245 |
+
" 'importance': model.feature_importances_\n",
|
| 246 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 249 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 250 |
+
"plt.xlabel('Importance')\n",
|
| 251 |
+
"plt.title('Feature Importance')\n",
|
| 252 |
+
"plt.gca().invert_yaxis()\n",
|
| 253 |
+
"plt.show()"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task 2: Write your code here:\n",
|
| 263 |
+
"print(\"P_2\")"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"# Task Bonus: Write your code here:"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
}
|
| 277 |
+
],
|
| 278 |
+
"metadata": {
|
| 279 |
+
"kernelspec": {
|
| 280 |
+
"display_name": "Python 3",
|
| 281 |
+
"name": "python3"
|
| 282 |
+
},
|
| 283 |
+
"language_info": {
|
| 284 |
+
"name": "python"
|
| 285 |
+
}
|
| 286 |
+
},
|
| 287 |
+
"nbformat": 4,
|
| 288 |
+
"nbformat_minor": 0
|
| 289 |
+
}
|
submissions_extracted/465/Q1.ipynb
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import os\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"print(\"Path to dataset files:\", path)"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"# Task 1: Write your code here:\n",
|
| 24 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\") # We initialize the complete path with Q1_data.csv\n",
|
| 25 |
+
"df = pd.read_csv(csv_path) # Now We can read the csv file we prepared"
|
| 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 |
+
"df.head() #printing the first 5 samples with the features"
|
| 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 |
+
"df.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 |
+
"df.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 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 66 |
+
"plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n",
|
| 67 |
+
"plt.title('Delivery time Distribution')\n",
|
| 68 |
+
"plt.xlabel('Target')\n",
|
| 69 |
+
"plt.ylabel('Frequency')\n",
|
| 70 |
+
"plt.show()"
|
| 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 |
+
"df = df.drop(columns=['Order_ID'])\n",
|
| 81 |
+
"# df.head() # to check that the column is deleted"
|
| 82 |
+
],
|
| 83 |
+
"execution_count": null,
|
| 84 |
+
"outputs": []
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"cell_type": "code",
|
| 88 |
+
"metadata": {},
|
| 89 |
+
"source": [
|
| 90 |
+
"# Task 2: Write your code here:\n",
|
| 91 |
+
"print(\"Missing values per column:\")\n",
|
| 92 |
+
"print(df.isnull().sum())\n",
|
| 93 |
+
"print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"missing_pct = (df.isnull().sum() / len(df)) * 100\n",
|
| 96 |
+
"print(missing_pct[missing_pct > 0].sort_values(ascending=False))\n",
|
| 97 |
+
"print(\"tot:\", (df.isnull().sum().sum() / len(df)) * 100) # 18% is a lot so we will not drop the columns\n",
|
| 98 |
+
"# For objects (text) I used the most frequent with None\n",
|
| 99 |
+
"df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
|
| 100 |
+
"df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
|
| 101 |
+
"df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
|
| 102 |
+
"# Since the the plot is balanced and makes a bell shape then I will use mean, if the plot was skewed i will use median\n",
|
| 103 |
+
"df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
|
| 104 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"# Now there is no missing values."
|
| 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 |
+
"df.drop_duplicates(inplace=True) # inplace will modify the origianl df\n",
|
| 117 |
+
"print(f\"Duplicates: {df.duplicated().sum()}\")\n",
|
| 118 |
+
"#Now all duplicates are removed"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 4: Write your code here:\n",
|
| 128 |
+
"from sklearn.preprocessing import OneHotEncoder, LabelEncoder\n",
|
| 129 |
+
"#The following columns has no order so we use OneHotEncoder. + The columns have few unique samples, if many wouldn't use it\n",
|
| 130 |
+
"encoder = OneHotEncoder(sparse_output=False)\n",
|
| 131 |
+
"encoded = encoder.fit_transform(df[['Weather']])\n",
|
| 132 |
+
"df[\"Weather\"] = encoded\n",
|
| 133 |
+
"encoded = encoder.fit_transform(df[['Vehicle_Type']])\n",
|
| 134 |
+
"df[\"Vehicle_Type\"] = encoded\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"# When order matters daytime and time of the day is ordered\n",
|
| 137 |
+
"categorical_cols = df.select_dtypes(include=['object']).columns\n",
|
| 138 |
+
"for col in categorical_cols:\n",
|
| 139 |
+
" le = LabelEncoder()\n",
|
| 140 |
+
" df[col] = le.fit_transform(df[col].astype(str))\n",
|
| 141 |
+
"df.head()\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 5: Write your code here:\n",
|
| 151 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 152 |
+
"# The target should not be scaled we need to seperate them.\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") ### DON'T SCALE THE TARGET\n",
|
| 155 |
+
"scaler = StandardScaler()\n",
|
| 156 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 6: Write your code here:\n",
|
| 166 |
+
"# The data before adding the mean to nulls were balanced, but after adding the mean to nulls that data showed a huge spike in mean\n",
|
| 167 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 168 |
+
"plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n",
|
| 169 |
+
"plt.title('Delivery time Distribution')\n",
|
| 170 |
+
"plt.xlabel('Target')\n",
|
| 171 |
+
"plt.ylabel('Frequency')\n",
|
| 172 |
+
"plt.show()"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 1: Write your code here:\n",
|
| 182 |
+
"from sklearn.model_selection import KFold\n",
|
| 183 |
+
"X = df.drop('Delivery_Time', axis=1)\n",
|
| 184 |
+
"y = df['Delivery_Time']\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 194 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 195 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 196 |
+
"import numpy as np\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"avg = []\n",
|
| 199 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 200 |
+
"for fold, (train_idx, val_idx) in enumerate(kf.split(X)):\n",
|
| 201 |
+
" X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
|
| 202 |
+
" y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
|
| 203 |
+
" rf = RandomForestRegressor(n_estimators=100, max_depth=5, random_state=42)\n",
|
| 204 |
+
" rf.fit(X_train, y_train)\n",
|
| 205 |
+
" y_pred = rf.predict(X_val)\n",
|
| 206 |
+
" mae = mean_absolute_error(y_val, y_pred)\n",
|
| 207 |
+
" avg.append(mae)\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"print(np.average(avg))\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n"
|
| 213 |
+
],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"source": [
|
| 221 |
+
"# Task 1: Write your code here:\n",
|
| 222 |
+
"print(\"\\nTop important features (Random Forest):\")\n",
|
| 223 |
+
"importances = rf.feature_importances_\n",
|
| 224 |
+
"for i in np.argsort(importances)[::-1]:\n",
|
| 225 |
+
" print(f\" Feature {i}: {importances[i]:.3f}\")"
|
| 226 |
+
],
|
| 227 |
+
"execution_count": null,
|
| 228 |
+
"outputs": []
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"# Task 2: Write your code here:\n",
|
| 235 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 236 |
+
"plt.hist(importances, bins=10, edgecolor='black')\n",
|
| 237 |
+
"plt.title('Target Distribution')\n",
|
| 238 |
+
"plt.xlabel('Target')\n",
|
| 239 |
+
"plt.ylabel('Frequency')\n",
|
| 240 |
+
"plt.show()"
|
| 241 |
+
],
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"outputs": []
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"cell_type": "code",
|
| 247 |
+
"metadata": {},
|
| 248 |
+
"source": [
|
| 249 |
+
"# Task Bonus: Write your code here:"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
}
|
| 254 |
+
],
|
| 255 |
+
"metadata": {
|
| 256 |
+
"kernelspec": {
|
| 257 |
+
"display_name": "Python 3",
|
| 258 |
+
"name": "python3"
|
| 259 |
+
},
|
| 260 |
+
"language_info": {
|
| 261 |
+
"name": "python"
|
| 262 |
+
}
|
| 263 |
+
},
|
| 264 |
+
"nbformat": 4,
|
| 265 |
+
"nbformat_minor": 0
|
| 266 |
+
}
|
submissions_extracted/465/Q2.ipynb
ADDED
|
@@ -0,0 +1,393 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"from torch.utils.data import TensorDataset\n",
|
| 70 |
+
"from torch.utils.data import DataLoader\n",
|
| 71 |
+
"import torch\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 74 |
+
"X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 75 |
+
"y_train_tensor = torch.tensor(y_train, dtype=torch.float32) #float for regression\n",
|
| 76 |
+
"y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\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 |
+
"train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n",
|
| 88 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 89 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\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 |
+
"# DataLoader for training data\n",
|
| 101 |
+
"train_loader = DataLoader(\n",
|
| 102 |
+
" train_dataset,\n",
|
| 103 |
+
" batch_size=32,\n",
|
| 104 |
+
" shuffle=True,\n",
|
| 105 |
+
" num_workers=2\n",
|
| 106 |
+
")\n",
|
| 107 |
+
"# DataLoader for test/validation data\n",
|
| 108 |
+
"test_loader = DataLoader(\n",
|
| 109 |
+
" test_dataset,\n",
|
| 110 |
+
" batch_size=32,\n",
|
| 111 |
+
" shuffle=False,\n",
|
| 112 |
+
" num_workers=2\n",
|
| 113 |
+
")\n",
|
| 114 |
+
"\n"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# 4. Print shape of one batch\n",
|
| 124 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 125 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 126 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"import matplotlib.pyplot as plt\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"# 5. Display sample images\n",
|
| 138 |
+
"# Get one batch of images and labels\n",
|
| 139 |
+
"images, labels = next(iter(train_loader))\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Display the first 6 images in the batch\n",
|
| 142 |
+
"# plt.figure(figsize=(8, 4))\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# for i in range(6):\n",
|
| 145 |
+
"# plt.subplot(2, 3, i + 1)\n",
|
| 146 |
+
"# plt.imshow(images[i].squeeze(dim=1), cmap='gray')\n",
|
| 147 |
+
"# plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 148 |
+
"# plt.axis('off')\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"# plt.tight_layout()\n",
|
| 151 |
+
"# plt.show()\n"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"import torch\n",
|
| 161 |
+
"import torch.nn as nn\n",
|
| 162 |
+
"from torchvision.datasets import MNIST\n",
|
| 163 |
+
"from torch.utils.data import DataLoader\n",
|
| 164 |
+
"from torch.optim import Adam\n",
|
| 165 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 166 |
+
"import torch.nn.functional as F\n",
|
| 167 |
+
"import matplotlib.pyplot as plt\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# Task 1: Write your model class here:\n",
|
| 170 |
+
"class ModelClass(nn.Module):\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 173 |
+
" super(ModelClass, self).__init__()\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # First linear layer\n",
|
| 176 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" # Second linear layer\n",
|
| 179 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Third linear layer\n",
|
| 182 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" # Output layer:\n",
|
| 185 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # ReLU activation for non-linearity\n",
|
| 188 |
+
" self.relu = nn.ReLU()\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Defines how input data flows through the network\n",
|
| 191 |
+
" def forward(self, x):\n",
|
| 192 |
+
" # First hidden layer\n",
|
| 193 |
+
" z1 = self.layer1(x)\n",
|
| 194 |
+
" a1 = self.relu(z1)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" # Second hidden layer\n",
|
| 197 |
+
" z2 = self.layer2(a1)\n",
|
| 198 |
+
" a2 = self.relu(z2)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" z3 = self.layer3(a2)\n",
|
| 201 |
+
" a3 = self.relu(z2)\n",
|
| 202 |
+
" # Output layer (raw scores / logits)\n",
|
| 203 |
+
" output = self.layer3(a3) # there is something missing here, remember? :)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" return output"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [
|
| 214 |
+
"# Task 2: Write your training loop here:\n",
|
| 215 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 216 |
+
" # Set the model to training mode\n",
|
| 217 |
+
" model.train()\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" running_loss = 0.0\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 222 |
+
" # Move batch to the selected device (3456x36 and 784x14)\n",
|
| 223 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 224 |
+
" y_batch = y_batch.to(device)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Forward pass\n",
|
| 227 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 228 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" # Backward pass & optimization\n",
|
| 231 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 232 |
+
" loss.backward() # Compute gradients\n",
|
| 233 |
+
" optimizer.step() # Update model parameters\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" running_loss += loss.item()\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" # Average loss over all batches\n",
|
| 238 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" return avg_loss"
|
| 241 |
+
],
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"outputs": []
|
| 244 |
+
},
|
| 245 |
+
{
|
| 246 |
+
"cell_type": "code",
|
| 247 |
+
"metadata": {},
|
| 248 |
+
"source": [
|
| 249 |
+
"# Task 3: Write your validation loop here:\n",
|
| 250 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 251 |
+
" # Set the model to evaluation mode\n",
|
| 252 |
+
" model.eval()\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" running_loss = 0.0\n",
|
| 255 |
+
" correct = 0\n",
|
| 256 |
+
" total = 0\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" with torch.no_grad():\n",
|
| 259 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 260 |
+
" # Move data to device\n",
|
| 261 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 262 |
+
" y_batch = y_batch.to(device)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" # Forward pass\n",
|
| 265 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 266 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 267 |
+
" running_loss += loss.item()\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # Apply Softmax to get probabilities\n",
|
| 270 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" # Multiclass predictions\n",
|
| 273 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" # Accuracy calculation\n",
|
| 276 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 277 |
+
" total += y_batch.size(0)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 280 |
+
" accuracy = correct / total\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" return avg_loss, accuracy\n"
|
| 283 |
+
],
|
| 284 |
+
"execution_count": null,
|
| 285 |
+
"outputs": []
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"cell_type": "code",
|
| 289 |
+
"metadata": {},
|
| 290 |
+
"source": [
|
| 291 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 292 |
+
"# Device setup\n",
|
| 293 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"# Model parameters\n",
|
| 296 |
+
"input_dim = 28 * 28 # MNIST images flattened\n",
|
| 297 |
+
"hidden_dim = 14 # Design choice\n",
|
| 298 |
+
"output_dim = 10 # Digits 0–9\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Instantiate model\n",
|
| 301 |
+
"model = ModelClass(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"# Print the model architecture\n",
|
| 304 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 305 |
+
"print(model)\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"# Calculate the total number of trainable parameters\n",
|
| 308 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 309 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\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 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 327 |
+
"# Run Training\n",
|
| 328 |
+
"train_losses = []\n",
|
| 329 |
+
"val_losses = []\n",
|
| 330 |
+
"val_accuracies = []\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"print('Starting Training...')\n",
|
| 333 |
+
"for epoch in range(num_epochs):\n",
|
| 334 |
+
" # Train one epoch\n",
|
| 335 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 336 |
+
"\n",
|
| 337 |
+
" # Validate\n",
|
| 338 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" train_losses.append(train_loss)\n",
|
| 341 |
+
" val_losses.append(val_loss)\n",
|
| 342 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"print('Training Complete!')"
|
| 347 |
+
],
|
| 348 |
+
"execution_count": null,
|
| 349 |
+
"outputs": []
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"cell_type": "code",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"source": [
|
| 355 |
+
"# Task 1: Write your code here:\n",
|
| 356 |
+
"# Plotting results\n",
|
| 357 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 360 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 361 |
+
"plt.title('Loss over Epochs')\n",
|
| 362 |
+
"plt.xlabel('Epoch')\n",
|
| 363 |
+
"plt.ylabel('Loss')\n",
|
| 364 |
+
"plt.legend()\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"plt.tight_layout()\n",
|
| 367 |
+
"plt.show()"
|
| 368 |
+
],
|
| 369 |
+
"execution_count": null,
|
| 370 |
+
"outputs": []
|
| 371 |
+
},
|
| 372 |
+
{
|
| 373 |
+
"cell_type": "code",
|
| 374 |
+
"metadata": {},
|
| 375 |
+
"source": [
|
| 376 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 377 |
+
],
|
| 378 |
+
"execution_count": null,
|
| 379 |
+
"outputs": []
|
| 380 |
+
}
|
| 381 |
+
],
|
| 382 |
+
"metadata": {
|
| 383 |
+
"kernelspec": {
|
| 384 |
+
"display_name": "Python 3",
|
| 385 |
+
"name": "python3"
|
| 386 |
+
},
|
| 387 |
+
"language_info": {
|
| 388 |
+
"name": "python"
|
| 389 |
+
}
|
| 390 |
+
},
|
| 391 |
+
"nbformat": 4,
|
| 392 |
+
"nbformat_minor": 0
|
| 393 |
+
}
|