Intro to AI Stage 2 practical exam: 1038 dual-graded students, rubric, solutions (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- submissions_extracted/572/Q1.ipynb +384 -0
- submissions_extracted/572/Q2.ipynb +377 -0
- submissions_extracted/573/Q1.ipynb +464 -0
- submissions_extracted/573/Q2.ipynb +448 -0
- submissions_extracted/574/Q1.ipynb +365 -0
- submissions_extracted/574/Q2.ipynb +440 -0
- submissions_extracted/574/Q3.ipynb +376 -0
- submissions_extracted/575/Q1.ipynb +279 -0
- submissions_extracted/575/Q2.ipynb +362 -0
- submissions_extracted/575/Q3.ipynb +258 -0
- submissions_extracted/576/Q1.ipynb +486 -0
- submissions_extracted/576/Q2.ipynb +394 -0
- submissions_extracted/576/Q3.ipynb +388 -0
- submissions_extracted/577/Q1.ipynb +429 -0
- submissions_extracted/577/Q2.ipynb +404 -0
- submissions_extracted/577/Q3.ipynb +375 -0
- submissions_extracted/578/Q1.ipynb +394 -0
- submissions_extracted/578/Q2.ipynb +464 -0
- submissions_extracted/578/Q3.ipynb +606 -0
- submissions_extracted/579/Q1.ipynb +298 -0
- submissions_extracted/579/Q2.ipynb +361 -0
- submissions_extracted/579/Q3.ipynb +212 -0
- submissions_extracted/58/Q1.ipynb +287 -0
- submissions_extracted/58/Q2.ipynb +374 -0
- submissions_extracted/58/Q3.ipynb +218 -0
- submissions_extracted/580/Q1.ipynb +368 -0
- submissions_extracted/580/Q2.ipynb +418 -0
- submissions_extracted/580/Q3.ipynb +281 -0
- submissions_extracted/581/Q1.ipynb +291 -0
- submissions_extracted/581/Q2.ipynb +246 -0
- submissions_extracted/581/Q3.ipynb +257 -0
- submissions_extracted/582/Q1.ipynb +400 -0
- submissions_extracted/582/Q2.ipynb +367 -0
- submissions_extracted/582/Q3.ipynb +442 -0
- submissions_extracted/583/Q1.ipynb +338 -0
- submissions_extracted/583/Q2.ipynb +657 -0
- submissions_extracted/583/Q3.ipynb +227 -0
- submissions_extracted/584/Q1.ipynb +442 -0
- submissions_extracted/584/Q2.ipynb +420 -0
- submissions_extracted/584/Q3.ipynb +403 -0
- submissions_extracted/585/Q1.ipynb +255 -0
- submissions_extracted/585/Q2.ipynb +381 -0
- submissions_extracted/585/Q3.ipynb +314 -0
- submissions_extracted/586/Q1.ipynb +362 -0
- submissions_extracted/586/Q2.ipynb +406 -0
- submissions_extracted/586/Q3.ipynb +254 -0
- submissions_extracted/587/Q1.ipynb +485 -0
- submissions_extracted/587/Q2.ipynb +387 -0
- submissions_extracted/587/Q3.ipynb +294 -0
- submissions_extracted/588/Q1.ipynb +248 -0
submissions_extracted/572/Q1.ipynb
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
],
|
| 15 |
+
"execution_count": null,
|
| 16 |
+
"outputs": []
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"cell_type": "code",
|
| 20 |
+
"metadata": {},
|
| 21 |
+
"source": [
|
| 22 |
+
"import kagglehub\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"# Download latest version\n",
|
| 25 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)"
|
| 28 |
+
],
|
| 29 |
+
"execution_count": null,
|
| 30 |
+
"outputs": []
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"cell_type": "code",
|
| 34 |
+
"metadata": {},
|
| 35 |
+
"source": [
|
| 36 |
+
"# Task 1: Write your code here:\n",
|
| 37 |
+
"df = pd.read_csv(f'{path}/Q1_data.csv')"
|
| 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.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.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.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 |
+
"def check_target_distribution(df, target_column):\n",
|
| 78 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 81 |
+
" plt.xlabel(target_column)\n",
|
| 82 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 83 |
+
" plt.grid(False)\n",
|
| 84 |
+
"\n",
|
| 85 |
+
" plt.show()\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 1: Write your code here:\n",
|
| 97 |
+
"df.drop('Order_ID', axis=1, inplace=True)\n",
|
| 98 |
+
"df.head()"
|
| 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 |
+
"def check_missing_values(df):\n",
|
| 109 |
+
" missing_values = df.isnull().sum()\n",
|
| 110 |
+
" print(\"Missing Values per Column:\")\n",
|
| 111 |
+
" print(missing_values[missing_values > 0])\n",
|
| 112 |
+
" if missing_values.any():\n",
|
| 113 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 114 |
+
" else:\n",
|
| 115 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"check_missing_values(df)"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"categoricalC = df.select_dtypes(include=['object']).columns\n",
|
| 127 |
+
"numericalC = df.select_dtypes(include=['float', 'int']).columns\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"for col in categoricalC:\n",
|
| 130 |
+
" df[col] = df[col].fillna(df[col].mode()[0])\n",
|
| 131 |
+
"\n",
|
| 132 |
+
"for col in numericalC:\n",
|
| 133 |
+
" df[col] = df[col].fillna(df[col].mean())\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"print('After handling missing values (categorical by mode, numerical by mean)')\n",
|
| 136 |
+
"check_missing_values(df)\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"df.info()"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 3: Write your code here:\n",
|
| 148 |
+
"def check_duplicates(df):\n",
|
| 149 |
+
" duplicates = df.duplicated().sum()\n",
|
| 150 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 151 |
+
" if duplicates > 0:\n",
|
| 152 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 153 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 154 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 155 |
+
" else:\n",
|
| 156 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"check_duplicates(df)\n",
|
| 159 |
+
"df.info()"
|
| 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 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"for col in categoricalC:\n",
|
| 172 |
+
" le = LabelEncoder()\n",
|
| 173 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"df.head()"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task 5: Write your code here:\n",
|
| 185 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"features = df.columns.drop(\"Delivery_Time\")\n",
|
| 188 |
+
"print(features)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"scaler = StandardScaler()\n",
|
| 191 |
+
"df[features] = scaler.fit_transform(df[features])"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"df.head()"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 6: Write your code here:\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# Since we train for regression we won't have classes to look for their balance"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 1: Write your code here: Split the dataset into features (X) and target (y)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"X = df[features]\n",
|
| 226 |
+
"y = df['Delivery_Time']\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"print('Input shape: ', X.shape)\n",
|
| 229 |
+
"print('Target shape: ', y.shape)"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 239 |
+
"from sklearn.model_selection import KFold\n",
|
| 240 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 241 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"\n",
|
| 244 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
"kf= KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 247 |
+
"mae_scores = []\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"for fold, (trainIdx, testIdx) in enumerate(kf.split(X)):\n",
|
| 250 |
+
" xtrain, xtest = X.iloc[trainIdx], X.iloc[testIdx]\n",
|
| 251 |
+
" ytrain, ytest = y.iloc[trainIdx], y.iloc[testIdx]\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" model.fit(xtrain, ytrain)\n",
|
| 255 |
+
" ypred = model.predict(xtest)\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" mae_score = mean_absolute_error(ytest, ypred)\n",
|
| 259 |
+
" mae_scores.append(mae_score)\n",
|
| 260 |
+
" print(f'Fold {fold+1}/5 | MAE score: {mae_score:.4f}')\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"print(f'\\nAverage MAE score across all folds is: {np.mean(mae_scores):.4f} ')\n"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"# Task 1: Write your code here:\n",
|
| 273 |
+
"importance = model.feature_importances_\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"features = X.columns\n",
|
| 276 |
+
"sorted_idx = np.argsort(importance)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"plt.barh(features[sorted_idx], importance[sorted_idx])\n",
|
| 280 |
+
"plt.title(\"Random Forest Regressor Feature Importance\")\n",
|
| 281 |
+
"plt.xlabel(\"Importance Score\")\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"plt.tight_layout()\n",
|
| 284 |
+
"plt.show()"
|
| 285 |
+
],
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"outputs": []
|
| 288 |
+
},
|
| 289 |
+
{
|
| 290 |
+
"cell_type": "code",
|
| 291 |
+
"metadata": {},
|
| 292 |
+
"source": [
|
| 293 |
+
"# Task 2: Write your code here:\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"ypred = pd.DataFrame({\n",
|
| 296 |
+
" \"Delivery_Time\": ypred\n",
|
| 297 |
+
"})\n",
|
| 298 |
+
"\n",
|
| 299 |
+
"ypred.hist()\n",
|
| 300 |
+
"plt.grid(False)\n",
|
| 301 |
+
"plt.show()"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"%pip install catboost"
|
| 311 |
+
],
|
| 312 |
+
"execution_count": null,
|
| 313 |
+
"outputs": []
|
| 314 |
+
},
|
| 315 |
+
{
|
| 316 |
+
"cell_type": "code",
|
| 317 |
+
"metadata": {},
|
| 318 |
+
"source": [
|
| 319 |
+
"# Task Bonus: Write your code here:\n",
|
| 320 |
+
"from catboost import CatBoostRegressor\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"models = {\n",
|
| 323 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1),\n",
|
| 324 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 325 |
+
" }\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"kf= KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 328 |
+
"mae_scores = []\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"for fold, (trainIdx, testIdx) in enumerate(kf.split(X)):\n",
|
| 331 |
+
" xtrain, xtest = X.iloc[trainIdx], X.iloc[testIdx]\n",
|
| 332 |
+
" ytrain, ytest = y.iloc[trainIdx], y.iloc[testIdx]\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" ypreds = []\n",
|
| 335 |
+
" for model_name, model in models.items():\n",
|
| 336 |
+
" print(f\"Training {model_name}...\")\n",
|
| 337 |
+
" model.fit(xtrain, ytrain)\n",
|
| 338 |
+
" ypred = model.predict(xtest)\n",
|
| 339 |
+
" ypreds.append(ypred)\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" ypreds = np.mean(ypreds)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" mae_score = mean_absolute_error(ytest, ypred)\n",
|
| 345 |
+
" mae_scores.append(mae_score)\n",
|
| 346 |
+
" print(f'\\nFold {fold+1}/5 | MAE score (avg both model): {mae_score:.4f}\\n')\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"print('\\n'+ '-'*30)\n",
|
| 349 |
+
"print(f'Average MAE score across all folds is: {np.mean(mae_scores):.4f} ')\n",
|
| 350 |
+
"print('-'*30)\n",
|
| 351 |
+
"\n"
|
| 352 |
+
],
|
| 353 |
+
"execution_count": null,
|
| 354 |
+
"outputs": []
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"cell_type": "code",
|
| 358 |
+
"metadata": {},
|
| 359 |
+
"source": [
|
| 360 |
+
"print('Average MAE between the model is better than having one model')"
|
| 361 |
+
],
|
| 362 |
+
"execution_count": null,
|
| 363 |
+
"outputs": []
|
| 364 |
+
},
|
| 365 |
+
{
|
| 366 |
+
"cell_type": "code",
|
| 367 |
+
"metadata": {},
|
| 368 |
+
"source": [],
|
| 369 |
+
"execution_count": null,
|
| 370 |
+
"outputs": []
|
| 371 |
+
}
|
| 372 |
+
],
|
| 373 |
+
"metadata": {
|
| 374 |
+
"kernelspec": {
|
| 375 |
+
"display_name": "Python 3",
|
| 376 |
+
"name": "python3"
|
| 377 |
+
},
|
| 378 |
+
"language_info": {
|
| 379 |
+
"name": "python"
|
| 380 |
+
}
|
| 381 |
+
},
|
| 382 |
+
"nbformat": 4,
|
| 383 |
+
"nbformat_minor": 0
|
| 384 |
+
}
|
submissions_extracted/572/Q2.ipynb
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"from torch.utils.data import TensorDataset\n",
|
| 71 |
+
"from torch.utils.data import DataLoader\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 74 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 75 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 76 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 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, y_train)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test, y_test)"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 3. Create DataLoaders\n",
|
| 97 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
|
| 98 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=2)"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# 4. Print shape of one batch\n",
|
| 108 |
+
"images, labels = next(iter(train_loader))\n",
|
| 109 |
+
"print(f'Training Batch Input Size: {images.shape}')\n",
|
| 110 |
+
"print(f'Training Batch Labels Size: {labels.shape}')"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# 5. Display sample images\n",
|
| 120 |
+
"import matplotlib.pyplot as plt\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"for i in range(6):\n",
|
| 125 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 126 |
+
"\n",
|
| 127 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 128 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
" plt.imshow(img)\n",
|
| 131 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 132 |
+
" plt.axis('off')\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"plt.tight_layout()\n",
|
| 135 |
+
"plt.show()\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 1: Write your model class here:\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"import torch.nn as nn\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"class NN4Layer(nn.Module):\n",
|
| 150 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 151 |
+
" super().__init__()\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" self.Layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 154 |
+
" self.Layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 155 |
+
" self.Layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 156 |
+
" self.Layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" self.relu = nn.ReLU()\n",
|
| 159 |
+
"\n",
|
| 160 |
+
" def forward(self, x):\n",
|
| 161 |
+
" a1 = self.relu(self.Layer1(x))\n",
|
| 162 |
+
" a2 = self.relu(self.Layer2(a1))\n",
|
| 163 |
+
" a3 = self.relu(self.Layer3(a2))\n",
|
| 164 |
+
" output = self.Layer4(a3)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" return output"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 2: Write your training loop here:\n",
|
| 176 |
+
"from tqdm import tqdm\n",
|
| 177 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 178 |
+
" model.train()\n",
|
| 179 |
+
" tot_loss = 0\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" for xb, yb in train_loader:\n",
|
| 182 |
+
" xb = xb.view(xb.size(0), -1).to(device)\n",
|
| 183 |
+
" yb = yb.view(-1, 1).to(device)\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" output = model(xb)\n",
|
| 186 |
+
" loss = criterion(output, yb)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" optimizer.zero_grad()\n",
|
| 189 |
+
" loss.backward()\n",
|
| 190 |
+
" optimizer.step()\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" tot_loss += loss.item()\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" avg = tot_loss/ len(train_loader)\n",
|
| 195 |
+
" return avg"
|
| 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 |
+
"\n",
|
| 206 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 207 |
+
" model.eval()\n",
|
| 208 |
+
" tot_loss = 0\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" with torch.no_grad():\n",
|
| 211 |
+
" for xb, yb in test_loader:\n",
|
| 212 |
+
" xb = xb.view(xb.size(0), -1).to(device)\n",
|
| 213 |
+
" yb = yb.view(-1, 1).to(device)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" print(xb.size)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" output = model(xb)\n",
|
| 218 |
+
" loss = criterion(output, yb)\n",
|
| 219 |
+
" tot_loss += loss.item()\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" avg = tot_loss/len(test_loader)\n",
|
| 222 |
+
" return avg"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"from torch.optim import AdamW\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"print(f'Input dim (channels, height, width): {images[0].size()}') #(3, 36, 36)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
"inputD = 3 * 36 * 36\n",
|
| 242 |
+
"hiddenD = 128\n",
|
| 243 |
+
"outputD = 1 #regression models ouputs a single number\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"model = NN4Layer(inputD, hiddenD, outputD)\n",
|
| 246 |
+
"model.to(device)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"criterion = nn.MSELoss()\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"optimizer = AdamW(model.parameters(), 1e-3)"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"num_epochs = 20\n",
|
| 263 |
+
"train_losses = []\n",
|
| 264 |
+
"val_losses = []\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"print('Start Training ---')\n",
|
| 267 |
+
"for epoch in range(num_epochs):\n",
|
| 268 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 269 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" train_losses.append(train_loss)\n",
|
| 272 |
+
" val_losses.append(val_loss)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
" print('-'*30)\n",
|
| 275 |
+
" print(f'\\nEpoch {epoch+1}/{num_epochs} || Train loss: {train_loss:4f}, Val Loss: {val_loss:.4f}\\n')\n",
|
| 276 |
+
" print('-'*30)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"print('Training Completed!!')"
|
| 279 |
+
],
|
| 280 |
+
"execution_count": null,
|
| 281 |
+
"outputs": []
|
| 282 |
+
},
|
| 283 |
+
{
|
| 284 |
+
"cell_type": "code",
|
| 285 |
+
"metadata": {},
|
| 286 |
+
"source": [
|
| 287 |
+
"# Task 1: Write your code here:\n",
|
| 288 |
+
"# Plotting results\n",
|
| 289 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 292 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 293 |
+
"plt.title('Loss over Epochs')\n",
|
| 294 |
+
"plt.xlabel('Epoch')\n",
|
| 295 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 296 |
+
"plt.legend()\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"plt.tight_layout()\n",
|
| 299 |
+
"plt.show()"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"cell_type": "code",
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"source": [
|
| 308 |
+
"#The loss plot seem so noisy we need to fix it so it gets smother"
|
| 309 |
+
],
|
| 310 |
+
"execution_count": null,
|
| 311 |
+
"outputs": []
|
| 312 |
+
},
|
| 313 |
+
{
|
| 314 |
+
"cell_type": "code",
|
| 315 |
+
"metadata": {},
|
| 316 |
+
"source": [
|
| 317 |
+
"# @title\n",
|
| 318 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"#something went off\n",
|
| 321 |
+
"'''\n",
|
| 322 |
+
"model.eval()\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"test_images, test_labels = next(iter(test_loader))\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"#\n",
|
| 327 |
+
"with torch.no_grad():\n",
|
| 328 |
+
" predictLabel = model(test_images.view(test_images.size(0), -1).to(device))\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"# Move to CPU for plotting\n",
|
| 331 |
+
"test_images = test_images.cpu()\n",
|
| 332 |
+
"predictLabel = predictLabel.cpu()\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# Plot original vs reconstructed\n",
|
| 335 |
+
"n_images = 9\n",
|
| 336 |
+
"fig, axes = plt.subplots(2, n_images, figsize=(18, 6))\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"for i in range(n_images):\n",
|
| 339 |
+
" # Original\n",
|
| 340 |
+
" axes[0, i].imshow(test_images[i], cmap='gray')\n",
|
| 341 |
+
" axes[0, i].axis('off')\n",
|
| 342 |
+
" axes[0, i].set_title(f'Original - \"{test_labels[i]}\"', fontsize=12)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" # Reconstructed\n",
|
| 345 |
+
" axes[1, i].imshow(predictLabel[i].squeeze(), cmap='gray')\n",
|
| 346 |
+
" axes[1, i].axis('off')\n",
|
| 347 |
+
" axes[1, i].set_title(f'Reconstructed - \"{test_labels[i]}\"', fontsize=12)\n",
|
| 348 |
+
"\n",
|
| 349 |
+
"plt.suptitle('Original vs Reconstructed Images', fontsize=14)\n",
|
| 350 |
+
"plt.tight_layout()\n",
|
| 351 |
+
"plt.show()\n",
|
| 352 |
+
"'''\n",
|
| 353 |
+
"print()"
|
| 354 |
+
],
|
| 355 |
+
"execution_count": null,
|
| 356 |
+
"outputs": []
|
| 357 |
+
},
|
| 358 |
+
{
|
| 359 |
+
"cell_type": "code",
|
| 360 |
+
"metadata": {},
|
| 361 |
+
"source": [],
|
| 362 |
+
"execution_count": null,
|
| 363 |
+
"outputs": []
|
| 364 |
+
}
|
| 365 |
+
],
|
| 366 |
+
"metadata": {
|
| 367 |
+
"kernelspec": {
|
| 368 |
+
"display_name": "Python 3",
|
| 369 |
+
"name": "python3"
|
| 370 |
+
},
|
| 371 |
+
"language_info": {
|
| 372 |
+
"name": "python"
|
| 373 |
+
}
|
| 374 |
+
},
|
| 375 |
+
"nbformat": 4,
|
| 376 |
+
"nbformat_minor": 0
|
| 377 |
+
}
|
submissions_extracted/573/Q1.ipynb
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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"
|
| 11 |
+
],
|
| 12 |
+
"execution_count": null,
|
| 13 |
+
"outputs": []
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"source": [
|
| 19 |
+
"import kagglehub\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 |
+
"# TODO: Load the CSV file into df\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"df_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 37 |
+
"df = pd.read_csv(df_path)\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"print(f\"Shape: {df.shape}\")"
|
| 40 |
+
],
|
| 41 |
+
"execution_count": null,
|
| 42 |
+
"outputs": []
|
| 43 |
+
},
|
| 44 |
+
{
|
| 45 |
+
"cell_type": "code",
|
| 46 |
+
"metadata": {},
|
| 47 |
+
"source": [
|
| 48 |
+
"# Task 2: Write your code here:\n",
|
| 49 |
+
"#Inspect the first few rows using head()\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 |
+
"#Display dataset information using info()\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 |
+
"#Show statistical description using describe()\n",
|
| 72 |
+
"df.describe()"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 5: Write your code here:\n",
|
| 82 |
+
"#Plot the target distribution (delivery_time)\n",
|
| 83 |
+
"print(\"\\nValue counts for the target variable 'class':\")\n",
|
| 84 |
+
"class_distribution = df['Delivery_Time'].value_counts()\n",
|
| 85 |
+
"print(class_distribution)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"# Delivery Time distribution (target variable)\n",
|
| 88 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 89 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 90 |
+
"plt.title('Delivery Time')\n",
|
| 91 |
+
"plt.xlabel('Delivery Time')\n",
|
| 92 |
+
"plt.ylabel('Frequency')\n",
|
| 93 |
+
"plt.show()"
|
| 94 |
+
],
|
| 95 |
+
"execution_count": null,
|
| 96 |
+
"outputs": []
|
| 97 |
+
},
|
| 98 |
+
{
|
| 99 |
+
"cell_type": "code",
|
| 100 |
+
"metadata": {},
|
| 101 |
+
"source": [
|
| 102 |
+
"df_clean = df.copy() #ALWAYS COPY"
|
| 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 |
+
"#Drop the 'Order_ID' column from the data\n",
|
| 113 |
+
"df_clean=df_clean.drop(columns=['Order_ID'])"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"df_clean.info()"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"# Task 2: Write your code here:\n",
|
| 132 |
+
"#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :)\n",
|
| 133 |
+
"df_clean = df_clean.dropna(subset=['Delivery_Time']) #target cannot be empty\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 136 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 137 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"# Fill Courier_Experience_yrs with mode - discrete feature, mode is most representative\n",
|
| 140 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mean())\n",
|
| 141 |
+
"\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"# Task 3: Write your code here:\n",
|
| 151 |
+
"#Check and remove duplicates if any exist\n",
|
| 152 |
+
"# 4. Do we have duplicate samples?\n",
|
| 153 |
+
"def check_duplicates(df):\n",
|
| 154 |
+
" duplicates = df_clean.duplicated().sum()\n",
|
| 155 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 156 |
+
" if duplicates > 0:\n",
|
| 157 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 158 |
+
" df_clean.drop_duplicates(inplace=True) #edit on og df\n",
|
| 159 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 160 |
+
" else:\n",
|
| 161 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"check_duplicates(df_clean)"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# 3. Do we have categorical columns?\n",
|
| 173 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"label_encoders = {} #Creates an empty dictionary\n",
|
| 187 |
+
"for col in categorical_cols:\n",
|
| 188 |
+
" le = LabelEncoder()\n",
|
| 189 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 190 |
+
" label_encoders[col] = le #This line stores the fitted LabelEncoder for each categorical column\n",
|
| 191 |
+
" #so the same encoding can be reused on new data or reversed later.\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"df_clean"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 203 |
+
"# Task 5: Write your code here:\n",
|
| 204 |
+
"#Apply feature scaling for all features (Use StandardScaler)\n",
|
| 205 |
+
"#selecting numerical columns\n",
|
| 206 |
+
"# [\"int64\", \"float64\"] == [\"number\"]\n",
|
| 207 |
+
"#numerical_cols = df_clean.select_dtypes(include=[\"number\"],exclude=[\"object\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"#scaler = StandardScaler()\n",
|
| 210 |
+
"#df_clean[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 211 |
+
"#df_clean.head()\n"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"import seaborn as sns\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"# Task 6: Write your code here:\n",
|
| 223 |
+
"#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 224 |
+
"# 1. Is the target imbalanced?\n",
|
| 225 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 226 |
+
" print(\"Target Distribution:\")\n",
|
| 227 |
+
" print(df[target_column].value_counts(normalize=True)) #each value ÷ total number of rows (between 0 and 1 )\n",
|
| 228 |
+
" #(normalize=False) will show true numbers\n",
|
| 229 |
+
" sns.countplot(x=df[target_column])\n",
|
| 230 |
+
" plt.title(\"Target Distribution\")\n",
|
| 231 |
+
" plt.show()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"check_target_imbalance(df_clean, \"Delivery_Time\")"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 1: Write your code here:\n",
|
| 243 |
+
"#Split the dataset into features (X) and target (y)\n",
|
| 244 |
+
"# we use .astype(float) because some models expect ONLY float and not integers\n",
|
| 245 |
+
"X = df.drop(\"Delivery_Time\", axis=1)\n",
|
| 246 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"import pandas as pd\n",
|
| 256 |
+
"import numpy as np\n",
|
| 257 |
+
"import matplotlib.pyplot as plt\n",
|
| 258 |
+
"import seaborn as sns\n",
|
| 259 |
+
"import kagglehub\n",
|
| 260 |
+
"import os\n",
|
| 261 |
+
"from tqdm import tqdm\n",
|
| 262 |
+
"# sigmoid in NumPy\n",
|
| 263 |
+
"def sigmoid(z):\n",
|
| 264 |
+
" return 1 / (1 + np.exp(-z))\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 267 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 268 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 269 |
+
" losses = []\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
|
| 272 |
+
" z = np.dot(X, theta)\n",
|
| 273 |
+
" y_hat = sigmoid(z)\n",
|
| 274 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 275 |
+
" theta -= learning_rate * gradient\n",
|
| 276 |
+
"\n",
|
| 277 |
+
" loss = binary_cross_entropy(y, y_hat)\n",
|
| 278 |
+
" losses.append(loss)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" return theta, losses\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"%matplotlib inline\n",
|
| 283 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 284 |
+
"#Use the correct split: KFold OR StratifiedKFold\n",
|
| 285 |
+
"#Train a RandomForest model\n",
|
| 286 |
+
"#Evaluate using MAE (Mean Absolute Error) ONLY\n",
|
| 287 |
+
"#Print the averaged score across all folds\n",
|
| 288 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 289 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 294 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Storage for logistic regression results for each fold\n",
|
| 297 |
+
"lr_losses = []\n",
|
| 298 |
+
"lr_accuracy = []\n",
|
| 299 |
+
"lr_precision = []\n",
|
| 300 |
+
"lr_recall = []\n",
|
| 301 |
+
"lr_f1 = []\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 304 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 305 |
+
"\n",
|
| 306 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 307 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" # Train\n",
|
| 310 |
+
" theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" # Validate\n",
|
| 313 |
+
" y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
|
| 314 |
+
" y_pred = (y_pred_proba >= 0.5).astype(int) #if we increse 0.5 to 0.8\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" # Calculate evaluation metrics\n",
|
| 317 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 318 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 319 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 320 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" # Store results\n",
|
| 323 |
+
" lr_losses.append(losses)\n",
|
| 324 |
+
" lr_accuracy.append(accuracy)\n",
|
| 325 |
+
" lr_precision.append(precision)\n",
|
| 326 |
+
" lr_recall.append(recall)\n",
|
| 327 |
+
" lr_f1.append(f1)\n",
|
| 328 |
+
"\n",
|
| 329 |
+
" # Calculate average loss across folds\n",
|
| 330 |
+
"avg_loss = np.mean(lr_losses, axis=0)\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 333 |
+
"plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
|
| 334 |
+
"plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
|
| 335 |
+
"plt.xlabel('Iteration')\n",
|
| 336 |
+
"plt.ylabel('Binary Cross-Entropy Loss')\n",
|
| 337 |
+
"plt.legend()\n",
|
| 338 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 339 |
+
"plt.show()\n",
|
| 340 |
+
"# Calculate average loss across folds\n",
|
| 341 |
+
"avg_loss = np.mean(lr_losses, axis=0)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 344 |
+
"plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
|
| 345 |
+
"plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
|
| 346 |
+
"plt.xlabel('Iteration')\n",
|
| 347 |
+
"plt.ylabel('Binary Cross-Entropy Loss')\n",
|
| 348 |
+
"plt.legend()\n",
|
| 349 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 350 |
+
"plt.show()"
|
| 351 |
+
],
|
| 352 |
+
"execution_count": null,
|
| 353 |
+
"outputs": []
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"cell_type": "code",
|
| 357 |
+
"metadata": {},
|
| 358 |
+
"source": [
|
| 359 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 360 |
+
"sklearn_models = {\n",
|
| 361 |
+
"\n",
|
| 362 |
+
" \"Random Forest\": RandomForestClassifier(\n",
|
| 363 |
+
" n_estimators=320, # Number of trees\n",
|
| 364 |
+
" max_depth=4\n",
|
| 365 |
+
" )\n",
|
| 366 |
+
"}\n",
|
| 367 |
+
"all_results = {}\n",
|
| 368 |
+
"\n",
|
| 369 |
+
"for name in sklearn_models:\n",
|
| 370 |
+
" all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"n_splits = 5 # K\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 376 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 380 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 381 |
+
"\n",
|
| 382 |
+
" # 1. Split data\n",
|
| 383 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 384 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 385 |
+
"\n",
|
| 386 |
+
" # 2. Train & Validate sklearn models\n",
|
| 387 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 388 |
+
" print(f\"Training {model_name}...\")\n",
|
| 389 |
+
" model.fit(X_train, y_train) # train\n",
|
| 390 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 391 |
+
"\n",
|
| 392 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 393 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 394 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 395 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 396 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 397 |
+
"\n",
|
| 398 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 399 |
+
" all_results[model_name]['precision'].append(precision)\n",
|
| 400 |
+
" all_results[model_name]['recall'].append(recall)\n",
|
| 401 |
+
" all_results[model_name]['f1'].append(f1)\n",
|
| 402 |
+
"\n",
|
| 403 |
+
" for model_name in all_results:\n",
|
| 404 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 405 |
+
" print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
|
| 406 |
+
" print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n",
|
| 407 |
+
" print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n",
|
| 408 |
+
" print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
|
| 409 |
+
],
|
| 410 |
+
"execution_count": null,
|
| 411 |
+
"outputs": []
|
| 412 |
+
},
|
| 413 |
+
{
|
| 414 |
+
"cell_type": "code",
|
| 415 |
+
"metadata": {},
|
| 416 |
+
"source": [
|
| 417 |
+
"# Task 1: Write your code here:\n",
|
| 418 |
+
"# Feature importance\n",
|
| 419 |
+
"feature_importance = pd.DataFrame({\n",
|
| 420 |
+
" 'feature': feature_cols,\n",
|
| 421 |
+
" 'importance': model.feature_importances_\n",
|
| 422 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 425 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 426 |
+
"plt.xlabel('Importance')\n",
|
| 427 |
+
"plt.title('Feature Importance')\n",
|
| 428 |
+
"plt.gca().invert_yaxis()\n",
|
| 429 |
+
"plt.show()"
|
| 430 |
+
],
|
| 431 |
+
"execution_count": null,
|
| 432 |
+
"outputs": []
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"cell_type": "code",
|
| 436 |
+
"metadata": {},
|
| 437 |
+
"source": [
|
| 438 |
+
"# Task 2: Write your code here:"
|
| 439 |
+
],
|
| 440 |
+
"execution_count": null,
|
| 441 |
+
"outputs": []
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"cell_type": "code",
|
| 445 |
+
"metadata": {},
|
| 446 |
+
"source": [
|
| 447 |
+
"# Task Bonus: Write your code here:"
|
| 448 |
+
],
|
| 449 |
+
"execution_count": null,
|
| 450 |
+
"outputs": []
|
| 451 |
+
}
|
| 452 |
+
],
|
| 453 |
+
"metadata": {
|
| 454 |
+
"kernelspec": {
|
| 455 |
+
"display_name": "Python 3",
|
| 456 |
+
"name": "python3"
|
| 457 |
+
},
|
| 458 |
+
"language_info": {
|
| 459 |
+
"name": "python"
|
| 460 |
+
}
|
| 461 |
+
},
|
| 462 |
+
"nbformat": 4,
|
| 463 |
+
"nbformat_minor": 0
|
| 464 |
+
}
|
submissions_extracted/573/Q2.ipynb
ADDED
|
@@ -0,0 +1,448 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
"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 |
+
"\n",
|
| 70 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 71 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 72 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 73 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 74 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"from torch.utils.data import TensorDataset\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"# 2. Create TensorDataset objects\n",
|
| 86 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 88 |
+
"\n"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"from torch.utils.data import DataLoader\n",
|
| 98 |
+
"\n",
|
| 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 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# 4. Print shape of one batch\n",
|
| 112 |
+
"# Get the first batch from the training DataLoader\n",
|
| 113 |
+
"X_batch, y_batch = next(iter(train_loader)) # next-> first batch iter-> make train_batch iterable\n",
|
| 114 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 115 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"import matplotlib.pyplot as plt\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"# 5. Display sample images\n",
|
| 127 |
+
"# Get one batch of images and labels\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 |
+
"import torch.nn as nn\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"# Task 1: Write your model class here:\n",
|
| 156 |
+
"class NN4Layer(nn.Module):\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 159 |
+
" super(NN4Layer, self).__init__()\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 162 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 165 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 168 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 171 |
+
" self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # activation function for non-linearity\n",
|
| 174 |
+
" self.relu = nn.ReLU()\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Defines how input data flows through the network\n",
|
| 177 |
+
" def forward(self, x):\n",
|
| 178 |
+
" # Layer 1: TODO\n",
|
| 179 |
+
" z1 = self.layer1(x)\n",
|
| 180 |
+
" a1 = self.relu(z1)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # Layer 2 TODO\n",
|
| 183 |
+
" z2 = self.layer2(a1)\n",
|
| 184 |
+
" a2 = self.relu(z2)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Layer 3 TODO\n",
|
| 187 |
+
" z3 = self.layer3(a2)\n",
|
| 188 |
+
" a3 = self.relu(z3)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Output layer TODO\n",
|
| 191 |
+
" z4 = self.layer4(a3)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" return z4"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 2: Write your training loop here:\n",
|
| 205 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 206 |
+
" # Set the model to training mode\n",
|
| 207 |
+
" model.train()\n",
|
| 208 |
+
"\n",
|
| 209 |
+
" running_loss = 0.0\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 212 |
+
" # Move batch to the selected device\n",
|
| 213 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 214 |
+
" y_batch = y_batch.to(device)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Forward pass\n",
|
| 217 |
+
" # TODO: make predictions\n",
|
| 218 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 219 |
+
" # TODO: compute loss\n",
|
| 220 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Backward pass & optimization\n",
|
| 223 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 224 |
+
" loss.backward() # Compute gradients\n",
|
| 225 |
+
" optimizer.step() # Update model parameters\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" running_loss += loss.item()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Average loss over all batches\n",
|
| 230 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" return avg_loss"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task 3: Write your validation loop here:\n",
|
| 242 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 243 |
+
" # Set the model to evaluation mode\n",
|
| 244 |
+
" model.eval()\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" running_loss = 0.0\n",
|
| 247 |
+
" correct = 0\n",
|
| 248 |
+
" total = 0\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" with torch.no_grad():\n",
|
| 251 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 252 |
+
" # Move data to device\n",
|
| 253 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 254 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" # Forward pass\n",
|
| 257 |
+
" # TODO: make predictions\n",
|
| 258 |
+
" outputs = model(X_batch)\n",
|
| 259 |
+
" # TODO: compute loss\n",
|
| 260 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 261 |
+
" running_loss += loss.item()\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Average loss over all batches\n",
|
| 264 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" return avg_loss"
|
| 267 |
+
],
|
| 268 |
+
"execution_count": null,
|
| 269 |
+
"outputs": []
|
| 270 |
+
},
|
| 271 |
+
{
|
| 272 |
+
"cell_type": "code",
|
| 273 |
+
"metadata": {},
|
| 274 |
+
"source": [
|
| 275 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 276 |
+
"# Device setup\n",
|
| 277 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"# Model parameters\n",
|
| 280 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 281 |
+
"input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"# TODO: choose number of hidden neurons\n",
|
| 284 |
+
"hidden_dim = 32 # Design choice\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"# TODO: what are the number of classes ?\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 289 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# TODO: Print the model architecture\n",
|
| 292 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 293 |
+
"print(model)\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"# Calculate the total number of trainable parameters\n",
|
| 296 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 297 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n"
|
| 298 |
+
],
|
| 299 |
+
"execution_count": null,
|
| 300 |
+
"outputs": []
|
| 301 |
+
},
|
| 302 |
+
{
|
| 303 |
+
"cell_type": "code",
|
| 304 |
+
"metadata": {},
|
| 305 |
+
"source": [
|
| 306 |
+
"from torch.optim import AdamW\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 309 |
+
"# Hyperparameters (feel free to experiment!)\n",
|
| 310 |
+
"num_epochs = 20\n",
|
| 311 |
+
"learning_rate = 0.001\n",
|
| 312 |
+
"# Define criterion (loss function)\n",
|
| 313 |
+
"criterion = nn.MSELoss()\n",
|
| 314 |
+
"# Define optimizer\n",
|
| 315 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Run Training\n",
|
| 325 |
+
"train_losses = []\n",
|
| 326 |
+
"val_losses = []\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"print('Starting Training...')\n",
|
| 329 |
+
"for epoch in range(num_epochs):\n",
|
| 330 |
+
" # Train one epoch\n",
|
| 331 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" # Validate\n",
|
| 334 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 335 |
+
"\n",
|
| 336 |
+
" train_losses.append(train_loss)\n",
|
| 337 |
+
" val_losses.append(val_loss)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 340 |
+
" print(\n",
|
| 341 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 342 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 343 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 344 |
+
" )\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 (MSE)')\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 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"# Get predictions on test set\n",
|
| 379 |
+
"model.eval()\n",
|
| 380 |
+
"with torch.no_grad():\n",
|
| 381 |
+
" # TODO: Get predictions for X_test\n",
|
| 382 |
+
" # [HINT]: Move X_test to device, pass through model, then move back to CPU\n",
|
| 383 |
+
" predictions = model(X_test.to(device)).cpu().numpy()\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"# TODO: Calculate evaluation metrics\n",
|
| 386 |
+
"# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n",
|
| 387 |
+
"mae = mean_absolute_error(y_test.numpy(), predictions)\n",
|
| 388 |
+
"mse = mean_squared_error(y_test.numpy(), predictions)\n",
|
| 389 |
+
"rmse = np.sqrt(mse)\n",
|
| 390 |
+
"r2 = r2_score(y_test.numpy(), predictions)\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"print(\"Model Evaluation\")\n",
|
| 393 |
+
"print(f\" MAE: ${mae:.2f}\")\n",
|
| 394 |
+
"print(f\" MSE: {mse:.2f}\")\n",
|
| 395 |
+
"print(f\" RMSE: ${rmse:.2f}\")\n",
|
| 396 |
+
"print(f\" R2: {r2:.4f}\")"
|
| 397 |
+
],
|
| 398 |
+
"execution_count": null,
|
| 399 |
+
"outputs": []
|
| 400 |
+
},
|
| 401 |
+
{
|
| 402 |
+
"cell_type": "code",
|
| 403 |
+
"metadata": {},
|
| 404 |
+
"source": [
|
| 405 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 406 |
+
"# Scatter plot: Predicted vs Actual\n",
|
| 407 |
+
"plt.figure(figsize=(8, 6))\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"# Plot: Predicted vs Actual scatter\n",
|
| 410 |
+
"plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n",
|
| 411 |
+
"\n",
|
| 412 |
+
"# Add perfect prediction line\n",
|
| 413 |
+
"min_val = min(y_test.min(), predictions.min())\n",
|
| 414 |
+
"max_val = max(y_test.max(), predictions.max())\n",
|
| 415 |
+
"plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n",
|
| 416 |
+
"\n",
|
| 417 |
+
"plt.xlabel('Actual', fontsize=12)\n",
|
| 418 |
+
"plt.ylabel('Predicted', fontsize=12)\n",
|
| 419 |
+
"plt.title('Predicted vs Actual Prediction', fontsize=14)\n",
|
| 420 |
+
"plt.legend()\n",
|
| 421 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"plt.tight_layout()\n",
|
| 424 |
+
"plt.show()"
|
| 425 |
+
],
|
| 426 |
+
"execution_count": null,
|
| 427 |
+
"outputs": []
|
| 428 |
+
},
|
| 429 |
+
{
|
| 430 |
+
"cell_type": "code",
|
| 431 |
+
"metadata": {},
|
| 432 |
+
"source": [],
|
| 433 |
+
"execution_count": null,
|
| 434 |
+
"outputs": []
|
| 435 |
+
}
|
| 436 |
+
],
|
| 437 |
+
"metadata": {
|
| 438 |
+
"kernelspec": {
|
| 439 |
+
"display_name": "Python 3",
|
| 440 |
+
"name": "python3"
|
| 441 |
+
},
|
| 442 |
+
"language_info": {
|
| 443 |
+
"name": "python"
|
| 444 |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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 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 13 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 14 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 15 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 16 |
+
"import warnings\n",
|
| 17 |
+
"warnings.filterwarnings('ignore')\n",
|
| 18 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 19 |
+
"from sklearn.svm import SVR\n",
|
| 20 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 21 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 22 |
+
"from lightgbm import LGBMRegressor"
|
| 23 |
+
],
|
| 24 |
+
"execution_count": null,
|
| 25 |
+
"outputs": []
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"cell_type": "code",
|
| 29 |
+
"metadata": {},
|
| 30 |
+
"source": [
|
| 31 |
+
"import kagglehub\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"# Download latest version\n",
|
| 34 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"print(\"Path to dataset files:\", 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 |
+
"df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')\n",
|
| 47 |
+
"df"
|
| 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 5: Write your code here:\n",
|
| 87 |
+
"def check_target_distribution(df, target_column):\n",
|
| 88 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 89 |
+
"\n",
|
| 90 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 91 |
+
" plt.xlabel(target_column)\n",
|
| 92 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 93 |
+
" plt.grid(False)\n",
|
| 94 |
+
"\n",
|
| 95 |
+
" plt.show()\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 1: Write your code here:\n",
|
| 107 |
+
"df.drop('Order_ID',axis=1,inplace=True)\n"
|
| 108 |
+
],
|
| 109 |
+
"execution_count": null,
|
| 110 |
+
"outputs": []
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"cell_type": "code",
|
| 114 |
+
"metadata": {},
|
| 115 |
+
"source": [
|
| 116 |
+
"df"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 2: Write your code here:\n",
|
| 126 |
+
"df.isnull().sum()"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
|
| 136 |
+
"df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
|
| 137 |
+
"df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n",
|
| 140 |
+
"df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
|
| 141 |
+
"\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"df.isnull().sum().sum()"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 3: Write your code here:\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 |
+
"check_duplicates(df)"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"df"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"#from sklearn.preprocessing import OneHotEncoder\n",
|
| 189 |
+
"#categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 190 |
+
"#for col in categorical_cols:\n",
|
| 191 |
+
" # ohe = OneHotEncoder(sparse_output=False,handle_unknown='ignore')\n",
|
| 192 |
+
" # encoded = ohe.fit_transform(df[[col]])\n",
|
| 193 |
+
" # encoded_df = pd.DataFrame(encoded, columns=ohe.get_feature_names_out([col]))\n",
|
| 194 |
+
" #df = pd.concat([df, encoded_df], axis=1)\n",
|
| 195 |
+
" #df.drop(col,axis=1,inplace=True)"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"\n",
|
| 205 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 206 |
+
"for col in categorical_cols:\n",
|
| 207 |
+
" le = LabelEncoder()\n",
|
| 208 |
+
" df[col] = le.fit_transform(df[col].astype(str))\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"label_encoder = LabelEncoder()\n",
|
| 211 |
+
"for col in df.select_dtypes(include=[\"object\"]).columns:\n",
|
| 212 |
+
" df[col] = label_encoder.fit_transform(df[col])\n",
|
| 213 |
+
"df.head()"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"df.isnull().sum()"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"# Task 5: Write your code here:\n",
|
| 232 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"scaler = StandardScaler()\n",
|
| 237 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 238 |
+
"df.head()"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 6: Write your code here:\n",
|
| 248 |
+
"import seaborn as sns\n",
|
| 249 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 250 |
+
" print(\"Target Distribution:\")\n",
|
| 251 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 252 |
+
" sns.countplot(x=df[target_column])\n",
|
| 253 |
+
" plt.title(\"Target Distribution\")\n",
|
| 254 |
+
" plt.show()\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"### We Dont Cheack Target Imbalance sine the target is continues varibale \"but i added the method in case\"\n"
|
| 258 |
+
],
|
| 259 |
+
"execution_count": null,
|
| 260 |
+
"outputs": []
|
| 261 |
+
},
|
| 262 |
+
{
|
| 263 |
+
"cell_type": "code",
|
| 264 |
+
"metadata": {},
|
| 265 |
+
"source": [
|
| 266 |
+
"# Task 1: Write your code here:\n",
|
| 267 |
+
"X= df.drop('Delivery_Time',axis=1)\n",
|
| 268 |
+
"y = df['Delivery_Time']"
|
| 269 |
+
],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 278 |
+
"avg= []\n",
|
| 279 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 280 |
+
"rf=RandomForestRegressor(n_estimators=200)\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 286 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
" # Train\n",
|
| 290 |
+
" rf.fit(X_train, y_train)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # Predict\n",
|
| 293 |
+
" y_pred = rf.predict(X_test)\n",
|
| 294 |
+
"\n",
|
| 295 |
+
" # Calculate metrics\n",
|
| 296 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" # Store results\n",
|
| 300 |
+
" avg.append(mae)\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"print(sum(avg))\n",
|
| 304 |
+
""
|
| 305 |
+
],
|
| 306 |
+
"execution_count": null,
|
| 307 |
+
"outputs": []
|
| 308 |
+
},
|
| 309 |
+
{
|
| 310 |
+
"cell_type": "code",
|
| 311 |
+
"metadata": {},
|
| 312 |
+
"source": [
|
| 313 |
+
"# Task 1: Write your code here:\n",
|
| 314 |
+
"importance = pd.DataFrame({\n",
|
| 315 |
+
" 'feature': X.columns,\n",
|
| 316 |
+
" 'importance': rf.feature_importances_\n",
|
| 317 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 320 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 321 |
+
"plt.xlabel('Importance')\n",
|
| 322 |
+
"plt.title('Feature Importance')\n",
|
| 323 |
+
"plt.gca().invert_yaxis()\n",
|
| 324 |
+
"plt.show()"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"cell_type": "code",
|
| 331 |
+
"metadata": {},
|
| 332 |
+
"source": [
|
| 333 |
+
"# Task 2: Write your code here:\n",
|
| 334 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 335 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 336 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 337 |
+
"plt.xlabel('Delivery Time')\n",
|
| 338 |
+
"plt.ylabel('Frequency')\n",
|
| 339 |
+
"plt.show()"
|
| 340 |
+
],
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"outputs": []
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"cell_type": "code",
|
| 346 |
+
"metadata": {},
|
| 347 |
+
"source": [
|
| 348 |
+
"# Task Bonus: Write your code here:"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
}
|
| 353 |
+
],
|
| 354 |
+
"metadata": {
|
| 355 |
+
"kernelspec": {
|
| 356 |
+
"display_name": "Python 3",
|
| 357 |
+
"name": "python3"
|
| 358 |
+
},
|
| 359 |
+
"language_info": {
|
| 360 |
+
"name": "python"
|
| 361 |
+
}
|
| 362 |
+
},
|
| 363 |
+
"nbformat": 4,
|
| 364 |
+
"nbformat_minor": 0
|
| 365 |
+
}
|
submissions_extracted/574/Q2.ipynb
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import torch\n",
|
| 8 |
+
"import torch.nn as nn\n",
|
| 9 |
+
"from torch.optim import Adam\n",
|
| 10 |
+
"import matplotlib.pyplot as plt\n",
|
| 11 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 12 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 13 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 14 |
+
"from torch.utils.data import TensorDataset\n",
|
| 15 |
+
"from torch.utils.data import DataLoader\n",
|
| 16 |
+
"import kagglehub\n",
|
| 17 |
+
"import pandas as pd\n",
|
| 18 |
+
"import torch\n",
|
| 19 |
+
"import torch.nn as nn\n",
|
| 20 |
+
"from torch.optim import AdamW\n",
|
| 21 |
+
"import matplotlib.pyplot as plt\n",
|
| 22 |
+
"import torch.nn.functional as F\n",
|
| 23 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 24 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 25 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\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"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"import kagglehub\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"# Download latest version\n",
|
| 45 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"print(\"Path to dataset files:\", path)"
|
| 48 |
+
],
|
| 49 |
+
"execution_count": null,
|
| 50 |
+
"outputs": []
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"cell_type": "code",
|
| 54 |
+
"metadata": {},
|
| 55 |
+
"source": [
|
| 56 |
+
"import os\n",
|
| 57 |
+
"import pandas as pd\n",
|
| 58 |
+
"import numpy as np\n",
|
| 59 |
+
"from PIL import Image\n",
|
| 60 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Load Labels\n",
|
| 63 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 64 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"images = []\n",
|
| 67 |
+
"ages = []\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"# Load Images and Resize\n",
|
| 70 |
+
"print(\"Loading images...\")\n",
|
| 71 |
+
"for index, row in labels_df.iterrows():\n",
|
| 72 |
+
" img_name = row.iloc[0]\n",
|
| 73 |
+
" age = row.iloc[1]\n",
|
| 74 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 75 |
+
"\n",
|
| 76 |
+
" if os.path.exists(img_path):\n",
|
| 77 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 78 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 79 |
+
" images.append(img_array)\n",
|
| 80 |
+
" ages.append(age)\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"X = np.array(images)\n",
|
| 83 |
+
"y = np.array(ages)\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 86 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"# Split Data\n",
|
| 89 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 92 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 93 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 94 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 104 |
+
"\n",
|
| 105 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32) # <Replace None with your code>\n",
|
| 106 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32) # <Replace None with your code>\n",
|
| 107 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32) # <Replace None with your code>\n",
|
| 108 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32) # <Replace None with your code>\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# 2. Create TensorDataset objects\n",
|
| 118 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 119 |
+
"test_dataset = TensorDataset(X_test, y_test) # <Replace None with your code>\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"\n"
|
| 124 |
+
],
|
| 125 |
+
"execution_count": null,
|
| 126 |
+
"outputs": []
|
| 127 |
+
},
|
| 128 |
+
{
|
| 129 |
+
"cell_type": "code",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"# 3. Create DataLoaders\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # <Replace None with your code>\n",
|
| 135 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False) # <Replace None with your code>\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# 4. Print shape of one batch\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"# Print dataset sizes\n",
|
| 147 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 148 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 149 |
+
"\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 |
+
],
|
| 155 |
+
"execution_count": null,
|
| 156 |
+
"outputs": []
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"cell_type": "code",
|
| 160 |
+
"metadata": {},
|
| 161 |
+
"source": [
|
| 162 |
+
"# 5. Display sample images\n",
|
| 163 |
+
"images, labels = next(iter(train_loader))\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"# Display the first 6 images in the batch\n",
|
| 166 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"for i in range(6):\n",
|
| 169 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 172 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" plt.imshow(img)\n",
|
| 175 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 176 |
+
" plt.axis('off')\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"plt.tight_layout()\n",
|
| 179 |
+
"plt.show()\n"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"# Task 1: Write your model class here:\n",
|
| 189 |
+
"class NN4Layer(nn.Module):\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" def __init__(self, input_dim,hidden_dim):\n",
|
| 192 |
+
" super(NN4Layer, self).__init__()\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 195 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 198 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 206 |
+
" # ReLU activation for non-linearity\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" self.relu = nn.ReLU()\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Defines how input data flows through the network\n",
|
| 211 |
+
" def forward(self, x):\n",
|
| 212 |
+
" # First hidden layer\n",
|
| 213 |
+
" z1 = self.layer1(x)\n",
|
| 214 |
+
" a1 = self.relu(z1)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Second hidden layer\n",
|
| 217 |
+
" z2 = self.layer2(a1)\n",
|
| 218 |
+
" a2 = self.relu(z2)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" z3 = self.layer3(a2)\n",
|
| 221 |
+
" a3 = self.relu(z3)\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" # Output layer (raw scores / logits)\n",
|
| 225 |
+
" output = self.layer4(a3)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" return output"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 237 |
+
" # TODO: Set the model to training mode\n",
|
| 238 |
+
" # <YOUR CODE HERE>\n",
|
| 239 |
+
" model.train()\n",
|
| 240 |
+
" running_loss = 0.0\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 243 |
+
" # TODO: Move batch to the selected device\n",
|
| 244 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # <Replace None with your code>\n",
|
| 245 |
+
" y_batch = y_batch.reshape(-1,1).to(device) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 246 |
+
"\n",
|
| 247 |
+
" outputs = model(X_batch) # <Replace None with your code>\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # TODO: Compute loss using criterion\n",
|
| 250 |
+
" loss = criterion(outputs,y_batch) # <Replace None with your code>\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # TODO: Backward pass & optimization\n",
|
| 253 |
+
" # Step 1: Clear previous gradients\n",
|
| 254 |
+
" # <YOUR CODE HERE>\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" # Step 2: Compute gradients (backward pass)\n",
|
| 257 |
+
" # <YOUR CODE HERE>\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # Step 3: Update model parameters\n",
|
| 260 |
+
" # <YOUR CODE HERE>\n",
|
| 261 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 262 |
+
" loss.backward() # Compute gradients\n",
|
| 263 |
+
" optimizer.step()\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" running_loss += loss.item()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Calculate 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 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 280 |
+
" # TODO: Set the model to evaluation mode\n",
|
| 281 |
+
" # <YOUR CODE HERE>\n",
|
| 282 |
+
" model.eval()\n",
|
| 283 |
+
" running_loss = 0.0\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" # TODO: Disable gradient computation using torch.no_grad()\n",
|
| 286 |
+
" with torch.no_grad():\n",
|
| 287 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 288 |
+
" # TODO: Move data to device\n",
|
| 289 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 290 |
+
" y_batch = y_batch.reshape(-1, 1).to(device) # <Replace None with your code> [HINT: reshape to (-1, 1)]\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" # TODO: Forward pass - get model predictions\n",
|
| 293 |
+
" outputs = model(X_batch) # <Replace None with your code\n",
|
| 294 |
+
" # TODO: Compute loss using criterion\n",
|
| 295 |
+
" loss = criterion(outputs, y_batch) # <Replace None with your code>\n",
|
| 296 |
+
"\n",
|
| 297 |
+
" running_loss += loss.item()\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" return avg_loss"
|
| 302 |
+
],
|
| 303 |
+
"execution_count": null,
|
| 304 |
+
"outputs": []
|
| 305 |
+
},
|
| 306 |
+
{
|
| 307 |
+
"cell_type": "code",
|
| 308 |
+
"metadata": {},
|
| 309 |
+
"source": [
|
| 310 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 311 |
+
"device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
|
| 312 |
+
"input_dim = 36 * 36 * 3\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"hidden_dim = 64 # Design choice (feel free to experiment!)\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"num_epochs = 20\n",
|
| 319 |
+
"learning_rate = 0.001\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"# TODO: Instantiate the model and move it to the device\n",
|
| 322 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device) # <Replace None with your code>\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"# Print the model architecture\n",
|
| 325 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 326 |
+
"print(model)\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"# Calculate the total number of trainable parameters\n",
|
| 329 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 330 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"criterion = nn.MSELoss()\n",
|
| 333 |
+
"optimizer = AdamW(model.parameters(), lr=learning_rate)"
|
| 334 |
+
],
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"outputs": []
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"cell_type": "code",
|
| 340 |
+
"metadata": {},
|
| 341 |
+
"source": [
|
| 342 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 343 |
+
"train_losses = []\n",
|
| 344 |
+
"val_losses = []\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"print('Starting Training...')\n",
|
| 347 |
+
"for epoch in range(num_epochs):\n",
|
| 348 |
+
" # TODO: Train one epoch using the train_one_epoch function\n",
|
| 349 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device) # <Replace None with your code>\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" # TODO: Validate using the validate function\n",
|
| 352 |
+
" val_loss = validate(model, criterion, test_loader, device) # <Replace None with your code>\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" train_losses.append(train_loss)\n",
|
| 355 |
+
" val_losses.append(val_loss)\n",
|
| 356 |
+
"\n",
|
| 357 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"print('Training Complete!')"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"# Task 1: Write your code here:\n",
|
| 369 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 370 |
+
"\n",
|
| 371 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 372 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 373 |
+
"plt.title('Loss over Epochs')\n",
|
| 374 |
+
"plt.xlabel('Epoch')\n",
|
| 375 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 376 |
+
"plt.legend()\n",
|
| 377 |
+
"\n",
|
| 378 |
+
"plt.tight_layout()\n",
|
| 379 |
+
"plt.show()"
|
| 380 |
+
],
|
| 381 |
+
"execution_count": null,
|
| 382 |
+
"outputs": []
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"metadata": {},
|
| 387 |
+
"source": [
|
| 388 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 389 |
+
"# Set model to evaluation mode\n",
|
| 390 |
+
"model.eval()\n",
|
| 391 |
+
"# Get one batch from the test DataLoader\n",
|
| 392 |
+
"images, labels = next(iter(test_loader))\n",
|
| 393 |
+
"# Move images to device\n",
|
| 394 |
+
"images = images.to(device)\n",
|
| 395 |
+
"labels = labels.to(device)\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"with torch.no_grad():\n",
|
| 398 |
+
" # Flatten images before passing to the model\n",
|
| 399 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 400 |
+
" predictions = outputs\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"# Move tensors back to CPU for plotting\n",
|
| 403 |
+
"images = images.cpu()\n",
|
| 404 |
+
"labels = labels.cpu()\n",
|
| 405 |
+
"predictions = predictions.cpu()\n",
|
| 406 |
+
"\n",
|
| 407 |
+
"# Plot first 6 predictions\n",
|
| 408 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 409 |
+
"for i in range(6):\n",
|
| 410 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 411 |
+
" plt.imshow(images[i].permute(1, 2, 0))\n",
|
| 412 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i].item():.2f}\")\n",
|
| 413 |
+
" plt.axis('off')\n",
|
| 414 |
+
"\n",
|
| 415 |
+
"plt.tight_layout()\n",
|
| 416 |
+
"plt.show()"
|
| 417 |
+
],
|
| 418 |
+
"execution_count": null,
|
| 419 |
+
"outputs": []
|
| 420 |
+
},
|
| 421 |
+
{
|
| 422 |
+
"cell_type": "code",
|
| 423 |
+
"metadata": {},
|
| 424 |
+
"source": [],
|
| 425 |
+
"execution_count": null,
|
| 426 |
+
"outputs": []
|
| 427 |
+
}
|
| 428 |
+
],
|
| 429 |
+
"metadata": {
|
| 430 |
+
"kernelspec": {
|
| 431 |
+
"display_name": "Python 3",
|
| 432 |
+
"name": "python3"
|
| 433 |
+
},
|
| 434 |
+
"language_info": {
|
| 435 |
+
"name": "python"
|
| 436 |
+
}
|
| 437 |
+
},
|
| 438 |
+
"nbformat": 4,
|
| 439 |
+
"nbformat_minor": 0
|
| 440 |
+
}
|
submissions_extracted/574/Q3.ipynb
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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"
|
| 9 |
+
],
|
| 10 |
+
"execution_count": null,
|
| 11 |
+
"outputs": []
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"cell_type": "code",
|
| 15 |
+
"metadata": {},
|
| 16 |
+
"source": [
|
| 17 |
+
"import kagglehub\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"# Download latest version\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"print(\"Path to dataset files:\", path)"
|
| 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 |
+
"df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')"
|
| 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.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.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.describe()"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"df.isnull().sum()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 1: Write your code here:\n",
|
| 86 |
+
"def check_missing_values(df):\n",
|
| 87 |
+
" missing_values = df.isnull().sum()\n",
|
| 88 |
+
" print(\"Missing Values per Column:\")\n",
|
| 89 |
+
" x=missing_values[missing_values > 0]\n",
|
| 90 |
+
" print(len(x))\n",
|
| 91 |
+
" print(missing_values[missing_values > 0])\n",
|
| 92 |
+
" if missing_values.any():\n",
|
| 93 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 94 |
+
" else:\n",
|
| 95 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"check_missing_values(df)\n",
|
| 98 |
+
"\n"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"for col in df.columns:\n",
|
| 108 |
+
" df[col] = df[col].fillna(df[col].mean())\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"df.isnull().sum().sum()"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 2: Write your code here:\n",
|
| 127 |
+
"def check_duplicates(df):\n",
|
| 128 |
+
" duplicates = df.duplicated().sum()\n",
|
| 129 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 130 |
+
" if duplicates > 0:\n",
|
| 131 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 132 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 133 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 134 |
+
" else:\n",
|
| 135 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"check_duplicates(df)"
|
| 138 |
+
],
|
| 139 |
+
"execution_count": null,
|
| 140 |
+
"outputs": []
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"cell_type": "code",
|
| 144 |
+
"metadata": {},
|
| 145 |
+
"source": [
|
| 146 |
+
"# Task 3: Write your code here:\n",
|
| 147 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 148 |
+
"print(categorical_cols)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"#No categorical columns"
|
| 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 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"scaler = StandardScaler()\n",
|
| 166 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 167 |
+
"df.head()"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 5: Write your code here:\n",
|
| 177 |
+
"import seaborn as sns\n",
|
| 178 |
+
"import matplotlib.pyplot as plt\n",
|
| 179 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 180 |
+
" print(\"Target Distribution:\")\n",
|
| 181 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 182 |
+
" sns.countplot(x=df[target_column])\n",
|
| 183 |
+
" plt.title(\"Target Distribution\")\n",
|
| 184 |
+
" plt.show()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"check_target_imbalance(df, 'Target')\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"## There is an imbalance in the data\n"
|
| 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)\n",
|
| 200 |
+
"y=df['Target']"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"!pip install catboost"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 219 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 220 |
+
"from sklearn.metrics import accuracy_score, f1_score\n",
|
| 221 |
+
"n_splits = 5 # K\n",
|
| 222 |
+
"from catboost import CatBoostClassifier\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"model = CatBoostClassifier( verbose=0,\n",
|
| 225 |
+
" n_estimators=320,\n",
|
| 226 |
+
" max_depth=4)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"results = {}\n",
|
| 229 |
+
"results['CatBoostClassifier'] = {'accuracy': [], 'f1': []}\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 232 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" # 1. Split data\n",
|
| 237 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 238 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" model.fit(X_train, y_train) # train\n",
|
| 241 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 244 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" results[\"CatBoostClassifier\"]['accuracy'].append(accuracy)\n",
|
| 249 |
+
" results[\"CatBoostClassifier\"]['f1'].append(f1)\n",
|
| 250 |
+
""
|
| 251 |
+
],
|
| 252 |
+
"execution_count": null,
|
| 253 |
+
"outputs": []
|
| 254 |
+
},
|
| 255 |
+
{
|
| 256 |
+
"cell_type": "code",
|
| 257 |
+
"metadata": {},
|
| 258 |
+
"source": [
|
| 259 |
+
"print(sum(results[\"CatBoostClassifier\"]['accuracy'])/len(results[\"CatBoostClassifier\"]['accuracy']))\n",
|
| 260 |
+
"print(sum(results[\"CatBoostClassifier\"]['f1'])/len(results[\"CatBoostClassifier\"]['f1']))"
|
| 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 |
+
"feature_importance = pd.DataFrame({\n",
|
| 271 |
+
" 'feature': X.columns,\n",
|
| 272 |
+
" 'importance': model.feature_importances_\n",
|
| 273 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 276 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 277 |
+
"plt.xlabel('Importance')\n",
|
| 278 |
+
"plt.title('Feature Importance')\n",
|
| 279 |
+
"plt.gca().invert_yaxis()\n",
|
| 280 |
+
"plt.show()"
|
| 281 |
+
],
|
| 282 |
+
"execution_count": null,
|
| 283 |
+
"outputs": []
|
| 284 |
+
},
|
| 285 |
+
{
|
| 286 |
+
"cell_type": "code",
|
| 287 |
+
"metadata": {},
|
| 288 |
+
"source": [
|
| 289 |
+
"# Task 2: Write your code here:\n",
|
| 290 |
+
"feature_importance['feature'][0]"
|
| 291 |
+
],
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"outputs": []
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "code",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"# Task Bonus: Write your code here:\n",
|
| 300 |
+
"X= df[['P_2']]"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"source": [
|
| 309 |
+
"results_single_f = {}\n",
|
| 310 |
+
"results_single_f['CatBoostClassifier'] = {'accuracy': [], 'f1': []}\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 313 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" # 1. Split data\n",
|
| 318 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 319 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 320 |
+
"\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" model.fit(X_train, y_train) # train\n",
|
| 324 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 328 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 331 |
+
"\n",
|
| 332 |
+
" results_single_f[\"CatBoostClassifier\"]['accuracy'].append(accuracy)\n",
|
| 333 |
+
" results_single_f[\"CatBoostClassifier\"]['f1'].append(f1)"
|
| 334 |
+
],
|
| 335 |
+
"execution_count": null,
|
| 336 |
+
"outputs": []
|
| 337 |
+
},
|
| 338 |
+
{
|
| 339 |
+
"cell_type": "code",
|
| 340 |
+
"metadata": {},
|
| 341 |
+
"source": [
|
| 342 |
+
"\n",
|
| 343 |
+
"print(f\"\\n{'CatBoostClassifier'}:\")\n",
|
| 344 |
+
"print(f\" Accuracy: {np.mean(results['CatBoostClassifier']['accuracy']):.4f}\")\n",
|
| 345 |
+
"print(f\" Precision: {np.mean(results[\"CatBoostClassifier\"]['f1']):.4f}\")\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"print(f\"\\n{'CatBoostClassifier with golden feature'}:\")\n",
|
| 349 |
+
"print(f\" Accuracy: {np.mean(results_single_f['CatBoostClassifier']['accuracy']):.4f}\")\n",
|
| 350 |
+
"print(f\" Precision: {np.mean(results_single_f[\"CatBoostClassifier\"]['f1']):.4f}\")\n"
|
| 351 |
+
],
|
| 352 |
+
"execution_count": null,
|
| 353 |
+
"outputs": []
|
| 354 |
+
},
|
| 355 |
+
{
|
| 356 |
+
"cell_type": "code",
|
| 357 |
+
"metadata": {},
|
| 358 |
+
"source": [
|
| 359 |
+
"# This feature alone reached an accuracy of 0.79 and f1 of 0.5846"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
}
|
| 364 |
+
],
|
| 365 |
+
"metadata": {
|
| 366 |
+
"kernelspec": {
|
| 367 |
+
"display_name": "Python 3",
|
| 368 |
+
"name": "python3"
|
| 369 |
+
},
|
| 370 |
+
"language_info": {
|
| 371 |
+
"name": "python"
|
| 372 |
+
}
|
| 373 |
+
},
|
| 374 |
+
"nbformat": 4,
|
| 375 |
+
"nbformat_minor": 0
|
| 376 |
+
}
|
submissions_extracted/575/Q1.ipynb
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"\n",
|
| 23 |
+
"# add the required imports\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"import pandas as pd\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"food_dilvery_path = os.path.join(path, 'Q1_data.csv') # add the the path to the csv file using os.path.join\n",
|
| 28 |
+
"df_food_delivery = pd.read_csv(food_dilvery_path) # read the file into a dataframe\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"print(f\"Dataset shape: {df_food_delivery.shape}\") # print the shape of the dataframe"
|
| 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_food_delivery.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_food_delivery.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_food_delivery.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 5: Write your code here:\n",
|
| 70 |
+
"import matplotlib.pyplot as plt\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"def check_target_distribution(df, target_column):\n",
|
| 73 |
+
" df[target_column].hist(bins=30, edgecolor='black') # create a histogram to plot the distribution of delivery time\n",
|
| 74 |
+
"\n",
|
| 75 |
+
" plt.title(f\"Target Distribution ({target_column})\") # set the title for the plot\n",
|
| 76 |
+
" plt.xlabel(target_column) # name the x axis\n",
|
| 77 |
+
" plt.ylabel(\"Frequency\") # name the y axis\n",
|
| 78 |
+
" plt.grid(False) # don't show th grid\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" plt.show() # display the plot\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"check_target_distribution(df_food_delivery, \"Delivery_Time\")"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 1: Write your code here:\n",
|
| 92 |
+
"df_food_delivery = df_food_delivery.drop(columns=\"Order_ID\", axis=1)"
|
| 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 |
+
"cols_with_missing_vals = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time']\n",
|
| 103 |
+
"df_clean = df_food_delivery.copy()\n",
|
| 104 |
+
"df_clean = df_clean.dropna(subset=['Courier_Experience_yrs', 'Delivery_Time'])\n",
|
| 105 |
+
"for col in cols_with_missing_vals:\n",
|
| 106 |
+
" df_clean[col].fillna(df_food_delivery[col].mode()[0])"
|
| 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 |
+
"def check_duplicates(df):\n",
|
| 117 |
+
" duplicates = df_clean.duplicated().sum()\n",
|
| 118 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 119 |
+
" if duplicates > 0:\n",
|
| 120 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 121 |
+
" df_clean.drop_duplicates(inplace=True)\n",
|
| 122 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 123 |
+
" else:\n",
|
| 124 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"check_duplicates(df_clean)"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 4: Write your code here:\n",
|
| 136 |
+
"from sklearn.preprocessing import LabelEncoder # import LabelEncoder\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"#categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 139 |
+
"categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
|
| 140 |
+
"le = LabelEncoder() # Instantiate LabelEncoder\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"for col in categorical_cols:\n",
|
| 143 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"df_clean.head()"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 5: Write your code here:\n",
|
| 155 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"features = df_clean.columns.drop(\"Delivery_Time\") # select only the features for scaling\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 160 |
+
"df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n",
|
| 161 |
+
"df_clean.head()"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# Task 6: Write your code here:\n",
|
| 171 |
+
"# We can't check for target imabalance here because the target is countinuous"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 1: Write your code here:\n",
|
| 181 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 182 |
+
"y = df_clean[\"Delivery_Time\"].astype(float)"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 192 |
+
"from sklearn.model_selection import KFold\n",
|
| 193 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 194 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 197 |
+
"rf_mae = []\n",
|
| 198 |
+
"rf_regressor = RandomForestRegressor(n_estimators=200)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 201 |
+
" print(f\"\\nFold {fold_idx + 1}/5\")\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 204 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" # Train\n",
|
| 208 |
+
" rf_regressor.fit(X_train, y_train)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Predict\n",
|
| 211 |
+
" y_pred = rf_regressor.predict(X_test)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Calculate metrics\n",
|
| 214 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" rf_mae.append(mae)\n"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 1: Write your code here:\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"# Feature importance\n",
|
| 228 |
+
"feature_importance = pd.DataFrame({\n",
|
| 229 |
+
" 'feature': list(X),\n",
|
| 230 |
+
" 'importance': rf_regressor.feature_importances_\n",
|
| 231 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 234 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 235 |
+
"plt.xlabel('Importance')\n",
|
| 236 |
+
"plt.title('Feature Importance')\n",
|
| 237 |
+
"plt.gca().invert_yaxis()\n",
|
| 238 |
+
"plt.show()"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"# Task 2: Write your code here:\n",
|
| 248 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 249 |
+
"plt.hist(y_pred, bins=50, edgecolor='black', color='green')\n",
|
| 250 |
+
"plt.title('Predicted Delivery Time')\n",
|
| 251 |
+
"plt.xlabel('Delivery Time')\n",
|
| 252 |
+
"plt.ylabel('Frequency')\n",
|
| 253 |
+
"plt.show()"
|
| 254 |
+
],
|
| 255 |
+
"execution_count": null,
|
| 256 |
+
"outputs": []
|
| 257 |
+
},
|
| 258 |
+
{
|
| 259 |
+
"cell_type": "code",
|
| 260 |
+
"metadata": {},
|
| 261 |
+
"source": [
|
| 262 |
+
"# Task Bonus: Write your code here:"
|
| 263 |
+
],
|
| 264 |
+
"execution_count": null,
|
| 265 |
+
"outputs": []
|
| 266 |
+
}
|
| 267 |
+
],
|
| 268 |
+
"metadata": {
|
| 269 |
+
"kernelspec": {
|
| 270 |
+
"display_name": "Python 3",
|
| 271 |
+
"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 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"import torch.nn as nn\n",
|
| 71 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 74 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 75 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 76 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 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, y_train)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test, y_test)"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 3. Create DataLoaders\n",
|
| 97 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 98 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
|
| 99 |
+
],
|
| 100 |
+
"execution_count": null,
|
| 101 |
+
"outputs": []
|
| 102 |
+
},
|
| 103 |
+
{
|
| 104 |
+
"cell_type": "code",
|
| 105 |
+
"metadata": {},
|
| 106 |
+
"source": [
|
| 107 |
+
"# 4. Print shape of one batch\n",
|
| 108 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 109 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 110 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# 5. Display sample images\n",
|
| 120 |
+
"import matplotlib.pyplot as plt\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"images, labels = next(iter(train_loader))\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"# Display the first 6 images in the batch\n",
|
| 125 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"for i in range(6):\n",
|
| 128 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 131 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 132 |
+
"\n",
|
| 133 |
+
" plt.imshow(img)\n",
|
| 134 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 135 |
+
" plt.axis('off')\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"plt.tight_layout()\n",
|
| 138 |
+
"plt.show()"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 1: Write your model class here:\n",
|
| 148 |
+
"class NN4Layer(nn.Module):\n",
|
| 149 |
+
"\n",
|
| 150 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 151 |
+
" super(NN4Layer, self).__init__()\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 154 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 157 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 160 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" # Output layer: hidden layer -> 1 (single value for regression)\n",
|
| 163 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # ReLU activation for non-linearity\n",
|
| 166 |
+
" self.relu = nn.ReLU()\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # Defines how input data flows through the network\n",
|
| 169 |
+
" def forward(self, x):\n",
|
| 170 |
+
" # First hidden layer\n",
|
| 171 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # Second hidden layer\n",
|
| 174 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Third hidden layer\n",
|
| 177 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # Output layer\n",
|
| 180 |
+
" output = self.layer4(a3)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" return output"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task 2: Write your training loop here:\n",
|
| 192 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 193 |
+
" # Set the model to training mode\n",
|
| 194 |
+
" model.train()\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" running_loss = 0.0\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 199 |
+
" # Move batch to the selected device\n",
|
| 200 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
|
| 201 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" # Forward pass (outputs are logits)\n",
|
| 204 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 205 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 206 |
+
"\n",
|
| 207 |
+
" # Backward pass & optimization\n",
|
| 208 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 209 |
+
" loss.backward() # Compute gradients\n",
|
| 210 |
+
" optimizer.step() # Update model parameters\n",
|
| 211 |
+
"\n",
|
| 212 |
+
" running_loss += loss.item()\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" # Average loss over all batches\n",
|
| 215 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" return avg_loss"
|
| 218 |
+
],
|
| 219 |
+
"execution_count": null,
|
| 220 |
+
"outputs": []
|
| 221 |
+
},
|
| 222 |
+
{
|
| 223 |
+
"cell_type": "code",
|
| 224 |
+
"metadata": {},
|
| 225 |
+
"source": [
|
| 226 |
+
"# Task 3: Write your validation loop here:\n",
|
| 227 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 228 |
+
" # Set the model to evaluation mode\n",
|
| 229 |
+
" model.eval()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" running_loss = 0.0\n",
|
| 232 |
+
" correct = 0\n",
|
| 233 |
+
" total = 0\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" with torch.no_grad(): # Disable gradient computation\n",
|
| 236 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 237 |
+
" # Move batch to the selected device\n",
|
| 238 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 239 |
+
" y_batch = y_batch.view(-1,1).to(device)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Forward pass\n",
|
| 242 |
+
" outputs = model(X_batch)\n",
|
| 243 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 244 |
+
" running_loss += loss.item()\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" # Binary predictions\n",
|
| 247 |
+
" predicted = (outputs > 0.5).float()\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # Accuracy calculation\n",
|
| 250 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 251 |
+
" total += y_batch.size(0)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 254 |
+
" accuracy = correct / total\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" return avg_loss, accuracy"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 266 |
+
"from torch.optim import AdamW\n",
|
| 267 |
+
"num_epochs = 20\n",
|
| 268 |
+
"learning_rate = 0.001\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Device setup\n",
|
| 272 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# Model parameters\n",
|
| 275 |
+
"input_dim = 3 * 36 * 36 # Number of tabular features\n",
|
| 276 |
+
"hidden_dim = 14 # Design choice\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Instantiate model\n",
|
| 279 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"criterion = nn.MSELoss()\n",
|
| 282 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# Print the model architecture\n",
|
| 285 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 286 |
+
"print(model)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# Calculate the total number of trainable parameters\n",
|
| 289 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 290 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 291 |
+
],
|
| 292 |
+
"execution_count": null,
|
| 293 |
+
"outputs": []
|
| 294 |
+
},
|
| 295 |
+
{
|
| 296 |
+
"cell_type": "code",
|
| 297 |
+
"metadata": {},
|
| 298 |
+
"source": [
|
| 299 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 300 |
+
"train_losses = []\n",
|
| 301 |
+
"val_losses = []\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"print('Starting Training...')\n",
|
| 304 |
+
"for epoch in range(num_epochs):\n",
|
| 305 |
+
" # Train one epoch\n",
|
| 306 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" # Validate\n",
|
| 309 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" train_losses.append(train_loss)\n",
|
| 312 |
+
" val_losses.append(val_loss)\n",
|
| 313 |
+
"\n",
|
| 314 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"print('Training Complete!')\n"
|
| 317 |
+
],
|
| 318 |
+
"execution_count": null,
|
| 319 |
+
"outputs": []
|
| 320 |
+
},
|
| 321 |
+
{
|
| 322 |
+
"cell_type": "code",
|
| 323 |
+
"metadata": {},
|
| 324 |
+
"source": [
|
| 325 |
+
"# Task 1: Write your code here:\n",
|
| 326 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 329 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 330 |
+
"plt.title('Loss over Epochs')\n",
|
| 331 |
+
"plt.xlabel('Epoch')\n",
|
| 332 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 333 |
+
"plt.legend()\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"plt.tight_layout()\n",
|
| 336 |
+
"plt.show()"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
}
|
| 350 |
+
],
|
| 351 |
+
"metadata": {
|
| 352 |
+
"kernelspec": {
|
| 353 |
+
"display_name": "Python 3",
|
| 354 |
+
"name": "python3"
|
| 355 |
+
},
|
| 356 |
+
"language_info": {
|
| 357 |
+
"name": "python"
|
| 358 |
+
}
|
| 359 |
+
},
|
| 360 |
+
"nbformat": 4,
|
| 361 |
+
"nbformat_minor": 0
|
| 362 |
+
}
|
submissions_extracted/575/Q3.ipynb
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
"\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 |
+
"# add the required imports\n",
|
| 28 |
+
"import os\n",
|
| 29 |
+
"import pandas as pd\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"anonymized_dataset_path = os.path.join(path, 'Q3_data.csv') # add the the path to the csv file using os.path.join\n",
|
| 32 |
+
"df_anonymized = pd.read_csv(anonymized_dataset_path) # read the file into a dataframe\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"print(f\"Dataset shape: {df_anonymized.shape}\") # print the shape of the dataframe"
|
| 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_anonymized.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_anonymized.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_anonymized.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 |
+
"missing_values = df_anonymized.isnull().sum()\n",
|
| 75 |
+
"print(\"Missing Values per Column (before cleaning):\")\n",
|
| 76 |
+
"print(missing_values[missing_values > 0])\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"df_clean = df_anonymized.copy()\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"for col in df_clean.isnull().columns:\n",
|
| 81 |
+
" df_clean[col] = df_clean[col].fillna(df_clean[col].mean())\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"\n",
|
| 84 |
+
"missing_values = df_clean.isnull().sum()\n",
|
| 85 |
+
"print(\"Missing Values per Column (after cleaning):\")\n",
|
| 86 |
+
"print(missing_values[missing_values > 0])"
|
| 87 |
+
],
|
| 88 |
+
"execution_count": null,
|
| 89 |
+
"outputs": []
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"cell_type": "code",
|
| 93 |
+
"metadata": {},
|
| 94 |
+
"source": [
|
| 95 |
+
"# Task 2: Write your code here:\n",
|
| 96 |
+
"def check_duplicates(df):\n",
|
| 97 |
+
" duplicates = df_clean.duplicated().sum()\n",
|
| 98 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 99 |
+
" if duplicates > 0:\n",
|
| 100 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 101 |
+
" df_clean.drop_duplicates(inplace=True)\n",
|
| 102 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 103 |
+
" else:\n",
|
| 104 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"check_duplicates(df_clean)"
|
| 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 |
+
"# The dataset doesn't contain categorical columns\n",
|
| 117 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# Task 4: Write your code here:\n",
|
| 129 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"features = df_clean.columns.drop(\"Target\") # select only the features for scaling\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 134 |
+
"df_clean[features] = standard_scaler.fit_transform(df_clean[features]) # Apply fit_transform\n",
|
| 135 |
+
"df_clean.head()"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 5: Write your code here:\n",
|
| 145 |
+
"import seaborn as sns, matplotlib.pyplot as plt\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 148 |
+
" print(\"Target Distribution:\")\n",
|
| 149 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 150 |
+
" sns.countplot(x=df[target_column])\n",
|
| 151 |
+
" plt.title(\"Target Distribution\")\n",
|
| 152 |
+
" plt.show()\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"check_target_imbalance(df_clean, \"Target\")\n",
|
| 155 |
+
"# the target is imbalanced"
|
| 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 |
+
"X = df_clean.drop(\"Target\", axis=1).astype(float)\n",
|
| 166 |
+
"y = df_clean[\"Target\"].astype(float)"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"%pip install catboost -q"
|
| 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 sklearn.model_selection import StratifiedKFold\n",
|
| 186 |
+
"from sklearn.metrics import f1_score\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 191 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"from catboost import CatBoostRegressor\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"catboost = CatBoostRegressor(verbose=0)\n",
|
| 196 |
+
"f1 = []\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X)):\n",
|
| 199 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 202 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" # Train\n",
|
| 206 |
+
" catboost.fit(X_train, y_train)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Predict\n",
|
| 209 |
+
" y_pred = catboost.predict(X_test)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # Calculate metrics\n",
|
| 212 |
+
" f1_score = f1_score(y_test, y_pred)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" f1.append(f1_score)"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 1: Write your code here:"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 2: Write your code here:"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task Bonus: Write your code here:"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
}
|
| 246 |
+
],
|
| 247 |
+
"metadata": {
|
| 248 |
+
"kernelspec": {
|
| 249 |
+
"display_name": "Python 3",
|
| 250 |
+
"name": "python3"
|
|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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 |
+
"!pip install catboost"
|
| 22 |
+
],
|
| 23 |
+
"execution_count": null,
|
| 24 |
+
"outputs": []
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"import numpy as np\n",
|
| 31 |
+
"from sklearn.preprocessing import MinMaxScaler\n",
|
| 32 |
+
"from sklearn.feature_selection import RFE\n",
|
| 33 |
+
"from sklearn.model_selection import cross_val_score\n",
|
| 34 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 35 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 36 |
+
"from sklearn.feature_selection import SelectKBest, f_classif # Import SelectKBest and f_classif\n",
|
| 37 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 38 |
+
"from scipy.stats import chi2_contingency\n",
|
| 39 |
+
"import seaborn as sns\n",
|
| 40 |
+
"from catboost import CatBoostRegressor\n",
|
| 41 |
+
"import matplotlib.pyplot as plt"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"import pandas as pd\n",
|
| 51 |
+
"import numpy as np\n",
|
| 52 |
+
"import matplotlib.pyplot as plt\n",
|
| 53 |
+
"import seaborn as sns\n",
|
| 54 |
+
"import kagglehub\n",
|
| 55 |
+
"import os\n",
|
| 56 |
+
"from tqdm import tqdm\n",
|
| 57 |
+
"\n",
|
| 58 |
+
"%matplotlib inline"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"# Task 1: Write your code here:\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"df_quiz = pd.read_csv(f\"{path}/Q1_data.csv\")\n",
|
| 70 |
+
"print(f\"Dataset shape: {df_quiz.shape}\")"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 2: Write your code here:\n",
|
| 80 |
+
"df_quiz.head()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 3: Write your code here:\n",
|
| 90 |
+
"df_quiz.info()"
|
| 91 |
+
],
|
| 92 |
+
"execution_count": null,
|
| 93 |
+
"outputs": []
|
| 94 |
+
},
|
| 95 |
+
{
|
| 96 |
+
"cell_type": "code",
|
| 97 |
+
"metadata": {},
|
| 98 |
+
"source": [
|
| 99 |
+
"# Task 4: Write your code here:\n",
|
| 100 |
+
"df_quiz.describe()\n"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# Task 5: Write your code here:\n",
|
| 110 |
+
"# Target distribution\n",
|
| 111 |
+
"condition_counts = df_quiz['Delivery_Time'].value_counts()\n",
|
| 112 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 113 |
+
"plt.bar(condition_counts.index, condition_counts.values, color='coral')\n",
|
| 114 |
+
"plt.title('Delivery_Time Distribution')\n",
|
| 115 |
+
"plt.xlabel('Delivery_Time')\n",
|
| 116 |
+
"plt.ylabel('Count')\n",
|
| 117 |
+
"plt.xticks(rotation=45)\n",
|
| 118 |
+
"plt.show()"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"# Task 1: Write your code here:\n",
|
| 128 |
+
"#df_quiz = df_quiz.columns.drop(\"Order_ID\")\n",
|
| 129 |
+
"df_quiz= df_quiz.drop('Order_ID', axis=1)"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"print(f\"Dataset shape: {df_quiz.shape}\")"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 2: Write your code here:\n",
|
| 148 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 149 |
+
"print(df_quiz.isnull().sum())"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"mode_values = df_quiz.mode().iloc[0]\n",
|
| 159 |
+
"print(mode_values)"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Analyze missing values\n",
|
| 169 |
+
"missing_percentage = (df_quiz.isnull().sum() / len(df_quiz)) * 100\n",
|
| 170 |
+
"missing_data = pd.DataFrame({\n",
|
| 171 |
+
" 'Column': missing_percentage.index,\n",
|
| 172 |
+
" 'Missing_Percentage': missing_percentage.values\n",
|
| 173 |
+
"})\n",
|
| 174 |
+
"missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"print(\"Missing Data Analysis:\")\n",
|
| 177 |
+
"missing_data.head(10)"
|
| 178 |
+
],
|
| 179 |
+
"execution_count": null,
|
| 180 |
+
"outputs": []
|
| 181 |
+
},
|
| 182 |
+
{
|
| 183 |
+
"cell_type": "code",
|
| 184 |
+
"metadata": {},
|
| 185 |
+
"source": [
|
| 186 |
+
"cols = ['Delivery_Time', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs']\n",
|
| 187 |
+
"df_quiz = df_quiz[cols].copy()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"df_quiz= df_quiz.dropna(subset=['Delivery_Time']) #bc rows with no target labels are useless\n",
|
| 190 |
+
"df_quiz['Weather'].fillna(df_quiz['Weather'].mode()[0]) #we take the avg redundunt weather for the reagion\n",
|
| 191 |
+
"df_quiz['Traffic_Level'].fillna(df_quiz['Traffic_Level'].mode()[0]) #we take the avg redundunt Trafic level for the reagion\n",
|
| 192 |
+
"df_quiz['Time_of_Day'].fillna(df_quiz['Time_of_Day'].mode()[0]) #we take the avg redundunt time of day\n",
|
| 193 |
+
"df_quiz['Courier_Experience_yrs'].fillna(0) #bc people usually leave fields empty if they dont have entry (experience) do i assumed they dont have experience\n"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 3: Write your code here:\n",
|
| 203 |
+
"def check_duplicates(df_quiz):\n",
|
| 204 |
+
" duplicates = df_quiz.duplicated().sum()\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 207 |
+
" if duplicates > 0:\n",
|
| 208 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 209 |
+
" df_quiz.drop_duplicates(inplace=True)\n",
|
| 210 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 211 |
+
" else:\n",
|
| 212 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"check_duplicates(df_quiz)"
|
| 215 |
+
],
|
| 216 |
+
"execution_count": null,
|
| 217 |
+
"outputs": []
|
| 218 |
+
},
|
| 219 |
+
{
|
| 220 |
+
"cell_type": "code",
|
| 221 |
+
"metadata": {},
|
| 222 |
+
"source": [
|
| 223 |
+
"# Task 4: Write your code here:\n",
|
| 224 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"categorical_cols = df_quiz.select_dtypes(include=[\"object\"]).columns\n",
|
| 227 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 228 |
+
"\n",
|
| 229 |
+
"# Encode the target column\n",
|
| 230 |
+
"label_encoders = {}\n",
|
| 231 |
+
"for col in categorical_cols:\n",
|
| 232 |
+
" le = LabelEncoder()\n",
|
| 233 |
+
" df_quiz[col] = le.fit_transform(df_quiz[col])\n",
|
| 234 |
+
" label_encoders[col] = le\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"df_quiz"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Task 5: Write your code here:\n",
|
| 246 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"numerical_cols = df_quiz.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"scaler = StandardScaler()\n",
|
| 251 |
+
"df_quiz[numerical_cols] = scaler.fit_transform(df_quiz[numerical_cols])\n",
|
| 252 |
+
"df_quiz.head()\n"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"# Task 6: Write your code here:\n",
|
| 262 |
+
"#since it is multi regressign task and delevery time can ranges then it does not need to be distributed"
|
| 263 |
+
],
|
| 264 |
+
"execution_count": null,
|
| 265 |
+
"outputs": []
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
"cell_type": "code",
|
| 269 |
+
"metadata": {},
|
| 270 |
+
"source": [
|
| 271 |
+
"def check_target_imbalance(df_quiz, target_column):\n",
|
| 272 |
+
" print(\"Target Distribution:\")\n",
|
| 273 |
+
" print(df_quiz[target_column].value_counts(normalize=True))\n",
|
| 274 |
+
" sns.countplot(x=df_quiz[target_column])\n",
|
| 275 |
+
" plt.title(\"Target Distribution\")\n",
|
| 276 |
+
" plt.show()\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"check_target_imbalance(df_quiz, \"Delivery_Time\")"
|
| 279 |
+
],
|
| 280 |
+
"execution_count": null,
|
| 281 |
+
"outputs": []
|
| 282 |
+
},
|
| 283 |
+
{
|
| 284 |
+
"cell_type": "code",
|
| 285 |
+
"metadata": {},
|
| 286 |
+
"source": [
|
| 287 |
+
"import numpy as np\n",
|
| 288 |
+
"import pandas as pd\n",
|
| 289 |
+
"import matplotlib.pyplot as plt\n",
|
| 290 |
+
"import os\n",
|
| 291 |
+
"import kagglehub\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 294 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 295 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 296 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 297 |
+
"# Import models\n",
|
| 298 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 299 |
+
"from sklearn.svm import SVC\n",
|
| 300 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 301 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 302 |
+
"from xgboost import XGBClassifier\n",
|
| 303 |
+
"from catboost import CatBoostClassifier\n",
|
| 304 |
+
"import warnings\n",
|
| 305 |
+
"warnings.filterwarnings('ignore')\n",
|
| 306 |
+
"\n"
|
| 307 |
+
],
|
| 308 |
+
"execution_count": null,
|
| 309 |
+
"outputs": []
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"cell_type": "code",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"# Task 1: Write your code here:\n",
|
| 316 |
+
"# Define features (X) and target (y)\n",
|
| 317 |
+
"feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
|
| 318 |
+
" 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
|
| 319 |
+
"X = df_quiz[feature_cols]\n",
|
| 320 |
+
"y = df_quiz['Delivery_Time']\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 323 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 324 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
|
| 325 |
+
],
|
| 326 |
+
"execution_count": null,
|
| 327 |
+
"outputs": []
|
| 328 |
+
},
|
| 329 |
+
{
|
| 330 |
+
"cell_type": "code",
|
| 331 |
+
"metadata": {},
|
| 332 |
+
"source": [
|
| 333 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 334 |
+
"sklearn_models = {\n",
|
| 335 |
+
" \"Random Forest\": RandomForestClassifier(\n",
|
| 336 |
+
" n_estimators=320, # Number of trees\n",
|
| 337 |
+
" max_depth=4\n",
|
| 338 |
+
" )\n",
|
| 339 |
+
"}\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 342 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"mae_scores = []\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"for train_idx, val_idx in kfold.split(X_train):\n",
|
| 349 |
+
" #randomforest model\n",
|
| 350 |
+
" model= RandomForestClassifier()\n",
|
| 351 |
+
"\n",
|
| 352 |
+
" X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n",
|
| 353 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 354 |
+
" # Train and predict\n",
|
| 355 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 356 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 357 |
+
"\n",
|
| 358 |
+
" # Calculate metrics\n",
|
| 359 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 360 |
+
"\n",
|
| 361 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 364 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")"
|
| 365 |
+
],
|
| 366 |
+
"execution_count": null,
|
| 367 |
+
"outputs": []
|
| 368 |
+
},
|
| 369 |
+
{
|
| 370 |
+
"cell_type": "code",
|
| 371 |
+
"metadata": {},
|
| 372 |
+
"source": [
|
| 373 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 374 |
+
"from sklearn.svm import SVR\n",
|
| 375 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 376 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 377 |
+
"from lightgbm import LGBMRegressor\n",
|
| 378 |
+
"from catboost import CatBoostRegressor\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"# Task 1: Write your code here:\n",
|
| 381 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 382 |
+
"importances = {}\n",
|
| 383 |
+
"\n",
|
| 384 |
+
"importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"# Create a 1x3 plot\n",
|
| 387 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 388 |
+
"axes = axes.flatten()\n",
|
| 389 |
+
"features = X.columns\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 392 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 393 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 394 |
+
"\n",
|
| 395 |
+
" ax = axes[i]\n",
|
| 396 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 397 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 398 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"plt.tight_layout()\n",
|
| 401 |
+
"plt.show()"
|
| 402 |
+
],
|
| 403 |
+
"execution_count": null,
|
| 404 |
+
"outputs": []
|
| 405 |
+
},
|
| 406 |
+
{
|
| 407 |
+
"cell_type": "code",
|
| 408 |
+
"metadata": {},
|
| 409 |
+
"source": [
|
| 410 |
+
"# Task 2: Write your code here:\n",
|
| 411 |
+
"df_quiz['Delivery_Time'].plot.hist(bins=30, color='blue', title='Delivery_Time')"
|
| 412 |
+
],
|
| 413 |
+
"execution_count": null,
|
| 414 |
+
"outputs": []
|
| 415 |
+
},
|
| 416 |
+
{
|
| 417 |
+
"cell_type": "code",
|
| 418 |
+
"metadata": {},
|
| 419 |
+
"source": [
|
| 420 |
+
"# Task Bonus: Write your code here:\n",
|
| 421 |
+
"models = {\n",
|
| 422 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 423 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 424 |
+
"}\n",
|
| 425 |
+
"# Storage for results\n",
|
| 426 |
+
"all_results = {}\n",
|
| 427 |
+
"\n",
|
| 428 |
+
"for name in models:\n",
|
| 429 |
+
" all_results[name] = {'mae': []}"
|
| 430 |
+
],
|
| 431 |
+
"execution_count": null,
|
| 432 |
+
"outputs": []
|
| 433 |
+
},
|
| 434 |
+
{
|
| 435 |
+
"cell_type": "code",
|
| 436 |
+
"metadata": {},
|
| 437 |
+
"source": [
|
| 438 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 439 |
+
"\n",
|
| 440 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 441 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 442 |
+
"\n",
|
| 443 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 444 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" for model_name, model in models.items():\n",
|
| 447 |
+
" print(f\"Training {model_name}...\")\n",
|
| 448 |
+
"\n",
|
| 449 |
+
" # Train\n",
|
| 450 |
+
" model.fit(X_train, y_train)\n",
|
| 451 |
+
"\n",
|
| 452 |
+
" # Predict\n",
|
| 453 |
+
" y_pred = model.predict(X_test)\n",
|
| 454 |
+
"\n",
|
| 455 |
+
" # Calculate metrics\n",
|
| 456 |
+
" mae = sklearn_mae(y_test, y_pred)\n",
|
| 457 |
+
" # Store results\n",
|
| 458 |
+
" all_results[model_name][\"mae\"].append(mse)"
|
| 459 |
+
],
|
| 460 |
+
"execution_count": null,
|
| 461 |
+
"outputs": []
|
| 462 |
+
},
|
| 463 |
+
{
|
| 464 |
+
"cell_type": "code",
|
| 465 |
+
"metadata": {},
|
| 466 |
+
"source": [
|
| 467 |
+
"for model_name in all_results:\n",
|
| 468 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 469 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mse']):.4f}\")"
|
| 470 |
+
],
|
| 471 |
+
"execution_count": null,
|
| 472 |
+
"outputs": []
|
| 473 |
+
}
|
| 474 |
+
],
|
| 475 |
+
"metadata": {
|
| 476 |
+
"kernelspec": {
|
| 477 |
+
"display_name": "Python 3",
|
| 478 |
+
"name": "python3"
|
| 479 |
+
},
|
| 480 |
+
"language_info": {
|
| 481 |
+
"name": "python"
|
| 482 |
+
}
|
| 483 |
+
},
|
| 484 |
+
"nbformat": 4,
|
| 485 |
+
"nbformat_minor": 0
|
| 486 |
+
}
|
submissions_extracted/576/Q2.ipynb
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 required libraries\n",
|
| 69 |
+
"import kagglehub\n",
|
| 70 |
+
"import pandas as pd\n",
|
| 71 |
+
"import numpy as np\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 |
+
"print(f\"PyTorch version: {torch.__version__}\")\n",
|
| 82 |
+
"print(f\"CUDA available: {torch.cuda.is_available()}\")"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 94 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 95 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 96 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# 2. Create TensorDataset objects\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 108 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# 3. Create DataLoaders\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 120 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 121 |
+
"\n",
|
| 122 |
+
"# Print dataset sizes\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 |
+
"# 4. Print shape of one batch\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"# Get the first batch from the training DataLoader\n",
|
| 136 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 137 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 138 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Get some test images\n",
|
| 148 |
+
"images, labels = next(iter(train_loader))\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"# Display the first 6 images in the batch\n",
|
| 151 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"for i in range(6):\n",
|
| 154 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 155 |
+
"\n",
|
| 156 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 157 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 158 |
+
"\n",
|
| 159 |
+
" plt.imshow(img)\n",
|
| 160 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 161 |
+
" plt.axis('off')\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"plt.tight_layout()\n",
|
| 164 |
+
"plt.show()"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 1: Write your model class here:\n",
|
| 174 |
+
"class NN4Layer(nn.Module):\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 177 |
+
" super(NN4Layer, self).__init__()\n",
|
| 178 |
+
"\n",
|
| 179 |
+
" # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 180 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 181 |
+
"\n",
|
| 182 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 183 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 186 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 189 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 190 |
+
"\n",
|
| 191 |
+
" # activation function for non-linearity\n",
|
| 192 |
+
" self.relu = nn.ReLU()\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Defines how input data flows through the network\n",
|
| 195 |
+
" def forward(self, x):\n",
|
| 196 |
+
" # Layer 1: TODO\n",
|
| 197 |
+
" z1 = self.layer1(x)\n",
|
| 198 |
+
" a1 = self.relu(z1)\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Layer 2 TODO\n",
|
| 201 |
+
" z2 = self.layer2(a1)\n",
|
| 202 |
+
" a2 = self.relu(z2)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" # Layer 3 TODO\n",
|
| 205 |
+
" z3 = self.layer3(a2)\n",
|
| 206 |
+
" a3 = self.relu(z3)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" # Layer 4 TODO\n",
|
| 209 |
+
" z4 = self.layer4(a3)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 212 |
+
" #we dont use softmax because it is built in\n",
|
| 213 |
+
" return z4"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 2: Write your training loop here:\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 225 |
+
" # Set the model to training mode\n",
|
| 226 |
+
" model.train()\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" running_loss = 0.0\n",
|
| 229 |
+
"\n",
|
| 230 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 231 |
+
" # Move batch to the selected device\n",
|
| 232 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 233 |
+
" y_batch = y_batch.to(device)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Forward pass\n",
|
| 236 |
+
" # TODO: make predictions\n",
|
| 237 |
+
" outputs = model(X_batch)\n",
|
| 238 |
+
" # TODO: compute loss\n",
|
| 239 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" # Backward pass & optimization\n",
|
| 242 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 243 |
+
" loss.backward() # Compute gradients\n",
|
| 244 |
+
" optimizer.step() # Update model parameters\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" running_loss += loss.item()\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" # Average loss over all batches\n",
|
| 249 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" return avg_loss"
|
| 252 |
+
],
|
| 253 |
+
"execution_count": null,
|
| 254 |
+
"outputs": []
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"cell_type": "code",
|
| 258 |
+
"metadata": {},
|
| 259 |
+
"source": [
|
| 260 |
+
"# Task 3: Write your validation loop here:\n",
|
| 261 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 262 |
+
" # Set the model to evaluation mode\n",
|
| 263 |
+
" model.eval()\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" running_loss = 0.0\n",
|
| 266 |
+
" correct = 0\n",
|
| 267 |
+
" total = 0\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" with torch.no_grad():\n",
|
| 270 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 271 |
+
" # Move data to device\n",
|
| 272 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 273 |
+
" y_batch = y_batch.to(device)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" # Forward pass\n",
|
| 276 |
+
" # TODO: make predictions\n",
|
| 277 |
+
" outputs = model(X_batch)\n",
|
| 278 |
+
" # TODO: compute loss\n",
|
| 279 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 280 |
+
" running_loss += loss.item()\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 283 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" # TODO: Multiclass predictions\n",
|
| 286 |
+
" predicted = torch.argmax(probabilities, dim=1) #to get the index of highest probability\n",
|
| 287 |
+
"\n",
|
| 288 |
+
" # Accuracy calculation\n",
|
| 289 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 290 |
+
" total += y_batch.size(0)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 293 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 294 |
+
" accuracy = correct / total\n",
|
| 295 |
+
"\n",
|
| 296 |
+
" return avg_loss, accuracy\n"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 306 |
+
"from torch.optim import Adam\n",
|
| 307 |
+
"num_epochs = 20\n",
|
| 308 |
+
"learning_rate = 0.01\n",
|
| 309 |
+
"input_dim = 3*36*36\n",
|
| 310 |
+
"# TODO: choose number of hidden neurons\n",
|
| 311 |
+
"hidden_dim = 14\n",
|
| 312 |
+
"# TODO: what are the number of classes ?\n",
|
| 313 |
+
"output_dim = 2000\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 316 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 319 |
+
"optimizer = Adam(model.parameters(), learning_rate)"
|
| 320 |
+
],
|
| 321 |
+
"execution_count": null,
|
| 322 |
+
"outputs": []
|
| 323 |
+
},
|
| 324 |
+
{
|
| 325 |
+
"cell_type": "code",
|
| 326 |
+
"metadata": {},
|
| 327 |
+
"source": [
|
| 328 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 329 |
+
"# Run Training\n",
|
| 330 |
+
"train_losses = []\n",
|
| 331 |
+
"val_losses = []\n",
|
| 332 |
+
"val_accuracies = []\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"print('Starting Training...')\n",
|
| 335 |
+
"for epoch in range(num_epochs):\n",
|
| 336 |
+
" # Train one epoch\n",
|
| 337 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
" # Validate\n",
|
| 340 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
" train_losses.append(train_loss)\n",
|
| 343 |
+
" val_losses.append(val_loss)\n",
|
| 344 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"print('Training Complete!')"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"# Task 1: Write your code here:\n",
|
| 358 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 361 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 362 |
+
"plt.title('Loss over Epochs')\n",
|
| 363 |
+
"plt.xlabel('Epoch')\n",
|
| 364 |
+
"plt.ylabel('Loss')\n",
|
| 365 |
+
"plt.legend()\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"plt.tight_layout()\n",
|
| 368 |
+
"plt.show()"
|
| 369 |
+
],
|
| 370 |
+
"execution_count": null,
|
| 371 |
+
"outputs": []
|
| 372 |
+
},
|
| 373 |
+
{
|
| 374 |
+
"cell_type": "code",
|
| 375 |
+
"metadata": {},
|
| 376 |
+
"source": [
|
| 377 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
}
|
| 382 |
+
],
|
| 383 |
+
"metadata": {
|
| 384 |
+
"kernelspec": {
|
| 385 |
+
"display_name": "Python 3",
|
| 386 |
+
"name": "python3"
|
| 387 |
+
},
|
| 388 |
+
"language_info": {
|
| 389 |
+
"name": "python"
|
| 390 |
+
}
|
| 391 |
+
},
|
| 392 |
+
"nbformat": 4,
|
| 393 |
+
"nbformat_minor": 0
|
| 394 |
+
}
|
submissions_extracted/576/Q3.ipynb
ADDED
|
@@ -0,0 +1,388 @@
|
|
|
|
|
|
|
|
|
|
|
|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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 pandas as pd\n",
|
| 24 |
+
"import numpy as np\n",
|
| 25 |
+
"import matplotlib.pyplot as plt\n",
|
| 26 |
+
"import seaborn as sns\n",
|
| 27 |
+
"import kagglehub\n",
|
| 28 |
+
"import os\n",
|
| 29 |
+
"from tqdm import tqdm\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"%matplotlib inline"
|
| 32 |
+
],
|
| 33 |
+
"execution_count": null,
|
| 34 |
+
"outputs": []
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"metadata": {},
|
| 39 |
+
"source": [
|
| 40 |
+
"import kagglehub\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"# Download latest version\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"print(\"Path to dataset files:\", path)"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 1: Write your code here:\n",
|
| 60 |
+
"df = pd.read_csv(f\"{path}/Q3_data.csv\")\n",
|
| 61 |
+
"print(f\"Dataset shape: {df.shape}\")"
|
| 62 |
+
],
|
| 63 |
+
"execution_count": null,
|
| 64 |
+
"outputs": []
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"cell_type": "code",
|
| 68 |
+
"metadata": {},
|
| 69 |
+
"source": [
|
| 70 |
+
"# Task 2: Write your code here:\n",
|
| 71 |
+
"df.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.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 |
+
"df.describe()"
|
| 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 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 102 |
+
"print(df.isnull().sum())"
|
| 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 |
+
"cols = df.shape[1].values\n",
|
| 113 |
+
"df = df[cols].copy()\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"df= df.dropna(subset=['D_142']) #because lots of missing\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"if (df.isnull().sum()) > 0:\n",
|
| 118 |
+
" for i in cols:\n",
|
| 119 |
+
" df[i].fillna(df[i].mode()[0])\n"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"# Task 2: Write your code here:\n",
|
| 129 |
+
"def check_duplicates(df):\n",
|
| 130 |
+
" duplicates = df.duplicated().sum()\n",
|
| 131 |
+
"\n",
|
| 132 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 133 |
+
" if duplicates > 0:\n",
|
| 134 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 135 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 136 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 137 |
+
" else:\n",
|
| 138 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"check_duplicates(df)"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 3: Write your code here:\n",
|
| 150 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 153 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"scaler = StandardScaler()\n",
|
| 168 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 169 |
+
"df.head()\n"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Task 5: Write your code here:\n",
|
| 179 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 180 |
+
" print(\"Target Distribution:\")\n",
|
| 181 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 182 |
+
" sns.countplot(x=df[target_column])\n",
|
| 183 |
+
" plt.title(\"Target Distribution\")\n",
|
| 184 |
+
" plt.show()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"check_target_imbalance(df, \"Target\")"
|
| 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 |
+
"\n",
|
| 200 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 201 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 202 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 203 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 204 |
+
"# Import models\n",
|
| 205 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 206 |
+
"from sklearn.svm import SVC\n",
|
| 207 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 208 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 209 |
+
"import warnings\n",
|
| 210 |
+
"warnings.filterwarnings('ignore')\n"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"c= df.shape[1]\n",
|
| 220 |
+
"print(c)"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 1: Write your code here:\n",
|
| 230 |
+
"# Define features (X) and target (y)\n",
|
| 231 |
+
"X = df.shape[1].values\n",
|
| 232 |
+
"y = df['Target']\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"# Train-test split (80% train, 20% test)\n",
|
| 235 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 236 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"!pip install CatBoost"
|
| 246 |
+
],
|
| 247 |
+
"execution_count": null,
|
| 248 |
+
"outputs": []
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"import numpy as np\n",
|
| 255 |
+
"import pandas as pd\n",
|
| 256 |
+
"import matplotlib.pyplot as plt\n",
|
| 257 |
+
"import os\n",
|
| 258 |
+
"import kagglehub\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 261 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 262 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 263 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 264 |
+
"# Import models\n",
|
| 265 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 266 |
+
"from sklearn.svm import SVC\n",
|
| 267 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 268 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 269 |
+
"from xgboost import XGBClassifier\n",
|
| 270 |
+
"from catboost import CatBoostClassifier\n",
|
| 271 |
+
"import warnings\n",
|
| 272 |
+
"warnings.filterwarnings('ignore')\n",
|
| 273 |
+
"\n"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 283 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 284 |
+
"sklearn_models = {\n",
|
| 285 |
+
" \"Random Forest\": CatBoostClassifier(\n",
|
| 286 |
+
" n_estimators=320, # Number of trees\n",
|
| 287 |
+
" max_depth=4\n",
|
| 288 |
+
" )\n",
|
| 289 |
+
"}\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 292 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"mae_scores = []\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"for train_idx, val_idx in kfold.split(X_train):\n",
|
| 299 |
+
" #randomforest model\n",
|
| 300 |
+
" model= CatBoostClassifier()\n",
|
| 301 |
+
"\n",
|
| 302 |
+
" X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n",
|
| 303 |
+
" y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
|
| 304 |
+
" # Train and predict\n",
|
| 305 |
+
" model.fit(X_fold_train, y_fold_train)\n",
|
| 306 |
+
" y_fold_pred = model.predict(X_fold_val)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" # Calculate metrics\n",
|
| 309 |
+
" mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 314 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\n"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task 1: Write your code here:\n",
|
| 324 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 325 |
+
"from sklearn.svm import SVR\n",
|
| 326 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 327 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 328 |
+
"from lightgbm import LGBMRegressor\n",
|
| 329 |
+
"from catboost import CatBoostRegressor\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"# Task 1: Write your code here:\n",
|
| 332 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 333 |
+
"importances = {}\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"importances['catboost'] = sklearn_models['catboost'].feature_importances_\n",
|
| 336 |
+
"\n",
|
| 337 |
+
"# Create a 1x3 plot\n",
|
| 338 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 339 |
+
"axes = axes.flatten()\n",
|
| 340 |
+
"features = X.columns\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 343 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 344 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" ax = axes[i]\n",
|
| 347 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 348 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 349 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"plt.tight_layout()\n",
|
| 352 |
+
"plt.show()"
|
| 353 |
+
],
|
| 354 |
+
"execution_count": null,
|
| 355 |
+
"outputs": []
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"source": [
|
| 361 |
+
"# Task 2: Write your code here:\n",
|
| 362 |
+
"df['golden feature'].plot.hist(bins=30, color='blue', title='golden feature')"
|
| 363 |
+
],
|
| 364 |
+
"execution_count": null,
|
| 365 |
+
"outputs": []
|
| 366 |
+
},
|
| 367 |
+
{
|
| 368 |
+
"cell_type": "code",
|
| 369 |
+
"metadata": {},
|
| 370 |
+
"source": [
|
| 371 |
+
"# Task Bonus: Write your code here:"
|
| 372 |
+
],
|
| 373 |
+
"execution_count": null,
|
| 374 |
+
"outputs": []
|
| 375 |
+
}
|
| 376 |
+
],
|
| 377 |
+
"metadata": {
|
| 378 |
+
"kernelspec": {
|
| 379 |
+
"display_name": "Python 3",
|
| 380 |
+
"name": "python3"
|
| 381 |
+
},
|
| 382 |
+
"language_info": {
|
| 383 |
+
"name": "python"
|
| 384 |
+
}
|
| 385 |
+
},
|
| 386 |
+
"nbformat": 4,
|
| 387 |
+
"nbformat_minor": 0
|
| 388 |
+
}
|
submissions_extracted/577/Q1.ipynb
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"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 |
+
"import seaborn as sns\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 14 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"import warnings\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')"
|
| 20 |
+
],
|
| 21 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"import kagglehub\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"# Download latest version\n",
|
| 31 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(\"Path to dataset files:\", path)"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 1: Write your code here:\n",
|
| 43 |
+
"data_path = os.path.join(path,'Q1_data.csv')\n",
|
| 44 |
+
"df = pd.read_csv(data_path)\n",
|
| 45 |
+
"\n",
|
| 46 |
+
"print(f\"Dataset shape: {df.shape}\")"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 2: Write your code here:\n",
|
| 56 |
+
"df.head()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 3: Write your code here:\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"df.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 5: Write your code here:\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 88 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 89 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 90 |
+
"plt.xlabel('Delivery')\n",
|
| 91 |
+
"plt.ylabel('Frequency')\n",
|
| 92 |
+
"plt.show()"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"df.columns"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"# Task 1: Write your code here:\n",
|
| 111 |
+
"df.drop(columns = 'Order_ID',inplace=True)"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 2: Write your code here:\n",
|
| 121 |
+
"df.isnull().sum()"
|
| 122 |
+
],
|
| 123 |
+
"execution_count": null,
|
| 124 |
+
"outputs": []
|
| 125 |
+
},
|
| 126 |
+
{
|
| 127 |
+
"cell_type": "code",
|
| 128 |
+
"metadata": {},
|
| 129 |
+
"source": [
|
| 130 |
+
"# dropping missing target labels\n",
|
| 131 |
+
"df.dropna(subset=\"Delivery_Time\",inplace=True)"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"df.isnull().sum()"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"cols = ['Weather','Traffic_Level','Time_of_Day']\n",
|
| 150 |
+
"for c in cols:\n",
|
| 151 |
+
" df[c]= df[c].fillna(df[c].mode()[0])"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 3: Write your code here:\n",
|
| 170 |
+
"def check_duplicates(df):\n",
|
| 171 |
+
" duplicates = df.duplicated().sum()\n",
|
| 172 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 173 |
+
" if duplicates > 0:\n",
|
| 174 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 175 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 176 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 177 |
+
" else:\n",
|
| 178 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 179 |
+
"\n",
|
| 180 |
+
"check_duplicates(df)"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Task 4: Write your code here:\n",
|
| 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 |
+
"for col in categorical_cols:\n",
|
| 201 |
+
" le = LabelEncoder()\n",
|
| 202 |
+
" df[col] = le.fit_transform(df[col].astype(str))"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 5: Write your code here:\n",
|
| 212 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 213 |
+
"numerical_cols = df.select_dtypes(include=['number']).columns.drop('Delivery_Time')\n",
|
| 214 |
+
"print('data before scaling:\\n', numerical_cols) #show before scaling\n",
|
| 215 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 216 |
+
"df[numerical_cols] = standard_scaler.fit_transform(df[numerical_cols]) # Apply fit_transform"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 6: Write your code here:\n",
|
| 226 |
+
"df['Delivery_Time'].head()"
|
| 227 |
+
],
|
| 228 |
+
"execution_count": null,
|
| 229 |
+
"outputs": []
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"cell_type": "code",
|
| 233 |
+
"metadata": {},
|
| 234 |
+
"source": [
|
| 235 |
+
"# Task 1: Write your code here:\n",
|
| 236 |
+
"X = df.drop('Delivery_Time', axis=1)\n",
|
| 237 |
+
"y = df['Delivery_Time']"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 247 |
+
"from sklearn.model_selection import KFold\n",
|
| 248 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 249 |
+
"# Define K-Fold Cross Validation\n",
|
| 250 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 251 |
+
"model = RandomForestClassifier(class_weight='balanced')\n",
|
| 252 |
+
"mae_scores = []\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"# Iterate through folds\n",
|
| 255 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 256 |
+
" # indexing for each fold\n",
|
| 257 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 258 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 259 |
+
" # print shapes\n",
|
| 260 |
+
" print(f\"Fold {fold}\")\n",
|
| 261 |
+
" print(\" X_train shape:\", X_train.shape)\n",
|
| 262 |
+
" print(\" X_test shape :\", X_test.shape)\n",
|
| 263 |
+
" print(\" y_train shape:\", y_train.shape)\n",
|
| 264 |
+
" print(\" y_test shape :\", y_test.shape)\n",
|
| 265 |
+
" print(\"-\" * 30)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Train and predict\n",
|
| 268 |
+
" model.fit(X_train, y_train)\n",
|
| 269 |
+
" y_pred = model.predict(X_test)\n",
|
| 270 |
+
" # Calculate metrics\n",
|
| 271 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"mae_scores = np.array(mae_scores)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"print(f\"5-Fold CV Results:\")\n",
|
| 276 |
+
"print(f\"MAE: ${mae_scores.mean():,.2f}\")\n"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 1: Write your code here:\n",
|
| 286 |
+
"coeffs = {}\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"coeffs['RandomForest'] = model.feature_importances_\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
|
| 291 |
+
"axes = axes.flatten()\n",
|
| 292 |
+
"features = X.columns\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 295 |
+
" # Sort features by absolute coefficient value\n",
|
| 296 |
+
" absolute_coef = np.abs(coef)\n",
|
| 297 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" ax = axes[0]\n",
|
| 300 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 301 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 302 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 303 |
+
"\n",
|
| 304 |
+
"plt.tight_layout()\n",
|
| 305 |
+
"plt.show()"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"# Task 2: Write your code here:\n",
|
| 315 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 316 |
+
"plt.hist(y_test, bins=50, edgecolor='black')\n",
|
| 317 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 318 |
+
"plt.xlabel('Predicted Delivery')\n",
|
| 319 |
+
"plt.ylabel('Frequency')\n",
|
| 320 |
+
"plt.show()"
|
| 321 |
+
],
|
| 322 |
+
"execution_count": null,
|
| 323 |
+
"outputs": []
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "code",
|
| 327 |
+
"metadata": {},
|
| 328 |
+
"source": [
|
| 329 |
+
"# Task Bonus: Write your code here:"
|
| 330 |
+
],
|
| 331 |
+
"execution_count": null,
|
| 332 |
+
"outputs": []
|
| 333 |
+
},
|
| 334 |
+
{
|
| 335 |
+
"cell_type": "code",
|
| 336 |
+
"metadata": {},
|
| 337 |
+
"source": [
|
| 338 |
+
"!pip install catboost"
|
| 339 |
+
],
|
| 340 |
+
"execution_count": null,
|
| 341 |
+
"outputs": []
|
| 342 |
+
},
|
| 343 |
+
{
|
| 344 |
+
"cell_type": "code",
|
| 345 |
+
"metadata": {},
|
| 346 |
+
"source": [
|
| 347 |
+
"from catboost import CatBoostRegressor"
|
| 348 |
+
],
|
| 349 |
+
"execution_count": null,
|
| 350 |
+
"outputs": []
|
| 351 |
+
},
|
| 352 |
+
{
|
| 353 |
+
"cell_type": "code",
|
| 354 |
+
"metadata": {},
|
| 355 |
+
"source": [
|
| 356 |
+
"models = {\n",
|
| 357 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 358 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 359 |
+
"}"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"all_results = {}\n",
|
| 369 |
+
"\n",
|
| 370 |
+
"for name in models:\n",
|
| 371 |
+
" all_results[name] = {'mae': []}"
|
| 372 |
+
],
|
| 373 |
+
"execution_count": null,
|
| 374 |
+
"outputs": []
|
| 375 |
+
},
|
| 376 |
+
{
|
| 377 |
+
"cell_type": "code",
|
| 378 |
+
"metadata": {},
|
| 379 |
+
"source": [
|
| 380 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 383 |
+
" print(f\"\\nFold {fold_idx + 1}/5\")\n",
|
| 384 |
+
"\n",
|
| 385 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 386 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" for model_name, model in models.items():\n",
|
| 389 |
+
" print(f\"Training {model_name}...\")\n",
|
| 390 |
+
"\n",
|
| 391 |
+
" # Train\n",
|
| 392 |
+
" model.fit(X_train, y_train)\n",
|
| 393 |
+
"\n",
|
| 394 |
+
" # Predict\n",
|
| 395 |
+
" y_pred = model.predict(X_test)\n",
|
| 396 |
+
"\n",
|
| 397 |
+
" # Calculate metrics\n",
|
| 398 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 399 |
+
"\n",
|
| 400 |
+
" # Store results\n",
|
| 401 |
+
" all_results[model_name][\"mae\"].append(mae)"
|
| 402 |
+
],
|
| 403 |
+
"execution_count": null,
|
| 404 |
+
"outputs": []
|
| 405 |
+
},
|
| 406 |
+
{
|
| 407 |
+
"cell_type": "code",
|
| 408 |
+
"metadata": {},
|
| 409 |
+
"source": [
|
| 410 |
+
"for model_name in all_results:\n",
|
| 411 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 412 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")"
|
| 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/577/Q2.ipynb
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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.optim import AdamW\n",
|
| 71 |
+
"import matplotlib.pyplot as plt\n",
|
| 72 |
+
"import torch.nn.functional as F\n",
|
| 73 |
+
"from torch.utils.data import DataLoader, TensorDataset"
|
| 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 |
+
"\n",
|
| 84 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 85 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 86 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 87 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 2. Create TensorDataset objects\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 99 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# 3. Create DataLoaders\n",
|
| 109 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 110 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 111 |
+
"\n"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# 4. Print shape of one batch\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 |
+
"images, labels = next(iter(train_loader))\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"# Display the first 6 images in the batch\n",
|
| 136 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"for i in range(6):\n",
|
| 139 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 140 |
+
"\n",
|
| 141 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 142 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 143 |
+
"\n",
|
| 144 |
+
" plt.imshow(img)\n",
|
| 145 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 146 |
+
" plt.axis('off')\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"plt.tight_layout()\n",
|
| 149 |
+
"plt.show()"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 1: Write your model class here:\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"class NN4Layer(nn.Module):\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 163 |
+
" super(NN4Layer, self).__init__()\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" #: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
|
| 166 |
+
" self.layer1 = nn.Linear(input_dim,hidden_dim)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" #: What are the dimensions from previous and next layer?\n",
|
| 169 |
+
" self.layer2 = nn.Linear(hidden_dim,hidden_dim)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" #: What are the dimensions from previous and next layer?\n",
|
| 172 |
+
" self.layer3 = nn.Linear(hidden_dim,hidden_dim)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" #: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n",
|
| 175 |
+
" self.layer4 = nn.Linear(hidden_dim,output_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # activation function for non-linearity\n",
|
| 178 |
+
" self.relu = nn.ReLU()\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Defines how input data flows through the network\n",
|
| 181 |
+
" def forward(self, x):\n",
|
| 182 |
+
" # Layer 1:\n",
|
| 183 |
+
" z1 = self.layer1(x)\n",
|
| 184 |
+
" a1 = self.relu(z1)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Layer 2\n",
|
| 187 |
+
" z2 = self.layer2(a1)\n",
|
| 188 |
+
" a2 = self.relu(z2)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" # Layer 3\n",
|
| 191 |
+
" z3 = self.layer3(a2)\n",
|
| 192 |
+
" a3 = self.relu(z3)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # Output layer\n",
|
| 195 |
+
" z4 = self.layer4(a3)\n",
|
| 196 |
+
"\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 |
+
" # TODO: make predictions\n",
|
| 222 |
+
" outputs = model(X_batch)\n",
|
| 223 |
+
" # TODO: compute loss\n",
|
| 224 |
+
" loss = criterion(outputs,y_batch)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # Backward pass & optimization\n",
|
| 227 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 228 |
+
" loss.backward() # Compute gradients\n",
|
| 229 |
+
" optimizer.step() # Update model parameters\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" running_loss += loss.item()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Average loss over all batches\n",
|
| 234 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" return avg_loss"
|
| 237 |
+
],
|
| 238 |
+
"execution_count": null,
|
| 239 |
+
"outputs": []
|
| 240 |
+
},
|
| 241 |
+
{
|
| 242 |
+
"cell_type": "code",
|
| 243 |
+
"metadata": {},
|
| 244 |
+
"source": [
|
| 245 |
+
"# Task 3: Write your validation loop here:\n",
|
| 246 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 247 |
+
" # TODO: Set the model to evaluation mode\n",
|
| 248 |
+
" # <YOUR CODE HERE>\n",
|
| 249 |
+
" model.eval()\n",
|
| 250 |
+
" running_loss = 0.0\n",
|
| 251 |
+
"\n",
|
| 252 |
+
" # TODO: Disable gradient computation using torch.no_grad()\n",
|
| 253 |
+
" with torch.no_grad():\n",
|
| 254 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 255 |
+
" # TODO: Move data to device\n",
|
| 256 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 257 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" # TODO: Forward pass - get model predictions\n",
|
| 260 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # TODO: Compute loss using criterion\n",
|
| 263 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" running_loss += loss.item()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" return avg_loss\n"
|
| 270 |
+
],
|
| 271 |
+
"execution_count": null,
|
| 272 |
+
"outputs": []
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"cell_type": "code",
|
| 276 |
+
"metadata": {},
|
| 277 |
+
"source": [
|
| 278 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 279 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"# Model parameters\n",
|
| 282 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 283 |
+
"input_dim = 3*36*36\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# TODO: choose number of hidden neurons\n",
|
| 286 |
+
"hidden_dim = 18\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# TODO: what are the number of classes ?\n",
|
| 289 |
+
"output_dim = 1\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 292 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 293 |
+
"\n",
|
| 294 |
+
"# TODO: Print the model architecture\n",
|
| 295 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 296 |
+
"print(model)\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"# Calculate the total number of trainable parameters\n",
|
| 299 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 300 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 301 |
+
],
|
| 302 |
+
"execution_count": null,
|
| 303 |
+
"outputs": []
|
| 304 |
+
},
|
| 305 |
+
{
|
| 306 |
+
"cell_type": "code",
|
| 307 |
+
"metadata": {},
|
| 308 |
+
"source": [
|
| 309 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 310 |
+
"num_epochs = 20\n",
|
| 311 |
+
"learning_rate = 0.001\n",
|
| 312 |
+
"criterion = nn.MSELoss()\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# TODO: Define optimizer - use AdamW with the model parameters and learning rate\n",
|
| 315 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"train_losses = []\n",
|
| 318 |
+
"val_losses = []\n",
|
| 319 |
+
"\n",
|
| 320 |
+
"print('Starting Training...')\n",
|
| 321 |
+
"for epoch in range(num_epochs):\n",
|
| 322 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"\n",
|
| 325 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" train_losses.append(train_loss)\n",
|
| 328 |
+
" val_losses.append(val_loss)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"print('Training Complete!')"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
},
|
| 337 |
+
{
|
| 338 |
+
"cell_type": "code",
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"source": [
|
| 341 |
+
"# Task 1: Write your code here:\n",
|
| 342 |
+
"# Plotting results\n",
|
| 343 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 344 |
+
"\n",
|
| 345 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 346 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 347 |
+
"plt.title('Loss over Epochs')\n",
|
| 348 |
+
"plt.xlabel('Epoch')\n",
|
| 349 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 350 |
+
"plt.legend()\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 (Bonus): Write your code here:"
|
| 363 |
+
],
|
| 364 |
+
"execution_count": null,
|
| 365 |
+
"outputs": []
|
| 366 |
+
},
|
| 367 |
+
{
|
| 368 |
+
"cell_type": "code",
|
| 369 |
+
"metadata": {},
|
| 370 |
+
"source": [
|
| 371 |
+
"images, labels = next(iter(test_loader))\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"# Display the first 6 images in the batch\n",
|
| 374 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 375 |
+
"\n",
|
| 376 |
+
"for i in range(6):\n",
|
| 377 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 378 |
+
"\n",
|
| 379 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 380 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
" plt.imshow(img)\n",
|
| 383 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 384 |
+
" plt.axis('off')\n",
|
| 385 |
+
"\n",
|
| 386 |
+
"plt.tight_layout()\n",
|
| 387 |
+
"plt.show()"
|
| 388 |
+
],
|
| 389 |
+
"execution_count": null,
|
| 390 |
+
"outputs": []
|
| 391 |
+
}
|
| 392 |
+
],
|
| 393 |
+
"metadata": {
|
| 394 |
+
"kernelspec": {
|
| 395 |
+
"display_name": "Python 3",
|
| 396 |
+
"name": "python3"
|
| 397 |
+
},
|
| 398 |
+
"language_info": {
|
| 399 |
+
"name": "python"
|
| 400 |
+
}
|
| 401 |
+
},
|
| 402 |
+
"nbformat": 4,
|
| 403 |
+
"nbformat_minor": 0
|
| 404 |
+
}
|
submissions_extracted/577/Q3.ipynb
ADDED
|
@@ -0,0 +1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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"!pip install catboost"
|
| 8 |
+
],
|
| 9 |
+
"execution_count": null,
|
| 10 |
+
"outputs": []
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "code",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"import seaborn as sns"
|
| 17 |
+
],
|
| 18 |
+
"execution_count": null,
|
| 19 |
+
"outputs": []
|
| 20 |
+
},
|
| 21 |
+
{
|
| 22 |
+
"cell_type": "code",
|
| 23 |
+
"metadata": {},
|
| 24 |
+
"source": [
|
| 25 |
+
"import numpy as np\n",
|
| 26 |
+
"import pandas as pd\n",
|
| 27 |
+
"import matplotlib.pyplot as plt\n",
|
| 28 |
+
"import os\n",
|
| 29 |
+
"import kagglehub\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score, KFold\n",
|
| 32 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 33 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 34 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, f1_score\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"import warnings\n",
|
| 37 |
+
"warnings.filterwarnings('ignore')"
|
| 38 |
+
],
|
| 39 |
+
"execution_count": null,
|
| 40 |
+
"outputs": []
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"cell_type": "code",
|
| 44 |
+
"metadata": {},
|
| 45 |
+
"source": [
|
| 46 |
+
"import kagglehub\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Download latest version\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(\"Path to dataset files:\", path)"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 1: Write your code here:\n",
|
| 66 |
+
"data_path = os.path.join(path,'Q3_data.csv')\n",
|
| 67 |
+
"df = pd.read_csv(data_path)\n",
|
| 68 |
+
"\n",
|
| 69 |
+
"print(f\"Dataset shape: {df.shape}\")"
|
| 70 |
+
],
|
| 71 |
+
"execution_count": null,
|
| 72 |
+
"outputs": []
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"cell_type": "code",
|
| 76 |
+
"metadata": {},
|
| 77 |
+
"source": [
|
| 78 |
+
"# Task 2: Write your code here:\n",
|
| 79 |
+
"df.head()"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# Task 3: Write your code here:\n",
|
| 89 |
+
"df.info()"
|
| 90 |
+
],
|
| 91 |
+
"execution_count": null,
|
| 92 |
+
"outputs": []
|
| 93 |
+
},
|
| 94 |
+
{
|
| 95 |
+
"cell_type": "code",
|
| 96 |
+
"metadata": {},
|
| 97 |
+
"source": [
|
| 98 |
+
"# Task 4: Write your code here:\n",
|
| 99 |
+
"df.describe()"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# Task 1: Write your code here:\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"def check_missing_values(df):\n",
|
| 111 |
+
" missing_values = df.isnull().sum()\n",
|
| 112 |
+
" print(\"Missing Values per Column:\")\n",
|
| 113 |
+
" print(missing_values[missing_values > 0])\n",
|
| 114 |
+
" if missing_values.any():\n",
|
| 115 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 116 |
+
" else:\n",
|
| 117 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 118 |
+
"\n",
|
| 119 |
+
"check_missing_values(df)"
|
| 120 |
+
],
|
| 121 |
+
"execution_count": null,
|
| 122 |
+
"outputs": []
|
| 123 |
+
},
|
| 124 |
+
{
|
| 125 |
+
"cell_type": "code",
|
| 126 |
+
"metadata": {},
|
| 127 |
+
"source": [
|
| 128 |
+
"for i in df.columns:\n",
|
| 129 |
+
" df[i]=df[i].fillna(df[i].mean())"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# Task 2: Write your code here:\n",
|
| 139 |
+
"def check_duplicates(df):\n",
|
| 140 |
+
" duplicates = df.duplicated().sum()\n",
|
| 141 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 142 |
+
" if duplicates > 0:\n",
|
| 143 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 144 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 145 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 146 |
+
" else:\n",
|
| 147 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"check_duplicates(df)"
|
| 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 |
+
"categorical_cols = df.select_dtypes(include=['object']).columns\n",
|
| 160 |
+
"categorical_cols"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 4: Write your code here:\n",
|
| 170 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 171 |
+
"numerical_cols = df.select_dtypes(include=['number']).columns.drop('Target')\n",
|
| 172 |
+
"print('data before scaling:\\n', numerical_cols) #show before scaling\n",
|
| 173 |
+
"standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 174 |
+
"df[numerical_cols] = standard_scaler.fit_transform(df[numerical_cols]) # Apply fit_transform"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task 5: Write your code here:\n",
|
| 184 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 185 |
+
" print(\"Target Distribution:\")\n",
|
| 186 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 187 |
+
" sns.countplot(x=df[target_column])\n",
|
| 188 |
+
" plt.title(\"Target Distribution\")\n",
|
| 189 |
+
" plt.show()\n",
|
| 190 |
+
"check_target_imbalance(df, \"Target\")"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 1: Write your code here:\n",
|
| 200 |
+
"X = df.drop('Target', axis=1)\n",
|
| 201 |
+
"y = df['Target']"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"from catboost import CatBoostClassifier"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"results = {'acc': [], 'f1': []}"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 229 |
+
"n_splits = 5\n",
|
| 230 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 231 |
+
"model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 234 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" # 1. Split data\n",
|
| 237 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 238 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # 2. Train & Validate sklearn models\n",
|
| 241 |
+
" print(f\"Training CatBoost Classifier...\")\n",
|
| 242 |
+
" model.fit(X_train, y_train) # train\n",
|
| 243 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 246 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 247 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" results['acc'].append(accuracy)\n",
|
| 250 |
+
" results['f1'].append(f1)"
|
| 251 |
+
],
|
| 252 |
+
"execution_count": null,
|
| 253 |
+
"outputs": []
|
| 254 |
+
},
|
| 255 |
+
{
|
| 256 |
+
"cell_type": "code",
|
| 257 |
+
"metadata": {},
|
| 258 |
+
"source": [
|
| 259 |
+
"print(f\" Accuracy: {np.mean(results['acc']):.4f}\")\n",
|
| 260 |
+
"print(f\" F1-Score: {np.mean(results['f1']):.4f}\")\n",
|
| 261 |
+
"print(f\"However, since the data is imbalanced. The best metric here would be F1-Score which is {np.mean(results['f1']):.2f}\")"
|
| 262 |
+
],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"cell_type": "code",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [
|
| 270 |
+
"# Task 1: Write your code here:\n",
|
| 271 |
+
"catboost_model = model\n",
|
| 272 |
+
"catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n",
|
| 273 |
+
"sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"# Extract features and their importances\n",
|
| 276 |
+
"features, importances = zip(*sorted_catboost_importance)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Plot feature importances\n",
|
| 279 |
+
"plt.figure(figsize=(48, 44))\n",
|
| 280 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 281 |
+
"plt.xlabel('Importance Score')\n",
|
| 282 |
+
"plt.ylabel('Features')\n",
|
| 283 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 284 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 285 |
+
"plt.show()"
|
| 286 |
+
],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [
|
| 294 |
+
"# Task 2: Write your code here:\n",
|
| 295 |
+
"for i in sorted_catboost_importance:\n",
|
| 296 |
+
" print(i[0])"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"print(f\"The most important feature is {sorted_catboost_importance[0][0]}\")"
|
| 306 |
+
],
|
| 307 |
+
"execution_count": null,
|
| 308 |
+
"outputs": []
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"cell_type": "code",
|
| 312 |
+
"metadata": {},
|
| 313 |
+
"source": [
|
| 314 |
+
"r = {'acc': [], 'f1': []}"
|
| 315 |
+
],
|
| 316 |
+
"execution_count": null,
|
| 317 |
+
"outputs": []
|
| 318 |
+
},
|
| 319 |
+
{
|
| 320 |
+
"cell_type": "code",
|
| 321 |
+
"metadata": {},
|
| 322 |
+
"source": [
|
| 323 |
+
"# Task Bonus: Write your code here:\n",
|
| 324 |
+
"X = df[['P_2']]\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"n_splits = 5\n",
|
| 328 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 329 |
+
"model_golden = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 332 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" # 1. Split data\n",
|
| 335 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 336 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" # 2. Train & Validate sklearn models\n",
|
| 339 |
+
" print(f\"Training CatBoost Classifier...\")\n",
|
| 340 |
+
" model_golden.fit(X_train, y_train) # train\n",
|
| 341 |
+
" y_pred = model_golden.predict(X_test) # validate\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 344 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 345 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 346 |
+
"\n",
|
| 347 |
+
" r['acc'].append(accuracy)\n",
|
| 348 |
+
" r['f1'].append(f1)\n"
|
| 349 |
+
],
|
| 350 |
+
"execution_count": null,
|
| 351 |
+
"outputs": []
|
| 352 |
+
},
|
| 353 |
+
{
|
| 354 |
+
"cell_type": "code",
|
| 355 |
+
"metadata": {},
|
| 356 |
+
"source": [
|
| 357 |
+
"print(f\" Accuracy: {np.mean(r['acc']):.4f}\")\n",
|
| 358 |
+
"print(f\" F1-Score: {np.mean(r['f1']):.4f}\")"
|
| 359 |
+
],
|
| 360 |
+
"execution_count": null,
|
| 361 |
+
"outputs": []
|
| 362 |
+
}
|
| 363 |
+
],
|
| 364 |
+
"metadata": {
|
| 365 |
+
"kernelspec": {
|
| 366 |
+
"display_name": "Python 3",
|
| 367 |
+
"name": "python3"
|
| 368 |
+
},
|
| 369 |
+
"language_info": {
|
| 370 |
+
"name": "python"
|
| 371 |
+
}
|
| 372 |
+
},
|
| 373 |
+
"nbformat": 4,
|
| 374 |
+
"nbformat_minor":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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 numpy as np\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import matplotlib.pyplot as plt\n",
|
| 24 |
+
"import os\n",
|
| 25 |
+
"import kagglehub\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
|
| 28 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 29 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 30 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"import warnings\n",
|
| 33 |
+
"warnings.filterwarnings('ignore')\n"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"\n",
|
| 43 |
+
"# Load the CSV file\n",
|
| 44 |
+
"food_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 45 |
+
"df_food = pd.read_csv(food_path)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"print(f\"Shape: {df_food.shape}\")\n",
|
| 48 |
+
"\n"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {},
|
| 56 |
+
"source": [
|
| 57 |
+
"df_food.head()"
|
| 58 |
+
],
|
| 59 |
+
"execution_count": null,
|
| 60 |
+
"outputs": []
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"cell_type": "code",
|
| 64 |
+
"metadata": {},
|
| 65 |
+
"source": [
|
| 66 |
+
"df_food.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"df_food.describe()"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"\n",
|
| 85 |
+
"# Target distribution\n",
|
| 86 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 87 |
+
"plt.hist(df_food['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 88 |
+
"plt.title('Delivery time Distribution')\n",
|
| 89 |
+
"plt.xlabel('Time')\n",
|
| 90 |
+
"plt.ylabel('Frequency')\n",
|
| 91 |
+
"plt.show()\n",
|
| 92 |
+
"\n"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"df_food1 = df_food.drop('Order_ID' , axis = 1)\n"
|
| 102 |
+
],
|
| 103 |
+
"execution_count": null,
|
| 104 |
+
"outputs": []
|
| 105 |
+
},
|
| 106 |
+
{
|
| 107 |
+
"cell_type": "code",
|
| 108 |
+
"metadata": {},
|
| 109 |
+
"source": [
|
| 110 |
+
"df_food1.head()"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 120 |
+
"print(df_food1.isnull().sum())\n",
|
| 121 |
+
"cols = {\"Distance_km\",\"Weather\" ,\"Traffic_Level\" , \t\"Time_of_Day\", \t\"Vehicle_Type\", \t\"Preparation_Time_min\", \t\"Courier_Experience_yrs\", \t\"Delivery_Time\"}\n",
|
| 122 |
+
"df_clean = df_food1.dropna(subset=cols).copy()\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"print(\"\\nMissing Values (df.isnull().sum()):\")\n",
|
| 126 |
+
"print(df_clean.isnull().sum())"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"\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.\")"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [
|
| 152 |
+
"from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"print(\"Separating target variable and features...\")\n",
|
| 164 |
+
"X = df_clean.drop('Delivery_Time', axis=1)\n",
|
| 165 |
+
"y = df_clean['Delivery_Time']\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"print(\"Applying Label Encoding to target variable 'y'...\")\n",
|
| 168 |
+
"onehot_encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=False)\n",
|
| 169 |
+
"print(\"Applying One-Hot Encoding to feature DataFrame 'X'...\")\n",
|
| 170 |
+
"X_encoded = pd.DataFrame(onehot_encoder.fit_transform(X), columns=onehot_encoder.get_feature_names_out(X.columns))\n",
|
| 171 |
+
"print(\"Applying Label Encoding to target variable 'y'...\")\n",
|
| 172 |
+
"label_encoder = LabelEncoder()\n",
|
| 173 |
+
"y_encoded = label_encoder.fit_transform(y)\n",
|
| 174 |
+
"print(\"Verification of encoded data shapes:\")\n",
|
| 175 |
+
"print(f\"Shape of X_encoded: {X_encoded.shape}\")\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"print(\"First 5 rows of X_encoded:\")\n",
|
| 178 |
+
"display(X_encoded.head())\n",
|
| 179 |
+
"print(\"First 5 elements of y_encoded:\")\n",
|
| 180 |
+
"print(y_encoded[:5])\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"\n"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Scale features\n",
|
| 192 |
+
"#scaler = StandardScaler()\n",
|
| 193 |
+
"#X_scaled = scaler.fit_transform(X_encoded)\n",
|
| 194 |
+
"#y_scaled = scaler.fit_transform(y_encoded)\n"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"# Task 6: Write your code here:"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"print(\"Splitting data into training and testing sets...\")\n",
|
| 222 |
+
"X_train, X_test, y_train, y_test = train_test_split(X_encoded, y_encoded, test_size=0.3, random_state=42)\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"print(\"Data split successful.\")\n",
|
| 225 |
+
"print(f\"Shape of X_train: {X_train.shape}\")\n",
|
| 226 |
+
"print(f\"Shape of X_test: {X_test.shape}\")\n",
|
| 227 |
+
"print(f\"Shape of y_train: {y_train.shape}\")\n",
|
| 228 |
+
"print(f\"Shape of y_test: {y_test.shape}\")\n",
|
| 229 |
+
"\n"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"from sklearn.model_selection import train_test_split, KFold, cross_val_score"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
},
|
| 243 |
+
{
|
| 244 |
+
"cell_type": "code",
|
| 245 |
+
"metadata": {},
|
| 246 |
+
"source": [
|
| 247 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 248 |
+
"model = RandomForestClassifier(n_estimators=100, random_state=42)\n"
|
| 249 |
+
],
|
| 250 |
+
"execution_count": null,
|
| 251 |
+
"outputs": []
|
| 252 |
+
},
|
| 253 |
+
{
|
| 254 |
+
"cell_type": "code",
|
| 255 |
+
"metadata": {},
|
| 256 |
+
"source": [
|
| 257 |
+
"def categorical_cross_entropy(y_true, y_pred):\n",
|
| 258 |
+
" \"\"\"Compute categorical cross-entropy loss.\"\"\"\n",
|
| 259 |
+
" epsilon = 1e-10 # Small value to prevent log(0)\n",
|
| 260 |
+
" y_pred = np.clip(y_pred, epsilon, 1. - epsilon)\n",
|
| 261 |
+
" loss = -np.sum(y_true * np.log(y_pred), axis=-1)\n",
|
| 262 |
+
" return np.mean(loss)\n"
|
| 263 |
+
],
|
| 264 |
+
"execution_count": null,
|
| 265 |
+
"outputs": []
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
"cell_type": "code",
|
| 269 |
+
"metadata": {},
|
| 270 |
+
"source": [
|
| 271 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, mean_absolute_error"
|
| 272 |
+
],
|
| 273 |
+
"execution_count": null,
|
| 274 |
+
"outputs": []
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"cell_type": "code",
|
| 278 |
+
"metadata": {},
|
| 279 |
+
"source": [],
|
| 280 |
+
"execution_count": null,
|
| 281 |
+
"outputs": []
|
| 282 |
+
},
|
| 283 |
+
{
|
| 284 |
+
"cell_type": "code",
|
| 285 |
+
"metadata": {},
|
| 286 |
+
"source": [],
|
| 287 |
+
"execution_count": null,
|
| 288 |
+
"outputs": []
|
| 289 |
+
},
|
| 290 |
+
{
|
| 291 |
+
"cell_type": "code",
|
| 292 |
+
"metadata": {},
|
| 293 |
+
"source": [
|
| 294 |
+
"\n",
|
| 295 |
+
"fold_losses = [] # List to store loss from each fold\n",
|
| 296 |
+
"for fold, (train_index, val_index) in enumerate(kf.split(X_train)):\n",
|
| 297 |
+
" # Split X_train and y_train into training and validation sets for the current fold\n",
|
| 298 |
+
" X_train_fold, X_val_fold = X_train.iloc[train_index], X_train.iloc[val_index]\n",
|
| 299 |
+
" y_train_fold, y_val_fold = y_train[train_index], y_train[val_index]\n",
|
| 300 |
+
"\n",
|
| 301 |
+
" # Train the current model\n",
|
| 302 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 303 |
+
"\n",
|
| 304 |
+
" # Generate predictions (probabilities) on the validation set\n",
|
| 305 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 306 |
+
" # Convert y_val_fold (true labels) into a one-hot encoded format\n",
|
| 307 |
+
" y_val_one_hot = y_val_fold,\n",
|
| 308 |
+
"\n",
|
| 309 |
+
" # Calculate categorical cross-entropy loss for the current fold\n",
|
| 310 |
+
" #loss = mean_absolute_error(y_val_one_hot, y_pred_proba)\n",
|
| 311 |
+
" #fold_losses.append(loss)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"\n",
|
| 315 |
+
"\n"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
|
| 325 |
+
"import seaborn as sns"
|
| 326 |
+
],
|
| 327 |
+
"execution_count": null,
|
| 328 |
+
"outputs": []
|
| 329 |
+
},
|
| 330 |
+
{
|
| 331 |
+
"cell_type": "code",
|
| 332 |
+
"metadata": {},
|
| 333 |
+
"source": [
|
| 334 |
+
"\n",
|
| 335 |
+
" # Make predictions on the test set (hard labels)\n",
|
| 336 |
+
" y_pred = model.predict(X_test)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" # Calculate evaluation metrics\n",
|
| 339 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 340 |
+
" precision = precision_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 341 |
+
" recall = recall_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 342 |
+
" f1 = f1_score(y_test, y_pred, average='weighted', zero_division=0)\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" # Print metrics\n",
|
| 346 |
+
" print(f\" Accuracy: {accuracy:.4f}\")\n",
|
| 347 |
+
" print(f\" Precision: {precision:.4f}\")\n",
|
| 348 |
+
" print(f\" Recall: {recall:.4f}\")\n",
|
| 349 |
+
" print(f\" F1-Score: {f1:.4f}\")\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" # Generate and visualize Confusion Matrix\n",
|
| 352 |
+
" cm = confusion_matrix(y_test, y_pred)\n",
|
| 353 |
+
" plt.figure(figsize=(6, 5))\n",
|
| 354 |
+
" sns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False,\n",
|
| 355 |
+
" xticklabels=label_encoder.classes_, yticklabels=label_encoder.classes_)\n",
|
| 356 |
+
" plt.title(f'Confusion Matrix for random forest')\n",
|
| 357 |
+
" plt.xlabel('Predicted Label')\n",
|
| 358 |
+
" plt.ylabel('True Label')\n",
|
| 359 |
+
" plt.show()"
|
| 360 |
+
],
|
| 361 |
+
"execution_count": null,
|
| 362 |
+
"outputs": []
|
| 363 |
+
},
|
| 364 |
+
{
|
| 365 |
+
"cell_type": "code",
|
| 366 |
+
"metadata": {},
|
| 367 |
+
"source": [
|
| 368 |
+
"# Task 2: Write your code here:"
|
| 369 |
+
],
|
| 370 |
+
"execution_count": null,
|
| 371 |
+
"outputs": []
|
| 372 |
+
},
|
| 373 |
+
{
|
| 374 |
+
"cell_type": "code",
|
| 375 |
+
"metadata": {},
|
| 376 |
+
"source": [
|
| 377 |
+
"# Task Bonus: Write your code here:"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
}
|
| 382 |
+
],
|
| 383 |
+
"metadata": {
|
| 384 |
+
"kernelspec": {
|
| 385 |
+
"display_name": "Python 3",
|
| 386 |
+
"name": "python3"
|
| 387 |
+
},
|
| 388 |
+
"language_info": {
|
| 389 |
+
"name": "python"
|
| 390 |
+
}
|
| 391 |
+
},
|
| 392 |
+
"nbformat": 4,
|
| 393 |
+
"nbformat_minor": 0
|
| 394 |
+
}
|
submissions_extracted/578/Q2.ipynb
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# 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 DataLoader, TensorDataset\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"import torch.nn as nn"
|
| 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 |
+
"X_train1 = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 81 |
+
"X_test1 = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 82 |
+
"y_train1 = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 83 |
+
"y_test1 = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 84 |
+
"# 2. Create TensorDataset objects\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"train_dataset = TensorDataset(X_train1, y_train1)\n",
|
| 87 |
+
"test_dataset = TensorDataset(X_test1, y_test1)\n",
|
| 88 |
+
"# 3. Create DataLoaders\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 92 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 93 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"# Get one batch of images and labels\n",
|
| 97 |
+
"images, labels = next(iter(train_loader))\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"# Display the first 6 images in the batch\n",
|
| 100 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"for i in range(6):\n",
|
| 103 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 104 |
+
"\n",
|
| 105 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 106 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 107 |
+
"\n",
|
| 108 |
+
" plt.imshow(img)\n",
|
| 109 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 110 |
+
" plt.axis('off')\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"plt.tight_layout()\n",
|
| 113 |
+
"plt.show()"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 130 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32).flatten(start_dim=1)\n",
|
| 131 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32).flatten(start_dim=1)\n",
|
| 132 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 133 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 134 |
+
],
|
| 135 |
+
"execution_count": null,
|
| 136 |
+
"outputs": []
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"cell_type": "code",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"source": [],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# 2. Create TensorDataset objects\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 152 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# 3. Create DataLoaders\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 165 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 166 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 167 |
+
"\n"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# 4. Print shape of one batch\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# Print dataset sizes\n",
|
| 186 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 187 |
+
"print(\"Test dataset:\", len(test_dataset))\n",
|
| 188 |
+
"\n",
|
| 189 |
+
"# Get the first batch from the training DataLoader\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"\n",
|
| 192 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 193 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 194 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 195 |
+
],
|
| 196 |
+
"execution_count": null,
|
| 197 |
+
"outputs": []
|
| 198 |
+
},
|
| 199 |
+
{
|
| 200 |
+
"cell_type": "code",
|
| 201 |
+
"metadata": {},
|
| 202 |
+
"source": [],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"# Task 1: Write your model class here:\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"class NN4Layer(nn.Module):\n",
|
| 213 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 214 |
+
" super(NN4Layer, self).__init__()\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 217 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 220 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Output layer: hidden layer -> single continuous value\n",
|
| 223 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 224 |
+
" self.layer3 = nn.Linear(hidden_dim, 70)\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" # ReLU activation for non-linearity in hidden layers\n",
|
| 227 |
+
" self.relu = nn.ReLU()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Defines how input data flows through the network\n",
|
| 230 |
+
" def forward(self, x):\n",
|
| 231 |
+
" # First hidden layer\n",
|
| 232 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" # Second hidden layer\n",
|
| 235 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 236 |
+
"\n",
|
| 237 |
+
" # Output layer (regression output)\n",
|
| 238 |
+
" output = self.layer3(a2)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" return output\n",
|
| 241 |
+
"\n"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task 2: Write your training loop here:\n",
|
| 251 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 252 |
+
" # Set the model to training mode\n",
|
| 253 |
+
" model.train()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" running_loss = 0.0\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 258 |
+
" # Move batch to the selected device\n",
|
| 259 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 260 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # Forward pass (continuous output)\n",
|
| 263 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 264 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 265 |
+
"\n",
|
| 266 |
+
" # Backward pass & optimization\n",
|
| 267 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 268 |
+
" loss.backward() # Compute gradients\n",
|
| 269 |
+
" optimizer.step() # Update model parameters\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" running_loss += loss.item()\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Average loss over all batches\n",
|
| 274 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" return avg_loss"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 3: Write your validation loop here:\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 288 |
+
" # Set the model to evaluation mode\n",
|
| 289 |
+
" model.eval()\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" running_loss = 0.0\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" with torch.no_grad():\n",
|
| 294 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 295 |
+
" # Move data to device\n",
|
| 296 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 297 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 298 |
+
"\n",
|
| 299 |
+
" # Forward pass (continuous output)\n",
|
| 300 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 301 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" running_loss += loss.item()\n",
|
| 304 |
+
"\n",
|
| 305 |
+
" # Average loss over all batches\n",
|
| 306 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
" return avg_loss\n"
|
| 309 |
+
],
|
| 310 |
+
"execution_count": null,
|
| 311 |
+
"outputs": []
|
| 312 |
+
},
|
| 313 |
+
{
|
| 314 |
+
"cell_type": "code",
|
| 315 |
+
"metadata": {},
|
| 316 |
+
"source": [],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"# TODO: Set up the device (use GPU if available, otherwise CPU)\n",
|
| 329 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"\n",
|
| 332 |
+
"# Model parameters\n",
|
| 333 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 334 |
+
"hidden_dim = 64 # Design choice\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"# Instantiate regression model\n",
|
| 337 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"# Print the model architecture\n",
|
| 340 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 341 |
+
"print(model)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
"# Calculate the total number of trainable parameters\n",
|
| 344 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 345 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 346 |
+
"\n"
|
| 347 |
+
],
|
| 348 |
+
"execution_count": null,
|
| 349 |
+
"outputs": []
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"cell_type": "code",
|
| 353 |
+
"metadata": {},
|
| 354 |
+
"source": [
|
| 355 |
+
"from torch.optim import AdamW"
|
| 356 |
+
],
|
| 357 |
+
"execution_count": null,
|
| 358 |
+
"outputs": []
|
| 359 |
+
},
|
| 360 |
+
{
|
| 361 |
+
"cell_type": "code",
|
| 362 |
+
"metadata": {},
|
| 363 |
+
"source": [
|
| 364 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 365 |
+
"\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"\n",
|
| 368 |
+
"# Hyperparameters (feel free to experiment!)\n",
|
| 369 |
+
"num_epochs = 20\n",
|
| 370 |
+
"learning_rate = 0.001\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"\n",
|
| 373 |
+
"# Define criterion (loss function)\n",
|
| 374 |
+
"criterion = nn.MSELoss()\n",
|
| 375 |
+
"# Define optimizer\n",
|
| 376 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 377 |
+
"\n"
|
| 378 |
+
],
|
| 379 |
+
"execution_count": null,
|
| 380 |
+
"outputs": []
|
| 381 |
+
},
|
| 382 |
+
{
|
| 383 |
+
"cell_type": "code",
|
| 384 |
+
"metadata": {},
|
| 385 |
+
"source": [
|
| 386 |
+
"# Task 1: Write your code here:\n",
|
| 387 |
+
"# Run Training\n",
|
| 388 |
+
"train_losses = []\n",
|
| 389 |
+
"val_losses = []\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"print('Starting Training...')\n",
|
| 392 |
+
"for epoch in range(num_epochs):\n",
|
| 393 |
+
" # Train one epoch\n",
|
| 394 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 395 |
+
"\n",
|
| 396 |
+
" # Validate\n",
|
| 397 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 398 |
+
"\n",
|
| 399 |
+
" train_losses.append(train_loss)\n",
|
| 400 |
+
" val_losses.append(val_loss)\n",
|
| 401 |
+
"\n",
|
| 402 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 403 |
+
" print(\n",
|
| 404 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 405 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 406 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 407 |
+
" )\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"print('Training Complete!')"
|
| 410 |
+
],
|
| 411 |
+
"execution_count": null,
|
| 412 |
+
"outputs": []
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"cell_type": "code",
|
| 416 |
+
"metadata": {},
|
| 417 |
+
"source": [
|
| 418 |
+
"import matplotlib.pyplot as plt"
|
| 419 |
+
],
|
| 420 |
+
"execution_count": null,
|
| 421 |
+
"outputs": []
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"cell_type": "code",
|
| 425 |
+
"metadata": {},
|
| 426 |
+
"source": [
|
| 427 |
+
"# Plotting results\n",
|
| 428 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 429 |
+
"\n",
|
| 430 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 431 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 432 |
+
"plt.title('Loss over Epochs')\n",
|
| 433 |
+
"plt.xlabel('Epoch')\n",
|
| 434 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 435 |
+
"plt.legend()\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"plt.tight_layout()\n",
|
| 438 |
+
"plt.show()"
|
| 439 |
+
],
|
| 440 |
+
"execution_count": null,
|
| 441 |
+
"outputs": []
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"cell_type": "code",
|
| 445 |
+
"metadata": {},
|
| 446 |
+
"source": [
|
| 447 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 448 |
+
],
|
| 449 |
+
"execution_count": null,
|
| 450 |
+
"outputs": []
|
| 451 |
+
}
|
| 452 |
+
],
|
| 453 |
+
"metadata": {
|
| 454 |
+
"kernelspec": {
|
| 455 |
+
"display_name": "Python 3",
|
| 456 |
+
"name": "python3"
|
| 457 |
+
},
|
| 458 |
+
"language_info": {
|
| 459 |
+
"name": "python"
|
| 460 |
+
}
|
| 461 |
+
},
|
| 462 |
+
"nbformat": 4,
|
| 463 |
+
"nbformat_minor": 0
|
| 464 |
+
}
|
submissions_extracted/578/Q3.ipynb
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import pandas as pd\n",
|
| 10 |
+
"import numpy as np\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"from sklearn.model_selection import train_test_split, KFold, cross_val_score\n",
|
| 14 |
+
"from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
|
| 15 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
|
| 16 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 17 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 18 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 19 |
+
"from sklearn.svm import SVC\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"print(\"Libraries imported successfully.\")\n"
|
| 22 |
+
],
|
| 23 |
+
"execution_count": null,
|
| 24 |
+
"outputs": []
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"cell_type": "code",
|
| 28 |
+
"metadata": {},
|
| 29 |
+
"source": [
|
| 30 |
+
"import kagglehub\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Download latest version\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(\"Path to dataset files:\", path)"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 1: Write your code here:\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"df = pd.read_csv(path + \"/Q3_data.csv\")"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 2: Write your code here:\n",
|
| 62 |
+
"df.head()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 3: Write your code here:\n",
|
| 72 |
+
"df.info()"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 4: Write your code here:\n",
|
| 82 |
+
"df.describe()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [],
|
| 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(f\"Shape before cleaning: {df.shape}\")\n",
|
| 100 |
+
"df[df.columns] = df[df.columns].fillna(0)\n",
|
| 101 |
+
"# Drop rows with missing stat values\n",
|
| 102 |
+
"print(f\"Shape after cleaning: {df.shape}\")"
|
| 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 |
+
"\n",
|
| 113 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 114 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 115 |
+
"if duplicate_rows > 0:\n",
|
| 116 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 117 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 118 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 119 |
+
"else:\n",
|
| 120 |
+
" print(\"No duplicate rows found.\")"
|
| 121 |
+
],
|
| 122 |
+
"execution_count": null,
|
| 123 |
+
"outputs": []
|
| 124 |
+
},
|
| 125 |
+
{
|
| 126 |
+
"cell_type": "code",
|
| 127 |
+
"metadata": {},
|
| 128 |
+
"source": [
|
| 129 |
+
"# no catagoerical"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"\n",
|
| 139 |
+
"print(\"Separating target variable and features...\")\n",
|
| 140 |
+
"X = df.drop('Target', axis=1)\n",
|
| 141 |
+
"y = df['Target']\n"
|
| 142 |
+
],
|
| 143 |
+
"execution_count": null,
|
| 144 |
+
"outputs": []
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"cell_type": "code",
|
| 148 |
+
"metadata": {},
|
| 149 |
+
"source": [
|
| 150 |
+
"\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"print(\"Splitting data into training and testing sets...\")\n",
|
| 153 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"print(\"Data split successful.\")\n",
|
| 156 |
+
"print(f\"Shape of X_train: {X_train.shape}\")\n",
|
| 157 |
+
"print(f\"Shape of X_test: {X_test.shape}\")\n",
|
| 158 |
+
"print(f\"Shape of y_train: {y_train.shape}\")\n",
|
| 159 |
+
"print(f\"Shape of y_test: {y_test.shape}\")\n",
|
| 160 |
+
"\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"df.head()"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"# Fill missing type2\n",
|
| 179 |
+
"for i in df.columns:\n",
|
| 180 |
+
" df[i] = df[i].fillna('none')\n"
|
| 181 |
+
],
|
| 182 |
+
"execution_count": null,
|
| 183 |
+
"outputs": []
|
| 184 |
+
},
|
| 185 |
+
{
|
| 186 |
+
"cell_type": "code",
|
| 187 |
+
"metadata": {},
|
| 188 |
+
"source": [
|
| 189 |
+
"# Fill missing type2\n",
|
| 190 |
+
"for i in df.columns:\n",
|
| 191 |
+
" le = LabelEncoder()\n",
|
| 192 |
+
" df[i] = le.fit_transform(df[i])"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"df.head()"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [],
|
| 210 |
+
"execution_count": null,
|
| 211 |
+
"outputs": []
|
| 212 |
+
},
|
| 213 |
+
{
|
| 214 |
+
"cell_type": "code",
|
| 215 |
+
"metadata": {},
|
| 216 |
+
"source": [
|
| 217 |
+
"# Task 5: Write your code here:\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"plt.figure(figsize=(6, 4))\n",
|
| 221 |
+
"sns.countplot(data=df, x='Target')\n",
|
| 222 |
+
"plt.title('Distribution of Target Variable (Class)')\n",
|
| 223 |
+
"plt.xlabel('Class')\n",
|
| 224 |
+
"plt.ylabel('Count')\n",
|
| 225 |
+
"plt.show()"
|
| 226 |
+
],
|
| 227 |
+
"execution_count": null,
|
| 228 |
+
"outputs": []
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"# DATA IS IMBALANCED"
|
| 235 |
+
],
|
| 236 |
+
"execution_count": null,
|
| 237 |
+
"outputs": []
|
| 238 |
+
},
|
| 239 |
+
{
|
| 240 |
+
"cell_type": "code",
|
| 241 |
+
"metadata": {},
|
| 242 |
+
"source": [
|
| 243 |
+
"# Task 1: Write your code here:\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"print(\"Separating target variable and features...\")\n",
|
| 246 |
+
"X = df.drop('Target', axis=1)\n",
|
| 247 |
+
"y = df['Target']"
|
| 248 |
+
],
|
| 249 |
+
"execution_count": null,
|
| 250 |
+
"outputs": []
|
| 251 |
+
},
|
| 252 |
+
{
|
| 253 |
+
"cell_type": "code",
|
| 254 |
+
"metadata": {},
|
| 255 |
+
"source": [
|
| 256 |
+
"\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"from IPython.display import clear_output\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"clear_output()\n",
|
| 263 |
+
"\n"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"from catboost import CatBoostClassifier"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"from tqdm import tqdm"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"source": [
|
| 290 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# sigmoid in NumPy\n",
|
| 294 |
+
"def sigmoid(z):\n",
|
| 295 |
+
" return 1 / (1 + np.exp(-z))\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"\n",
|
| 298 |
+
"# BCE in NumPy\n",
|
| 299 |
+
"def binary_cross_entropy(y, y_hat):\n",
|
| 300 |
+
" epsilon = 1e-15 # Very small number to prevent log(0)\n",
|
| 301 |
+
" y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
|
| 302 |
+
"\n",
|
| 303 |
+
" loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
|
| 304 |
+
" return loss\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 308 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 309 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 310 |
+
" losses = []\n",
|
| 311 |
+
"\n",
|
| 312 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
|
| 313 |
+
" z = np.dot(X, theta)\n",
|
| 314 |
+
" y_hat = sigmoid(z)\n",
|
| 315 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 316 |
+
" theta -= learning_rate * gradient\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" loss = binary_cross_entropy(y, y_hat)\n",
|
| 319 |
+
" losses.append(loss)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" return theta, losses\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 325 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 331 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"\n",
|
| 334 |
+
"# Storage for logistic regression results for each fold\n",
|
| 335 |
+
"lr_losses = []\n",
|
| 336 |
+
"lr_accuracy = []\n",
|
| 337 |
+
"lr_precision = []\n",
|
| 338 |
+
"lr_recall = []\n",
|
| 339 |
+
"lr_f1 = []\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 343 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 344 |
+
"\n",
|
| 345 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 346 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 347 |
+
"\n",
|
| 348 |
+
" # Train\n",
|
| 349 |
+
" theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
" # Validate\n",
|
| 352 |
+
" y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
|
| 353 |
+
" y_pred = (y_pred_proba >= 0.5).astype(int)\n",
|
| 354 |
+
"\n",
|
| 355 |
+
" # Calculate evaluation metrics\n",
|
| 356 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 357 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" # Store results\n",
|
| 360 |
+
" lr_losses.append(losses)\n",
|
| 361 |
+
" lr_accuracy.append(accuracy)\n",
|
| 362 |
+
" lr_f1.append(f1)\n",
|
| 363 |
+
"\n"
|
| 364 |
+
],
|
| 365 |
+
"execution_count": null,
|
| 366 |
+
"outputs": []
|
| 367 |
+
},
|
| 368 |
+
{
|
| 369 |
+
"cell_type": "code",
|
| 370 |
+
"metadata": {},
|
| 371 |
+
"source": [
|
| 372 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
|
| 373 |
+
],
|
| 374 |
+
"execution_count": null,
|
| 375 |
+
"outputs": []
|
| 376 |
+
},
|
| 377 |
+
{
|
| 378 |
+
"cell_type": "code",
|
| 379 |
+
"metadata": {},
|
| 380 |
+
"source": [
|
| 381 |
+
"\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 384 |
+
"from sklearn.svm import SVR\n",
|
| 385 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 386 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 387 |
+
"from lightgbm import LGBMRegressor\n",
|
| 388 |
+
"from catboost import CatBoostRegressor\n",
|
| 389 |
+
"\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"models = {\n",
|
| 392 |
+
" \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
|
| 393 |
+
" \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
|
| 394 |
+
"}\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"\n",
|
| 397 |
+
"# Storage for results\n",
|
| 398 |
+
"all_results = {}\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"for name in models:\n",
|
| 401 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 402 |
+
"\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 407 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 408 |
+
"\n",
|
| 409 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 410 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 411 |
+
"\n",
|
| 412 |
+
" for model_name, model in models.items():\n",
|
| 413 |
+
" print(f\"Training {model_name}...\")\n",
|
| 414 |
+
"\n",
|
| 415 |
+
" # Train\n",
|
| 416 |
+
" model.fit(X_train, y_train)\n",
|
| 417 |
+
"\n",
|
| 418 |
+
" # Predict\n",
|
| 419 |
+
" y_pred = model.predict(X_test)\n",
|
| 420 |
+
"\n",
|
| 421 |
+
" # Calculate metrics\n",
|
| 422 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 423 |
+
" rmse = np.sqrt(mse)\n",
|
| 424 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 425 |
+
"\n",
|
| 426 |
+
" # Store results\n",
|
| 427 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 428 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 429 |
+
" all_results[model_name][\"r2\"].append(r2)\n",
|
| 430 |
+
"\n"
|
| 431 |
+
],
|
| 432 |
+
"execution_count": null,
|
| 433 |
+
"outputs": []
|
| 434 |
+
},
|
| 435 |
+
{
|
| 436 |
+
"cell_type": "code",
|
| 437 |
+
"metadata": {},
|
| 438 |
+
"source": [
|
| 439 |
+
"average_losses = np.mean(lr_losses, axis=0)\n",
|
| 440 |
+
"\n",
|
| 441 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 442 |
+
"plt.plot(average_losses, label='Average Loss')\n",
|
| 443 |
+
"plt.xlabel('Iteration')\n",
|
| 444 |
+
"plt.ylabel('MSE Loss')\n",
|
| 445 |
+
"plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
|
| 446 |
+
"plt.legend()\n",
|
| 447 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 448 |
+
"plt.show()"
|
| 449 |
+
],
|
| 450 |
+
"execution_count": null,
|
| 451 |
+
"outputs": []
|
| 452 |
+
},
|
| 453 |
+
{
|
| 454 |
+
"cell_type": "code",
|
| 455 |
+
"metadata": {},
|
| 456 |
+
"source": [
|
| 457 |
+
"# Task 2: Write your code here:\n",
|
| 458 |
+
"\n",
|
| 459 |
+
"\n",
|
| 460 |
+
"coeffs = {}\n",
|
| 461 |
+
"\n",
|
| 462 |
+
"coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
|
| 463 |
+
"coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
|
| 464 |
+
"\n",
|
| 465 |
+
"fig, axes = plt.subplots(1, 2, figsize=(150, 60))\n",
|
| 466 |
+
"axes = axes.flatten()\n",
|
| 467 |
+
"features = X.columns\n",
|
| 468 |
+
"\n",
|
| 469 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 470 |
+
" # Sort features by absolute coefficient value\n",
|
| 471 |
+
" absolute_coef = np.abs(coef)\n",
|
| 472 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 473 |
+
"\n",
|
| 474 |
+
" ax = axes[i]\n",
|
| 475 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 476 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 477 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 478 |
+
"\n",
|
| 479 |
+
"plt.tight_layout()\n",
|
| 480 |
+
"plt.show()\n",
|
| 481 |
+
"\n"
|
| 482 |
+
],
|
| 483 |
+
"execution_count": null,
|
| 484 |
+
"outputs": []
|
| 485 |
+
},
|
| 486 |
+
{
|
| 487 |
+
"cell_type": "code",
|
| 488 |
+
"metadata": {},
|
| 489 |
+
"source": [
|
| 490 |
+
"# Task Bonus: Write your code here:\n",
|
| 491 |
+
"\n",
|
| 492 |
+
"goldenX = df['D_42']\n",
|
| 493 |
+
"goldeny = df['Target']\n",
|
| 494 |
+
"\n",
|
| 495 |
+
"\n",
|
| 496 |
+
"\n",
|
| 497 |
+
"# sigmoid in NumPy\n",
|
| 498 |
+
"def sigmoid(z):\n",
|
| 499 |
+
" return 1 / (1 + np.exp(-z))\n",
|
| 500 |
+
"\n",
|
| 501 |
+
"\n",
|
| 502 |
+
"# BCE in NumPy\n",
|
| 503 |
+
"def binary_cross_entropy(y, y_hat):\n",
|
| 504 |
+
" epsilon = 1e-15 # Very small number to prevent log(0)\n",
|
| 505 |
+
" y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
|
| 506 |
+
"\n",
|
| 507 |
+
" loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
|
| 508 |
+
" return loss\n",
|
| 509 |
+
"\n",
|
| 510 |
+
"\n",
|
| 511 |
+
"def gradient_descent(X, y, learning_rate, n_iters=500):\n",
|
| 512 |
+
" m, n = X.shape # m rows, n columns (dimensions)\n",
|
| 513 |
+
" theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
|
| 514 |
+
" losses = []\n",
|
| 515 |
+
"\n",
|
| 516 |
+
" for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
|
| 517 |
+
" z = np.dot(X, theta)\n",
|
| 518 |
+
" y_hat = sigmoid(z)\n",
|
| 519 |
+
" gradient = np.dot(X.T, (y_hat - y)) / m\n",
|
| 520 |
+
" theta -= learning_rate * gradient\n",
|
| 521 |
+
"\n",
|
| 522 |
+
" loss = binary_cross_entropy(y, y_hat)\n",
|
| 523 |
+
" losses.append(loss)\n",
|
| 524 |
+
"\n",
|
| 525 |
+
" return theta, losses\n",
|
| 526 |
+
"\n",
|
| 527 |
+
"\n",
|
| 528 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 529 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 530 |
+
"\n",
|
| 531 |
+
"\n",
|
| 532 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 533 |
+
"\n",
|
| 534 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 535 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 536 |
+
"\n",
|
| 537 |
+
"\n",
|
| 538 |
+
"# Storage for logistic regression results for each fold\n",
|
| 539 |
+
"lr_losses = []\n",
|
| 540 |
+
"lr_accuracy = []\n",
|
| 541 |
+
"lr_precision = []\n",
|
| 542 |
+
"lr_recall = []\n",
|
| 543 |
+
"lr_f1 = []\n",
|
| 544 |
+
"\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(goldenX, goldeny)):\n",
|
| 547 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 548 |
+
"\n",
|
| 549 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 550 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 551 |
+
"\n",
|
| 552 |
+
" # Train\n",
|
| 553 |
+
" theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
|
| 554 |
+
"\n",
|
| 555 |
+
" # Validate\n",
|
| 556 |
+
" y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
|
| 557 |
+
" y_pred = (y_pred_proba >= 0.5).astype(int)\n",
|
| 558 |
+
"\n",
|
| 559 |
+
" # Calculate evaluation metrics\n",
|
| 560 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 561 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 562 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 563 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 564 |
+
"\n",
|
| 565 |
+
" # Store results\n",
|
| 566 |
+
" lr_losses.append(losses)\n",
|
| 567 |
+
" lr_accuracy.append(accuracy)\n",
|
| 568 |
+
" lr_precision.append(precision)\n",
|
| 569 |
+
" lr_recall.append(recall)\n",
|
| 570 |
+
" lr_f1.append(f1)\n",
|
| 571 |
+
"\n"
|
| 572 |
+
],
|
| 573 |
+
"execution_count": null,
|
| 574 |
+
"outputs": []
|
| 575 |
+
},
|
| 576 |
+
{
|
| 577 |
+
"cell_type": "code",
|
| 578 |
+
"metadata": {},
|
| 579 |
+
"source": [
|
| 580 |
+
"average_losses = np.mean(lr_losses, axis=0)\n",
|
| 581 |
+
"\n",
|
| 582 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 583 |
+
"plt.plot(average_losses, label='Average Loss')\n",
|
| 584 |
+
"plt.xlabel('Iteration')\n",
|
| 585 |
+
"plt.ylabel('MSE Loss')\n",
|
| 586 |
+
"plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
|
| 587 |
+
"plt.legend()\n",
|
| 588 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 589 |
+
"plt.show()"
|
| 590 |
+
],
|
| 591 |
+
"execution_count": null,
|
| 592 |
+
"outputs": []
|
| 593 |
+
}
|
| 594 |
+
],
|
| 595 |
+
"metadata": {
|
| 596 |
+
"kernelspec": {
|
| 597 |
+
"display_name": "Python 3",
|
| 598 |
+
"name": "python3"
|
| 599 |
+
},
|
| 600 |
+
"language_info": {
|
| 601 |
+
"name": "python"
|
| 602 |
+
}
|
| 603 |
+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.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,OneHotEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 20 |
+
"from sklearn.svm import SVR\n",
|
| 21 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 22 |
+
"from sklearn.ensemble import RandomForestRegressor\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 |
+
"# Download latest version\n",
|
| 34 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"print(\"Path to dataset files:\", 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 |
+
"df = pd.read_csv(path + \"/Q1_data.csv\")\n"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 2: Write your code here:\n",
|
| 56 |
+
"df.head()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 3: Write your code here:\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"df.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 86 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 87 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 88 |
+
"plt.xlabel('Delivery Time')\n",
|
| 89 |
+
"plt.ylabel('Frequency')\n",
|
| 90 |
+
"plt.show()"
|
| 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(columns='Order_ID')"
|
| 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 |
+
"\n",
|
| 111 |
+
"for col in df.columns:\n",
|
| 112 |
+
" df[col]=df[col].fillna('unknown')\n",
|
| 113 |
+
"\n"
|
| 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)"
|
| 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 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 144 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"for col in categorical_cols:\n",
|
| 147 |
+
" le = LabelEncoder()\n",
|
| 148 |
+
" df[col] = le.fit_transform(df[col].astype(str))\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"\n"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 5: Write your code here:\n",
|
| 160 |
+
"features = df.columns.drop(\"Delivery_Time\")\n",
|
| 161 |
+
"scaler = StandardScaler()\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"df[features]=scaler.fit_transform(df[features])\n"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# Task 6: Write your code here:\n"
|
| 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 |
+
"\n",
|
| 183 |
+
"X = df.drop(\"Delivery_Time\", axis=1)\n",
|
| 184 |
+
"y = df['Delivery_Time']"
|
| 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 |
+
"model_results = {}\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"models = {\n",
|
| 198 |
+
" \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
|
| 199 |
+
" \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
|
| 200 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n",
|
| 201 |
+
"}\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"for name in models:\n",
|
| 204 |
+
" model_results[name] = {'mae': []}\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 208 |
+
"for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
|
| 209 |
+
" # indexing for each fold\n",
|
| 210 |
+
" X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
|
| 211 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 212 |
+
" for model_name, model in models.items():\n",
|
| 213 |
+
" print(f\"Training {model_name}...\")\n",
|
| 214 |
+
" model.fit(X_train, y_train)\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" y_pred = model.predict(X_test)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # Calculate metrics\n",
|
| 219 |
+
" mae=mean_absolute_error(y_test, y_pred)\n",
|
| 220 |
+
" model_results[model_name][\"mae\"].append(mae)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"for model_name in model_results:\n",
|
| 224 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 225 |
+
" print(f\" MAE: {np.mean(model_results[model_name]['mae']):.4f}\")"
|
| 226 |
+
],
|
| 227 |
+
"execution_count": null,
|
| 228 |
+
"outputs": []
|
| 229 |
+
},
|
| 230 |
+
{
|
| 231 |
+
"cell_type": "code",
|
| 232 |
+
"metadata": {},
|
| 233 |
+
"source": [
|
| 234 |
+
"coeffs = {}\n",
|
| 235 |
+
"\n",
|
| 236 |
+
"coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
|
| 237 |
+
"coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
|
| 240 |
+
"axes = axes.flatten()\n",
|
| 241 |
+
"features = X.columns\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"for i, (model_name, coef) in enumerate(coeffs.items()):\n",
|
| 244 |
+
" # Sort features by absolute coefficient value\n",
|
| 245 |
+
" absolute_coef = np.abs(coef)\n",
|
| 246 |
+
" sorted_idx = np.argsort(absolute_coef)\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" ax = axes[i]\n",
|
| 249 |
+
" ax.barh(features[sorted_idx], coef[sorted_idx])\n",
|
| 250 |
+
" ax.set_title(f\"{model_name} Coefficients\")\n",
|
| 251 |
+
" ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"plt.tight_layout()\n",
|
| 254 |
+
"plt.show()\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 259 |
+
"plt.hist(y_pred, bins=30, edgecolor='black')\n",
|
| 260 |
+
"plt.title('Predicted Delivery Time Histogram')\n",
|
| 261 |
+
"plt.xlabel('Predicted Delivery Time')\n",
|
| 262 |
+
"plt.ylabel('Frequency')\n",
|
| 263 |
+
"plt.show()"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"# Task 2: Write your code here:"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task Bonus: Write your code here:"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
}
|
| 286 |
+
],
|
| 287 |
+
"metadata": {
|
| 288 |
+
"kernelspec": {
|
| 289 |
+
"display_name": "Python 3",
|
| 290 |
+
"name": "python3"
|
| 291 |
+
},
|
| 292 |
+
"language_info": {
|
| 293 |
+
"name": "python"
|
| 294 |
+
}
|
| 295 |
+
},
|
| 296 |
+
"nbformat": 4,
|
| 297 |
+
"nbformat_minor": 0
|
| 298 |
+
}
|
submissions_extracted/579/Q2.ipynb
ADDED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import pandas as pd\n",
|
| 8 |
+
"import torch\n",
|
| 9 |
+
"import torch.nn as nn\n",
|
| 10 |
+
"from torch.optim import AdamW\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import torch.nn.functional as F\n",
|
| 13 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 14 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder"
|
| 16 |
+
],
|
| 17 |
+
"execution_count": null,
|
| 18 |
+
"outputs": []
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"cell_type": "code",
|
| 22 |
+
"metadata": {},
|
| 23 |
+
"source": [
|
| 24 |
+
"import kagglehub\n",
|
| 25 |
+
"\n",
|
| 26 |
+
"# Download latest version\n",
|
| 27 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"print(\"Path to dataset files:\", path)"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"import os\n",
|
| 39 |
+
"import pandas as pd\n",
|
| 40 |
+
"import numpy as np\n",
|
| 41 |
+
"from PIL import Image\n",
|
| 42 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 43 |
+
"\n",
|
| 44 |
+
"# Load Labels\n",
|
| 45 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 46 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 47 |
+
"\n",
|
| 48 |
+
"images = []\n",
|
| 49 |
+
"ages = []\n",
|
| 50 |
+
"\n",
|
| 51 |
+
"# Load Images and Resize\n",
|
| 52 |
+
"print(\"Loading images...\")\n",
|
| 53 |
+
"for index, row in labels_df.iterrows():\n",
|
| 54 |
+
" img_name = row.iloc[0]\n",
|
| 55 |
+
" age = row.iloc[1]\n",
|
| 56 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 57 |
+
"\n",
|
| 58 |
+
" if os.path.exists(img_path):\n",
|
| 59 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 60 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 61 |
+
" images.append(img_array)\n",
|
| 62 |
+
" ages.append(age)\n",
|
| 63 |
+
"\n",
|
| 64 |
+
"X = np.array(images)\n",
|
| 65 |
+
"y = np.array(ages)\n",
|
| 66 |
+
"\n",
|
| 67 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 68 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"# Split Data\n",
|
| 71 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 74 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 75 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 76 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 86 |
+
"\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 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 2. Create TensorDataset objects\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 103 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# 3. Create DataLoaders\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 115 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 116 |
+
"\n"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# 4. Print shape of one batch\n",
|
| 126 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# 5. Display sample images\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"mages, 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 |
+
"\n",
|
| 147 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 148 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
" plt.imshow(img)\n",
|
| 151 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 152 |
+
" plt.axis('off')\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"plt.tight_layout()\n",
|
| 155 |
+
"plt.show()"
|
| 156 |
+
],
|
| 157 |
+
"execution_count": null,
|
| 158 |
+
"outputs": []
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"cell_type": "code",
|
| 162 |
+
"metadata": {},
|
| 163 |
+
"source": [
|
| 164 |
+
"# Task 1: Write your model class here:\n",
|
| 165 |
+
"class NN4Layer(nn.Module):\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 168 |
+
" super(NN4Layer, self).__init__()\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\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:\n",
|
| 184 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Layer 2\n",
|
| 187 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Layer 3 TODO\n",
|
| 190 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" output = self.relu(a3)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # TODO: are we missing output activation function? (hint: Loss Function)\n",
|
| 196 |
+
"\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 |
+
"\n",
|
| 211 |
+
" running_loss = 0.0\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 214 |
+
" # Move batch to the selected device\n",
|
| 215 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 216 |
+
" y_batch = y_batch.to(device)\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 220 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Backward pass & optimization\n",
|
| 223 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 224 |
+
" loss.backward() # Compute gradients\n",
|
| 225 |
+
" optimizer.step() # Update model parameters\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" running_loss += loss.item()\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Average loss over all batches\n",
|
| 230 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" return avg_loss"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task 3: Write your validation loop here:\n",
|
| 242 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 243 |
+
" # Set the model to evaluation mode\n",
|
| 244 |
+
" model.eval()\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" running_loss = 0.0\n",
|
| 247 |
+
"\n",
|
| 248 |
+
" with torch.no_grad():\n",
|
| 249 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 250 |
+
" # Move data to device\n",
|
| 251 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
|
| 252 |
+
" y_batch = y_batch.to(device) # shape: (batch_size, 1)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
" # Forward pass (continuous output)\n",
|
| 255 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 256 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" running_loss += loss.item()\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" # Average loss over all batches\n",
|
| 261 |
+
" avg_loss = running_loss / len(test_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 4: Define device, model, loss, optimizer:\n",
|
| 273 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 274 |
+
"# Model parameters\n",
|
| 275 |
+
"input_dim = 3*36*36 # Number of tabular features\n",
|
| 276 |
+
"hidden_dim = 64 # Design choice\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Instantiate regression model\n",
|
| 279 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
"# Print the model architecture\n",
|
| 282 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 283 |
+
"print(model)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# Calculate the total number of trainable parameters\n",
|
| 286 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 287 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 297 |
+
"# Hyperparameters (feel free to experiment!)\n",
|
| 298 |
+
"num_epochs = 20\n",
|
| 299 |
+
"learning_rate = 0.001\n",
|
| 300 |
+
"# Define criterion (loss function)\n",
|
| 301 |
+
"criterion = nn.MSELoss()\n",
|
| 302 |
+
"# Define optimizer\n",
|
| 303 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 304 |
+
"# Run Training\n",
|
| 305 |
+
"train_losses = []\n",
|
| 306 |
+
"val_losses = []\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print('Starting Training...')\n",
|
| 309 |
+
"for epoch in range(num_epochs):\n",
|
| 310 |
+
" # Train one epoch\n",
|
| 311 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" # Validate\n",
|
| 314 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" train_losses.append(train_loss)\n",
|
| 317 |
+
" val_losses.append(val_loss)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 320 |
+
" print(\n",
|
| 321 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 322 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 323 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 324 |
+
" )\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:"
|
| 336 |
+
],
|
| 337 |
+
"execution_count": null,
|
| 338 |
+
"outputs": []
|
| 339 |
+
},
|
| 340 |
+
{
|
| 341 |
+
"cell_type": "code",
|
| 342 |
+
"metadata": {},
|
| 343 |
+
"source": [
|
| 344 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 345 |
+
],
|
| 346 |
+
"execution_count": null,
|
| 347 |
+
"outputs": []
|
| 348 |
+
}
|
| 349 |
+
],
|
| 350 |
+
"metadata": {
|
| 351 |
+
"kernelspec": {
|
| 352 |
+
"display_name": "Python 3",
|
| 353 |
+
"name": "python3"
|
| 354 |
+
},
|
| 355 |
+
"language_info": {
|
| 356 |
+
"name": "python"
|
| 357 |
+
}
|
| 358 |
+
},
|
| 359 |
+
"nbformat": 4,
|
| 360 |
+
"nbformat_minor": 0
|
| 361 |
+
}
|
submissions_extracted/579/Q3.ipyn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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,OneHotEncoder\n",
|
| 15 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"from sklearn.linear_model import Ridge, Lasso\n",
|
| 20 |
+
"from sklearn.svm import SVR\n",
|
| 21 |
+
"from sklearn.tree import DecisionTreeRegressor\n",
|
| 22 |
+
"from sklearn.ensemble import RandomForestRegressor\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 |
+
"\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"# Download latest version\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 38 |
+
"\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"\n",
|
| 41 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 42 |
+
"df = pd.read_csv(path + \"/Q3_data.csv\")"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 1: Write your code here:\n",
|
| 52 |
+
"df = pd.read_csv(path + \"/Q3_data.csv\")\n"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 2: Write your code here:\n",
|
| 62 |
+
"df.head()\n"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 3: Write your code here:\n",
|
| 72 |
+
"df.info()\n"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 4: Write your code here:\n",
|
| 82 |
+
"df.describe()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 1: Write your code here:\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"for col in df.columns:\n",
|
| 94 |
+
" df[col]=df[col].fillna('unknown')"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# Task 2: Write your code here:\n",
|
| 104 |
+
"# Task 3: Write your code here:\n",
|
| 105 |
+
"def check_duplicates(df):\n",
|
| 106 |
+
" duplicates = df.duplicated().sum()\n",
|
| 107 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 108 |
+
" if duplicates > 0:\n",
|
| 109 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 110 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 111 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 112 |
+
" else:\n",
|
| 113 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"check_duplicates(df)"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 3: Write your code here:\n",
|
| 125 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 126 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"for col in categorical_cols:\n",
|
| 129 |
+
" le = LabelEncoder()\n",
|
| 130 |
+
" df[col] = le.fit_transform(df[col].astype(str))"
|
| 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 |
+
"features = df.columns.drop(\"Target\")\n",
|
| 141 |
+
"scaler = StandardScaler()\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"df[features]=scaler.fit_transform(df[features])"
|
| 144 |
+
],
|
| 145 |
+
"execution_count": null,
|
| 146 |
+
"outputs": []
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"cell_type": "code",
|
| 150 |
+
"metadata": {},
|
| 151 |
+
"source": [],
|
| 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,3,4,5: Write your code here:"
|
| 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/58/Q1.ipynb
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
| 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\n",
|
| 19 |
+
"warnings.filterwarnings('ignore')\n",
|
| 20 |
+
"import kagglehub\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"# Download latest version\n",
|
| 23 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"print(\"Path to dataset files:\", path)"
|
| 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 |
+
"Q1_path =os.path.join(path, 'Q1_data.csv')\n",
|
| 36 |
+
"df_Q1 = pd.read_csv(Q1_path)\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"print(f\"Shape: {df_Q1.shape}\")\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 |
+
"\n",
|
| 49 |
+
"df_Q1.head()"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 3: Write your code here:\n",
|
| 59 |
+
"df_Q1.info()"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# Task 4: Write your code here:\n",
|
| 69 |
+
"df_Q1.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 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 80 |
+
"plt.hist(df_Q1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 81 |
+
"plt.title('delivery_time Distribution')\n",
|
| 82 |
+
"plt.xlabel('x')\n",
|
| 83 |
+
"plt.ylabel('Frequency')\n",
|
| 84 |
+
"plt.show()"
|
| 85 |
+
],
|
| 86 |
+
"execution_count": null,
|
| 87 |
+
"outputs": []
|
| 88 |
+
},
|
| 89 |
+
{
|
| 90 |
+
"cell_type": "code",
|
| 91 |
+
"metadata": {},
|
| 92 |
+
"source": [
|
| 93 |
+
"# Task 1: Write your code here:\n",
|
| 94 |
+
"Drop_set = ['Order_ID']\n",
|
| 95 |
+
"df_clean = df_Q1.drop(columns=Drop_set).copy()\n",
|
| 96 |
+
"print(f\"Shape after cleaning: {df_clean.shape}\")"
|
| 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(df):\n",
|
| 107 |
+
" missing_values = df.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(df_clean)"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 3: Write your code here:\n",
|
| 125 |
+
"def check_duplicates(df):\n",
|
| 126 |
+
" duplicates = df.duplicated().sum()\n",
|
| 127 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 128 |
+
" if duplicates > 0:\n",
|
| 129 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 130 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 131 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 132 |
+
" else:\n",
|
| 133 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"check_duplicates(df_clean)"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 4: Write your code here:\n",
|
| 145 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 146 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"le = LabelEncoder()\n",
|
| 151 |
+
"df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 5: Write your code here:\n",
|
| 167 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"features = df_clean.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"scaler = StandardScaler()\n",
|
| 172 |
+
"df_clean[features] = scaler.fit_transform(df_clean[features])\n",
|
| 173 |
+
"df_clean.head()"
|
| 174 |
+
],
|
| 175 |
+
"execution_count": null,
|
| 176 |
+
"outputs": []
|
| 177 |
+
},
|
| 178 |
+
{
|
| 179 |
+
"cell_type": "code",
|
| 180 |
+
"metadata": {},
|
| 181 |
+
"source": [
|
| 182 |
+
"# Task 6: Write your code here:"
|
| 183 |
+
],
|
| 184 |
+
"execution_count": null,
|
| 185 |
+
"outputs": []
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"cell_type": "code",
|
| 189 |
+
"metadata": {},
|
| 190 |
+
"source": [
|
| 191 |
+
"# Task 1: Write your code here:\n",
|
| 192 |
+
"X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 193 |
+
"y = df_clean['Delivery_Time'].astype(float)"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 203 |
+
"from sklearn.model_selection import KFold\n",
|
| 204 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 205 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"models = {\n",
|
| 208 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 209 |
+
"}\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"all_results = {}\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"for name in models:\n",
|
| 215 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 221 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 222 |
+
"\n",
|
| 223 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 224 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" for model_name, model in models.items():\n",
|
| 227 |
+
" print(f\"Training {model_name}...\")\n",
|
| 228 |
+
"\n",
|
| 229 |
+
" # Train\n",
|
| 230 |
+
" model.fit(X_train, y_train)\n",
|
| 231 |
+
"\n",
|
| 232 |
+
" # Predict\n",
|
| 233 |
+
" y_pred = model.predict(X_test)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Calculate metrics\n",
|
| 236 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 237 |
+
" rmse = np.sqrt(mse)\n",
|
| 238 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Store results\n",
|
| 241 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 242 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 243 |
+
" all_results[model_name][\"r2\"].append(r2)"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"# Task 1: Write your code here:"
|
| 253 |
+
],
|
| 254 |
+
"execution_count": null,
|
| 255 |
+
"outputs": []
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"metadata": {},
|
| 260 |
+
"source": [
|
| 261 |
+
"# Task 2: Write your code here:"
|
| 262 |
+
],
|
| 263 |
+
"execution_count": null,
|
| 264 |
+
"outputs": []
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"cell_type": "code",
|
| 268 |
+
"metadata": {},
|
| 269 |
+
"source": [
|
| 270 |
+
"# Task Bonus: Write your code here:"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
}
|
| 275 |
+
],
|
| 276 |
+
"metadata": {
|
| 277 |
+
"kernelspec": {
|
| 278 |
+
"display_name": "Python 3",
|
| 279 |
+
"name": "python3"
|
| 280 |
+
},
|
| 281 |
+
"language_info": {
|
| 282 |
+
"name": "python"
|
| 283 |
+
}
|
| 284 |
+
},
|
| 285 |
+
"nbformat": 4,
|
| 286 |
+
"nbformat_minor": 0
|
| 287 |
+
}
|
submissions_extracted/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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.optim import AdamW\n",
|
| 71 |
+
"import matplotlib.pyplot as plt\n",
|
| 72 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 73 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 74 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 84 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 85 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 86 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 87 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# 2. Create TensorDataset objects\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 99 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 100 |
+
"\n",
|
| 101 |
+
"X_train.shape\n",
|
| 102 |
+
"\n",
|
| 103 |
+
"\n"
|
| 104 |
+
],
|
| 105 |
+
"execution_count": null,
|
| 106 |
+
"outputs": []
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"cell_type": "code",
|
| 110 |
+
"metadata": {},
|
| 111 |
+
"source": [
|
| 112 |
+
"# 3. Create DataLoaders\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 115 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# 4. Print shape of one batch\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 127 |
+
"print(\"Test dataset:\", len(test_dataset))"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# 5. Display sample images\n",
|
| 137 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 138 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 139 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# Task 1: Write your model class here:\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"class NN4Layer(nn.Module):\n",
|
| 151 |
+
"\n",
|
| 152 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 153 |
+
" super(NN4Layer, self).__init__()\n",
|
| 154 |
+
"\n",
|
| 155 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 156 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 159 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 162 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 163 |
+
"\n",
|
| 164 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 165 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" # ReLU activation for non-linearity\n",
|
| 168 |
+
" self.relu = nn.ReLU()\n",
|
| 169 |
+
"\n",
|
| 170 |
+
" # Defines how input data flows through the network\n",
|
| 171 |
+
" def forward(self, x):\n",
|
| 172 |
+
" # First hidden layer\n",
|
| 173 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" # Second hidden layer\n",
|
| 176 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" # Third hidden layer\n",
|
| 179 |
+
" a3 = self.relu(self.layer3(a2))\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" # Output layer (raw scores / logits)\n",
|
| 182 |
+
" output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" return output\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 2: Write your training loop here:\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 196 |
+
" # Set the model to training mode\n",
|
| 197 |
+
" model.train()\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" running_loss = 0.0\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 202 |
+
" # Move batch to the selected device\n",
|
| 203 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 204 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" # Forward pass (outputs are logits)\n",
|
| 207 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 208 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" # Backward pass & optimization\n",
|
| 211 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 212 |
+
" loss.backward() # Compute gradients\n",
|
| 213 |
+
" optimizer.step() # Update model parameters\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" running_loss += loss.item()\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Average loss over all batches\n",
|
| 218 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" return avg_loss\n"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 3: Write your validation loop here:\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 232 |
+
" # Set the model to evaluation mode\n",
|
| 233 |
+
" model.eval()\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" running_loss = 0.0\n",
|
| 236 |
+
" correct = 0\n",
|
| 237 |
+
" total = 0\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" with torch.no_grad():\n",
|
| 240 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 241 |
+
" # Move data to device\n",
|
| 242 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 243 |
+
" y_batch = y_batch.to(device) # shape: (batch_size,)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" # Forward pass\n",
|
| 246 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
|
| 247 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 248 |
+
" running_loss += loss.item()\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" # Apply Softmax to get probabilities\n",
|
| 251 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" # Pick the classes with highest probabilities\n",
|
| 254 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" # Accuracy calculation\n",
|
| 257 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 258 |
+
" total += y_batch.size(0)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 261 |
+
" accuracy = correct / total\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" return avg_loss, accuracy"
|
| 264 |
+
],
|
| 265 |
+
"execution_count": null,
|
| 266 |
+
"outputs": []
|
| 267 |
+
},
|
| 268 |
+
{
|
| 269 |
+
"cell_type": "code",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# Device setup\n",
|
| 275 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"# Model parameters\n",
|
| 278 |
+
"input_dim = 3 *36* 36 # Number of tabular features\n",
|
| 279 |
+
"hidden_dim = 14 # Design choice\n",
|
| 280 |
+
"output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
|
| 281 |
+
"\n",
|
| 282 |
+
"# Instantiate model\n",
|
| 283 |
+
"model = NN4Layer(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}\")\n"
|
| 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 |
+
"\n",
|
| 309 |
+
"# Run Training\n",
|
| 310 |
+
"train_losses = []\n",
|
| 311 |
+
"val_losses = []\n",
|
| 312 |
+
"val_accuracies = []\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"print('Starting Training...')\n",
|
| 315 |
+
"for epoch in range(num_epochs):\n",
|
| 316 |
+
" # Train one epoch\n",
|
| 317 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
" # Validate\n",
|
| 320 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 321 |
+
"\n",
|
| 322 |
+
" train_losses.append(train_loss)\n",
|
| 323 |
+
" val_losses.append(val_loss)\n",
|
| 324 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\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/58/Q3.ipynb
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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[
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import pandas as pd\n",
|
| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import torch\n",
|
| 11 |
+
"import torch.nn as nn\n",
|
| 12 |
+
"from torch.optim import AdamW\n",
|
| 13 |
+
"import matplotlib.pyplot as plt\n",
|
| 14 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 15 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 16 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 17 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"\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 |
+
"\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 |
+
"df = pd.read_csv(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(df):\n",
|
| 79 |
+
"\n",
|
| 80 |
+
" # Get missing values using pandas\n",
|
| 81 |
+
" missing_values = df.isnull().sum()\n",
|
| 82 |
+
"\n",
|
| 83 |
+
" print(\"Missing Values per Column:\")\n",
|
| 84 |
+
" print(missing_values[missing_values > 0])\n",
|
| 85 |
+
"\n",
|
| 86 |
+
" if missing_values.any():\n",
|
| 87 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 88 |
+
" df.dropna(inplace=True)\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 |
+
"def check_duplicates(df):\n",
|
| 103 |
+
"\n",
|
| 104 |
+
" #TODO: get duplicated data using pandas\n",
|
| 105 |
+
" duplicates = df.duplicated().sum()\n",
|
| 106 |
+
"\n",
|
| 107 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 108 |
+
" if duplicates > 0:\n",
|
| 109 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 110 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 111 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 112 |
+
" else:\n",
|
| 113 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"check_duplicates(df)"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 3: Write your code here:\n",
|
| 125 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 4: Write your code here:\n",
|
| 137 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"# Pick only the numerical columns, NOT the target\n",
|
| 140 |
+
"numerical_cols = df.select_dtypes(include=[\"number\"]).columns\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"scaler = StandardScaler()\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# scale the `numerical_cols`\n",
|
| 145 |
+
"df = scaler.fit_transform(df)\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"df.head()"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 5: Write your code here:"
|
| 157 |
+
],
|
| 158 |
+
"execution_count": null,
|
| 159 |
+
"outputs": []
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"cell_type": "code",
|
| 163 |
+
"metadata": {},
|
| 164 |
+
"source": [
|
| 165 |
+
"# Task 1: Write your code here:"
|
| 166 |
+
],
|
| 167 |
+
"execution_count": null,
|
| 168 |
+
"outputs": []
|
| 169 |
+
},
|
| 170 |
+
{
|
| 171 |
+
"cell_type": "code",
|
| 172 |
+
"metadata": {},
|
| 173 |
+
"source": [
|
| 174 |
+
"# Task 2,3,4,5: Write your code here:"
|
| 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 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"# Importing all required libraries\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"
|
| 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 |
+
"# reading the dataset\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"df = pd.read_csv(csv_path)"
|
| 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 |
+
"# inspecting the first few rows\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"df.head()"
|
| 55 |
+
],
|
| 56 |
+
"execution_count": null,
|
| 57 |
+
"outputs": []
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "code",
|
| 61 |
+
"metadata": {},
|
| 62 |
+
"source": [
|
| 63 |
+
"# Task 3: Write your code here:\n",
|
| 64 |
+
"# viewing the dataset information\n",
|
| 65 |
+
"\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"# Show statistical description using describe()\n",
|
| 77 |
+
"\n",
|
| 78 |
+
"df.describe()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 5: Write your code here:\n",
|
| 88 |
+
"# Plot the target distribution (delivery_time)\n",
|
| 89 |
+
"\n",
|
| 90 |
+
"def check_target_distribution(df, target_column):\n",
|
| 91 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 92 |
+
"\n",
|
| 93 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 94 |
+
" plt.xlabel(target_column)\n",
|
| 95 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 96 |
+
" plt.grid(False)\n",
|
| 97 |
+
"\n",
|
| 98 |
+
" plt.show()\n",
|
| 99 |
+
"\n",
|
| 100 |
+
"check_target_distribution(df, \"Delivery_Time\")"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"# Task 1: Write your code here:\n",
|
| 110 |
+
"# drop the order ID column from the data\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"df = df.drop(columns = \"Order_ID\", axis = 1)\n",
|
| 113 |
+
"df.head()"
|
| 114 |
+
],
|
| 115 |
+
"execution_count": null,
|
| 116 |
+
"outputs": []
|
| 117 |
+
},
|
| 118 |
+
{
|
| 119 |
+
"cell_type": "code",
|
| 120 |
+
"metadata": {},
|
| 121 |
+
"source": [
|
| 122 |
+
"# Task 2: Write your code here:\n",
|
| 123 |
+
"# check for missing values in the dataset\n",
|
| 124 |
+
"def check_missing_values(df):\n",
|
| 125 |
+
" missing_values = df.isnull().sum()\n",
|
| 126 |
+
" print(\"Missing Values per Column:\")\n",
|
| 127 |
+
" print(missing_values[missing_values > 0])\n",
|
| 128 |
+
" if missing_values.any():\n",
|
| 129 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 130 |
+
" else:\n",
|
| 131 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 132 |
+
"\n",
|
| 133 |
+
"check_missing_values(df)\n",
|
| 134 |
+
"\n",
|
| 135 |
+
"# handle if any\n",
|
| 136 |
+
"# drop the samples with missing delivery time\n",
|
| 137 |
+
"df = df.dropna(subset = \"Delivery_Time\")\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"# check again\n",
|
| 140 |
+
"check_missing_values(df)\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 143 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 144 |
+
" df[col] = df[col].fillna('unknown')\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"# Fill courier experience years with mode - discrete feature, mode is most representative\n",
|
| 147 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"check_missing_values(df)\n"
|
| 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 |
+
"# check for duplicates and remove them\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 |
+
"check_duplicates(df)"
|
| 171 |
+
],
|
| 172 |
+
"execution_count": null,
|
| 173 |
+
"outputs": []
|
| 174 |
+
},
|
| 175 |
+
{
|
| 176 |
+
"cell_type": "code",
|
| 177 |
+
"metadata": {},
|
| 178 |
+
"source": [
|
| 179 |
+
"# Task 4: Write your code here:\n",
|
| 180 |
+
"# encode catrgorical variables\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 183 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# check and print the categorical columns\n",
|
| 186 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 189 |
+
"\n",
|
| 190 |
+
"# use one hot encoding\n",
|
| 191 |
+
"for col in categorical_cols:\n",
|
| 192 |
+
" le = LabelEncoder()\n",
|
| 193 |
+
" df[col] = le.fit_transform(df[col].astype(str))\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # onehot_encoder = OneHotEncoder(sparse_output=False)\n",
|
| 196 |
+
" # df[col] = onehot_encoder.fit_transform(df[col].astype(str))\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"df.head()"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"# Task 5: Write your code here:\n",
|
| 209 |
+
"# Apply feature scaling for all features\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
|
| 212 |
+
"\n",
|
| 213 |
+
"scaler = StandardScaler() # Instantiate StandardScaler\n",
|
| 214 |
+
"features = df.columns.drop(\"Delivery_Time\") # remove the target\n",
|
| 215 |
+
"df[features] = scaler.fit_transform(df[features])\n",
|
| 216 |
+
"df.head()"
|
| 217 |
+
],
|
| 218 |
+
"execution_count": null,
|
| 219 |
+
"outputs": []
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"cell_type": "code",
|
| 223 |
+
"metadata": {},
|
| 224 |
+
"source": [
|
| 225 |
+
"# Task 6: Write your code here:\n",
|
| 226 |
+
"# Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 227 |
+
"# not needed"
|
| 228 |
+
],
|
| 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 |
+
"# splittind dataset into X and y\n",
|
| 238 |
+
"\n",
|
| 239 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 240 |
+
"y = df[\"Delivery_Time\"].astype(float)\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"print(X.shape)\n",
|
| 243 |
+
"y.shape"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"# importing the needed libraries\n",
|
| 253 |
+
"from sklearn.model_selection import KFold\n",
|
| 254 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 255 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"# splitting data by KFold\n",
|
| 260 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"# train a RandomForest Model\n",
|
| 263 |
+
"model = RandomForestRegressor(n_estimators=200)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"mae_list = []\n",
|
| 266 |
+
"\n",
|
| 267 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 268 |
+
" print(f\"\\nFold {fold_idx + 1}/5\")\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 |
+
" model.fit(X_train, y_train)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" # Predict\n",
|
| 277 |
+
" y_pred = model.predict(X_test)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" # Calculate metrics\n",
|
| 280 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 281 |
+
"\n",
|
| 282 |
+
" print(mae)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" # Store results\n",
|
| 285 |
+
" mae_list.append(mae)\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"# print the averages score across all folds"
|
| 289 |
+
],
|
| 290 |
+
"execution_count": null,
|
| 291 |
+
"outputs": []
|
| 292 |
+
},
|
| 293 |
+
{
|
| 294 |
+
"cell_type": "code",
|
| 295 |
+
"metadata": {},
|
| 296 |
+
"source": [
|
| 297 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 298 |
+
"importances = {}\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"importances = model.feature_importances_\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"# Create a 1x3 plot\n",
|
| 303 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 304 |
+
"axes = axes.flatten()\n",
|
| 305 |
+
"features = X.columns\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 308 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 309 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" ax = axes[i]\n",
|
| 312 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 313 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 314 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"plt.tight_layout()\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 |
+
"# Task 5: Write your code here:\n",
|
| 328 |
+
"# Plot the target distribution (delivery_time)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"def check_target_distribution(df, target_column):\n",
|
| 331 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 334 |
+
" plt.xlabel(target_column)\n",
|
| 335 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 336 |
+
" plt.grid(False)\n",
|
| 337 |
+
"\n",
|
| 338 |
+
" plt.show()\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"y_pred = model.predict(X_test)\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"check_target_distribution(df, y_pred)\n"
|
| 343 |
+
],
|
| 344 |
+
"execution_count": null,
|
| 345 |
+
"outputs": []
|
| 346 |
+
},
|
| 347 |
+
{
|
| 348 |
+
"cell_type": "code",
|
| 349 |
+
"metadata": {},
|
| 350 |
+
"source": [
|
| 351 |
+
"# Task Bonus: Write your code here:"
|
| 352 |
+
],
|
| 353 |
+
"execution_count": null,
|
| 354 |
+
"outputs": []
|
| 355 |
+
}
|
| 356 |
+
],
|
| 357 |
+
"metadata": {
|
| 358 |
+
"kernelspec": {
|
| 359 |
+
"display_name": "Python 3",
|
| 360 |
+
"name": "python3"
|
| 361 |
+
},
|
| 362 |
+
"language_info": {
|
| 363 |
+
"name": "python"
|
| 364 |
+
}
|
| 365 |
+
},
|
| 366 |
+
"nbformat": 4,
|
| 367 |
+
"nbformat_minor": 0
|
| 368 |
+
}
|
submissions_extracted/580/Q2.ipynb
ADDED
|
@@ -0,0 +1,418 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"# Download latest version\n",
|
| 10 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
|
| 11 |
+
"\n",
|
| 12 |
+
"print(\"Path to dataset files:\", path)"
|
| 13 |
+
],
|
| 14 |
+
"execution_count": null,
|
| 15 |
+
"outputs": []
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"cell_type": "code",
|
| 19 |
+
"metadata": {},
|
| 20 |
+
"source": [
|
| 21 |
+
"import os\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"from PIL import Image\n",
|
| 25 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 26 |
+
"\n",
|
| 27 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import torch\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"X_train = torch.tensor(X_train.flatten(start_dim=1), dtype=torch.float32)\n",
|
| 73 |
+
"X_test = torch.tensor(X_test.flatten(start_dim=1), dtype=torch.float32)\n",
|
| 74 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 75 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 76 |
+
],
|
| 77 |
+
"execution_count": null,
|
| 78 |
+
"outputs": []
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"cell_type": "code",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"source": [
|
| 84 |
+
"# 2. Create TensorDataset objects\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"from torch.utils.data import TensorDataset\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
|
| 89 |
+
"# Each item in the dataset is returned as (X[i], y[i])\n",
|
| 90 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 91 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 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 |
+
"# DataLoader for training data\n",
|
| 104 |
+
"train_loader = DataLoader(\n",
|
| 105 |
+
" train_dataset,\n",
|
| 106 |
+
" batch_size=32,\n",
|
| 107 |
+
" shuffle=True,\n",
|
| 108 |
+
" num_workers=2\n",
|
| 109 |
+
")\n",
|
| 110 |
+
"# DataLoader for test/validation data\n",
|
| 111 |
+
"test_loader = DataLoader(\n",
|
| 112 |
+
" test_dataset,\n",
|
| 113 |
+
" batch_size=32,\n",
|
| 114 |
+
" shuffle=False,\n",
|
| 115 |
+
" num_workers=2\n",
|
| 116 |
+
")"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# 4. Print shape of one batch\n",
|
| 126 |
+
"# Get the first batch from the training DataLoader\n",
|
| 127 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 128 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 129 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 130 |
+
],
|
| 131 |
+
"execution_count": null,
|
| 132 |
+
"outputs": []
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"cell_type": "code",
|
| 136 |
+
"metadata": {},
|
| 137 |
+
"source": [
|
| 138 |
+
"# 5. Display sample images\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"import matplotlib.pyplot as plt\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"# Get one batch of images and labels\n",
|
| 143 |
+
"images, labels = next(iter(train_loader))\n",
|
| 144 |
+
"\n",
|
| 145 |
+
"# Display the first 6 images in the batch\n",
|
| 146 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"for i in range(6):\n",
|
| 149 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 150 |
+
"\n",
|
| 151 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 152 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 153 |
+
"\n",
|
| 154 |
+
" plt.imshow(img)\n",
|
| 155 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 156 |
+
" plt.axis('off')\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"plt.tight_layout()\n",
|
| 159 |
+
"plt.show()"
|
| 160 |
+
],
|
| 161 |
+
"execution_count": null,
|
| 162 |
+
"outputs": []
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"cell_type": "code",
|
| 166 |
+
"metadata": {},
|
| 167 |
+
"source": [
|
| 168 |
+
"# Task 1: Write your model class here:\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"import torch.nn as nn\n",
|
| 171 |
+
"import torch.nn.functional as F\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"class NN4Layer(nn.Module):\n",
|
| 174 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 175 |
+
" super(NN4Layer, self).__init__()\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 178 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 181 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # Third linear layer: hidden layer -> hidden layer\n",
|
| 184 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # Output layer: hidden layer -> single continuous value\n",
|
| 187 |
+
" self.layer3 = nn.Linear(hidden_dim, 1)\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # ReLU activation for non-linearity in hidden layers\n",
|
| 190 |
+
" self.relu = nn.ReLU()\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" # Defines how input data flows through the network\n",
|
| 193 |
+
" def forward(self, x):\n",
|
| 194 |
+
" # First hidden layer\n",
|
| 195 |
+
" a1 = self.relu(self.layer1(x))\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Second hidden layer\n",
|
| 198 |
+
" a2 = self.relu(self.layer2(a1))\n",
|
| 199 |
+
"\n",
|
| 200 |
+
" # Third hidden layer\n",
|
| 201 |
+
" a3 = self.relu(self.layer2(a2))\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" # Output layer (regression output)\n",
|
| 204 |
+
" output = self.layer3(a3)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" return output"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"# Task 2: Write your training loop here:\n",
|
| 216 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 217 |
+
" # Set the model to training mode\n",
|
| 218 |
+
" model.train()\n",
|
| 219 |
+
"\n",
|
| 220 |
+
" running_loss = 0.0\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 223 |
+
" # Move batch to the selected device\n",
|
| 224 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 225 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Forward pass (continuous output)\n",
|
| 228 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 229 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Backward pass & optimization\n",
|
| 232 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 233 |
+
" loss.backward() # Compute gradients\n",
|
| 234 |
+
" optimizer.step() # Update model parameters\n",
|
| 235 |
+
"\n",
|
| 236 |
+
" running_loss += loss.item()\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" # Average loss over all batches\n",
|
| 239 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" return avg_loss"
|
| 242 |
+
],
|
| 243 |
+
"execution_count": null,
|
| 244 |
+
"outputs": []
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"cell_type": "code",
|
| 248 |
+
"metadata": {},
|
| 249 |
+
"source": [
|
| 250 |
+
"# Task 3: Write your validation loop here:\n",
|
| 251 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 252 |
+
" # Set the model to evaluation mode\n",
|
| 253 |
+
" model.eval()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" running_loss = 0.0\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" with torch.no_grad():\n",
|
| 258 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 259 |
+
" # Move data to device\n",
|
| 260 |
+
" X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
|
| 261 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 262 |
+
"\n",
|
| 263 |
+
" # Forward pass (continuous output)\n",
|
| 264 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 265 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" running_loss += loss.item()\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" # Average loss over all batches\n",
|
| 270 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" return avg_loss"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 282 |
+
"# Device setup\n",
|
| 283 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# Model parameters\n",
|
| 286 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 287 |
+
"hidden_dim = 64 # Design choice\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"# Instantiate regression model\n",
|
| 290 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"# Print the model architecture\n",
|
| 293 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 294 |
+
"print(model)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Calculate the total number of trainable parameters\n",
|
| 297 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 298 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\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 |
+
"\n",
|
| 309 |
+
"from torch.optim import AdamW\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"num_epochs = 20\n",
|
| 312 |
+
"learning_rate = 0.001\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"# Define criterion (loss function)\n",
|
| 315 |
+
"criterion = nn.MSELoss()\n",
|
| 316 |
+
"# Define optimizer\n",
|
| 317 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"# Run Training\n",
|
| 320 |
+
"train_losses = []\n",
|
| 321 |
+
"val_losses = []\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 = validate(model, criterion, test_loader, device)\n",
|
| 330 |
+
"\n",
|
| 331 |
+
" train_losses.append(train_loss)\n",
|
| 332 |
+
" val_losses.append(val_loss)\n",
|
| 333 |
+
"\n",
|
| 334 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 335 |
+
" print(\n",
|
| 336 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 337 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 338 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 339 |
+
" )\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"print('Training Complete!')\n"
|
| 342 |
+
],
|
| 343 |
+
"execution_count": null,
|
| 344 |
+
"outputs": []
|
| 345 |
+
},
|
| 346 |
+
{
|
| 347 |
+
"cell_type": "code",
|
| 348 |
+
"metadata": {},
|
| 349 |
+
"source": [
|
| 350 |
+
"# Task 1: Write your code here:\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"# Plotting results\n",
|
| 353 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 354 |
+
"\n",
|
| 355 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 356 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 357 |
+
"plt.title('Loss over Epochs')\n",
|
| 358 |
+
"plt.xlabel('Epoch')\n",
|
| 359 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 360 |
+
"plt.legend()\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"plt.tight_layout()\n",
|
| 363 |
+
"plt.show()"
|
| 364 |
+
],
|
| 365 |
+
"execution_count": null,
|
| 366 |
+
"outputs": []
|
| 367 |
+
},
|
| 368 |
+
{
|
| 369 |
+
"cell_type": "code",
|
| 370 |
+
"metadata": {},
|
| 371 |
+
"source": [
|
| 372 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"# Set model to evaluation mode\n",
|
| 375 |
+
"model.eval()\n",
|
| 376 |
+
"# Get one batch from the test DataLoader\n",
|
| 377 |
+
"images, labels = next(iter(test_loader))\n",
|
| 378 |
+
"# Move images to device\n",
|
| 379 |
+
"images = images.to(device)\n",
|
| 380 |
+
"labels = labels.to(device)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
"with torch.no_grad():\n",
|
| 383 |
+
" # Flatten images before passing to the model\n",
|
| 384 |
+
" outputs = model(images.view(images.size(0), -1))\n",
|
| 385 |
+
" predictions = torch.argmax(outputs, dim=1)\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"# Move tensors back to CPU for plotting\n",
|
| 388 |
+
"images = images.cpu()\n",
|
| 389 |
+
"labels = labels.cpu()\n",
|
| 390 |
+
"predictions = predictions.cpu()\n",
|
| 391 |
+
"\n",
|
| 392 |
+
"# Plot first 6 predictions\n",
|
| 393 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 394 |
+
"for i in range(6):\n",
|
| 395 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 396 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 397 |
+
" plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
|
| 398 |
+
" plt.axis('off')\n",
|
| 399 |
+
"\n",
|
| 400 |
+
"plt.tight_layout()\n",
|
| 401 |
+
"plt.show()"
|
| 402 |
+
],
|
| 403 |
+
"execution_count": null,
|
| 404 |
+
"outputs": []
|
| 405 |
+
}
|
| 406 |
+
],
|
| 407 |
+
"metadata": {
|
| 408 |
+
"kernelspec": {
|
| 409 |
+
"display_name": "Python 3",
|
| 410 |
+
"name": "python3"
|
| 411 |
+
},
|
| 412 |
+
"language_info": {
|
| 413 |
+
"name": "python"
|
| 414 |
+
}
|
| 415 |
+
},
|
| 416 |
+
"nbformat": 4,
|
| 417 |
+
"nbformat_minor": 0
|
| 418 |
+
}
|
submissions_extracted/580/Q3.ipynb
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\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 |
+
"\n",
|
| 30 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"df = pd.read_csv(csv_path)\n"
|
| 33 |
+
],
|
| 34 |
+
"execution_count": null,
|
| 35 |
+
"outputs": []
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"source": [
|
| 41 |
+
"# Task 2: Write your code here:\n",
|
| 42 |
+
"df.head()"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 3: Write your code here:\n",
|
| 52 |
+
"df.info()"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 4: Write your code here:\n",
|
| 62 |
+
"df.describe()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 1: Write your code here:\n",
|
| 72 |
+
"def check_missing_values(df):\n",
|
| 73 |
+
" missing_values = df.isnull().sum()\n",
|
| 74 |
+
" print(\"Missing Values per Column:\")\n",
|
| 75 |
+
" print(missing_values[missing_values > 0])\n",
|
| 76 |
+
" if missing_values.any():\n",
|
| 77 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 78 |
+
" df[missing_values].fillna(df[missing_values].mean())\n",
|
| 79 |
+
" else:\n",
|
| 80 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"check_missing_values(df)"
|
| 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 |
+
"def check_duplicates(df):\n",
|
| 93 |
+
" duplicates = df.duplicated().sum()\n",
|
| 94 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 95 |
+
" if duplicates > 0:\n",
|
| 96 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 97 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 98 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 99 |
+
" else:\n",
|
| 100 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"check_duplicates(df)"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 3: Write your code here:\n",
|
| 112 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"print(\"Categorical Columns:\", list(categorical_cols))"
|
| 115 |
+
],
|
| 116 |
+
"execution_count": null,
|
| 117 |
+
"outputs": []
|
| 118 |
+
},
|
| 119 |
+
{
|
| 120 |
+
"cell_type": "code",
|
| 121 |
+
"metadata": {},
|
| 122 |
+
"source": [
|
| 123 |
+
"# Task 4: Write your code here:\n",
|
| 124 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"scaler = StandardScaler()\n",
|
| 129 |
+
"df[features] = scaler.fit_transform(df[features])\n",
|
| 130 |
+
"df.head()"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 5: Write your code here:\n",
|
| 140 |
+
"import matplotlib.pyplot as plt\n",
|
| 141 |
+
"import seaborn as sns\n",
|
| 142 |
+
"# 1. Is the target imbalanced?\n",
|
| 143 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 144 |
+
" print(\"Target Distribution:\")\n",
|
| 145 |
+
" print(df[target_column].value_counts(normalize=True))\n",
|
| 146 |
+
" sns.countplot(x=df[target_column])\n",
|
| 147 |
+
" plt.title(\"Target Distribution\")\n",
|
| 148 |
+
" plt.show()\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"check_target_imbalance(df, \"Target\")"
|
| 151 |
+
],
|
| 152 |
+
"execution_count": null,
|
| 153 |
+
"outputs": []
|
| 154 |
+
},
|
| 155 |
+
{
|
| 156 |
+
"cell_type": "code",
|
| 157 |
+
"metadata": {},
|
| 158 |
+
"source": [
|
| 159 |
+
"# Task 1: Write your code here:\n",
|
| 160 |
+
"X = df.drop(\"Target\", axis=1).astype(float)\n",
|
| 161 |
+
"y = df['Target'].astype(float)"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 171 |
+
"%pip install catboost\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 174 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 175 |
+
"from catboost import CatBoostClassifier\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"n_splits = 5 # K=5 Folds\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 |
+
"model = CatBoostClassifier(\n",
|
| 183 |
+
" verbose=0,\n",
|
| 184 |
+
" n_estimators=320,\n",
|
| 185 |
+
" max_depth=4\n",
|
| 186 |
+
" )\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"accuracyList = []\n",
|
| 189 |
+
"F1List = []\n",
|
| 190 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 191 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" # 1. Split data\n",
|
| 194 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 195 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # 2. Train & Validate sklearn models\n",
|
| 198 |
+
" model.fit(X_train, y_train) # train\n",
|
| 199 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 202 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 203 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" accuracyList.append(accuracy)\n",
|
| 206 |
+
" F1List.append(f1)\n"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 215 |
+
"df.shape"
|
| 216 |
+
],
|
| 217 |
+
"execution_count": null,
|
| 218 |
+
"outputs": []
|
| 219 |
+
},
|
| 220 |
+
{
|
| 221 |
+
"cell_type": "code",
|
| 222 |
+
"metadata": {},
|
| 223 |
+
"source": [
|
| 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()"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 2: Write your code here:"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task Bonus: Write your code here:"
|
| 265 |
+
],
|
| 266 |
+
"execution_count": null,
|
| 267 |
+
"outputs": []
|
| 268 |
+
}
|
| 269 |
+
],
|
| 270 |
+
"metadata": {
|
| 271 |
+
"kernelspec": {
|
| 272 |
+
"display_name": "Python 3",
|
| 273 |
+
"name": "python3"
|
| 274 |
+
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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 |
+
"# we import the pandas library\n",
|
| 23 |
+
"import pandas as pd\n",
|
| 24 |
+
"#ٌfirst we Load CSV file and read csv file\n",
|
| 25 |
+
"df= pd.read_csv(f\"{path}/Q1_data.csv\")"
|
| 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 |
+
"#first we print the output for idteify the head data\n",
|
| 36 |
+
"print(\"\\nDataset Head\")\n",
|
| 37 |
+
"df.head()\n",
|
| 38 |
+
"\n"
|
| 39 |
+
],
|
| 40 |
+
"execution_count": null,
|
| 41 |
+
"outputs": []
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"cell_type": "code",
|
| 45 |
+
"metadata": {},
|
| 46 |
+
"source": [
|
| 47 |
+
"# Task 3: Write your code here:\n",
|
| 48 |
+
"#check information dataset using info()\n",
|
| 49 |
+
"df.info()\n"
|
| 50 |
+
],
|
| 51 |
+
"execution_count": null,
|
| 52 |
+
"outputs": []
|
| 53 |
+
},
|
| 54 |
+
{
|
| 55 |
+
"cell_type": "code",
|
| 56 |
+
"metadata": {},
|
| 57 |
+
"source": [
|
| 58 |
+
"# Task 4: Write your code here:\n",
|
| 59 |
+
"#i well descibe statistical description using describe()\n",
|
| 60 |
+
"df.describe()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 5: Write your code here:\n",
|
| 70 |
+
"import matplotlib.pyplot as plt\n",
|
| 71 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 72 |
+
"plt.title('Price Distribution')\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"plt.show()"
|
| 75 |
+
],
|
| 76 |
+
"execution_count": null,
|
| 77 |
+
"outputs": []
|
| 78 |
+
},
|
| 79 |
+
{
|
| 80 |
+
"cell_type": "code",
|
| 81 |
+
"metadata": {},
|
| 82 |
+
"source": [
|
| 83 |
+
"# Task 1: Write your code here:\n",
|
| 84 |
+
"#drop entire column has name Order_ID\n",
|
| 85 |
+
"df.drop(columns=['Order_ID'])"
|
| 86 |
+
],
|
| 87 |
+
"execution_count": null,
|
| 88 |
+
"outputs": []
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"metadata": {},
|
| 93 |
+
"source": [
|
| 94 |
+
"# Task 2: Write your code here:\n",
|
| 95 |
+
"def check_missing_values(df):\n",
|
| 96 |
+
" missing_values = df.isnull().sum()\n",
|
| 97 |
+
" print(\"Missing Values per Column:\")\n",
|
| 98 |
+
" print(missing_values[missing_values > 0])\n",
|
| 99 |
+
" if missing_values.any():\n",
|
| 100 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 101 |
+
" else:\n",
|
| 102 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"check_missing_values(df)"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 3: Write your code here:\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"#first we need function for check duplicates\n",
|
| 116 |
+
"def check_duplicates(df):\n",
|
| 117 |
+
" #put in the data frame with sum\n",
|
| 118 |
+
" duplicates = df.duplicated().sum()\n",
|
| 119 |
+
" #print the number of Duplicate sample\n",
|
| 120 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 121 |
+
" #check duplicates more than 1 then we need to removed\n",
|
| 122 |
+
" if duplicates > 0:\n",
|
| 123 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 124 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 125 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 126 |
+
" #else we print No Duplicate Samples Found.\n",
|
| 127 |
+
" else:\n",
|
| 128 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 129 |
+
"#if thers duplicates then we print the data frame\n",
|
| 130 |
+
"check_duplicates(df)"
|
| 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 |
+
"#first we need to know about datatype of colimns\n",
|
| 141 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 142 |
+
"#import the LabelEncoder from sklearn.preprocessing to using in code\n",
|
| 143 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 144 |
+
"#empty dict\n",
|
| 145 |
+
"label_encoders = {}\n",
|
| 146 |
+
"#loop to know the wehere we encoder\n",
|
| 147 |
+
"for col in categorical_cols:\n",
|
| 148 |
+
" le = LabelEncoder()\n",
|
| 149 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 150 |
+
" label_encoders[col] = le\n",
|
| 151 |
+
"#output for data frame\n",
|
| 152 |
+
"df\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 5: Write your code here:\n",
|
| 162 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 163 |
+
"\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"#numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])# DON'T SCALE THE TARGET\n",
|
| 166 |
+
"categorical_cols = df.select_dtypes(include=[\"int64\",\"float64\"]).columns\n",
|
| 167 |
+
"scaler = StandardScaler()\n",
|
| 168 |
+
"df[categorical_cols] = scaler.fit_transform(df[categorical_cols])\n",
|
| 169 |
+
"df.head()"
|
| 170 |
+
],
|
| 171 |
+
"execution_count": null,
|
| 172 |
+
"outputs": []
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"cell_type": "code",
|
| 176 |
+
"metadata": {},
|
| 177 |
+
"source": [
|
| 178 |
+
"\n",
|
| 179 |
+
"# Task 6: Write your code here:\n",
|
| 180 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 181 |
+
" print(\"Target Distribution:\")\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 184 |
+
" plt.show()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"check_target_imbalance(df, \"Weather\")"
|
| 187 |
+
],
|
| 188 |
+
"execution_count": null,
|
| 189 |
+
"outputs": []
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"cell_type": "code",
|
| 193 |
+
"metadata": {},
|
| 194 |
+
"source": [
|
| 195 |
+
"# Task 1: Write your code here:\n",
|
| 196 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 197 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 198 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 199 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 200 |
+
"df = load_breast_cancer()\n",
|
| 201 |
+
"X = df.data\n",
|
| 202 |
+
"y = df.target\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"# Split the dataset into training and testing sets\n",
|
| 205 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 206 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 207 |
+
"\n",
|
| 208 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 209 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 210 |
+
"models= {\"Random Forest\": RandomForestClassifier(\n",
|
| 211 |
+
" n_estimators=200,\n",
|
| 212 |
+
" max_depth=10\n",
|
| 213 |
+
" ),}"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 223 |
+
"# Split the dataset into training and testing sets\n",
|
| 224 |
+
"import numpy as np\n",
|
| 225 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 226 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 227 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 228 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 229 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 230 |
+
"models= {\"Random Forest\": RandomForestClassifier(\n",
|
| 231 |
+
" n_estimators=200,\n",
|
| 232 |
+
" max_depth=10\n",
|
| 233 |
+
" ),}\n",
|
| 234 |
+
"#mae = mean_absolute_error(X_test, y_train)\n",
|
| 235 |
+
"\n"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 244 |
+
"# Task 1: Write your code here:\n",
|
| 245 |
+
"feature_importance = pd.DataFrame({\n",
|
| 246 |
+
" 'feature': categorical_cols,\n",
|
| 247 |
+
" 'importance': model.feature_importances_\n",
|
| 248 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 251 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 252 |
+
"plt.xlabel('Importance')\n",
|
| 253 |
+
"plt.title('Feature Importance')\n",
|
| 254 |
+
"plt.gca().invert_yaxis()\n",
|
| 255 |
+
"plt.show()"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task 2: Write your code here:\n",
|
| 265 |
+
"y_test = np.argmax(y_train, axis=1)"
|
| 266 |
+
],
|
| 267 |
+
"execution_count": null,
|
| 268 |
+
"outputs": []
|
| 269 |
+
},
|
| 270 |
+
{
|
| 271 |
+
"cell_type": "code",
|
| 272 |
+
"metadata": {},
|
| 273 |
+
"source": [
|
| 274 |
+
"# Task Bonus: Write your code here:"
|
| 275 |
+
],
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"outputs": []
|
| 278 |
+
}
|
| 279 |
+
],
|
| 280 |
+
"metadata": {
|
| 281 |
+
"kernelspec": {
|
| 282 |
+
"display_name": "Python 3",
|
| 283 |
+
"name": "python3"
|
| 284 |
+
},
|
| 285 |
+
"language_info": {
|
| 286 |
+
"name": "python"
|
| 287 |
+
}
|
| 288 |
+
},
|
| 289 |
+
"nbformat": 4,
|
| 290 |
+
"nbformat_minor": 0
|
| 291 |
+
}
|
submissions_extracted/581/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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 |
+
"from torchvision.transforms import ToTensor, Compose, Normalize\n",
|
| 70 |
+
"from torchvision.datasets import MNIST\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"# Prepare data\n",
|
| 73 |
+
"train_dataset = MNIST(\n",
|
| 74 |
+
" root='./data',\n",
|
| 75 |
+
" train=True,\n",
|
| 76 |
+
" transform=ToTensor(),\n",
|
| 77 |
+
" download=True\n",
|
| 78 |
+
")\n",
|
| 79 |
+
"\n",
|
| 80 |
+
"test_dataset = MNIST(\n",
|
| 81 |
+
" root='./data',\n",
|
| 82 |
+
" train=False,\n",
|
| 83 |
+
" transform=ToTensor(),\n",
|
| 84 |
+
" download=True\n",
|
| 85 |
+
")\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 |
+
"\n",
|
| 97 |
+
"transform = transforms.Compose([\n",
|
| 98 |
+
" transform.Resize((224, 224)),\n",
|
| 99 |
+
" transform.ToTensor()\n",
|
| 100 |
+
"])\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"test_transform = transform.Compose([\n",
|
| 103 |
+
" transform.Resize((224, 224)),\n",
|
| 104 |
+
" transform.ToTensor()\n",
|
| 105 |
+
"])\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"# Create (instantiate) dataset objects\n",
|
| 109 |
+
"# THIS IS THE MAIN TASK YOU ARE REQUIRED TO PERFORM\n",
|
| 110 |
+
"train_dataset = (path, split='train', transform=transform)\n",
|
| 111 |
+
"valid_dataset = (path, split='val', transform=test_transform)\n",
|
| 112 |
+
"\n",
|
| 113 |
+
"\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"# Check a batch of images\n"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# 3. Create DataLoaders\n",
|
| 125 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
|
| 126 |
+
"valid_loader = DataLoader(valid_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"\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 |
+
"images, labels = next(iter(train_loader))\n",
|
| 139 |
+
"print(f\"Batch shape: {images.shape}, Labels: {labels}\")\n"
|
| 140 |
+
],
|
| 141 |
+
"execution_count": null,
|
| 142 |
+
"outputs": []
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"cell_type": "code",
|
| 146 |
+
"metadata": {},
|
| 147 |
+
"source": [
|
| 148 |
+
"# 5. Display sample images\n",
|
| 149 |
+
"# Get one batch of images and labels\n",
|
| 150 |
+
"images, labels = next(iter(train_loader))\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"# Display the first 6 images in the batch\n",
|
| 153 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"for i in range(6):\n",
|
| 156 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 159 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 160 |
+
"\n",
|
| 161 |
+
" plt.imshow(img)\n",
|
| 162 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 163 |
+
" plt.axis('off')\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"plt.tight_layout()\n",
|
| 166 |
+
"plt.show()\n"
|
| 167 |
+
],
|
| 168 |
+
"execution_count": null,
|
| 169 |
+
"outputs": []
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"cell_type": "code",
|
| 173 |
+
"metadata": {},
|
| 174 |
+
"source": [
|
| 175 |
+
"# Task 1: Write your model class here:\n"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task 2: Write your training loop here:"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# Task 3: Write your validation loop here:"
|
| 194 |
+
],
|
| 195 |
+
"execution_count": null,
|
| 196 |
+
"outputs": []
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
"cell_type": "code",
|
| 200 |
+
"metadata": {},
|
| 201 |
+
"source": [
|
| 202 |
+
"# Task 4: Define device, model, loss, optimizer:"
|
| 203 |
+
],
|
| 204 |
+
"execution_count": null,
|
| 205 |
+
"outputs": []
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"cell_type": "code",
|
| 209 |
+
"metadata": {},
|
| 210 |
+
"source": [
|
| 211 |
+
"# Task 5: Start training for 20 epochs:"
|
| 212 |
+
],
|
| 213 |
+
"execution_count": null,
|
| 214 |
+
"outputs": []
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"cell_type": "code",
|
| 218 |
+
"metadata": {},
|
| 219 |
+
"source": [
|
| 220 |
+
"# Task 1: Write your code here:"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
}
|
| 234 |
+
],
|
| 235 |
+
"metadata": {
|
| 236 |
+
"kernelspec": {
|
| 237 |
+
"display_name": "Python 3",
|
| 238 |
+
"name": "python3"
|
| 239 |
+
},
|
| 240 |
+
"language_info": {
|
| 241 |
+
"name": "python"
|
| 242 |
+
}
|
| 243 |
+
},
|
| 244 |
+
"nbformat": 4,
|
| 245 |
+
"nbformat_minor": 0
|
| 246 |
+
}
|
submissions_extracted/581/Q3.ipynb
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
"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 |
+
"# we import the pandas library\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"#ٌfirst we Load CSV file and read csv file\n",
|
| 30 |
+
"df= pd.read_csv(f\"{path}/Q3_data.csv\")"
|
| 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 |
+
"#first we print the output for idteify the head data\n",
|
| 41 |
+
"print(\"\\nDataset Head\")\n",
|
| 42 |
+
"df.head()\n"
|
| 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 |
+
"#check information dataset using info()\n",
|
| 53 |
+
"df.info()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 4: Write your code here:\n",
|
| 63 |
+
"#i well descibe statistical description using describe()\n",
|
| 64 |
+
"df.describe()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 1: Write your code here:\n",
|
| 74 |
+
"def check_missing_values(df):\n",
|
| 75 |
+
" missing_values = df.isnull().sum()\n",
|
| 76 |
+
" print(\"Missing Values per Column:\")\n",
|
| 77 |
+
" print(missing_values[missing_values > 0])\n",
|
| 78 |
+
" if missing_values.any():\n",
|
| 79 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 80 |
+
" else:\n",
|
| 81 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 82 |
+
"\n",
|
| 83 |
+
"check_missing_values(df)"
|
| 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 |
+
"\n",
|
| 94 |
+
"#first we need function for check duplicates\n",
|
| 95 |
+
"def check_duplicates(df):\n",
|
| 96 |
+
" #put in the data frame with sum\n",
|
| 97 |
+
" duplicates = df.duplicated().sum()\n",
|
| 98 |
+
" #print the number of Duplicate sample\n",
|
| 99 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 100 |
+
" #check duplicates more than 1 then we need to removed\n",
|
| 101 |
+
" if duplicates > 0:\n",
|
| 102 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 103 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 104 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 105 |
+
" #else we print No Duplicate Samples Found.\n",
|
| 106 |
+
" else:\n",
|
| 107 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 108 |
+
"#if thers duplicates then we print the data frame\n",
|
| 109 |
+
"check_duplicates(df)"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# Task 3: Write your code here:\n",
|
| 119 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 120 |
+
"#import the LabelEncoder from sklearn.preprocessing to using in code\n",
|
| 121 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 122 |
+
"#empty dict\n",
|
| 123 |
+
"label_encoders = {}\n",
|
| 124 |
+
"#loop to know the wehere we encoder\n",
|
| 125 |
+
"for col in categorical_cols:\n",
|
| 126 |
+
" le = LabelEncoder()\n",
|
| 127 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 128 |
+
" label_encoders[col] = le\n",
|
| 129 |
+
"#output for data frame\n",
|
| 130 |
+
"df"
|
| 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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 141 |
+
"\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"#numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])# DON'T SCALE THE TARGET\n",
|
| 144 |
+
"categorical_cols = df.select_dtypes(include=[\"int64\",\"float64\"]).columns\n",
|
| 145 |
+
"scaler = StandardScaler()\n",
|
| 146 |
+
"df[categorical_cols] = scaler.fit_transform(df[categorical_cols])\n",
|
| 147 |
+
"df.head()"
|
| 148 |
+
],
|
| 149 |
+
"execution_count": null,
|
| 150 |
+
"outputs": []
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"cell_type": "code",
|
| 154 |
+
"metadata": {},
|
| 155 |
+
"source": [
|
| 156 |
+
"# Task 5: Write your code here:\n",
|
| 157 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 158 |
+
"\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"#numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"])# DON'T SCALE THE TARGET\n",
|
| 161 |
+
"categorical_cols = df.select_dtypes(include=[\"int64\",\"float64\"]).columns\n",
|
| 162 |
+
"scaler = StandardScaler()\n",
|
| 163 |
+
"df[categorical_cols] = scaler.fit_transform(df[categorical_cols])\n",
|
| 164 |
+
"df.head()"
|
| 165 |
+
],
|
| 166 |
+
"execution_count": null,
|
| 167 |
+
"outputs": []
|
| 168 |
+
},
|
| 169 |
+
{
|
| 170 |
+
"cell_type": "code",
|
| 171 |
+
"metadata": {},
|
| 172 |
+
"source": [
|
| 173 |
+
"# Task 1: Write your code here:\n",
|
| 174 |
+
"from sklearn.datasets import load_breast_cancer\n",
|
| 175 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 176 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 177 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 178 |
+
"df = load_breast_cancer()\n",
|
| 179 |
+
"X = df.data\n",
|
| 180 |
+
"y = df.target\n",
|
| 181 |
+
"\n",
|
| 182 |
+
"# Split the dataset into training and testing sets\n",
|
| 183 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 184 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 185 |
+
"\n",
|
| 186 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 187 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 188 |
+
"models= {\"Random Forest\": RandomForestClassifier(\n",
|
| 189 |
+
" n_estimators=200,\n",
|
| 190 |
+
" max_depth=10\n",
|
| 191 |
+
" ),}"
|
| 192 |
+
],
|
| 193 |
+
"execution_count": null,
|
| 194 |
+
"outputs": []
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"cell_type": "code",
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"source": [
|
| 200 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 201 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 202 |
+
"# Split the dataset into training and testing sets\n",
|
| 203 |
+
"import numpy as np\n",
|
| 204 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 205 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 206 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 207 |
+
"# 5-Fold Cross-Validation, shuffled\n",
|
| 208 |
+
"kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 209 |
+
"models= {\"Random Forest\": RandomForestClassifier(\n",
|
| 210 |
+
" n_estimators=200,\n",
|
| 211 |
+
" max_depth=10\n",
|
| 212 |
+
" ),}\n",
|
| 213 |
+
"#mae = mean_absolute_error(X_test, y_train)"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 1: Write your code here:"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"# Task 2: Write your code here:"
|
| 232 |
+
],
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"outputs": []
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"cell_type": "code",
|
| 238 |
+
"metadata": {},
|
| 239 |
+
"source": [
|
| 240 |
+
"# Task Bonus: Write your code here:"
|
| 241 |
+
],
|
| 242 |
+
"execution_count": null,
|
| 243 |
+
"outputs": []
|
| 244 |
+
}
|
| 245 |
+
],
|
| 246 |
+
"metadata": {
|
| 247 |
+
"kernelspec": {
|
| 248 |
+
"display_name": "Python 3",
|
| 249 |
+
"name": "python3"
|
| 250 |
+
},
|
| 251 |
+
"language_info": {
|
| 252 |
+
"name": "python"
|
| 253 |
+
}
|
| 254 |
+
},
|
| 255 |
+
"nbformat": 4,
|
| 256 |
+
"nbformat_minor": 0
|
| 257 |
+
}
|
submissions_extracted/582/Q1.ipynb
ADDED
|
@@ -0,0 +1,400 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"#import libraries\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import numpy as np\n",
|
| 12 |
+
"import matplotlib.pyplot as plt\n",
|
| 13 |
+
"\n",
|
| 14 |
+
"from sklearn.model_selection import KFold\n",
|
| 15 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n",
|
| 16 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"import os\n",
|
| 22 |
+
"from sklearn.preprocessing import LabelEncoder, StandardScaler, OneHotEncoder\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"import warnings\n",
|
| 25 |
+
"warnings.filterwarnings('ignore')\n"
|
| 26 |
+
],
|
| 27 |
+
"execution_count": null,
|
| 28 |
+
"outputs": []
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"cell_type": "code",
|
| 32 |
+
"metadata": {},
|
| 33 |
+
"source": [
|
| 34 |
+
"import kagglehub\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# Download latest version\n",
|
| 37 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\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 |
+
"# Task 1: Write your code here:\n",
|
| 49 |
+
"import os\n",
|
| 50 |
+
"import pandas as pd\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"print(\"Path to dataset files:\", path)\n",
|
| 53 |
+
"\n",
|
| 54 |
+
"\n",
|
| 55 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 56 |
+
"\n",
|
| 57 |
+
"og_df = pd.read_csv(csv_path)\n",
|
| 58 |
+
"\n"
|
| 59 |
+
],
|
| 60 |
+
"execution_count": null,
|
| 61 |
+
"outputs": []
|
| 62 |
+
},
|
| 63 |
+
{
|
| 64 |
+
"cell_type": "code",
|
| 65 |
+
"metadata": {},
|
| 66 |
+
"source": [
|
| 67 |
+
"df = og_df.copy()"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 2: Write your code here:\n",
|
| 77 |
+
"df.head()"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# Task 3: Write your code here:\n",
|
| 87 |
+
"df.info()"
|
| 88 |
+
],
|
| 89 |
+
"execution_count": null,
|
| 90 |
+
"outputs": []
|
| 91 |
+
},
|
| 92 |
+
{
|
| 93 |
+
"cell_type": "code",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"source": [
|
| 96 |
+
"# Task 4: Write your code here:\n",
|
| 97 |
+
"df.describe()"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 5: Write your code here:\n",
|
| 107 |
+
"\n",
|
| 108 |
+
"def check_target_distribution(df, target_column):\n",
|
| 109 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 110 |
+
"\n",
|
| 111 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 112 |
+
" plt.xlabel(target_column)\n",
|
| 113 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 114 |
+
" plt.grid(False)\n",
|
| 115 |
+
"\n",
|
| 116 |
+
" plt.show()\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"\n"
|
| 119 |
+
],
|
| 120 |
+
"execution_count": null,
|
| 121 |
+
"outputs": []
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"cell_type": "code",
|
| 125 |
+
"metadata": {},
|
| 126 |
+
"source": [
|
| 127 |
+
"target_column = 'Delivery_Time'\n",
|
| 128 |
+
"check_target_distribution(df, target_column)"
|
| 129 |
+
],
|
| 130 |
+
"execution_count": null,
|
| 131 |
+
"outputs": []
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"cell_type": "code",
|
| 135 |
+
"metadata": {},
|
| 136 |
+
"source": [
|
| 137 |
+
"# Task 1: Write your code here:\n",
|
| 138 |
+
"df = df.drop(columns=['Order_ID'])"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 2: Write your code here:\n",
|
| 148 |
+
"df.isnull().sum()\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"# Droppin rows with missing target or missing important feature\n",
|
| 151 |
+
"df = df.dropna(subset=['Delivery_Time', 'Traffic_Level'])\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"# filling with mean because no outliers\n",
|
| 154 |
+
"df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"#filling with mode for categorical\n",
|
| 157 |
+
"df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
|
| 158 |
+
"df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# Task 3: Write your code here:\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"def check_duplicates(df):\n",
|
| 170 |
+
" duplicates = df.duplicated().sum()\n",
|
| 171 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 172 |
+
" if duplicates > 0:\n",
|
| 173 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 174 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 175 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 176 |
+
" else:\n",
|
| 177 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"check_duplicates(df)"
|
| 180 |
+
],
|
| 181 |
+
"execution_count": null,
|
| 182 |
+
"outputs": []
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"cell_type": "code",
|
| 186 |
+
"metadata": {},
|
| 187 |
+
"source": [
|
| 188 |
+
"# Task 4: Write your code here:\n",
|
| 189 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 190 |
+
"# Encode Categorical Features\n",
|
| 191 |
+
"encoder = LabelEncoder()\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"for col in df.select_dtypes(include=[\"object\"]).columns:\n",
|
| 194 |
+
" df[col] = encoder.fit_transform(df[col])\n",
|
| 195 |
+
"\n"
|
| 196 |
+
],
|
| 197 |
+
"execution_count": null,
|
| 198 |
+
"outputs": []
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"cell_type": "code",
|
| 202 |
+
"metadata": {},
|
| 203 |
+
"source": [
|
| 204 |
+
"# Task 5: Write your code here:\n",
|
| 205 |
+
"scaler = StandardScaler()\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"# We want to scale all the columns, BUT NOT THE TARGET\n",
|
| 208 |
+
"cols = df.columns.drop(\"Delivery_Time\")\n",
|
| 209 |
+
"\n",
|
| 210 |
+
"df[cols] = scaler.fit_transform(df[cols])"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"# Task 6: Write your code here:\n",
|
| 220 |
+
"# no need for balance checking because this is a regression"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 1: Write your code here:\n",
|
| 230 |
+
"target_column = \"Delivery_Time\"\n",
|
| 231 |
+
"\n",
|
| 232 |
+
"X = df.drop(target_column, axis=1)\n",
|
| 233 |
+
"y = df[target_column]\n",
|
| 234 |
+
"\n",
|
| 235 |
+
"print(\"\\nDataset Shapes\")\n",
|
| 236 |
+
"print(\"X:\", X.shape)\n",
|
| 237 |
+
"print(\"y:\", y.shape)"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
},
|
| 242 |
+
{
|
| 243 |
+
"cell_type": "code",
|
| 244 |
+
"metadata": {},
|
| 245 |
+
"source": [
|
| 246 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"\n",
|
| 249 |
+
"model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
"# Training on KFold\n",
|
| 252 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"\n",
|
| 255 |
+
"mae_scores = []\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"for train_idx, test_idx in kf.split(X):\n",
|
| 258 |
+
" X_train, X_test = X.iloc[train_idx,:], X.iloc[test_idx,:]\n",
|
| 259 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" # Train model\n",
|
| 262 |
+
" model.fit(X_train, y_train)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" # Predict\n",
|
| 265 |
+
" y_pred = model.predict(X_test)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Evaluation metrics\n",
|
| 268 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Print Evaluation Metrics\n",
|
| 272 |
+
"print(\"\\nModel Evaluation \\n\" + \"-\"*40)\n",
|
| 273 |
+
"print(f\"Average MAE across all folds : {np.mean(mae_scores):.2f}\")\n",
|
| 274 |
+
"print(\"-\"*40)"
|
| 275 |
+
],
|
| 276 |
+
"execution_count": null,
|
| 277 |
+
"outputs": []
|
| 278 |
+
},
|
| 279 |
+
{
|
| 280 |
+
"cell_type": "code",
|
| 281 |
+
"metadata": {},
|
| 282 |
+
"source": [
|
| 283 |
+
"# Compare model to baseline\n",
|
| 284 |
+
"baseline_pred = np.full_like(y, y.median())\n",
|
| 285 |
+
"\n",
|
| 286 |
+
"baseline_mae = mean_absolute_error(y, baseline_pred)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"print(f\"Baseline MAE (using median target): {baseline_mae:.4f}\")\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"\n"
|
| 292 |
+
],
|
| 293 |
+
"execution_count": null,
|
| 294 |
+
"outputs": []
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"cell_type": "code",
|
| 298 |
+
"metadata": {},
|
| 299 |
+
"source": [
|
| 300 |
+
"# Task 1: Write your code here:\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"importance = list(zip(X.columns, model.feature_importances_))\n",
|
| 303 |
+
"sorted_importance = sorted(importance, key=lambda x: abs(x[1]), reverse=True)\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"# Extract sorted features and their coefficients\n",
|
| 306 |
+
"features, coefficients = zip(*sorted_importance)\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"# Plot feature importances\n",
|
| 309 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 310 |
+
"plt.barh(features, coefficients, color='darkblue')\n",
|
| 311 |
+
"plt.xlabel('Coefficient Value')\n",
|
| 312 |
+
"plt.ylabel('Features')\n",
|
| 313 |
+
"plt.title('Regression Feature Importance')\n",
|
| 314 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 315 |
+
"plt.show()\n"
|
| 316 |
+
],
|
| 317 |
+
"execution_count": null,
|
| 318 |
+
"outputs": []
|
| 319 |
+
},
|
| 320 |
+
{
|
| 321 |
+
"cell_type": "code",
|
| 322 |
+
"metadata": {},
|
| 323 |
+
"source": [
|
| 324 |
+
"# Task 2: Write your code here:\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"y_pred = model.predict(X)\n",
|
| 327 |
+
"prediction_df = pd.DataFrame(y_pred)\n",
|
| 328 |
+
"prediction_df.columns = ['Predicted Delivery Time']\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"check_target_distribution(prediction_df, 'Predicted Delivery Time')"
|
| 332 |
+
],
|
| 333 |
+
"execution_count": null,
|
| 334 |
+
"outputs": []
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"cell_type": "code",
|
| 338 |
+
"metadata": {},
|
| 339 |
+
"source": [
|
| 340 |
+
"!pip install dask[dataframe] catboost\n"
|
| 341 |
+
],
|
| 342 |
+
"execution_count": null,
|
| 343 |
+
"outputs": []
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "code",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"source": [
|
| 349 |
+
"# Task Bonus: Write your code here:\n",
|
| 350 |
+
"from catboost import CatBoostRegressor\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"\n",
|
| 354 |
+
"model1 = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
|
| 355 |
+
"model2 = CatBoostRegressor(verbose=0)\n",
|
| 356 |
+
"# Training on KFold\n",
|
| 357 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"mae_scores = []\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"for train_idx, test_idx in kf.split(X):\n",
|
| 363 |
+
" X_train, X_test = X.iloc[train_idx,:], X.iloc[test_idx,:]\n",
|
| 364 |
+
" y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
|
| 365 |
+
"\n",
|
| 366 |
+
" # Train model\n",
|
| 367 |
+
" model1.fit(X_train, y_train)\n",
|
| 368 |
+
" model2.fit(X_train, y_train)\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" # Predict\n",
|
| 371 |
+
" y_pred1 = model1.predict(X_test)\n",
|
| 372 |
+
" y_pred2 = model2.predict(X_test)\n",
|
| 373 |
+
" y_pred = (y_pred1 + y_pred2) / 2\n",
|
| 374 |
+
"\n",
|
| 375 |
+
"\n",
|
| 376 |
+
" # Evaluation metrics\n",
|
| 377 |
+
" mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"\n",
|
| 380 |
+
"# Print Evaluation Metrics\n",
|
| 381 |
+
"print(\"\\nModel Evaluation \\n\" + \"-\"*40)\n",
|
| 382 |
+
"print(f\"Average MAE across all folds : {np.mean(mae_scores):.2f}\")\n",
|
| 383 |
+
"print(\"-\"*40)\n"
|
| 384 |
+
],
|
| 385 |
+
"execution_count": null,
|
| 386 |
+
"outputs": []
|
| 387 |
+
}
|
| 388 |
+
],
|
| 389 |
+
"metadata": {
|
| 390 |
+
"kernelspec": {
|
| 391 |
+
"display_name": "Python 3",
|
| 392 |
+
"name": "python3"
|
| 393 |
+
},
|
| 394 |
+
"language_info": {
|
| 395 |
+
"name": "python"
|
| 396 |
+
}
|
| 397 |
+
},
|
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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 |
+
"\n",
|
| 69 |
+
"import torch\n",
|
| 70 |
+
"import torch.nn as nn\n",
|
| 71 |
+
"import torch.optim as optim\n",
|
| 72 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 73 |
+
"\n",
|
| 74 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 75 |
+
"from sklearn.preprocessing import LabelEncoder, StandardScaler\n",
|
| 76 |
+
"import matplotlib.pyplot as plt\n",
|
| 77 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 87 |
+
"\n",
|
| 88 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 89 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 90 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 91 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n"
|
| 92 |
+
],
|
| 93 |
+
"execution_count": null,
|
| 94 |
+
"outputs": []
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"cell_type": "code",
|
| 98 |
+
"metadata": {},
|
| 99 |
+
"source": [
|
| 100 |
+
"# 2. Create TensorDataset objects\n",
|
| 101 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 102 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 103 |
+
"\n",
|
| 104 |
+
"\n"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# 3. Create DataLoaders\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"# DataLoader for training data\n",
|
| 116 |
+
"train_loader = DataLoader(\n",
|
| 117 |
+
" train_dataset,\n",
|
| 118 |
+
" batch_size=32,\n",
|
| 119 |
+
" shuffle=True,\n",
|
| 120 |
+
" num_workers=2\n",
|
| 121 |
+
")\n",
|
| 122 |
+
"# DataLoader for test/validation data\n",
|
| 123 |
+
"test_loader = DataLoader(\n",
|
| 124 |
+
" test_dataset,\n",
|
| 125 |
+
" batch_size=32,\n",
|
| 126 |
+
" shuffle=False,\n",
|
| 127 |
+
" num_workers=2\n",
|
| 128 |
+
")"
|
| 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 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 139 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 140 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# 5. Display sample images\n",
|
| 150 |
+
"import torchvision.transforms as T\n",
|
| 151 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"samples=[]\n",
|
| 154 |
+
"with torch.no_grad():\n",
|
| 155 |
+
" for inputs, labels in train_loader:\n",
|
| 156 |
+
" inputs, labels = inputs.to(device), labels.to(device)\n",
|
| 157 |
+
" for i, label in enumerate(labels):\n",
|
| 158 |
+
" samples.append((inputs[i], label.item()))\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"for sample in samples[5]:\n",
|
| 161 |
+
" for image, true in samples[:3]:\n",
|
| 162 |
+
" plt.imshow(T.ToPILImage()(image))\n",
|
| 163 |
+
" plt.show()\n"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# Task 1: Write your model class here:\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"class regression(nn.Module):\n",
|
| 175 |
+
" def __init__(self, input_size, hidden_size1, hidden_size2, hidden_size3, output_size=1):\n",
|
| 176 |
+
" super(regression, self).__init__()\n",
|
| 177 |
+
" # Define layers\n",
|
| 178 |
+
" self.layer1 = nn.Linear(input_size, hidden_size1)\n",
|
| 179 |
+
" self.layer2 = nn.Linear(hidden_size1, hidden_size2)\n",
|
| 180 |
+
" self.layer3 = nn.Linear(hidden_size2, hidden_size3)\n",
|
| 181 |
+
" self.layer4 = nn.Linear(hidden_size3, output_size)\n",
|
| 182 |
+
" self.relu = nn.ReLU()\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"\n",
|
| 185 |
+
" def forward(self, x):\n",
|
| 186 |
+
" # Forward pass\n",
|
| 187 |
+
" x = self.layer1(x)\n",
|
| 188 |
+
" x = self.relu(x)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" x = self.layer2(x)\n",
|
| 191 |
+
" x = self.relu(x)\n",
|
| 192 |
+
"\n",
|
| 193 |
+
" x = self.layer3(x)\n",
|
| 194 |
+
" x = self.relu(x)\n",
|
| 195 |
+
"\n",
|
| 196 |
+
" x = self.layer4(x)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
" return x\n"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"# Task 2: Write your training loop function here:\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"\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) # shape: (batch_size, num_features)\n",
|
| 219 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size,)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
" # Forward pass (outputs are logits)\n",
|
| 222 |
+
" outputs = model(X_batch) # shape: (batch_size, num_classes)\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\n"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 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.0\n",
|
| 249 |
+
"\n",
|
| 250 |
+
" with torch.no_grad():\n",
|
| 251 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 252 |
+
" # Move data to device\n",
|
| 253 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
|
| 254 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" # Forward pass (continuous output)\n",
|
| 257 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 258 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
" running_loss += loss.item()\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # Average loss over all batches\n",
|
| 263 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" return avg_loss"
|
| 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 |
+
"\n",
|
| 276 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"# Model parameters\n",
|
| 279 |
+
"input_dim = 3 * 36 * 36 # Number of tabular features\n",
|
| 280 |
+
"hidden_dim1 = 1000\n",
|
| 281 |
+
"hidden_dim2 = 500\n",
|
| 282 |
+
"hidden_dim3 = 250\n",
|
| 283 |
+
"output_dim = 1\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"# Instantiate model\n",
|
| 286 |
+
"model = regression(input_dim, hidden_dim1, hidden_dim2, hidden_dim3, output_dim).to(device)\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"#loss and optimizer\n",
|
| 289 |
+
"criterion = nn.MSELoss() # MSE Loss for regression\n",
|
| 290 |
+
"optimizer = optim.AdamW(model.parameters(), lr=1e-4)\n",
|
| 291 |
+
"\n"
|
| 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 |
+
"# Run Training\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"num_epochs = 20\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"train_losses = []\n",
|
| 306 |
+
"val_losses = []\n",
|
| 307 |
+
"\n",
|
| 308 |
+
"print('Starting Training...')\n",
|
| 309 |
+
"for epoch in range(num_epochs):\n",
|
| 310 |
+
" # Train one epoch\n",
|
| 311 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" # Validate\n",
|
| 314 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" train_losses.append(train_loss)\n",
|
| 317 |
+
" val_losses.append(val_loss)\n",
|
| 318 |
+
"\n",
|
| 319 |
+
"\n",
|
| 320 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"print('Training Complete!')"
|
| 323 |
+
],
|
| 324 |
+
"execution_count": null,
|
| 325 |
+
"outputs": []
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"cell_type": "code",
|
| 329 |
+
"metadata": {},
|
| 330 |
+
"source": [
|
| 331 |
+
"# Task 1: Write your code here:\n",
|
| 332 |
+
"# Plotting results\n",
|
| 333 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 334 |
+
"\n",
|
| 335 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 336 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 337 |
+
"plt.title('Loss over Epochs')\n",
|
| 338 |
+
"plt.xlabel('Epoch')\n",
|
| 339 |
+
"plt.ylabel('Loss (MSE)')\n",
|
| 340 |
+
"plt.legend()\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"plt.tight_layout()\n",
|
| 343 |
+
"plt.show()"
|
| 344 |
+
],
|
| 345 |
+
"execution_count": null,
|
| 346 |
+
"outputs": []
|
| 347 |
+
},
|
| 348 |
+
{
|
| 349 |
+
"cell_type": "code",
|
| 350 |
+
"metadata": {},
|
| 351 |
+
"source": [],
|
| 352 |
+
"execution_count": null,
|
| 353 |
+
"outputs": []
|
| 354 |
+
}
|
| 355 |
+
],
|
| 356 |
+
"metadata": {
|
| 357 |
+
"kernelspec": {
|
| 358 |
+
"display_name": "Python 3",
|
| 359 |
+
"name": "python3"
|
| 360 |
+
},
|
| 361 |
+
"language_info": {
|
| 362 |
+
"name": "python"
|
| 363 |
+
}
|
| 364 |
+
},
|
| 365 |
+
"nbformat": 4,
|
| 366 |
+
"nbformat_minor": 0
|
| 367 |
+
}
|
submissions_extracted/582/Q3.ipynb
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
"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 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"og_df = pd.read_csv(csv_path)\n",
|
| 32 |
+
"df = og_df.copy()"
|
| 33 |
+
],
|
| 34 |
+
"execution_count": null,
|
| 35 |
+
"outputs": []
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"source": [
|
| 41 |
+
"# Task 2: Write your code here:\n",
|
| 42 |
+
"df.head()"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 3: Write your code here:\n",
|
| 52 |
+
"df.info()"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 4: Write your code here:\n",
|
| 62 |
+
"df.describe()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 1: Write your code here:\n",
|
| 72 |
+
"\n",
|
| 73 |
+
"# removing columns with many missing data (drop cols with more than 2.5% of data missing)\n",
|
| 74 |
+
"cols = df.columns\n",
|
| 75 |
+
"for col in cols:\n",
|
| 76 |
+
" if int(df[col].isnull().sum()) > 500:\n",
|
| 77 |
+
" df = df.drop(columns=[col])\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"\n"
|
| 80 |
+
],
|
| 81 |
+
"execution_count": null,
|
| 82 |
+
"outputs": []
|
| 83 |
+
},
|
| 84 |
+
{
|
| 85 |
+
"cell_type": "code",
|
| 86 |
+
"metadata": {},
|
| 87 |
+
"source": [
|
| 88 |
+
"# filling with median\n",
|
| 89 |
+
"cols = df.columns\n",
|
| 90 |
+
"columns_with_missing = []\n",
|
| 91 |
+
"for col in cols:\n",
|
| 92 |
+
" if int(df[col].isnull().sum()) > 0:\n",
|
| 93 |
+
" columns_with_missing.append(col)\n",
|
| 94 |
+
" df[col] = df[col].fillna(df[col].median())\n",
|
| 95 |
+
"\n"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 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:\n",
|
| 114 |
+
"# Control duplicates\n",
|
| 115 |
+
"def check_duplicates(df):\n",
|
| 116 |
+
" duplicates = df.duplicated().sum()\n",
|
| 117 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 118 |
+
" if duplicates > 0:\n",
|
| 119 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 120 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 121 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 122 |
+
" else:\n",
|
| 123 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"check_duplicates(df)"
|
| 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 |
+
"# no categorical variables requiring encoding\n",
|
| 136 |
+
"\n",
|
| 137 |
+
"print(df.select_dtypes(include=[\"object\"]).columns)\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"\n"
|
| 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 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 150 |
+
"scaler = StandardScaler()\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"\n",
|
| 153 |
+
"cols = df.columns.drop(\"Target\")\n",
|
| 154 |
+
"\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"df[cols] = scaler.fit_transform(df[cols])\n",
|
| 157 |
+
"\n"
|
| 158 |
+
],
|
| 159 |
+
"execution_count": null,
|
| 160 |
+
"outputs": []
|
| 161 |
+
},
|
| 162 |
+
{
|
| 163 |
+
"cell_type": "code",
|
| 164 |
+
"metadata": {},
|
| 165 |
+
"source": [
|
| 166 |
+
"# Task 5: Write your code here:\n",
|
| 167 |
+
"# Check balance\n",
|
| 168 |
+
"target_column = \"Target\"\n",
|
| 169 |
+
"print(df[target_column].value_counts())\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"#Target is imbalanced, we need to stratify our data & use metrics other than of accuracy"
|
| 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 |
+
"# Separate Features and Target\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"X = df.drop(target_column, axis=1)\n",
|
| 185 |
+
"y = df[target_column]\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"print(\"\\nDataset Shapes\")\n",
|
| 188 |
+
"print(\"X:\", X.shape)\n",
|
| 189 |
+
"print(\"y:\", y.shape)"
|
| 190 |
+
],
|
| 191 |
+
"execution_count": null,
|
| 192 |
+
"outputs": []
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"cell_type": "code",
|
| 196 |
+
"metadata": {},
|
| 197 |
+
"source": [
|
| 198 |
+
"!pip install dask[dataframe] catboost"
|
| 199 |
+
],
|
| 200 |
+
"execution_count": null,
|
| 201 |
+
"outputs": []
|
| 202 |
+
},
|
| 203 |
+
{
|
| 204 |
+
"cell_type": "code",
|
| 205 |
+
"metadata": {},
|
| 206 |
+
"source": [
|
| 207 |
+
"\n",
|
| 208 |
+
"import numpy as np\n",
|
| 209 |
+
"from sklearn.metrics import log_loss\n",
|
| 210 |
+
"from catboost import CatBoostClassifier\n",
|
| 211 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 212 |
+
"from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay, f1_score, classification_report\n",
|
| 213 |
+
"\n"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 223 |
+
"model = CatBoostClassifier(verbose=0)\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"# Train model Stratified Kfold\n",
|
| 226 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"scores_f1=[]\n",
|
| 229 |
+
"\n",
|
| 230 |
+
"for train_index, test_index in skf.split(X, y):\n",
|
| 231 |
+
" # Split data into training and testing sets\n",
|
| 232 |
+
" X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
|
| 233 |
+
" y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 234 |
+
" # Train the model\n",
|
| 235 |
+
" model.fit(X_Train, y_Train)\n",
|
| 236 |
+
" # Predict on the test set\n",
|
| 237 |
+
" y_pred = model.predict(X_Test)\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" # Calculate metrics\n",
|
| 240 |
+
" scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" # Print the results\n",
|
| 244 |
+
"print(f\" F1-Score: {np.mean(scores_f1):.4f}\")\n",
|
| 245 |
+
"print(\"\\n\")\n",
|
| 246 |
+
"\n"
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"import matplotlib.pyplot as plt"
|
| 256 |
+
],
|
| 257 |
+
"execution_count": null,
|
| 258 |
+
"outputs": []
|
| 259 |
+
},
|
| 260 |
+
{
|
| 261 |
+
"cell_type": "code",
|
| 262 |
+
"metadata": {},
|
| 263 |
+
"source": [
|
| 264 |
+
"# Task 1: Write your code here:\n",
|
| 265 |
+
"# Plotting coefficients\n",
|
| 266 |
+
"importance = list(zip(X.columns, model.feature_importances_))\n",
|
| 267 |
+
"# importance = list(zip(X_scaled.columns, model.coef_[0])) try indexing the model.coef_ if you get an error stating numpy array should be 1D\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"sorted_importance = sorted(importance, key=lambda x: abs(x[1]), reverse=True)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Extract sorted features and their coefficients\n",
|
| 272 |
+
"features, coefficients = zip(*sorted_importance)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"# Plot feature importances\n",
|
| 275 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 276 |
+
"plt.barh(features, coefficients, color='darkblue')\n",
|
| 277 |
+
"plt.xlabel('Coefficient Value')\n",
|
| 278 |
+
"plt.ylabel('Features')\n",
|
| 279 |
+
"plt.title('Regression Feature Importance')\n",
|
| 280 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 281 |
+
"plt.show()\n"
|
| 282 |
+
],
|
| 283 |
+
"execution_count": null,
|
| 284 |
+
"outputs": []
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"cell_type": "code",
|
| 288 |
+
"metadata": {},
|
| 289 |
+
"source": [
|
| 290 |
+
"# Task 2: Write your code here:\n",
|
| 291 |
+
"# the most important is D_45\n",
|
| 292 |
+
"golden_feature = sorted_importance[0][0]\n",
|
| 293 |
+
"print(golden_feature)\n"
|
| 294 |
+
],
|
| 295 |
+
"execution_count": null,
|
| 296 |
+
"outputs": []
|
| 297 |
+
},
|
| 298 |
+
{
|
| 299 |
+
"cell_type": "code",
|
| 300 |
+
"metadata": {},
|
| 301 |
+
"source": [
|
| 302 |
+
"# I STARTED ALL OVER AGAIN TO SOLVE THE BONUS BECAUSE IN THE FIRST PART I FILLED THE MISSING IN THE GOLDEN FEATURE WITH THE MEDIAN.\n",
|
| 303 |
+
"# Rather, i want to drop rows with missing data from the golden_feature"
|
| 304 |
+
],
|
| 305 |
+
"execution_count": null,
|
| 306 |
+
"outputs": []
|
| 307 |
+
},
|
| 308 |
+
{
|
| 309 |
+
"cell_type": "code",
|
| 310 |
+
"metadata": {},
|
| 311 |
+
"source": [
|
| 312 |
+
"# Task Bonus: Write your code here:\n",
|
| 313 |
+
"new_df = og_df.copy()"
|
| 314 |
+
],
|
| 315 |
+
"execution_count": null,
|
| 316 |
+
"outputs": []
|
| 317 |
+
},
|
| 318 |
+
{
|
| 319 |
+
"cell_type": "code",
|
| 320 |
+
"metadata": {},
|
| 321 |
+
"source": [
|
| 322 |
+
"new_df = new_df[[golden_feature,'Target']]"
|
| 323 |
+
],
|
| 324 |
+
"execution_count": null,
|
| 325 |
+
"outputs": []
|
| 326 |
+
},
|
| 327 |
+
{
|
| 328 |
+
"cell_type": "code",
|
| 329 |
+
"metadata": {},
|
| 330 |
+
"source": [
|
| 331 |
+
"#drop missing\n",
|
| 332 |
+
"new_df = new_df.dropna(subset=[golden_feature,'Target'])"
|
| 333 |
+
],
|
| 334 |
+
"execution_count": null,
|
| 335 |
+
"outputs": []
|
| 336 |
+
},
|
| 337 |
+
{
|
| 338 |
+
"cell_type": "code",
|
| 339 |
+
"metadata": {},
|
| 340 |
+
"source": [
|
| 341 |
+
"# Control duplicates\n",
|
| 342 |
+
"def check_duplicates(df):\n",
|
| 343 |
+
" duplicates = df.duplicated().sum()\n",
|
| 344 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 345 |
+
" if duplicates > 0:\n",
|
| 346 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 347 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 348 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 349 |
+
" else:\n",
|
| 350 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"check_duplicates(new_df)"
|
| 353 |
+
],
|
| 354 |
+
"execution_count": null,
|
| 355 |
+
"outputs": []
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"source": [
|
| 361 |
+
"# Separate Features and Target\n",
|
| 362 |
+
"target_column = \"Target\"\n",
|
| 363 |
+
"\n",
|
| 364 |
+
"new_X = new_df.drop(target_column, axis=1)\n",
|
| 365 |
+
"new_y = new_df[target_column]\n",
|
| 366 |
+
"\n",
|
| 367 |
+
"print(\"\\nDataset Shapes\")\n",
|
| 368 |
+
"print(\"new_X:\", X.shape)\n",
|
| 369 |
+
"print(\"new_y:\", y.shape)"
|
| 370 |
+
],
|
| 371 |
+
"execution_count": null,
|
| 372 |
+
"outputs": []
|
| 373 |
+
},
|
| 374 |
+
{
|
| 375 |
+
"cell_type": "code",
|
| 376 |
+
"metadata": {},
|
| 377 |
+
"source": [
|
| 378 |
+
"# Feature Scaling\n",
|
| 379 |
+
"scaler = StandardScaler()\n",
|
| 380 |
+
"new_X = scaler.fit_transform(X)"
|
| 381 |
+
],
|
| 382 |
+
"execution_count": null,
|
| 383 |
+
"outputs": []
|
| 384 |
+
},
|
| 385 |
+
{
|
| 386 |
+
"cell_type": "code",
|
| 387 |
+
"metadata": {},
|
| 388 |
+
"source": [
|
| 389 |
+
"new_X = pd.DataFrame(new_X)\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"# Transfer back to dataframe (encoding returns numpy array if the input was series)\n",
|
| 392 |
+
"new_y = pd.DataFrame(new_y)"
|
| 393 |
+
],
|
| 394 |
+
"execution_count": null,
|
| 395 |
+
"outputs": []
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "code",
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"source": [
|
| 401 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 402 |
+
"model = CatBoostClassifier(verbose=0)\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"# Train model Stratified Kfold\n",
|
| 405 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 406 |
+
"\n",
|
| 407 |
+
"scores_f1=[]\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"for train_index, test_index in skf.split(new_X, new_y):\n",
|
| 410 |
+
" # Split data into training and testing sets\n",
|
| 411 |
+
" X_Train, X_Test = new_X.iloc[train_index, :], new_X.iloc[test_index, :]\n",
|
| 412 |
+
" y_Train, y_Test = new_y.iloc[train_index], new_y.iloc[test_index]\n",
|
| 413 |
+
" # Train the model\n",
|
| 414 |
+
" model.fit(X_Train, y_Train)\n",
|
| 415 |
+
" # Predict on the test set\n",
|
| 416 |
+
" y_pred = model.predict(X_Test)\n",
|
| 417 |
+
"\n",
|
| 418 |
+
" # Calculate metrics\n",
|
| 419 |
+
" scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
|
| 420 |
+
"\n",
|
| 421 |
+
"\n",
|
| 422 |
+
" # Print the results\n",
|
| 423 |
+
"print(f\" F1-Score: {np.mean(scores_f1):.4f}\")\n",
|
| 424 |
+
"print(\"\\n\")\n",
|
| 425 |
+
"\n"
|
| 426 |
+
],
|
| 427 |
+
"execution_count": null,
|
| 428 |
+
"outputs": []
|
| 429 |
+
}
|
| 430 |
+
],
|
| 431 |
+
"metadata": {
|
| 432 |
+
"kernelspec": {
|
| 433 |
+
"display_name": "Python 3",
|
| 434 |
+
"name": "python3"
|
| 435 |
+
},
|
| 436 |
+
"language_info": {
|
| 437 |
+
"name": "python"
|
| 438 |
+
}
|
| 439 |
+
},
|
| 440 |
+
"nbformat": 4,
|
| 441 |
+
"nbformat_minor": 0
|
| 442 |
+
}
|
submissions_extracted/583/Q1.ipynb
ADDED
|
@@ -0,0 +1,338 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 9 |
+
"import numpy as np\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import seaborn as sns\n",
|
| 13 |
+
"from scipy import stats\n",
|
| 14 |
+
"from tqdm import tqdm\n",
|
| 15 |
+
"tqdm.pandas()\n",
|
| 16 |
+
"import kagglehub\n",
|
| 17 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 18 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 19 |
+
"from sklearn.model_selection import KFold\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"from lightgbm import LGBMClassifier\n",
|
| 22 |
+
"from xgboost import XGBClassifier\n",
|
| 23 |
+
"from catboost import CatBoostClassifier\n",
|
| 24 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 25 |
+
"from sklearn.ensemble import VotingClassifier\n",
|
| 26 |
+
"from sklearn.metrics import f1_score\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"import warnings\n",
|
| 29 |
+
"warnings.filterwarnings('ignore')\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 |
+
"# Load the dataset\n",
|
| 45 |
+
"Food_path = os.path.join(path,'Q1_data.csv')\n",
|
| 46 |
+
"df = pd.read_csv(Food_path)"
|
| 47 |
+
],
|
| 48 |
+
"execution_count": null,
|
| 49 |
+
"outputs": []
|
| 50 |
+
},
|
| 51 |
+
{
|
| 52 |
+
"cell_type": "code",
|
| 53 |
+
"metadata": {},
|
| 54 |
+
"source": [
|
| 55 |
+
"# Task 2: Write your code here:\n",
|
| 56 |
+
"df.head()"
|
| 57 |
+
],
|
| 58 |
+
"execution_count": null,
|
| 59 |
+
"outputs": []
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"cell_type": "code",
|
| 63 |
+
"metadata": {},
|
| 64 |
+
"source": [
|
| 65 |
+
"# Task 3: Write your code here:\n",
|
| 66 |
+
"df.info()"
|
| 67 |
+
],
|
| 68 |
+
"execution_count": null,
|
| 69 |
+
"outputs": []
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"cell_type": "code",
|
| 73 |
+
"metadata": {},
|
| 74 |
+
"source": [
|
| 75 |
+
"# Task 4: Write your code here:\n",
|
| 76 |
+
"df.describe()"
|
| 77 |
+
],
|
| 78 |
+
"execution_count": null,
|
| 79 |
+
"outputs": []
|
| 80 |
+
},
|
| 81 |
+
{
|
| 82 |
+
"cell_type": "code",
|
| 83 |
+
"metadata": {},
|
| 84 |
+
"source": [
|
| 85 |
+
"# Task 5: Write your code here:\n",
|
| 86 |
+
"#Plot the target distribution (delivery_time)\n",
|
| 87 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 88 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 89 |
+
"plt.title('delivery_time Distribution')\n",
|
| 90 |
+
"plt.xlabel('delivery_time')\n",
|
| 91 |
+
"plt.ylabel('Frequency')\n",
|
| 92 |
+
"plt.show()# we have to take off out layers , because of the the pic is bad now"
|
| 93 |
+
],
|
| 94 |
+
"execution_count": null,
|
| 95 |
+
"outputs": []
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"cell_type": "code",
|
| 99 |
+
"metadata": {},
|
| 100 |
+
"source": [
|
| 101 |
+
"# Task 1: Write your code here:Drop the 'Order_ID' column from the data\n",
|
| 102 |
+
"df.drop(columns=['Order_ID'])"
|
| 103 |
+
],
|
| 104 |
+
"execution_count": null,
|
| 105 |
+
"outputs": []
|
| 106 |
+
},
|
| 107 |
+
{
|
| 108 |
+
"cell_type": "code",
|
| 109 |
+
"metadata": {},
|
| 110 |
+
"source": [
|
| 111 |
+
"# Task 2: Write your code here:Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
|
| 112 |
+
"df_mode = df.copy()#Fill with mode (categorical)\n",
|
| 113 |
+
"df_mode['Weather'] = df_mode['Weather'].fillna(df_mode['Weather'].mode()[0])\n",
|
| 114 |
+
"print(\"\\n4. Fill with mode:\")\n",
|
| 115 |
+
"print(df_mode)\n",
|
| 116 |
+
"\n",
|
| 117 |
+
"# Strategy 3: Fill with mean/median (numerical)\n",
|
| 118 |
+
"df_mean = df.copy()\n",
|
| 119 |
+
"df_mean['Courier_Experience_yrs'] = df_mean['Courier_Experience_yrs'].fillna(df_mean['Courier_Experience_yrs'].median())\n",
|
| 120 |
+
"print(\"\\n3. Fill with mean/median:\")\n",
|
| 121 |
+
"print(df_mean)\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"#for over all missing data : Drop rows with ANY missing values\n",
|
| 124 |
+
"df_dropna = df.dropna()\n",
|
| 125 |
+
"print(\"\\n1. After dropna():\", len(df_dropna), \"rows\")\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"# Select relevant columns, we do not select 'model' (too many unique values, too sparse and will hurt the model performance)\n",
|
| 128 |
+
"cols = ['Delivery_Time','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
|
| 129 |
+
"df_clean = df[cols].copy()\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"# Drop rows where target (price) or key features are missing - can't predict without them\n",
|
| 132 |
+
"print(f\"Before: {df_clean.shape}\")\n",
|
| 133 |
+
"df_clean = df_clean.dropna(subset=['Delivery_Time', 'Courier_Experience_yrs', 'Weather'])\n",
|
| 134 |
+
"print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n",
|
| 135 |
+
"\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 3: Write your code here:Check and remove duplicates if any exist\n",
|
| 145 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 146 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 147 |
+
"if duplicate_rows > 0:\n",
|
| 148 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 149 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 150 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 151 |
+
"else:\n",
|
| 152 |
+
" print(\"No duplicate rows found.\")\n"
|
| 153 |
+
],
|
| 154 |
+
"execution_count": null,
|
| 155 |
+
"outputs": []
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"cell_type": "code",
|
| 159 |
+
"metadata": {},
|
| 160 |
+
"source": [
|
| 161 |
+
"# Task 4: Write your code here:Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
|
| 162 |
+
"#Traffic_Level\n",
|
| 163 |
+
"\"\"\"\n",
|
| 164 |
+
"# Example: Encoding car colors\n",
|
| 165 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 166 |
+
"\n",
|
| 167 |
+
"print('data before encoding:\\n',df.Traffic_Level) #show before encoding\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"encoder = OneHotEncoder(sparse_output=False)\n",
|
| 170 |
+
"encoded = encoder.fit_transform(Traffic_Level)\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"print(\"Original:\", df.Traffic_Level)\n",
|
| 173 |
+
"print(\"Encoded:\\n\", encoded)\"\"\"\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"X = df.drop('Delivery_Time', axis=1)# drop the Target\n",
|
| 176 |
+
"y = df['Delivery_Time']#save target her\n",
|
| 177 |
+
"categorical_cols = ['Traffic_Level', 'Weather','Vehicle_Type']\n",
|
| 178 |
+
"# Encode Categorical Features --> make them numbers\n",
|
| 179 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"label_encoder = LabelEncoder()\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"for col in X.select_dtypes(include=[\"object\"]).columns: #for loop on x , if it Obj\n",
|
| 185 |
+
" X[col] = label_encoder.fit_transform(X[col])#make them uniqe int num\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"\n"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 5: Write your code here:Apply feature scaling for all features (Use StandardScaler)\n",
|
| 197 |
+
"# Feature Scaling\n",
|
| 198 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 199 |
+
"\n",
|
| 200 |
+
"scaler = StandardScaler()# all num in same range\n",
|
| 201 |
+
"X_scaled = scaler.fit_transform(X)"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"# Task 6: Write your code here:Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 211 |
+
"# 1. Is the target imbalanced?\n",
|
| 212 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 213 |
+
" print(\"Target Distribution:\")\n",
|
| 214 |
+
" print(df[target_column].value_counts(normalize=True)) #Counts how many times each unique value appears in the column.(normalize:returns proportions (fractions))\n",
|
| 215 |
+
" sns.countplot(x=df[target_column])# like hist gram\n",
|
| 216 |
+
" plt.title(\"Target Distribution\")\n",
|
| 217 |
+
" plt.show()\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"check_target_imbalance(df, 'Delivery_Time')\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"#imbalanced data"
|
| 222 |
+
],
|
| 223 |
+
"execution_count": null,
|
| 224 |
+
"outputs": []
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"cell_type": "code",
|
| 228 |
+
"metadata": {},
|
| 229 |
+
"source": [
|
| 230 |
+
"# Task 1: Write your code here:Split the dataset into features (X) and target (y)\n",
|
| 231 |
+
"X = df.drop('Delivery_Time', axis=1)# drop the Target\n",
|
| 232 |
+
"y = df['Delivery_Time']#save target here"
|
| 233 |
+
],
|
| 234 |
+
"execution_count": null,
|
| 235 |
+
"outputs": []
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"cell_type": "code",
|
| 239 |
+
"metadata": {},
|
| 240 |
+
"source": [
|
| 241 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 242 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 243 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 244 |
+
"import numpy as np\n",
|
| 245 |
+
"model = LogisticRegression()\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n",
|
| 249 |
+
"#Use the correct split: KFold OR StratifiedKFold\n",
|
| 250 |
+
"# StratifiedKFold (for imbalanced data)\n",
|
| 251 |
+
"skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 252 |
+
"scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n",
|
| 253 |
+
"print(\"\\nStratifiedKFold scores:\", scores_strat)\n",
|
| 254 |
+
"#print(f\"Mean accuracy: {scores_strat.mean():.3f}\")\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"\n"
|
| 257 |
+
],
|
| 258 |
+
"execution_count": null,
|
| 259 |
+
"outputs": []
|
| 260 |
+
},
|
| 261 |
+
{
|
| 262 |
+
"cell_type": "code",
|
| 263 |
+
"metadata": {},
|
| 264 |
+
"source": [
|
| 265 |
+
"# Task 1: Write your code here:Plot feature importance from your trained model\n",
|
| 266 |
+
"# Retrieve CatBoost feature importances and sort them\n",
|
| 267 |
+
"models = {\n",
|
| 268 |
+
" \"Logistic Regression\": LogisticRegression(max_iter=10000),\n",
|
| 269 |
+
" \"Random Forest Classifier\": RandomForestClassifier(n_estimators=100),\n",
|
| 270 |
+
" \"CatBoost Classifier\": CatBoostClassifier(verbose=0)\n",
|
| 271 |
+
"}\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"catboost_model = models[\"CatBoost Classifier\"]\n",
|
| 274 |
+
"catboost_importance = list(zip(X.columns, catboost_model.feature_importances_))\n",
|
| 275 |
+
"sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n",
|
| 276 |
+
"\n",
|
| 277 |
+
"# Extract features and their importances\n",
|
| 278 |
+
"features, importances = zip(*sorted_catboost_importance)\n",
|
| 279 |
+
"# Plot feature importances\n",
|
| 280 |
+
"plt.figure(figsize=(18, 14))\n",
|
| 281 |
+
"plt.barh(features, importances, color='orange')\n",
|
| 282 |
+
"plt.xlabel('Importance Score')\n",
|
| 283 |
+
"plt.ylabel('Features')\n",
|
| 284 |
+
"plt.title('CatBoost Feature Importance')\n",
|
| 285 |
+
"plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
|
| 286 |
+
"plt.show()"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Task 2: Write your code here:Plot predicted delivery time histogram\n",
|
| 296 |
+
"# Plot Predictions vs Ground Truth\n",
|
| 297 |
+
"plt.figure(figsize=(6, 4))\n",
|
| 298 |
+
"plt.scatter(y_test, y_pred, alpha=0.6)\n",
|
| 299 |
+
"plt.plot(\n",
|
| 300 |
+
" [y_test.min(), y_test.max()],\n",
|
| 301 |
+
" [y_test.min(), y_test.max()],\n",
|
| 302 |
+
" \"r--\",\n",
|
| 303 |
+
" linewidth=2\n",
|
| 304 |
+
")\n",
|
| 305 |
+
"\n",
|
| 306 |
+
"plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n",
|
| 307 |
+
"plt.ylabel(\"Predicted Exam Scores\")\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/583/Q2.ipynb
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"import torch\n",
|
| 35 |
+
"import torch.nn as nn\n",
|
| 36 |
+
"from torchvision.datasets import MNIST\n",
|
| 37 |
+
"from torch.utils.data import DataLoader\n",
|
| 38 |
+
"from torch.optim import Adam\n",
|
| 39 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 40 |
+
"import torch.nn.functional as F\n",
|
| 41 |
+
"import matplotlib.pyplot as plt\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}\")"
|
| 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 |
+
"# Training dataset\n",
|
| 86 |
+
"train_dataset = MNIST(\n",
|
| 87 |
+
" root='./datasets', # Dataset storage path/Where the dataset will be stored on your computer\n",
|
| 88 |
+
" train=True, # Use training data/Load the training portion (60,000 images)\n",
|
| 89 |
+
" transform=to_tensor, # Convert images to tensors/Convert each image into a PyTorch tensor\n",
|
| 90 |
+
" download=True # Download if not available/Download MNIST if it’s not already there\n",
|
| 91 |
+
")\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"# Testing dataset\n",
|
| 94 |
+
"test_dataset = MNIST(\n",
|
| 95 |
+
" root='./datasets', # Dataset storage path\n",
|
| 96 |
+
" train=False, # Use test data/ train=False → loads the 10,000 test images\n",
|
| 97 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 98 |
+
" #Raw MNIST images are PIL images (like JPGs). / Neural networks can’t use images directly — they need numbers.\n",
|
| 99 |
+
" download=True # Download if not available\n",
|
| 100 |
+
")\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"# print one sample from the dataset\n",
|
| 103 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 104 |
+
"sample_image, sample_label = train_dataset[0]#gets the first example in the dataset.\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 107 |
+
"print(f\"Label: {sample_label}\")\n",
|
| 108 |
+
"\n"
|
| 109 |
+
],
|
| 110 |
+
"execution_count": null,
|
| 111 |
+
"outputs": []
|
| 112 |
+
},
|
| 113 |
+
{
|
| 114 |
+
"cell_type": "code",
|
| 115 |
+
"metadata": {},
|
| 116 |
+
"source": [
|
| 117 |
+
"# 2. Create TensorDataset objects\n",
|
| 118 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 119 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 120 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 121 |
+
"from torch.utils.data import TensorDataset\n",
|
| 122 |
+
"# Split the dataset into training and testing sets\n",
|
| 123 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"# Standardize the data\n",
|
| 126 |
+
"scaler = StandardScaler()\n",
|
| 127 |
+
"X_train = scaler.fit_transform(X_train)\n",
|
| 128 |
+
"X_test = scaler.transform(X_test)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"# transform to tensors\n",
|
| 131 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 132 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 133 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 134 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)\n",
|
| 135 |
+
"\n",
|
| 136 |
+
"# Wrap tensors into TensorDataset objects\n",
|
| 137 |
+
"# Create TensorDatasets for training and testing\n",
|
| 138 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 139 |
+
"test_dataset = TensorDataset(X_test, y_test)\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 142 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)# batch_size=32 means model will process 32 samples per step\n",
|
| 143 |
+
"# shuffle=True for train_loader ensures batches are randomized each epoch\n",
|
| 144 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 145 |
+
"# shuffle=False for test_loader ensures evaluation is deterministic\n",
|
| 146 |
+
"\n"
|
| 147 |
+
],
|
| 148 |
+
"execution_count": null,
|
| 149 |
+
"outputs": []
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"cell_type": "code",
|
| 153 |
+
"metadata": {},
|
| 154 |
+
"source": [
|
| 155 |
+
"# 3. Create DataLoaders\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# DataLoader for training data\n",
|
| 158 |
+
"train_loader = DataLoader(\n",
|
| 159 |
+
" train_dataset,\n",
|
| 160 |
+
" batch_size=32,\n",
|
| 161 |
+
" shuffle=True,\n",
|
| 162 |
+
" num_workers=2\n",
|
| 163 |
+
")\n",
|
| 164 |
+
"# DataLoader for test/validation data\n",
|
| 165 |
+
"test_loader = DataLoader(\n",
|
| 166 |
+
" test_dataset,#final exam in fixed order #You don’t reshuffle the exam while grading it\n",
|
| 167 |
+
" batch_size=32,\n",
|
| 168 |
+
" shuffle=False,\n",
|
| 169 |
+
" num_workers=2\n",
|
| 170 |
+
")\n",
|
| 171 |
+
"# Get the first batch from the training DataLoader\n",
|
| 172 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 173 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 174 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# 4. Print shape of one batch\n",
|
| 184 |
+
"X_batch.shape\n"
|
| 185 |
+
],
|
| 186 |
+
"execution_count": null,
|
| 187 |
+
"outputs": []
|
| 188 |
+
},
|
| 189 |
+
{
|
| 190 |
+
"cell_type": "code",
|
| 191 |
+
"metadata": {},
|
| 192 |
+
"source": [
|
| 193 |
+
"# 5. Display sample images\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"# print one sample from the dataset\n",
|
| 196 |
+
"# Each sample consists of an image tensor and its label\n",
|
| 197 |
+
"sample_image, sample_label = train_dataset[0]#gets the first example in the dataset.\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
|
| 200 |
+
"print(f\"Label: {sample_label}\")\n"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 1: Write your model class here:Create a model class with 4 linear layers\n",
|
| 210 |
+
"import torch\n",
|
| 211 |
+
"import torch.nn as nn\n",
|
| 212 |
+
"import torch.optim as optim\n",
|
| 213 |
+
"\n",
|
| 214 |
+
"# Complete neural network example\n",
|
| 215 |
+
"class NN4Layer(nn.Module):\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" def __init__(self, input_dim, hidden_dim,output_dim):\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" super(NN2Layer, self).__init__()\n",
|
| 220 |
+
" # input_dim = num of features, hidden_dim = num of neurons\n",
|
| 221 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 222 |
+
" # hidden_dim = num of neurons, Output for binary classification is 1\n",
|
| 223 |
+
" self.layer1 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 224 |
+
" self.layer1 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 225 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # non-linearity activation function\n",
|
| 229 |
+
" self.relu = nn.ReLU()\n",
|
| 230 |
+
" # output activation function\n",
|
| 231 |
+
" self.sigmoid = nn.Sigmoid()\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # forward pass\n",
|
| 234 |
+
" def forward(self, x):#X is : input_dim = number of features (here, 4)\n",
|
| 235 |
+
" z1 = self.layer1(x)# [batch_size, 3]\n",
|
| 236 |
+
" a1 = self.relu(z1)#relu for hidden layer (first one)\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" z2 = self.layer2(a1)\n",
|
| 239 |
+
" a2 = self.relu(z2)\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" z3= self.layer3(a2)\n",
|
| 242 |
+
" a3=self.relu(z3)\n",
|
| 243 |
+
"\n",
|
| 244 |
+
" z4= self.layer4(a2)\n",
|
| 245 |
+
"\n",
|
| 246 |
+
" return z4\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"# Initialize\n",
|
| 249 |
+
"model = SimpleNN(input_size=10, hidden_size=64, num_classes=3)\n",
|
| 250 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 251 |
+
"optimizer = optim.Adam(model.parameters(), lr=0.001)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"# Sample training loop\n",
|
| 254 |
+
"X_train = torch.randn(100, 10)\n",
|
| 255 |
+
"y_train = torch.randint(0, 3, (100,))\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"for epoch in range(5):\n",
|
| 258 |
+
" # Forward pass\n",
|
| 259 |
+
" outputs = model(X_train)\n",
|
| 260 |
+
" loss = criterion(outputs, y_train)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # Backward pass\n",
|
| 263 |
+
" optimizer.zero_grad()\n",
|
| 264 |
+
" loss.backward()\n",
|
| 265 |
+
" optimizer.step()\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" if (epoch + 1) % 1 == 0:\n",
|
| 268 |
+
" print(f'Epoch [{epoch+1}/5], Loss: {loss.item():.4f}')\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"print(\"\\nModel trained!\")"
|
| 271 |
+
],
|
| 272 |
+
"execution_count": null,
|
| 273 |
+
"outputs": []
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"metadata": {},
|
| 278 |
+
"source": [
|
| 279 |
+
"# Task 2: Write your training loop here:\n",
|
| 280 |
+
"'''\n",
|
| 281 |
+
"for epoch in range(epochs):\n",
|
| 282 |
+
" for batch in dataloader:\n",
|
| 283 |
+
" optimizer.zero_grad() # Clear gradients\n",
|
| 284 |
+
" loss = criterion(model(X), y) # Forward pass\n",
|
| 285 |
+
" loss.backward() # Compute gradients\n",
|
| 286 |
+
" optimizer.step() # Update weights'''\n",
|
| 287 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 288 |
+
" # Set the model to training mode\n",
|
| 289 |
+
" model.train()\n",
|
| 290 |
+
"\n",
|
| 291 |
+
" running_loss = 0.0\n",
|
| 292 |
+
"\n",
|
| 293 |
+
" # Loop over all mini-batches provided by the DataLoader\n",
|
| 294 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 295 |
+
" # Flatten images from (batch_size, channels, height, width)\n",
|
| 296 |
+
" # into (batch_size, 784) for a fully-connected network\n",
|
| 297 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 298 |
+
" y_batch = y_batch.to(device)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" # -----------------------\n",
|
| 301 |
+
" # Forward pass\n",
|
| 302 |
+
" # -----------------------\n",
|
| 303 |
+
" # TODO: make predictions\n",
|
| 304 |
+
" # Pass the input through the network\n",
|
| 305 |
+
" # Output shape: (batch_size, 10) → scores for 10 classes\n",
|
| 306 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 307 |
+
" # TODO: compute loss\n",
|
| 308 |
+
" # Compute the loss by comparing predictions with true labels\n",
|
| 309 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 310 |
+
"\n",
|
| 311 |
+
" # Backward pass & optimization\n",
|
| 312 |
+
" # -----------------------\n",
|
| 313 |
+
" # Backward pass\n",
|
| 314 |
+
" # -----------------------\n",
|
| 315 |
+
"\n",
|
| 316 |
+
" # Clear old gradients from the previous step\n",
|
| 317 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 318 |
+
" loss.backward() # Compute gradients\n",
|
| 319 |
+
" optimizer.step() # Update model parameters\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" running_loss += loss.item()\n",
|
| 322 |
+
"\n",
|
| 323 |
+
" # Average loss over all batches/ # Compute the average loss across all batches in this epoch\n",
|
| 324 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
" return avg_loss"
|
| 327 |
+
],
|
| 328 |
+
"execution_count": null,
|
| 329 |
+
"outputs": []
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"cell_type": "code",
|
| 333 |
+
"metadata": {},
|
| 334 |
+
"source": [
|
| 335 |
+
"# Task 3: Write your validation loop here:\n",
|
| 336 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 337 |
+
" # Set the model to evaluation mode\n",
|
| 338 |
+
" model.eval()\n",
|
| 339 |
+
"\n",
|
| 340 |
+
" running_loss = 0.0\n",
|
| 341 |
+
" correct = 0# number of correct predictions\n",
|
| 342 |
+
" total = 0# total number of samples\n",
|
| 343 |
+
"\n",
|
| 344 |
+
" # Disable gradient computation to save memory and speed up validation\n",
|
| 345 |
+
" with torch.no_grad():\n",
|
| 346 |
+
" # Loop over all validation batches/# Flatten the input images and move them to the device (CPU/GPU)\n",
|
| 347 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 348 |
+
" # Move data to device\n",
|
| 349 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 350 |
+
" # Move the labels to the same device\n",
|
| 351 |
+
" y_batch = y_batch.to(device)\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"\n",
|
| 354 |
+
" # -----------------------\n",
|
| 355 |
+
" # Forward pass\n",
|
| 356 |
+
" # -----------------------\n",
|
| 357 |
+
"\n",
|
| 358 |
+
" # Pass the batch through the model\n",
|
| 359 |
+
" # Output shape: (batch_size, 10) → raw class scores (logits)\n",
|
| 360 |
+
"\n",
|
| 361 |
+
" # TODO: make predictions\n",
|
| 362 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 363 |
+
" # TODO: compute loss\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" # Compute the loss between predicted scores and true labels\n",
|
| 366 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 367 |
+
" # Accumulate the loss for this batch\n",
|
| 368 |
+
" running_loss += loss.item()\n",
|
| 369 |
+
"\n",
|
| 370 |
+
" # TODO: Apply Softmax to get probabilities\n",
|
| 371 |
+
" # -----------------------\n",
|
| 372 |
+
" # Prediction step\n",
|
| 373 |
+
" # -----------------------\n",
|
| 374 |
+
"\n",
|
| 375 |
+
" # Convert raw scores (logits) into probabilities using Softmax\n",
|
| 376 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 377 |
+
"\n",
|
| 378 |
+
" # TODO: Multiclass predictions\n",
|
| 379 |
+
" # Choose the class with the highest probability for each sample\n",
|
| 380 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 381 |
+
"\n",
|
| 382 |
+
" # Accuracy calculation\n",
|
| 383 |
+
" # Count how many predictions match the true labels\n",
|
| 384 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 385 |
+
" # Count total number of samples processed so far\n",
|
| 386 |
+
" total += y_batch.size(0)\n",
|
| 387 |
+
"\n",
|
| 388 |
+
" avg_loss = running_loss / len(test_loader)# Compute average loss over all validation batches\n",
|
| 389 |
+
" # TODO: how do we calculate accuracy?\n",
|
| 390 |
+
" accuracy = correct / total # Accuracy = number of correct predictions / total number of samples\n",
|
| 391 |
+
"\n",
|
| 392 |
+
" return avg_loss, accuracy # Return validation loss and accuracy"
|
| 393 |
+
],
|
| 394 |
+
"execution_count": null,
|
| 395 |
+
"outputs": []
|
| 396 |
+
},
|
| 397 |
+
{
|
| 398 |
+
"cell_type": "code",
|
| 399 |
+
"metadata": {},
|
| 400 |
+
"source": [
|
| 401 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 402 |
+
"# ----------------------------\n",
|
| 403 |
+
"# Device setup\n",
|
| 404 |
+
"# ----------------------------\n",
|
| 405 |
+
"\n",
|
| 406 |
+
"# Use GPU if available, otherwise fall back to CPU\n",
|
| 407 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 408 |
+
"\n",
|
| 409 |
+
"# Model parameters\n",
|
| 410 |
+
"# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
|
| 411 |
+
"# ----------------------------\n",
|
| 412 |
+
"# Model parameters\n",
|
| 413 |
+
"# ----------------------------\n",
|
| 414 |
+
"\n",
|
| 415 |
+
"# CIFAR-10 images have shape: (3, 32, 32)\n",
|
| 416 |
+
"# 3 = RGB channels, 32x32 = image size\n",
|
| 417 |
+
"# Fully connected networks require 1D vectors, so we flatten:\n",
|
| 418 |
+
"# input_dim = 3 × 32 × 32 = 3072 features per image\n",
|
| 419 |
+
"input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n",
|
| 420 |
+
"\n",
|
| 421 |
+
"# TODO: choose number of hidden neurons\n",
|
| 422 |
+
"# Number of neurons in each hidden layer\n",
|
| 423 |
+
"# This controls the model capacity (bigger = more expressive but more overfitting risk)\n",
|
| 424 |
+
"hidden_dim = 64 # Design choice\n",
|
| 425 |
+
"\n",
|
| 426 |
+
"# TODO: what are the number of classes ?\n",
|
| 427 |
+
"# CIFAR-10 has 10 possible classes:\n",
|
| 428 |
+
"# airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck\n",
|
| 429 |
+
"output_dim = 10 # CIFAR-10 classes\n",
|
| 430 |
+
"\n",
|
| 431 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 432 |
+
"# CIFAR-10 has 10 possible classes:\n",
|
| 433 |
+
"# airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck\n",
|
| 434 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 435 |
+
"\n",
|
| 436 |
+
"\n",
|
| 437 |
+
"\n",
|
| 438 |
+
"\n"
|
| 439 |
+
],
|
| 440 |
+
"execution_count": null,
|
| 441 |
+
"outputs": []
|
| 442 |
+
},
|
| 443 |
+
{
|
| 444 |
+
"cell_type": "code",
|
| 445 |
+
"metadata": {},
|
| 446 |
+
"source": [
|
| 447 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 448 |
+
" # Set the model to training mode\n",
|
| 449 |
+
" model.train()\n",
|
| 450 |
+
"\n",
|
| 451 |
+
" running_loss = 0.0\n",
|
| 452 |
+
"\n",
|
| 453 |
+
" # Loop over all mini-batches provided by the DataLoader\n",
|
| 454 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 455 |
+
" # Flatten images from (batch_size, channels, height, width)\n",
|
| 456 |
+
" # into (batch_size, 784) for a fully-connected network\n",
|
| 457 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 458 |
+
" y_batch = y_batch.to(device)\n",
|
| 459 |
+
"\n",
|
| 460 |
+
" # -----------------------\n",
|
| 461 |
+
" # Forward pass\n",
|
| 462 |
+
" # -----------------------\n",
|
| 463 |
+
" # TODO: make predictions\n",
|
| 464 |
+
" # Pass the input through the network\n",
|
| 465 |
+
" # Output shape: (batch_size, 10) → scores for 10 classes\n",
|
| 466 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 467 |
+
" # TODO: compute loss\n",
|
| 468 |
+
" # Compute the loss by comparing predictions with true labels\n",
|
| 469 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 470 |
+
"\n",
|
| 471 |
+
" # Backward pass & optimization\n",
|
| 472 |
+
" # -----------------------\n",
|
| 473 |
+
" # Backward pass\n",
|
| 474 |
+
" # -----------------------\n",
|
| 475 |
+
"\n",
|
| 476 |
+
" # Clear old gradients from the previous step\n",
|
| 477 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 478 |
+
" loss.backward() # Compute gradients\n",
|
| 479 |
+
" optimizer.step() # Update model parameters\n",
|
| 480 |
+
"\n",
|
| 481 |
+
" running_loss += loss.item()\n",
|
| 482 |
+
"\n",
|
| 483 |
+
" # Average loss over all batches/ # Compute the average loss across all batches in this epoch\n",
|
| 484 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 485 |
+
"\n",
|
| 486 |
+
" return avg_loss\n",
|
| 487 |
+
"\n",
|
| 488 |
+
"\n",
|
| 489 |
+
"\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"input_dim = 3 * 32 * 32 # CIFAR-10 images flattened (RGB)\n",
|
| 492 |
+
"\n",
|
| 493 |
+
"# TODO: choose number of hidden neurons\n",
|
| 494 |
+
"# Number of neurons in each hidden layer\n",
|
| 495 |
+
"# This controls the model capacity (bigger = more expressive but more overfitting risk)\n",
|
| 496 |
+
"hidden_dim = 64 # Design choice\n",
|
| 497 |
+
"\n",
|
| 498 |
+
"# TODO: what are the number of classes ?\n",
|
| 499 |
+
"# CIFAR-10 has 10 possible classes:\n",
|
| 500 |
+
"# airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck\n",
|
| 501 |
+
"output_dim = 10 # CIFAR-10 classes\n",
|
| 502 |
+
"\n",
|
| 503 |
+
"# TODO: Instantiate model (what are the model class inputs?)\n",
|
| 504 |
+
"# CIFAR-10 has 10 possible classes:\n",
|
| 505 |
+
"# airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck\n",
|
| 506 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 507 |
+
"\n",
|
| 508 |
+
"# TODO: Print the model architecture\n",
|
| 509 |
+
"# ----------------------------\n",
|
| 510 |
+
"# Inspect the model\n",
|
| 511 |
+
"# ----------------------------\n",
|
| 512 |
+
"\n",
|
| 513 |
+
"# Print the full neural network architecture (layers and dimensions)\n",
|
| 514 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 515 |
+
"print(model)\n",
|
| 516 |
+
"\n",
|
| 517 |
+
"\n",
|
| 518 |
+
"# Calculate the total number of trainable parameters\n",
|
| 519 |
+
"# ----------------------------\n",
|
| 520 |
+
"# Count trainable parameters\n",
|
| 521 |
+
"# ----------------------------\n",
|
| 522 |
+
"\n",
|
| 523 |
+
"# p.numel() gives the number of elements (weights) in each parameter tensor\n",
|
| 524 |
+
"# p.requires_grad ensures we only count trainable parameters\n",
|
| 525 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 526 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 527 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 528 |
+
"# ----------------------------\n",
|
| 529 |
+
"# Training hyperparameters\n",
|
| 530 |
+
"# ----------------------------\n",
|
| 531 |
+
"\n",
|
| 532 |
+
"# Number of full passes over the entire training dataset\n",
|
| 533 |
+
"# More epochs → better learning, but too many → overfitting\n",
|
| 534 |
+
"# If you have a GPU, you can afford more epochs\n",
|
| 535 |
+
"num_epochs = 20\n",
|
| 536 |
+
"\n",
|
| 537 |
+
"# TODO: choose a learning rate (try different values and evaluate results)\n",
|
| 538 |
+
"# Learning rate controls how big each weight update is\n",
|
| 539 |
+
"# Too high → unstable training\n",
|
| 540 |
+
"# Too low → slow learning\n",
|
| 541 |
+
"learning_rate = 0.001\n",
|
| 542 |
+
"\n",
|
| 543 |
+
"# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
|
| 544 |
+
"# ----------------------------\n",
|
| 545 |
+
"# Loss function\n",
|
| 546 |
+
"# ----------------------------\n",
|
| 547 |
+
"\n",
|
| 548 |
+
"# CrossEntropyLoss is used for multi-class classification\n",
|
| 549 |
+
"# It internally applies:\n",
|
| 550 |
+
"# - Softmax to convert logits to probabilities\n",
|
| 551 |
+
"# - Negative log-likelihood to measure prediction error\n",
|
| 552 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 553 |
+
"\n",
|
| 554 |
+
"\n",
|
| 555 |
+
"\n",
|
| 556 |
+
"# TODO: Define optimizer(what is updated during training?)\n",
|
| 557 |
+
"# ----------------------------\n",
|
| 558 |
+
"# Optimizer\n",
|
| 559 |
+
"# ----------------------------\n",
|
| 560 |
+
"\n",
|
| 561 |
+
"# The optimizer updates the model’s trainable parameters (weights & biases)\n",
|
| 562 |
+
"# AdamW = Adam optimizer with better weight decay (regularization)\n",
|
| 563 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 564 |
+
"\n",
|
| 565 |
+
"# ----------------------------\n",
|
| 566 |
+
"# Run Training\n",
|
| 567 |
+
"# ----------------------------\n",
|
| 568 |
+
"\n",
|
| 569 |
+
"# Lists to store metrics for plotting and analysis\n",
|
| 570 |
+
"train_losses = [] # training loss per epoch\n",
|
| 571 |
+
"val_losses = [] # validation loss per epoch\n",
|
| 572 |
+
"val_accuracies = [] # validation accuracy per epoch\n",
|
| 573 |
+
"\n",
|
| 574 |
+
"print('Starting Training...')\n",
|
| 575 |
+
"for epoch in range(num_epochs):\n",
|
| 576 |
+
" # Train one epoch\n",
|
| 577 |
+
" # ------------------------\n",
|
| 578 |
+
" # Training phase\n",
|
| 579 |
+
" # ------------------------\n",
|
| 580 |
+
"\n",
|
| 581 |
+
" # Train the model for one full pass over the training dataset\n",
|
| 582 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 583 |
+
"\n",
|
| 584 |
+
"\n",
|
| 585 |
+
" # ------------------------\n",
|
| 586 |
+
" # Validation phase\n",
|
| 587 |
+
" # ------------------------\n",
|
| 588 |
+
"\n",
|
| 589 |
+
" # Evaluate the model on unseen test/validation data\n",
|
| 590 |
+
"\n",
|
| 591 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 592 |
+
"\n",
|
| 593 |
+
" train_losses.append(train_loss)\n",
|
| 594 |
+
" val_losses.append(val_loss)\n",
|
| 595 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 596 |
+
"# Print progress for this epoch\n",
|
| 597 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 598 |
+
"\n",
|
| 599 |
+
"print('Training Complete!')"
|
| 600 |
+
],
|
| 601 |
+
"execution_count": null,
|
| 602 |
+
"outputs": []
|
| 603 |
+
},
|
| 604 |
+
{
|
| 605 |
+
"cell_type": "code",
|
| 606 |
+
"metadata": {},
|
| 607 |
+
"source": [
|
| 608 |
+
"# Task 1: Write your code here:\n",
|
| 609 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 610 |
+
"\n",
|
| 611 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 612 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 613 |
+
"plt.title('Loss over Epochs')\n",
|
| 614 |
+
"plt.xlabel('Epoch')\n",
|
| 615 |
+
"plt.ylabel('Loss')\n",
|
| 616 |
+
"plt.legend()\n",
|
| 617 |
+
"\n",
|
| 618 |
+
"plt.tight_layout()\n",
|
| 619 |
+
"plt.show()"
|
| 620 |
+
],
|
| 621 |
+
"execution_count": null,
|
| 622 |
+
"outputs": []
|
| 623 |
+
},
|
| 624 |
+
{
|
| 625 |
+
"cell_type": "code",
|
| 626 |
+
"metadata": {},
|
| 627 |
+
"source": [
|
| 628 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 629 |
+
"# Plotting results\n",
|
| 630 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 631 |
+
"\n",
|
| 632 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 633 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 634 |
+
"plt.title('Loss over Epochs')\n",
|
| 635 |
+
"plt.xlabel('Epoch')\n",
|
| 636 |
+
"plt.ylabel('Loss')\n",
|
| 637 |
+
"plt.legend()\n",
|
| 638 |
+
"\n",
|
| 639 |
+
"plt.tight_layout()\n",
|
| 640 |
+
"plt.show()"
|
| 641 |
+
],
|
| 642 |
+
"execution_count": null,
|
| 643 |
+
"outputs": []
|
| 644 |
+
}
|
| 645 |
+
],
|
| 646 |
+
"metadata": {
|
| 647 |
+
"kernelspec": {
|
| 648 |
+
"display_name": "Python 3",
|
| 649 |
+
"name": "python3"
|
| 650 |
+
},
|
| 651 |
+
"language_info": {
|
| 652 |
+
"name": "python"
|
| 653 |
+
}
|
| 654 |
+
},
|
| 655 |
+
"nbformat": 4,
|
| 656 |
+
"nbformat_minor": 0
|
| 657 |
+
}
|
submissions_extracted/583/Q3.ipynb
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 10 |
+
"import os\n",
|
| 11 |
+
"import numpy as np\n",
|
| 12 |
+
"import pandas as pd\n",
|
| 13 |
+
"import matplotlib.pyplot as plt\n",
|
| 14 |
+
"import seaborn as sns\n",
|
| 15 |
+
"from scipy import stats\n",
|
| 16 |
+
"from tqdm import tqdm\n",
|
| 17 |
+
"tqdm.pandas()\n",
|
| 18 |
+
"import kagglehub\n",
|
| 19 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 20 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 21 |
+
"from sklearn.model_selection import KFold\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"from lightgbm import LGBMClassifier\n",
|
| 24 |
+
"from xgboost import XGBClassifier\n",
|
| 25 |
+
"from catboost import CatBoostClassifier\n",
|
| 26 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 27 |
+
"from sklearn.ensemble import VotingClassifier\n",
|
| 28 |
+
"from sklearn.metrics import f1_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 |
+
"\n",
|
| 36 |
+
"print(\"Path to dataset files:\", 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 |
+
"Anonymized_path = os.path.join(path,'Q3_data.csv')\n",
|
| 47 |
+
"df = pd.read_csv(Anonymized_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 = pd.read_csv(Anonymized_path)\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 |
+
"# Task 1: Write your code here:\n",
|
| 88 |
+
"df_dropna = df.dropna()\n",
|
| 89 |
+
"print(\"\\n1. After dropna():\", len(df_dropna), \"rows\")"
|
| 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 |
+
"print(\"Checking for duplicate rows...\")\n",
|
| 100 |
+
"duplicate_rows = df.duplicated().sum()\n",
|
| 101 |
+
"if duplicate_rows > 0:\n",
|
| 102 |
+
" print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
|
| 103 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 104 |
+
" print(\"Duplicate rows removed.\")\n",
|
| 105 |
+
"else:\n",
|
| 106 |
+
" print(\"No duplicate rows found.\")"
|
| 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 |
+
"#no need\n",
|
| 117 |
+
"X = df.drop('Delivery_Time', axis=1)# drop the Target\n",
|
| 118 |
+
"y = df['Delivery_Time']#save target her\n",
|
| 119 |
+
"categorical_cols = ['Traffic_Level', 'Weather','Vehicle_Type']\n",
|
| 120 |
+
"# Encode Categorical Features --> make them numbers\n",
|
| 121 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"label_encoder = LabelEncoder()\n",
|
| 124 |
+
"\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"for col in X.select_dtypes(include=[\"object\"]).columns: #for loop on x , if it Obj\n",
|
| 127 |
+
" X[col] = label_encoder.fit_transform(X[col])#make them uniqe int num"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# Task 4: Write your code here:\n",
|
| 137 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"scaler = StandardScaler()# all num in same range\n",
|
| 140 |
+
"X_scaled = scaler.fit_transform(X)"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"# Task 5: Write your code here:\n"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"# Task 1: Write your code here:\n",
|
| 159 |
+
"X = df.drop('Delivery_Time', axis=1)# drop the Target\n",
|
| 160 |
+
"y = df['Delivery_Time']#save target here\n"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 170 |
+
"from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
|
| 171 |
+
"from sklearn.linear_model import LogisticRegression\n",
|
| 172 |
+
"import numpy as np\n",
|
| 173 |
+
"model = LogisticRegression()\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"print(f\"After dropping missing price/year/odometer: {df_clean.shape}\")\n",
|
| 177 |
+
"#Use the correct split: KFold OR StratifiedKFold\n",
|
| 178 |
+
"# StratifiedKFold (for imbalanced data)\n",
|
| 179 |
+
"skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 180 |
+
"scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n",
|
| 181 |
+
"print(\"\\nStratifiedKFold scores:\", scores_strat)\n",
|
| 182 |
+
"#print(f\"Mean accuracy: {scores_strat.mean():.3f}\")\n",
|
| 183 |
+
"\n"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"# Task 1: Write your code here:"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task 2: Write your code here:"
|
| 202 |
+
],
|
| 203 |
+
"execution_count": null,
|
| 204 |
+
"outputs": []
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"cell_type": "code",
|
| 208 |
+
"metadata": {},
|
| 209 |
+
"source": [
|
| 210 |
+
"# Task Bonus: Write your code here:"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
}
|
| 215 |
+
],
|
| 216 |
+
"metadata": {
|
| 217 |
+
"kernelspec": {
|
| 218 |
+
"display_name": "Python 3",
|
| 219 |
+
"name": "python3"
|
| 220 |
+
},
|
| 221 |
+
"language_info": {
|
| 222 |
+
"name": "python"
|
| 223 |
+
}
|
| 224 |
+
},
|
| 225 |
+
"nbformat": 4,
|
| 226 |
+
"nbformat_minor": 0
|
| 227 |
+
}
|
submissions_extracted/584/Q1.ipynb
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 LabelEncoder, OneHotEncoder"
|
| 15 |
+
],
|
| 16 |
+
"execution_count": null,
|
| 17 |
+
"outputs": []
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"cell_type": "code",
|
| 21 |
+
"metadata": {},
|
| 22 |
+
"source": [
|
| 23 |
+
"import kagglehub\n",
|
| 24 |
+
"\n",
|
| 25 |
+
"# Download latest version\n",
|
| 26 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"print(\"Path to dataset files:\", path)"
|
| 29 |
+
],
|
| 30 |
+
"execution_count": null,
|
| 31 |
+
"outputs": []
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"cell_type": "code",
|
| 35 |
+
"metadata": {},
|
| 36 |
+
"source": [
|
| 37 |
+
"# Task 1: Write your code here:\n",
|
| 38 |
+
"csv_path = os.path.join(path, \"Q1_data.csv\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"df = pd.read_csv(csv_path)"
|
| 41 |
+
],
|
| 42 |
+
"execution_count": null,
|
| 43 |
+
"outputs": []
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"cell_type": "code",
|
| 47 |
+
"metadata": {},
|
| 48 |
+
"source": [
|
| 49 |
+
"# Task 2: Write your code here:\n",
|
| 50 |
+
"df.head()"
|
| 51 |
+
],
|
| 52 |
+
"execution_count": null,
|
| 53 |
+
"outputs": []
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"cell_type": "code",
|
| 57 |
+
"metadata": {},
|
| 58 |
+
"source": [
|
| 59 |
+
"# Task 3: Write your code here:\n",
|
| 60 |
+
"df.info()"
|
| 61 |
+
],
|
| 62 |
+
"execution_count": null,
|
| 63 |
+
"outputs": []
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"cell_type": "code",
|
| 67 |
+
"metadata": {},
|
| 68 |
+
"source": [
|
| 69 |
+
"# Task 4: Write your code here:\n",
|
| 70 |
+
"df.describe()"
|
| 71 |
+
],
|
| 72 |
+
"execution_count": null,
|
| 73 |
+
"outputs": []
|
| 74 |
+
},
|
| 75 |
+
{
|
| 76 |
+
"cell_type": "code",
|
| 77 |
+
"metadata": {},
|
| 78 |
+
"source": [
|
| 79 |
+
"# Task 5: Write your code here:\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(columns=\"Order_ID\", axis=1)"
|
| 101 |
+
],
|
| 102 |
+
"execution_count": null,
|
| 103 |
+
"outputs": []
|
| 104 |
+
},
|
| 105 |
+
{
|
| 106 |
+
"cell_type": "code",
|
| 107 |
+
"metadata": {},
|
| 108 |
+
"source": [
|
| 109 |
+
"df # Check that the Order_ID column is dropped"
|
| 110 |
+
],
|
| 111 |
+
"execution_count": null,
|
| 112 |
+
"outputs": []
|
| 113 |
+
},
|
| 114 |
+
{
|
| 115 |
+
"cell_type": "code",
|
| 116 |
+
"metadata": {},
|
| 117 |
+
"source": [
|
| 118 |
+
"# Task 2: Write your code here:\n",
|
| 119 |
+
"def check_missing_values(df):\n",
|
| 120 |
+
" missing_values = df.isnull().sum() # This line checks for the missing values and sums them\n",
|
| 121 |
+
" print(\"Missing Values per Column:\")\n",
|
| 122 |
+
" print(missing_values[missing_values > 0])\n",
|
| 123 |
+
" if missing_values.any():\n",
|
| 124 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 125 |
+
" else:\n",
|
| 126 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"check_missing_values(df)\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"# Dropping missing values. Another option is to drop missing values for target then check again if there are any\n",
|
| 131 |
+
"# missing values, if there are then fillna with mean for instance.\n",
|
| 132 |
+
"df = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs', 'Delivery_Time'])\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"check_missing_values(df)"
|
| 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() # This line checks for number of duplicates and sums them\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) # Here we drop the duplicates\n",
|
| 150 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 151 |
+
" else:\n",
|
| 152 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 153 |
+
"\n",
|
| 154 |
+
"check_duplicates(df)"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 4: Write your code here:\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"# I will label encode all categorical columns for now. If there is time I would label encode the weather and traffic level,\n",
|
| 166 |
+
"# and one hot encode the rest of the categorical features. Based on my domain knowledge order matters only in these 2 cols so why not.\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"for col in categorical_cols:\n",
|
| 171 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 172 |
+
" le = LabelEncoder()\n",
|
| 173 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"df.head()"
|
| 176 |
+
],
|
| 177 |
+
"execution_count": null,
|
| 178 |
+
"outputs": []
|
| 179 |
+
},
|
| 180 |
+
{
|
| 181 |
+
"cell_type": "code",
|
| 182 |
+
"metadata": {},
|
| 183 |
+
"source": [
|
| 184 |
+
"# Task 5: Write your code here:\n",
|
| 185 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 186 |
+
"\n",
|
| 187 |
+
"# following on what i said above, i would try scaling before encoding or maybe after but what i mean is that in features\n",
|
| 188 |
+
"# where order is important it means there is significant relationship between this feature and the target and hence it might\n",
|
| 189 |
+
"# be better to scale other features without the labelly encoded ones.\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\") # Drop delivery time (target) to avoid scaling it\n",
|
| 192 |
+
"\n",
|
| 193 |
+
"scaler = StandardScaler()\n",
|
| 194 |
+
"\n",
|
| 195 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols]) # apply fit transform to the cols\n",
|
| 196 |
+
"\n",
|
| 197 |
+
"df.head()"
|
| 198 |
+
],
|
| 199 |
+
"execution_count": null,
|
| 200 |
+
"outputs": []
|
| 201 |
+
},
|
| 202 |
+
{
|
| 203 |
+
"cell_type": "code",
|
| 204 |
+
"metadata": {},
|
| 205 |
+
"source": [
|
| 206 |
+
"# Task 6: Write your code here:\n",
|
| 207 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 208 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 209 |
+
"plt.title('Delivery Time Distribution')\n",
|
| 210 |
+
"plt.xlabel('Delivery Time')\n",
|
| 211 |
+
"plt.ylabel('Frequency')\n",
|
| 212 |
+
"plt.show()"
|
| 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 |
+
"X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
|
| 223 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 224 |
+
],
|
| 225 |
+
"execution_count": null,
|
| 226 |
+
"outputs": []
|
| 227 |
+
},
|
| 228 |
+
{
|
| 229 |
+
"cell_type": "code",
|
| 230 |
+
"metadata": {},
|
| 231 |
+
"source": [
|
| 232 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 235 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 236 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 239 |
+
"\n",
|
| 240 |
+
"# 5-Fold Cross-Validation, shuffled, and using stratified for imbalance issue\n",
|
| 241 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"models = {\n",
|
| 244 |
+
" \"Random Forest\": RandomForestRegressor(n_estimators=200),\n",
|
| 245 |
+
"}\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"# Storage for results\n",
|
| 248 |
+
"all_results = {}\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"for name in models:\n",
|
| 251 |
+
" all_results[name] = {'mae': []}\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 254 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 255 |
+
"\n",
|
| 256 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 257 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" for model_name, model in models.items():\n",
|
| 260 |
+
" print(f\"Training {model_name}...\")\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" # Train\n",
|
| 263 |
+
" model.fit(X_train, y_train)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" # Predict\n",
|
| 266 |
+
" y_pred = model.predict(X_test)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" # Calculate metrics\n",
|
| 269 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # Store results\n",
|
| 272 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 273 |
+
"\n",
|
| 274 |
+
"for model_name in all_results:\n",
|
| 275 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 276 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 1: Write your code here:\n",
|
| 286 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 287 |
+
"importances = {}\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"importances['Random Forest'] = models['Random Forest'].feature_importances_\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Create a 1x3 plot\n",
|
| 292 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6)) # change 3 to number of models, here we have only one model but cant change subplot need other code, will change later.\n",
|
| 293 |
+
"axes = axes.flatten()\n",
|
| 294 |
+
"features = X.columns\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 297 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 298 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 299 |
+
"\n",
|
| 300 |
+
" ax = axes[i]\n",
|
| 301 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 302 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 303 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"plt.tight_layout()\n",
|
| 306 |
+
"plt.show()"
|
| 307 |
+
],
|
| 308 |
+
"execution_count": null,
|
| 309 |
+
"outputs": []
|
| 310 |
+
},
|
| 311 |
+
{
|
| 312 |
+
"cell_type": "code",
|
| 313 |
+
"metadata": {},
|
| 314 |
+
"source": [
|
| 315 |
+
"# Task 2: Write your code here:\n",
|
| 316 |
+
"plt.figure(figsize=(6, 4))\n",
|
| 317 |
+
"plt.scatter(y_test, y_pred, alpha=0.6)\n",
|
| 318 |
+
"plt.plot(\n",
|
| 319 |
+
" [y_test.min(), y_test.max()],\n",
|
| 320 |
+
" [y_test.min(), y_test.max()],\n",
|
| 321 |
+
" \"r--\",\n",
|
| 322 |
+
" linewidth=2\n",
|
| 323 |
+
")\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"plt.xlabel(\"Actual Delivery Time (Ground Truth)\")\n",
|
| 326 |
+
"plt.ylabel(\"Predicted Delivery Time\")\n",
|
| 327 |
+
"plt.title(\"Random Forest: Predictions vs Ground Truth\")\n",
|
| 328 |
+
"plt.grid(True)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
"plt.tight_layout()\n",
|
| 331 |
+
"plt.show()"
|
| 332 |
+
],
|
| 333 |
+
"execution_count": null,
|
| 334 |
+
"outputs": []
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"cell_type": "code",
|
| 338 |
+
"metadata": {},
|
| 339 |
+
"source": [
|
| 340 |
+
"# Task Bonus: Write your code here:\n",
|
| 341 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 342 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 343 |
+
"from sklearn.metrics import mean_absolute_error\n",
|
| 344 |
+
"from catboost import CatBoostRegressor\n",
|
| 345 |
+
"\n",
|
| 346 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 347 |
+
"\n",
|
| 348 |
+
"# 5-Fold Cross-Validation, shuffled, and using stratified for imbalance issue\n",
|
| 349 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"models = {\n",
|
| 352 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 353 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 354 |
+
"}\n",
|
| 355 |
+
"\n",
|
| 356 |
+
"# Storage for results\n",
|
| 357 |
+
"all_results = {}\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"for name in models:\n",
|
| 360 |
+
" all_results[name] = {'mae': []}\n",
|
| 361 |
+
"\n",
|
| 362 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 363 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 364 |
+
"\n",
|
| 365 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 366 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 367 |
+
"\n",
|
| 368 |
+
" for model_name, model in models.items():\n",
|
| 369 |
+
" print(f\"Training {model_name}...\")\n",
|
| 370 |
+
"\n",
|
| 371 |
+
" # Train\n",
|
| 372 |
+
" model.fit(X_train, y_train)\n",
|
| 373 |
+
"\n",
|
| 374 |
+
" # Predict\n",
|
| 375 |
+
" y_pred = model.predict(X_test)\n",
|
| 376 |
+
"\n",
|
| 377 |
+
" # Calculate metrics\n",
|
| 378 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 379 |
+
"\n",
|
| 380 |
+
" # Store results\n",
|
| 381 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 382 |
+
"\n",
|
| 383 |
+
"for model_name in all_results:\n",
|
| 384 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 385 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n",
|
| 386 |
+
"\n",
|
| 387 |
+
"\n",
|
| 388 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 389 |
+
"importances = {}\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"importances['Random Forest Regressor'] = models['Random Forest Regressor'].feature_importances_\n",
|
| 392 |
+
"importances['Cat Boost'] = models['CatBoost'].feature_importances_\n",
|
| 393 |
+
"\n",
|
| 394 |
+
"# Create a 1x3 plot\n",
|
| 395 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6)) # change 3 to number of models, here we have only one model but cant change subplot need other code, will change later.\n",
|
| 396 |
+
"axes = axes.flatten()\n",
|
| 397 |
+
"features = X.columns\n",
|
| 398 |
+
"\n",
|
| 399 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 400 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 401 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 402 |
+
"\n",
|
| 403 |
+
" ax = axes[i]\n",
|
| 404 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 405 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 406 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 407 |
+
"\n",
|
| 408 |
+
"plt.tight_layout()\n",
|
| 409 |
+
"plt.show()"
|
| 410 |
+
],
|
| 411 |
+
"execution_count": null,
|
| 412 |
+
"outputs": []
|
| 413 |
+
},
|
| 414 |
+
{
|
| 415 |
+
"cell_type": "code",
|
| 416 |
+
"metadata": {},
|
| 417 |
+
"source": [
|
| 418 |
+
"%pip install kagglehub catboost lightgbm tqdm -q"
|
| 419 |
+
],
|
| 420 |
+
"execution_count": null,
|
| 421 |
+
"outputs": []
|
| 422 |
+
},
|
| 423 |
+
{
|
| 424 |
+
"cell_type": "code",
|
| 425 |
+
"metadata": {},
|
| 426 |
+
"source": [],
|
| 427 |
+
"execution_count": null,
|
| 428 |
+
"outputs": []
|
| 429 |
+
}
|
| 430 |
+
],
|
| 431 |
+
"metadata": {
|
| 432 |
+
"kernelspec": {
|
| 433 |
+
"display_name": "Python 3",
|
| 434 |
+
"name": "python3"
|
| 435 |
+
},
|
| 436 |
+
"language_info": {
|
| 437 |
+
"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 |
+
"# Load Labels\n",
|
| 28 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 29 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"images = []\n",
|
| 32 |
+
"ages = []\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"# Load Images and Resize\n",
|
| 35 |
+
"print(\"Loading images...\")\n",
|
| 36 |
+
"for index, row in labels_df.iterrows():\n",
|
| 37 |
+
" img_name = row.iloc[0]\n",
|
| 38 |
+
" age = row.iloc[1]\n",
|
| 39 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 40 |
+
"\n",
|
| 41 |
+
" if os.path.exists(img_path):\n",
|
| 42 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 43 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 44 |
+
" images.append(img_array)\n",
|
| 45 |
+
" ages.append(age)\n",
|
| 46 |
+
"\n",
|
| 47 |
+
"X = np.array(images)\n",
|
| 48 |
+
"y = np.array(ages)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 51 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 52 |
+
"\n",
|
| 53 |
+
"# Split Data\n",
|
| 54 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 57 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 58 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 59 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 60 |
+
],
|
| 61 |
+
"execution_count": null,
|
| 62 |
+
"outputs": []
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
"cell_type": "code",
|
| 66 |
+
"metadata": {},
|
| 67 |
+
"source": [
|
| 68 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"import torch\n",
|
| 71 |
+
"import torch.nn as nn\n",
|
| 72 |
+
"from torch.optim import Adam, AdamW\n",
|
| 73 |
+
"import matplotlib.pyplot as plt\n",
|
| 74 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 75 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 76 |
+
"from torch.utils.data import TensorDataset\n",
|
| 77 |
+
"from torch.utils.data import DataLoader\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"# transform to tensors\n",
|
| 80 |
+
"X_train = torch.tensor(X_train, dtype=torch.float32)\n",
|
| 81 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 82 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 83 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 84 |
+
],
|
| 85 |
+
"execution_count": null,
|
| 86 |
+
"outputs": []
|
| 87 |
+
},
|
| 88 |
+
{
|
| 89 |
+
"cell_type": "code",
|
| 90 |
+
"metadata": {},
|
| 91 |
+
"source": [
|
| 92 |
+
"# 2. Create TensorDataset objects\n",
|
| 93 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 94 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 95 |
+
],
|
| 96 |
+
"execution_count": null,
|
| 97 |
+
"outputs": []
|
| 98 |
+
},
|
| 99 |
+
{
|
| 100 |
+
"cell_type": "code",
|
| 101 |
+
"metadata": {},
|
| 102 |
+
"source": [
|
| 103 |
+
"# 3. Create DataLoaders\n",
|
| 104 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 105 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# 4. Print shape of one batch\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"# Print dataset sizes\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}\")\n"
|
| 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\"Label: {labels[i].item()}\")\n",
|
| 147 |
+
" plt.axis('off')\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"plt.tight_layout()\n",
|
| 150 |
+
"plt.show()"
|
| 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 |
+
"class NN4Layer(nn.Module):\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 163 |
+
" super(NN4Layer, self).__init__()\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 166 |
+
"\n",
|
| 167 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 168 |
+
"\n",
|
| 169 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 172 |
+
"\n",
|
| 173 |
+
" # activation function for non-linearity\n",
|
| 174 |
+
" self.relu = nn.ReLU()\n",
|
| 175 |
+
"\n",
|
| 176 |
+
" # Defining how input data flows through the network\n",
|
| 177 |
+
" def forward(self, x):\n",
|
| 178 |
+
" z1 = self.layer1(x)\n",
|
| 179 |
+
" a1 = self.relu(z1)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
" z2 = self.layer2(a1)\n",
|
| 182 |
+
" a2 = self.relu(z2)\n",
|
| 183 |
+
"\n",
|
| 184 |
+
" z3 = self.layer3(a2)\n",
|
| 185 |
+
" a3 = self.relu(z3)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" z4 = self.layer4(a3)\n",
|
| 188 |
+
" a4 = self.relu(z4)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" z5 = self.layer5(a4)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" return z5"
|
| 193 |
+
],
|
| 194 |
+
"execution_count": null,
|
| 195 |
+
"outputs": []
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"cell_type": "code",
|
| 199 |
+
"metadata": {},
|
| 200 |
+
"source": [
|
| 201 |
+
"# Task 2: Write your training loop here:\n",
|
| 202 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 203 |
+
" # Set the model to training mode\n",
|
| 204 |
+
" model.train()\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" running_loss = 0.0\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 209 |
+
" # Move batch to the selected device\n",
|
| 210 |
+
" X_batch.view(X_batch.size(0), -1) # shape: (batch_size, num_features)\n",
|
| 211 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" # Forward pass (continuous output)\n",
|
| 214 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 215 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
" # Backward pass & optimization\n",
|
| 218 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 219 |
+
" loss.backward() # Compute gradients\n",
|
| 220 |
+
" optimizer.step() # Update model parameters\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" running_loss += loss.item()\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" # Average loss over all batches\n",
|
| 225 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" return avg_loss"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 3: Write your validation loop here:\n",
|
| 237 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 238 |
+
" # Set the model to evaluation mode\n",
|
| 239 |
+
" model.eval()\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" running_loss = 0.0\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" with torch.no_grad():\n",
|
| 244 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 245 |
+
" # Move data to device\n",
|
| 246 |
+
" X_batch.view(X_batch.size(0), -1) # shape: (batch_size, num_features)\n",
|
| 247 |
+
" y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
|
| 248 |
+
"\n",
|
| 249 |
+
" # Forward pass (continuous output)\n",
|
| 250 |
+
" outputs = model(X_batch) # shape: (batch_size, 1)\n",
|
| 251 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" running_loss += loss.item()\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" # Average loss over all batches\n",
|
| 256 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 257 |
+
"\n",
|
| 258 |
+
" return avg_loss"
|
| 259 |
+
],
|
| 260 |
+
"execution_count": null,
|
| 261 |
+
"outputs": []
|
| 262 |
+
},
|
| 263 |
+
{
|
| 264 |
+
"cell_type": "code",
|
| 265 |
+
"metadata": {},
|
| 266 |
+
"source": [
|
| 267 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"# Model parameters\n",
|
| 272 |
+
"input_dim = X_train.shape[1] # Number of features (3*36*36)\n",
|
| 273 |
+
"hidden_dim = 32 # Design choice just small for the sake of finishing fast\n",
|
| 274 |
+
"output_dim = 1\n",
|
| 275 |
+
"\n",
|
| 276 |
+
"# Instantiate regression model\n",
|
| 277 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
"# Print the model architecture\n",
|
| 280 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 281 |
+
"print(model)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"# Calculate the total number of trainable parameters\n",
|
| 284 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 285 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")\n",
|
| 286 |
+
"\n",
|
| 287 |
+
"# Hyperparameters (will experiment if theres time)\n",
|
| 288 |
+
"num_epochs = 20\n",
|
| 289 |
+
"learning_rate = 0.001\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"# Define criterion (loss function), MSE since regression or else wouldve done cross entropy for classification\n",
|
| 292 |
+
"# and added activation function such as sigmoid or softmax based on if it's needed.\n",
|
| 293 |
+
"criterion = nn.MSELoss()\n",
|
| 294 |
+
"\n",
|
| 295 |
+
"# Define optimizer\n",
|
| 296 |
+
"optimizer = AdamW(model.parameters(), learning_rate)"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 306 |
+
"train_losses = []\n",
|
| 307 |
+
"val_losses = []\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 = validate(model, criterion, test_loader, device)\n",
|
| 316 |
+
"\n",
|
| 317 |
+
" train_losses.append(train_loss)\n",
|
| 318 |
+
" val_losses.append(val_loss)\n",
|
| 319 |
+
"\n",
|
| 320 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 321 |
+
" print(\n",
|
| 322 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 323 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 324 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 325 |
+
" )\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"print('Training Complete!')\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"# The error below is due to taking the number of channels instead of the actual size of the image, but I cant find what to change in the code\n",
|
| 330 |
+
"# will come back to it later if theres time"
|
| 331 |
+
],
|
| 332 |
+
"execution_count": null,
|
| 333 |
+
"outputs": []
|
| 334 |
+
},
|
| 335 |
+
{
|
| 336 |
+
"cell_type": "code",
|
| 337 |
+
"metadata": {},
|
| 338 |
+
"source": [
|
| 339 |
+
"# Task 1: Write your code here:\n",
|
| 340 |
+
"\n",
|
| 341 |
+
"# Plotting results\n",
|
| 342 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 343 |
+
"\n",
|
| 344 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 345 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 346 |
+
"plt.title('Loss over Epochs')\n",
|
| 347 |
+
"plt.xlabel('Epoch')\n",
|
| 348 |
+
"plt.ylabel('Loss')\n",
|
| 349 |
+
"plt.legend()\n",
|
| 350 |
+
"\n",
|
| 351 |
+
"plt.tight_layout()\n",
|
| 352 |
+
"plt.show()"
|
| 353 |
+
],
|
| 354 |
+
"execution_count": null,
|
| 355 |
+
"outputs": []
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"source": [
|
| 361 |
+
"# Task 2 (Bonus): Write your code here:\n",
|
| 362 |
+
"\n",
|
| 363 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"# Get predictions on test set\n",
|
| 366 |
+
"model.eval()\n",
|
| 367 |
+
"with torch.no_grad():\n",
|
| 368 |
+
" # TODO: Get predictions for X_test\n",
|
| 369 |
+
" # [HINT]: Move X_test to device, pass through model, then move back to CPU\n",
|
| 370 |
+
" predictions = model(X_test.to(device)).cpu().numpy()\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"# TODO: Calculate evaluation metrics\n",
|
| 373 |
+
"# [HINT]: Use sklearn metrics - mean_absolute_error, mean_squared_error, r2_score\n",
|
| 374 |
+
"mae = mean_absolute_error(y_test.numpy(), predictions)\n",
|
| 375 |
+
"mse = mean_squared_error(y_test.numpy(), predictions)\n",
|
| 376 |
+
"rmse = np.sqrt(mse)\n",
|
| 377 |
+
"r2 = r2_score(y_test.numpy(), predictions)\n",
|
| 378 |
+
"\n",
|
| 379 |
+
"print(\"Model Evaluation\")\n",
|
| 380 |
+
"print(f\" MAE: ${mae:.2f}\")\n",
|
| 381 |
+
"print(f\" MSE: {mse:.2f}\")\n",
|
| 382 |
+
"print(f\" RMSE: ${rmse:.2f}\")\n",
|
| 383 |
+
"print(f\" R2: {r2:.4f}\")\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"# Scatter plot: Predicted vs Actual\n",
|
| 386 |
+
"plt.figure(figsize=(8, 6))\n",
|
| 387 |
+
"\n",
|
| 388 |
+
"# Plot: Predicted vs Actual scatter\n",
|
| 389 |
+
"plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n",
|
| 390 |
+
"\n",
|
| 391 |
+
"# Add perfect prediction line\n",
|
| 392 |
+
"min_val = min(y_test.min(), predictions.min())\n",
|
| 393 |
+
"max_val = max(y_test.max(), predictions.max())\n",
|
| 394 |
+
"plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n",
|
| 395 |
+
"\n",
|
| 396 |
+
"plt.xlabel('Actual Age', fontsize=12)\n",
|
| 397 |
+
"plt.ylabel('Predicted Age', fontsize=12)\n",
|
| 398 |
+
"plt.title('Predicted vs Actual Age', fontsize=14)\n",
|
| 399 |
+
"plt.legend()\n",
|
| 400 |
+
"plt.grid(True, alpha=0.3)\n",
|
| 401 |
+
"\n",
|
| 402 |
+
"plt.tight_layout()\n",
|
| 403 |
+
"plt.show()"
|
| 404 |
+
],
|
| 405 |
+
"execution_count": null,
|
| 406 |
+
"outputs": []
|
| 407 |
+
}
|
| 408 |
+
],
|
| 409 |
+
"metadata": {
|
| 410 |
+
"kernelspec": {
|
| 411 |
+
"display_name": "Python 3",
|
| 412 |
+
"name": "python3"
|
| 413 |
+
},
|
| 414 |
+
"language_info": {
|
| 415 |
+
"name": "python"
|
| 416 |
+
}
|
| 417 |
+
},
|
| 418 |
+
"nbformat": 4,
|
| 419 |
+
"nbformat_minor": 0
|
| 420 |
+
}
|
submissions_extracted/584/Q3.ipynb
ADDED
|
@@ -0,0 +1,403 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 LabelEncoder, OneHotEncoder\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Download latest version\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"\n",
|
| 35 |
+
"csv_path = os.path.join(path, \"Q3_data.csv\")\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"df = pd.read_csv(csv_path)"
|
| 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.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.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.describe()"
|
| 68 |
+
],
|
| 69 |
+
"execution_count": null,
|
| 70 |
+
"outputs": []
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"cell_type": "code",
|
| 74 |
+
"metadata": {},
|
| 75 |
+
"source": [
|
| 76 |
+
"# Task 1: Write your code here:\n",
|
| 77 |
+
"df = df.dropna(subset=['Target'])"
|
| 78 |
+
],
|
| 79 |
+
"execution_count": null,
|
| 80 |
+
"outputs": []
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"cell_type": "code",
|
| 84 |
+
"metadata": {},
|
| 85 |
+
"source": [
|
| 86 |
+
"# Task 2: Write your code here:\n",
|
| 87 |
+
"def check_duplicates(df):\n",
|
| 88 |
+
" duplicates = df.duplicated().sum() # This line checks for number of duplicates and sums them\n",
|
| 89 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 90 |
+
" if duplicates > 0:\n",
|
| 91 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 92 |
+
" df.drop_duplicates(inplace=True) # Here we drop the duplicates\n",
|
| 93 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 94 |
+
" else:\n",
|
| 95 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 96 |
+
"\n",
|
| 97 |
+
"check_duplicates(df)"
|
| 98 |
+
],
|
| 99 |
+
"execution_count": null,
|
| 100 |
+
"outputs": []
|
| 101 |
+
},
|
| 102 |
+
{
|
| 103 |
+
"cell_type": "code",
|
| 104 |
+
"metadata": {},
|
| 105 |
+
"source": [
|
| 106 |
+
"# Task 3: Write your code here:\n",
|
| 107 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"label_encoders = {}\n",
|
| 112 |
+
"for col in categorical_cols:\n",
|
| 113 |
+
" le = LabelEncoder()\n",
|
| 114 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 115 |
+
" label_encoders[col] = le"
|
| 116 |
+
],
|
| 117 |
+
"execution_count": null,
|
| 118 |
+
"outputs": []
|
| 119 |
+
},
|
| 120 |
+
{
|
| 121 |
+
"cell_type": "code",
|
| 122 |
+
"metadata": {},
|
| 123 |
+
"source": [
|
| 124 |
+
"# Task 4: Write your code here:\n",
|
| 125 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"scaler = StandardScaler()\n",
|
| 130 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 131 |
+
"df.head()\n"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"# Task 5: Write your code here:\n",
|
| 141 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 142 |
+
" print(\"Target Distribution:\")\n",
|
| 143 |
+
"\n",
|
| 144 |
+
" df[target_column].hist()\n",
|
| 145 |
+
" plt.show()\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"check_target_imbalance(df, \"Target\")"
|
| 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(\"Target\", axis=1).astype(float)\n",
|
| 158 |
+
"y = df['Target'].astype(float)"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"%pip install kagglehub catboost lightgbm tqdm -q"
|
| 168 |
+
],
|
| 169 |
+
"execution_count": null,
|
| 170 |
+
"outputs": []
|
| 171 |
+
},
|
| 172 |
+
{
|
| 173 |
+
"cell_type": "code",
|
| 174 |
+
"metadata": {},
|
| 175 |
+
"source": [
|
| 176 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 179 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 180 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 181 |
+
"from catboost import CatBoostClassifier\n",
|
| 182 |
+
"\n",
|
| 183 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 184 |
+
"\n",
|
| 185 |
+
"# 5-Fold Cross-Validation, shuffled, and using stratified for imbalance issue\n",
|
| 186 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
"models = {\n",
|
| 189 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 190 |
+
" verbose=0,\n",
|
| 191 |
+
" n_estimators=320,\n",
|
| 192 |
+
" max_depth=4\n",
|
| 193 |
+
" ),\n",
|
| 194 |
+
"}\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"# Storage for results\n",
|
| 197 |
+
"all_results = {}\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"for name in models:\n",
|
| 200 |
+
" all_results[name] = {'mae': [], 'mse': [], 'rmse': [], 'r2': []}\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"lr_losses = []\n",
|
| 203 |
+
"lr_mse = []\n",
|
| 204 |
+
"lr_rmse = []\n",
|
| 205 |
+
"lr_r2 = []\n",
|
| 206 |
+
"\n",
|
| 207 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 208 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 211 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" for model_name, model in models.items():\n",
|
| 214 |
+
" print(f\"Training {model_name}...\")\n",
|
| 215 |
+
"\n",
|
| 216 |
+
" # Train\n",
|
| 217 |
+
" model.fit(X_train, y_train)\n",
|
| 218 |
+
"\n",
|
| 219 |
+
" # Predict\n",
|
| 220 |
+
" y_pred = model.predict(X_test)\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # Calculate metrics\n",
|
| 223 |
+
" mse = mean_squared_error(y_test, y_pred)\n",
|
| 224 |
+
" rmse = np.sqrt(mse)\n",
|
| 225 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 226 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # Store results\n",
|
| 229 |
+
" lr_mse.append(mse)\n",
|
| 230 |
+
" lr_rmse.append(rmse)\n",
|
| 231 |
+
" lr_r2.append(r2)\n",
|
| 232 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"for model_name in all_results:\n",
|
| 235 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 236 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n",
|
| 237 |
+
" print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
|
| 238 |
+
" print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
|
| 239 |
+
" print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
|
| 240 |
+
],
|
| 241 |
+
"execution_count": null,
|
| 242 |
+
"outputs": []
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"cell_type": "code",
|
| 246 |
+
"metadata": {},
|
| 247 |
+
"source": [
|
| 248 |
+
"# Task 1: Write your code here:\n",
|
| 249 |
+
"\n",
|
| 250 |
+
"# Feature importance for only 1\n",
|
| 251 |
+
"feature_importance = pd.DataFrame({\n",
|
| 252 |
+
" 'feature': X.columns,\n",
|
| 253 |
+
" 'importance': model.feature_importances_\n",
|
| 254 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 255 |
+
"\n",
|
| 256 |
+
"plt.figure(figsize=(10, 30))\n",
|
| 257 |
+
"plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
|
| 258 |
+
"plt.xlabel('Importance')\n",
|
| 259 |
+
"plt.title('Feature Importance')\n",
|
| 260 |
+
"plt.gca().invert_yaxis()\n",
|
| 261 |
+
"plt.show()\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"# Below is for reproducibility\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 266 |
+
"importances = {}\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"importances['CatBoost'] = models['CatBoost'].feature_importances_\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"# Create a 1x3 plot\n",
|
| 271 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 20)) # change 3 to number of models, here we have only one model but cant change subplot need other code, will change later.\n",
|
| 272 |
+
"axes = axes.flatten()\n",
|
| 273 |
+
"features = X.columns\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 276 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 277 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 278 |
+
"\n",
|
| 279 |
+
" ax = axes[i]\n",
|
| 280 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 281 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 282 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"plt.tight_layout()\n",
|
| 285 |
+
"plt.show()\n",
|
| 286 |
+
"\n"
|
| 287 |
+
],
|
| 288 |
+
"execution_count": null,
|
| 289 |
+
"outputs": []
|
| 290 |
+
},
|
| 291 |
+
{
|
| 292 |
+
"cell_type": "code",
|
| 293 |
+
"metadata": {},
|
| 294 |
+
"source": [
|
| 295 |
+
"# Task 2: Write your code here:\n",
|
| 296 |
+
"print(feature_importance['feature'][0])"
|
| 297 |
+
],
|
| 298 |
+
"execution_count": null,
|
| 299 |
+
"outputs": []
|
| 300 |
+
},
|
| 301 |
+
{
|
| 302 |
+
"cell_type": "code",
|
| 303 |
+
"metadata": {},
|
| 304 |
+
"source": [
|
| 305 |
+
"# Task Bonus: Write your code here:\n",
|
| 306 |
+
"X_new = df['P_2']\n",
|
| 307 |
+
"y = df['Target'].astype(float)"
|
| 308 |
+
],
|
| 309 |
+
"execution_count": null,
|
| 310 |
+
"outputs": []
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "code",
|
| 314 |
+
"metadata": {},
|
| 315 |
+
"source": [
|
| 316 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 319 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 320 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 321 |
+
"from catboost import CatBoostClassifier\n",
|
| 322 |
+
"\n",
|
| 323 |
+
"n_splits = 5 # K=5 Folds\n",
|
| 324 |
+
"\n",
|
| 325 |
+
"# 5-Fold Cross-Validation, shuffled, and using stratified for imbalance issue\n",
|
| 326 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 327 |
+
"\n",
|
| 328 |
+
"models = {\n",
|
| 329 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 330 |
+
" verbose=0,\n",
|
| 331 |
+
" n_estimators=320,\n",
|
| 332 |
+
" max_depth=4\n",
|
| 333 |
+
" ),\n",
|
| 334 |
+
"}\n",
|
| 335 |
+
"\n",
|
| 336 |
+
"# Storage for results\n",
|
| 337 |
+
"all_results = {}\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"for name in models:\n",
|
| 340 |
+
" all_results[name] = {'mae': [], 'mse': [], 'rmse': [], 'r2': []}\n",
|
| 341 |
+
"\n",
|
| 342 |
+
"lr_losses = []\n",
|
| 343 |
+
"lr_mse = []\n",
|
| 344 |
+
"lr_rmse = []\n",
|
| 345 |
+
"lr_r2 = []\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X_new, y)):\n",
|
| 348 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 349 |
+
"\n",
|
| 350 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 351 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 352 |
+
"\n",
|
| 353 |
+
" for model_name, model in models.items():\n",
|
| 354 |
+
" print(f\"Training {model_name}...\")\n",
|
| 355 |
+
"\n",
|
| 356 |
+
" # Train\n",
|
| 357 |
+
" model.fit(X_train, y_train)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
" # Predict\n",
|
| 360 |
+
" y_pred = model.predict(X_test)\n",
|
| 361 |
+
"\n",
|
| 362 |
+
" # Calculate metrics\n",
|
| 363 |
+
" mse = mean_squared_error(y_test, y_pred)\n",
|
| 364 |
+
" rmse = np.sqrt(mse)\n",
|
| 365 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 366 |
+
" mae = mean_absolute_error(y_test, y_pred)\n",
|
| 367 |
+
"\n",
|
| 368 |
+
" # Store results\n",
|
| 369 |
+
" lr_mse.append(mse)\n",
|
| 370 |
+
" lr_rmse.append(rmse)\n",
|
| 371 |
+
" lr_r2.append(r2)\n",
|
| 372 |
+
" all_results[model_name][\"mae\"].append(mae)\n",
|
| 373 |
+
"\n",
|
| 374 |
+
"for model_name in all_results:\n",
|
| 375 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 376 |
+
" print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n",
|
| 377 |
+
" print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
|
| 378 |
+
" print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
|
| 379 |
+
" print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
|
| 380 |
+
],
|
| 381 |
+
"execution_count": null,
|
| 382 |
+
"outputs": []
|
| 383 |
+
},
|
| 384 |
+
{
|
| 385 |
+
"cell_type": "code",
|
| 386 |
+
"metadata": {},
|
| 387 |
+
"source": [],
|
| 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/585/Q1.ipynb
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
"import numpy as np\n",
|
| 12 |
+
"from sklearn.model_selection import train_test_split, KFold\n",
|
| 13 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 14 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 15 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
|
| 16 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"\n",
|
| 19 |
+
"from sklearn.model_selection import StratifiedKFold, cross_val_score\n",
|
| 20 |
+
"\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"import warnings\n",
|
| 25 |
+
"warnings.filterwarnings('ignore')\n",
|
| 26 |
+
"# Download latest version\n",
|
| 27 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
|
| 28 |
+
"\n",
|
| 29 |
+
"print(\"Path to dataset files:\", path)"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"# Task 1: Write your code here:\n",
|
| 39 |
+
"food_df = os.path.join(path, 'Q1_data.csv')\n",
|
| 40 |
+
"df_read = pd.read_csv(food_df)\n",
|
| 41 |
+
"\n",
|
| 42 |
+
"print(f\"Dataset shape: {df_read.shape}\")\n",
|
| 43 |
+
"df_read.head()"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 2: Write your code here:\n",
|
| 53 |
+
"df_read.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 |
+
"df_read.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 |
+
"df_read.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 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 84 |
+
"plt.hist(df_read['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
|
| 85 |
+
"plt.title('Delivery-Time distribution')\n",
|
| 86 |
+
"plt.xlabel('Delivary_time')\n",
|
| 87 |
+
"plt.ylabel('Frequency')\n",
|
| 88 |
+
"plt.show()"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"df_read = df_read.drop(columns=['Order_ID'], 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 |
+
"print(\"Missing values:\")\n",
|
| 108 |
+
"print(df_read.isnull().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:\n"
|
| 118 |
+
],
|
| 119 |
+
"execution_count": null,
|
| 120 |
+
"outputs": []
|
| 121 |
+
},
|
| 122 |
+
{
|
| 123 |
+
"cell_type": "code",
|
| 124 |
+
"metadata": {},
|
| 125 |
+
"source": [
|
| 126 |
+
"# Task 4: Write your code here:\n",
|
| 127 |
+
"from sklearn.preprocessing import OneHotEncoder\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"print('data before encoding:\\n', df_read)\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"onehot_encoder = OneHotEncoder(sparse_output=False)\n",
|
| 132 |
+
"data_onehot_encoded = onehot_encoder.fit_transform(df_read)\n",
|
| 133 |
+
"\n",
|
| 134 |
+
"print('\\nData after encoding:\\n', data_onehot_encoded)"
|
| 135 |
+
],
|
| 136 |
+
"execution_count": null,
|
| 137 |
+
"outputs": []
|
| 138 |
+
},
|
| 139 |
+
{
|
| 140 |
+
"cell_type": "code",
|
| 141 |
+
"metadata": {},
|
| 142 |
+
"source": [
|
| 143 |
+
"# Task 5: Write your code here :\n",
|
| 144 |
+
"stat_cols = ['Order_ID',\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
|
| 145 |
+
"\n"
|
| 146 |
+
],
|
| 147 |
+
"execution_count": null,
|
| 148 |
+
"outputs": []
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"cell_type": "code",
|
| 152 |
+
"metadata": {},
|
| 153 |
+
"source": [
|
| 154 |
+
"# Task 6: Write your code here:\n",
|
| 155 |
+
"\n",
|
| 156 |
+
"\n"
|
| 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 |
+
"feature_cols = ['Distance_km'\t,'Preparation_Time_min'\t,'Courier_Experience_yrs']\n",
|
| 167 |
+
"\n",
|
| 168 |
+
"X = df_read[feature_cols]\n",
|
| 169 |
+
"y = df_read['Delivery_Time']\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 173 |
+
"print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
|
| 174 |
+
"print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n",
|
| 175 |
+
"\n",
|
| 176 |
+
"# Didn't know how to fix it."
|
| 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:\n",
|
| 186 |
+
"scaler = StandardScaler()\n",
|
| 187 |
+
"X_train_scaled = scaler.fit_transform(X_train)\n",
|
| 188 |
+
"X_test_scaled = scaler.transform(X_test)\n",
|
| 189 |
+
"#-------------------------------------------------------------------------\n",
|
| 190 |
+
"\n",
|
| 191 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 192 |
+
" class_weight='balanced', random_state=42)\n",
|
| 193 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 194 |
+
"print(\"Model trained!\")\n",
|
| 195 |
+
"\n",
|
| 196 |
+
"#-------------------------------------------------------------------------\n",
|
| 197 |
+
"y_pred = model.predict(X_test_scaled)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n",
|
| 200 |
+
"print(classification_report(y_test, y_pred, target_names=['Normal', 'Legendary']))\n"
|
| 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 |
+
"importance = pd.DataFrame({\n",
|
| 211 |
+
" 'feature': feature_cols,\n",
|
| 212 |
+
" 'importance': model.feature_importances_\n",
|
| 213 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 216 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 217 |
+
"plt.xlabel('Importance')\n",
|
| 218 |
+
"plt.title('Feature Importance')\n",
|
| 219 |
+
"plt.gca().invert_yaxis()\n",
|
| 220 |
+
"plt.show()"
|
| 221 |
+
],
|
| 222 |
+
"execution_count": null,
|
| 223 |
+
"outputs": []
|
| 224 |
+
},
|
| 225 |
+
{
|
| 226 |
+
"cell_type": "code",
|
| 227 |
+
"metadata": {},
|
| 228 |
+
"source": [
|
| 229 |
+
"# Task 2: Write your code here:"
|
| 230 |
+
],
|
| 231 |
+
"execution_count": null,
|
| 232 |
+
"outputs": []
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"cell_type": "code",
|
| 236 |
+
"metadata": {},
|
| 237 |
+
"source": [
|
| 238 |
+
"# Task Bonus: Write your code here:"
|
| 239 |
+
],
|
| 240 |
+
"execution_count": null,
|
| 241 |
+
"outputs": []
|
| 242 |
+
}
|
| 243 |
+
],
|
| 244 |
+
"metadata": {
|
| 245 |
+
"kernelspec": {
|
| 246 |
+
"display_name": "Python 3",
|
| 247 |
+
"name": "python3"
|
| 248 |
+
},
|
| 249 |
+
"language_info": {
|
| 250 |
+
"name": "python"
|
| 251 |
+
}
|
| 252 |
+
},
|
| 253 |
+
"nbformat": 4,
|
| 254 |
+
"nbformat_minor": 0
|
| 255 |
+
}
|
submissions_extracted/585/Q2.ipynb
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"import torch\n",
|
| 9 |
+
"import torch.nn as nn\n",
|
| 10 |
+
"from torchvision.datasets import MNIST\n",
|
| 11 |
+
"from torch.utils.data import DataLoader\n",
|
| 12 |
+
"from torch.optim import Adam\n",
|
| 13 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 14 |
+
"import torch.nn.functional as F\n",
|
| 15 |
+
"import matplotlib.pyplot as plt\n",
|
| 16 |
+
"from torch.optim import AdamW\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Download latest version\n",
|
| 19 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q2-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 |
+
"import os\n",
|
| 31 |
+
"import pandas as pd\n",
|
| 32 |
+
"import numpy as np\n",
|
| 33 |
+
"from PIL import Image\n",
|
| 34 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# Load Labels\n",
|
| 37 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 38 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"images = []\n",
|
| 41 |
+
"ages = []\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"# Load Images and Resize\n",
|
| 44 |
+
"print(\"Loading images...\")\n",
|
| 45 |
+
"for index, row in labels_df.iterrows():\n",
|
| 46 |
+
" img_name = row.iloc[0]\n",
|
| 47 |
+
" age = row.iloc[1]\n",
|
| 48 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
" if os.path.exists(img_path):\n",
|
| 51 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 52 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 53 |
+
" images.append(img_array)\n",
|
| 54 |
+
" ages.append(age)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"X = np.array(images)\n",
|
| 57 |
+
"y = np.array(ages)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 60 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Split Data\n",
|
| 63 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 66 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 67 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 68 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors , # 4. Print shape of one batch\n",
|
| 78 |
+
"\n",
|
| 79 |
+
"train_dataset = MNIST(\n",
|
| 80 |
+
" root='./datasets',\n",
|
| 81 |
+
" train=True,\n",
|
| 82 |
+
" transform=to_tensor,\n",
|
| 83 |
+
" download=True\n",
|
| 84 |
+
")\n",
|
| 85 |
+
"\n",
|
| 86 |
+
"# Testing dataset\n",
|
| 87 |
+
"test_dataset = MNIST(\n",
|
| 88 |
+
" root='./datasets', # Dataset storage path\n",
|
| 89 |
+
" train=False, # Use test data\n",
|
| 90 |
+
" transform=to_tensor, # Convert images to tensors\n",
|
| 91 |
+
" download=True # Download if not available\n",
|
| 92 |
+
")\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"\n",
|
| 95 |
+
"\n",
|
| 96 |
+
"sample_image, sample_label = train_dataset[0]\n",
|
| 97 |
+
"\n",
|
| 98 |
+
"print(f\"\\n Image shape: {sample_image.shape}\")\n",
|
| 99 |
+
"print(f\"Label: {sample_label}\")\n"
|
| 100 |
+
],
|
| 101 |
+
"execution_count": null,
|
| 102 |
+
"outputs": []
|
| 103 |
+
},
|
| 104 |
+
{
|
| 105 |
+
"cell_type": "code",
|
| 106 |
+
"metadata": {},
|
| 107 |
+
"source": [
|
| 108 |
+
"# 2. Create TensorDataset objects , # 3. Create DataLoaders\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"train_loader = DataLoader(\n",
|
| 112 |
+
" train_dataset,\n",
|
| 113 |
+
" batch_size=32,\n",
|
| 114 |
+
" shuffle=True,\n",
|
| 115 |
+
" num_workers=2\n",
|
| 116 |
+
")\n",
|
| 117 |
+
"# DataLoader for test/validation data\n",
|
| 118 |
+
"test_loader = DataLoader(\n",
|
| 119 |
+
" test_dataset,\n",
|
| 120 |
+
" batch_size=32,\n",
|
| 121 |
+
" shuffle=False,\n",
|
| 122 |
+
" num_workers=2\n",
|
| 123 |
+
")\n",
|
| 124 |
+
"# Get the first batch from the training DataLoader\n",
|
| 125 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 126 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 127 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")"
|
| 128 |
+
],
|
| 129 |
+
"execution_count": null,
|
| 130 |
+
"outputs": []
|
| 131 |
+
},
|
| 132 |
+
{
|
| 133 |
+
"cell_type": "code",
|
| 134 |
+
"metadata": {},
|
| 135 |
+
"source": [
|
| 136 |
+
"# 5. Display sample images\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"images, labels = next(iter(train_loader))\n",
|
| 139 |
+
"\n",
|
| 140 |
+
"# Display the first 6 images in the batch\n",
|
| 141 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"for i in range(6):\n",
|
| 144 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 145 |
+
" plt.imshow(images[i].squeeze(), cmap='gray')\n",
|
| 146 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 147 |
+
" plt.axis('off')\n",
|
| 148 |
+
"\n",
|
| 149 |
+
"plt.tight_layout()\n",
|
| 150 |
+
"plt.show()"
|
| 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 |
+
"class NN3Layer(nn.Module):\n",
|
| 161 |
+
"\n",
|
| 162 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 163 |
+
" super(NN3Layer, self).__init__()\n",
|
| 164 |
+
"\n",
|
| 165 |
+
" # First linear layer: input features -> hidden layer\n",
|
| 166 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 167 |
+
"\n",
|
| 168 |
+
" # Second linear layer: hidden layer -> hidden layer\n",
|
| 169 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" # Output layer: hidden layer -> number of classes (logits)\n",
|
| 172 |
+
" self.layer3 = nn.Linear(hidden_dim, output_dim)\n",
|
| 173 |
+
"\n",
|
| 174 |
+
" # ReLU activation for non-linearity\n",
|
| 175 |
+
" self.relu = nn.ReLU()\n",
|
| 176 |
+
"\n",
|
| 177 |
+
" # Defines how input data flows through the network\n",
|
| 178 |
+
" def forward(self, x):\n",
|
| 179 |
+
" # First hidden layer\n",
|
| 180 |
+
" z1 = self.layer1(x)\n",
|
| 181 |
+
" a1 = self.relu(z1)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # Second hidden layer\n",
|
| 184 |
+
" z2 = self.layer2(a1)\n",
|
| 185 |
+
" a2 = self.relu(z2)\n",
|
| 186 |
+
"\n",
|
| 187 |
+
" # Output layer (raw scores / logits)\n",
|
| 188 |
+
" output = self.layer3(a2) # there is something missing here, remember? :)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" return output"
|
| 191 |
+
],
|
| 192 |
+
"execution_count": null,
|
| 193 |
+
"outputs": []
|
| 194 |
+
},
|
| 195 |
+
{
|
| 196 |
+
"cell_type": "code",
|
| 197 |
+
"metadata": {},
|
| 198 |
+
"source": [
|
| 199 |
+
"# Task 2: Write your training loop here:\n",
|
| 200 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 201 |
+
" # Set the model to training mode\n",
|
| 202 |
+
" model.train()\n",
|
| 203 |
+
"\n",
|
| 204 |
+
" running_loss = 0.0\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 207 |
+
" # Move batch to the selected device\n",
|
| 208 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 209 |
+
" y_batch = y_batch.to(device)\n",
|
| 210 |
+
"\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"\n",
|
| 213 |
+
" outputs = model(X_batch)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 216 |
+
"\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" optimizer.zero_grad()\n",
|
| 219 |
+
" loss.backward()\n",
|
| 220 |
+
" optimizer.step()\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" running_loss += loss.item()\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"\n",
|
| 225 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" return avg_loss"
|
| 228 |
+
],
|
| 229 |
+
"execution_count": null,
|
| 230 |
+
"outputs": []
|
| 231 |
+
},
|
| 232 |
+
{
|
| 233 |
+
"cell_type": "code",
|
| 234 |
+
"metadata": {},
|
| 235 |
+
"source": [
|
| 236 |
+
"# Task 3: Write your validation loop here:\n",
|
| 237 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 238 |
+
"\n",
|
| 239 |
+
" model.eval()\n",
|
| 240 |
+
"\n",
|
| 241 |
+
" running_loss = 0.0\n",
|
| 242 |
+
" correct = 0\n",
|
| 243 |
+
" total = 0\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" with torch.no_grad():\n",
|
| 246 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 247 |
+
" # Move data to device\n",
|
| 248 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 249 |
+
" y_batch = y_batch.to(device)\n",
|
| 250 |
+
"\n",
|
| 251 |
+
" # Forward pass\n",
|
| 252 |
+
"\n",
|
| 253 |
+
" outputs = model(X_batch)\n",
|
| 254 |
+
"\n",
|
| 255 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 256 |
+
" running_loss += loss.item()\n",
|
| 257 |
+
"\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 260 |
+
"\n",
|
| 261 |
+
"\n",
|
| 262 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 263 |
+
"\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 266 |
+
" total += y_batch.size(0)\n",
|
| 267 |
+
"\n",
|
| 268 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" accuracy = correct / total\n",
|
| 271 |
+
"\n",
|
| 272 |
+
" return avg_loss, accuracy\n"
|
| 273 |
+
],
|
| 274 |
+
"execution_count": null,
|
| 275 |
+
"outputs": []
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"cell_type": "code",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"source": [
|
| 281 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 282 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 283 |
+
"\n",
|
| 284 |
+
"# Model parameters\n",
|
| 285 |
+
"input_dim = 28 * 28\n",
|
| 286 |
+
"hidden_dim = 14\n",
|
| 287 |
+
"output_dim = 10\n",
|
| 288 |
+
"\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 294 |
+
"print(model)\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 298 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 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 |
+
"num_epochs = 20\n",
|
| 309 |
+
"learning_rate = 0.003\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"\n",
|
| 312 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 313 |
+
"\n",
|
| 314 |
+
"optimizer = Adam(model.parameters(), learning_rate)\n",
|
| 315 |
+
"\n",
|
| 316 |
+
"#------------------------------------------------------------------------------------------\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 |
+
"\n",
|
| 324 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"\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": "python3"
|
| 374 |
+
},
|
| 375 |
+
"language_info": {
|
| 376 |
+
"name": "python"
|
| 377 |
+
}
|
| 378 |
+
},
|
| 379 |
+
"nbformat": 4,
|
| 380 |
+
"nbformat_minor": 0
|
| 381 |
+
}
|
submissions_extracted/585/Q3.ipynb
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"%pip install kagglehub catboost xgboost tqdm -q\n",
|
| 8 |
+
"import kagglehub\n",
|
| 9 |
+
"import os\n",
|
| 10 |
+
"import pandas as pd\n",
|
| 11 |
+
"import matplotlib.pyplot as plt\n",
|
| 12 |
+
"import numpy as np\n",
|
| 13 |
+
"from xgboost import XGBClassifier\n",
|
| 14 |
+
"from xgboost import XGBClassifier\n",
|
| 15 |
+
"from catboost import CatBoostClassifier\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"\n",
|
| 18 |
+
"# Download latest version\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"print(\"Path to dataset files:\", path)"
|
| 25 |
+
],
|
| 26 |
+
"execution_count": null,
|
| 27 |
+
"outputs": []
|
| 28 |
+
},
|
| 29 |
+
{
|
| 30 |
+
"cell_type": "code",
|
| 31 |
+
"metadata": {},
|
| 32 |
+
"source": [
|
| 33 |
+
"# Task 1: Write your code here:\n",
|
| 34 |
+
"food_df = os.path.join(path, 'Q3_data.csv')\n",
|
| 35 |
+
"df_read = pd.read_csv(food_df)\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"print(f\"Dataset shape: {df_read.shape}\")\n",
|
| 38 |
+
"df_read.head()"
|
| 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_read.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_read.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_read.describe()"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 1: Write your code here:\n",
|
| 78 |
+
"def check_missing_values(df_read):\n",
|
| 79 |
+
" missing_values = df_read.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_read)\n",
|
| 88 |
+
"#------------------------------------------------------------\n",
|
| 89 |
+
"categorical_cols = df_read.select_dtypes(include=[\"object\"]).columns\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 92 |
+
"\n",
|
| 93 |
+
"for col in df_read.columns:\n",
|
| 94 |
+
" if df_read[col].dtype in ['float64', 'int64']:\n",
|
| 95 |
+
" if df_read[col].isnull().any():\n",
|
| 96 |
+
" median_val = df_read[col].median()\n",
|
| 97 |
+
" df_read[col].fillna(median_val, inplace=True)\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"print(\"Missing values after imputation:\")\n",
|
| 100 |
+
"print(df_read.isnull().sum()[df_read.isnull().sum() > 0])\n",
|
| 101 |
+
"\n",
|
| 102 |
+
"if df_read.isnull().sum().sum() == 0:\n",
|
| 103 |
+
" print(\"\\nAll missing values have been handled.\")\n",
|
| 104 |
+
"else:\n",
|
| 105 |
+
" print(\"\\nSome missing values remain (e.g., if there were non-numeric columns with NaNs that were not handled).\")"
|
| 106 |
+
],
|
| 107 |
+
"execution_count": null,
|
| 108 |
+
"outputs": []
|
| 109 |
+
},
|
| 110 |
+
{
|
| 111 |
+
"cell_type": "code",
|
| 112 |
+
"metadata": {},
|
| 113 |
+
"source": [
|
| 114 |
+
"# Task 2: Write your code here:\n",
|
| 115 |
+
"\n",
|
| 116 |
+
"def check_duplicates(df_read):\n",
|
| 117 |
+
" duplicates = df_read.duplicated().sum()\n",
|
| 118 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 119 |
+
" if duplicates > 0:\n",
|
| 120 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 121 |
+
" df_read.drop_duplicates(inplace=True)\n",
|
| 122 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 123 |
+
" else:\n",
|
| 124 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"check_duplicates(df_read)"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 3: Write your code here:\n",
|
| 136 |
+
"categorical_cols = df_read.select_dtypes(include=[\"object\"]).columns\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n"
|
| 139 |
+
],
|
| 140 |
+
"execution_count": null,
|
| 141 |
+
"outputs": []
|
| 142 |
+
},
|
| 143 |
+
{
|
| 144 |
+
"cell_type": "code",
|
| 145 |
+
"metadata": {},
|
| 146 |
+
"source": [
|
| 147 |
+
"# Task 4: Write your code here:\n",
|
| 148 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 149 |
+
"\n",
|
| 150 |
+
"numerical_cols = df_read.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 151 |
+
"\n",
|
| 152 |
+
"scaler = StandardScaler()\n",
|
| 153 |
+
"df_read[numerical_cols] = scaler.fit_transform(df_read[numerical_cols])\n",
|
| 154 |
+
"df_read.head()"
|
| 155 |
+
],
|
| 156 |
+
"execution_count": null,
|
| 157 |
+
"outputs": []
|
| 158 |
+
},
|
| 159 |
+
{
|
| 160 |
+
"cell_type": "code",
|
| 161 |
+
"metadata": {},
|
| 162 |
+
"source": [
|
| 163 |
+
"# Task 5: Write your code here:\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"print(\"Target variable distribution:\")\n",
|
| 166 |
+
"print(df_read['Target'].value_counts())\n",
|
| 167 |
+
"print(\"\\nTarget variable percentages:\")\n",
|
| 168 |
+
"print(df_read['Target'].value_counts(normalize=True) * 100)\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"if df_read['Target'].value_counts(normalize=True).min() < 0.2:\n",
|
| 172 |
+
" print(\"\\nThe target variable is imbalanced.\")\n",
|
| 173 |
+
"else:\n",
|
| 174 |
+
" print(\"\\nThe target variable is not significantly imbalanced.\")"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"# Task 1: Write your code here:\n",
|
| 184 |
+
"X = df_read.drop(\"Target\", axis=1).astype(float)\n",
|
| 185 |
+
"y = df_read['Target'].astype(float)"
|
| 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 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 196 |
+
"from catboost import CatBoostClassifier\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"\n",
|
| 199 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 200 |
+
"\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"f1_scores = []\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"for fold, (train_index, val_index) in enumerate(skf.split(X, y)):\n",
|
| 206 |
+
" print(f\"\\nFold {fold+1}/\")\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n",
|
| 209 |
+
" y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n",
|
| 210 |
+
"\n",
|
| 211 |
+
" model = CatBoostClassifier(random_state=42, verbose=0, iterations=100)\n",
|
| 212 |
+
" model.fit(X_train, y_train)\n",
|
| 213 |
+
"\n",
|
| 214 |
+
" from sklearn.model_selection import StratifiedKFold\n",
|
| 215 |
+
"from catboost import CatBoostClassifier\n",
|
| 216 |
+
"from sklearn.metrics import f1_score\n",
|
| 217 |
+
"\n",
|
| 218 |
+
"\n",
|
| 219 |
+
"skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 220 |
+
"\n",
|
| 221 |
+
"\n",
|
| 222 |
+
"f1_scores = []\n",
|
| 223 |
+
"\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"for fold, (train_index, val_index) in enumerate(skf.split(X, y)):\n",
|
| 226 |
+
" print(f\"\\nFold {fold+1}/\")\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" X_train, X_val = X.iloc[train_index], X.iloc[val_index]\n",
|
| 229 |
+
" y_train, y_val = y.iloc[train_index], y.iloc[val_index]\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" model = CatBoostClassifier(random_state=42, verbose=0, iterations=100)\n",
|
| 232 |
+
" model.fit(X_train, y_train)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" y_pred = model.predict(X_val)\n",
|
| 236 |
+
"\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" f1 = f1_score(y_val, y_pred)\n",
|
| 239 |
+
" f1_scores.append(f1)\n",
|
| 240 |
+
" print(f\"F1-score for Fold {fold+1}: {f1:.4f}\")\n",
|
| 241 |
+
"\n",
|
| 242 |
+
"\n",
|
| 243 |
+
"avg_f1_score = np.mean(f1_scores)\n",
|
| 244 |
+
"print(f\"\\nAverage F1-score across all folds: {avg_f1_score:.4f}\")\n",
|
| 245 |
+
"\n",
|
| 246 |
+
""
|
| 247 |
+
],
|
| 248 |
+
"execution_count": null,
|
| 249 |
+
"outputs": []
|
| 250 |
+
},
|
| 251 |
+
{
|
| 252 |
+
"cell_type": "code",
|
| 253 |
+
"metadata": {},
|
| 254 |
+
"source": [
|
| 255 |
+
"# Task 1: Write your code here:\n",
|
| 256 |
+
"feature_importances = model.get_feature_importance()\n",
|
| 257 |
+
"feature_names = X.columns\n",
|
| 258 |
+
"\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"importance_series = pd.Series(feature_importances, index=feature_names)\n",
|
| 261 |
+
"\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"sorted_importance = importance_series.sort_values(ascending=False)\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"\n",
|
| 266 |
+
"top_n = 10\n",
|
| 267 |
+
"top_features = sorted_importance.head(top_n)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
"\n",
|
| 270 |
+
"plt.figure(figsize=(12, 8))\n",
|
| 271 |
+
"top_features.plot(kind='barh')\n",
|
| 272 |
+
"plt.xlabel('Feature Importance')\n",
|
| 273 |
+
"plt.ylabel('Feature Name')\n",
|
| 274 |
+
"plt.title(f'Top {top_n} Most Important Features')\n",
|
| 275 |
+
"plt.gca().invert_yaxis()\n",
|
| 276 |
+
"plt.show()\n"
|
| 277 |
+
],
|
| 278 |
+
"execution_count": null,
|
| 279 |
+
"outputs": []
|
| 280 |
+
},
|
| 281 |
+
{
|
| 282 |
+
"cell_type": "code",
|
| 283 |
+
"metadata": {},
|
| 284 |
+
"source": [
|
| 285 |
+
"# Task 2: Write your code here:\n",
|
| 286 |
+
"golden_feature = sorted_importance.index[0]\n",
|
| 287 |
+
"print(f\"The golden feature (most important feature) is: {golden_feature}\")"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"# Task Bonus: Write your code here:\n",
|
| 297 |
+
"X = df_read"
|
| 298 |
+
],
|
| 299 |
+
"execution_count": null,
|
| 300 |
+
"outputs": []
|
| 301 |
+
}
|
| 302 |
+
],
|
| 303 |
+
"metadata": {
|
| 304 |
+
"kernelspec": {
|
| 305 |
+
"display_name": "Python 3",
|
| 306 |
+
"name": "python3"
|
| 307 |
+
},
|
| 308 |
+
"language_info": {
|
| 309 |
+
"name": "python"
|
| 310 |
+
}
|
| 311 |
+
},
|
| 312 |
+
"nbformat": 4,
|
| 313 |
+
"nbformat_minor": 0
|
| 314 |
+
}
|
submissions_extracted/586/Q1.ipynb
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import numpy as np # Numerical computations\n",
|
| 8 |
+
"import pandas as pd # Data manipulation (DataFrames)\n",
|
| 9 |
+
"import matplotlib.pyplot as plt # Plotting and visualization\n",
|
| 10 |
+
"import os # Operating system utilities"
|
| 11 |
+
],
|
| 12 |
+
"execution_count": null,
|
| 13 |
+
"outputs": []
|
| 14 |
+
},
|
| 15 |
+
{
|
| 16 |
+
"cell_type": "code",
|
| 17 |
+
"metadata": {},
|
| 18 |
+
"source": [
|
| 19 |
+
"import kagglehub\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 |
+
"\n",
|
| 35 |
+
"data_path = os.path.join(path, 'Q1_data.csv') # Create full path to CSV file\n",
|
| 36 |
+
"df_Q1 = pd.read_csv(data_path) # Read CSV into DataFrame\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"print(f\"Dataset shape: {df_Q1.shape}\") # Show number of rows and columns"
|
| 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_Q1.head() # Display first 5 rows"
|
| 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_Q1.info() # Display dataset information"
|
| 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_Q1.describe() # Show statistical description using"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# Task 5: Write your code here:\n",
|
| 78 |
+
"# target distribution\n",
|
| 79 |
+
"plt.figure(figsize=(10, 8))\n",
|
| 80 |
+
"plt.hist(df_Q1['Delivery_Time'].dropna(), bins=50, color='pink', edgecolor='black') # dropna() removes rows with missing values.\n",
|
| 81 |
+
"plt.title('target distribution')\n",
|
| 82 |
+
"plt.show()"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 1: Write your code here:\n",
|
| 92 |
+
"cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n",
|
| 93 |
+
"df_clean = df_Q1[cols].copy()\n",
|
| 94 |
+
"df_clean = df_clean.drop(columns=['Order_ID'])\n",
|
| 95 |
+
"df_clean.head()"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# Task 2: Write your code here:\n",
|
| 105 |
+
"# Analyze missing values\n",
|
| 106 |
+
"missing_percentage = (df_Q1.isnull().sum() / len(df_Q1))\n",
|
| 107 |
+
"missing_data = pd.DataFrame({\n",
|
| 108 |
+
" 'Column': missing_percentage.index, # Column names\n",
|
| 109 |
+
" 'Missing_Percentage': missing_percentage.values # Missing value percentages\n",
|
| 110 |
+
"})\n",
|
| 111 |
+
"missing_data = missing_data[\n",
|
| 112 |
+
" missing_data['Missing_Percentage'] > 0\n",
|
| 113 |
+
"].sort_values('Missing_Percentage', ascending=False) # Keep columns with missing values and sort by percentage\n",
|
| 114 |
+
"print(\"Missing Data Analysis:\") # Print title\n",
|
| 115 |
+
"missing_data.head(10) # Show top 10 columns\n",
|
| 116 |
+
"#----------------------------------------------------\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
|
| 119 |
+
"for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
|
| 120 |
+
" df_clean[col] = df_clean[col].fillna('unknown')\n",
|
| 121 |
+
" # Replace missing text values with 'unknown'\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Fill numarical data with mode, mean\n",
|
| 124 |
+
"df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(\n",
|
| 125 |
+
" df_clean['Courier_Experience_yrs'].mode()[0] ) # Replace missing Courier_Experience_yrs with the most common value\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"\n",
|
| 128 |
+
"df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(\n",
|
| 129 |
+
" df_clean['Delivery_Time'].mode()[0] ) # Replace missing Delivery_Time with the mean\n",
|
| 130 |
+
"\n",
|
| 131 |
+
"print(\"Missing values remaining:\", df_clean.isnull().sum().sum()) # Check total remaining missing values\n"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"# Task 3: Write your code here:\n",
|
| 141 |
+
"def check_duplicates(df):\n",
|
| 142 |
+
" duplicates = df_clean.duplicated().sum()\n",
|
| 143 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 144 |
+
" if duplicates > 0:\n",
|
| 145 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 146 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 147 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 148 |
+
" else:\n",
|
| 149 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 150 |
+
"\n",
|
| 151 |
+
"check_duplicates(df_clean)"
|
| 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 LabelEncoder\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
|
| 164 |
+
"\n",
|
| 165 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 166 |
+
"label_encoders = {}\n",
|
| 167 |
+
"for col in categorical_cols:\n",
|
| 168 |
+
" le = LabelEncoder()\n",
|
| 169 |
+
" df_clean[col] = le.fit_transform(df_clean[col])\n",
|
| 170 |
+
" label_encoders[col] = le\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"df_clean"
|
| 173 |
+
],
|
| 174 |
+
"execution_count": null,
|
| 175 |
+
"outputs": []
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"cell_type": "code",
|
| 179 |
+
"metadata": {},
|
| 180 |
+
"source": [
|
| 181 |
+
"# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n",
|
| 182 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 183 |
+
"\n",
|
| 184 |
+
"numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # no need to scale target\n",
|
| 185 |
+
"scaler = StandardScaler()\n",
|
| 186 |
+
"df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
|
| 187 |
+
"df_clean.head()"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
|
| 197 |
+
"\n",
|
| 198 |
+
"def check_target_imbalance(df_clean, target_column):\n",
|
| 199 |
+
" print(\"Target Distribution:\")\n",
|
| 200 |
+
"\n",
|
| 201 |
+
" df_clean[target_column].hist()\n",
|
| 202 |
+
" plt.show()\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"check_target_imbalance(df_clean, \"Delivery_Time\")"
|
| 205 |
+
],
|
| 206 |
+
"execution_count": null,
|
| 207 |
+
"outputs": []
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"cell_type": "code",
|
| 211 |
+
"metadata": {},
|
| 212 |
+
"source": [
|
| 213 |
+
"#it is not impalanced"
|
| 214 |
+
],
|
| 215 |
+
"execution_count": null,
|
| 216 |
+
"outputs": []
|
| 217 |
+
},
|
| 218 |
+
{
|
| 219 |
+
"cell_type": "code",
|
| 220 |
+
"metadata": {},
|
| 221 |
+
"source": [
|
| 222 |
+
"%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n"
|
| 223 |
+
],
|
| 224 |
+
"execution_count": null,
|
| 225 |
+
"outputs": []
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"cell_type": "code",
|
| 229 |
+
"metadata": {},
|
| 230 |
+
"source": [
|
| 231 |
+
"# Task 1: Write your code here: 1. Split the dataset into features (X) and target (y)\n",
|
| 232 |
+
"X = df_clean.drop('Delivery_Time', axis=1)\n",
|
| 233 |
+
"y = df_clean['Delivery_Time']"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 243 |
+
"# Import models\n",
|
| 244 |
+
"from sklearn.neighbors import KNeighborsClassifier\n",
|
| 245 |
+
"from sklearn.svm import SVC\n",
|
| 246 |
+
"from sklearn.tree import DecisionTreeClassifier\n",
|
| 247 |
+
"from xgboost import XGBClassifier\n",
|
| 248 |
+
"from catboost import CatBoostClassifier\n",
|
| 249 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 250 |
+
"from sklearn.model_selection import KFold #cuz its not impalanced\n",
|
| 251 |
+
"\n",
|
| 252 |
+
"num_classes = len(np.unique(y_encoded))\n",
|
| 253 |
+
"\n",
|
| 254 |
+
"# 1. Initialize the machine learning models\n",
|
| 255 |
+
"models = {\n",
|
| 256 |
+
" 'Random Forest': RandomForestClassifier(n_estimators=100, random_state=42)}\n",
|
| 257 |
+
"# 2. Create a KFold object\n",
|
| 258 |
+
"kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"# 3. Create an empty dictionary to store average losses\n",
|
| 261 |
+
"model_losses = {}\n",
|
| 262 |
+
"\n",
|
| 263 |
+
"print(\"Starting K-Fold Cross-Validation for each model...\")\n",
|
| 264 |
+
"\n",
|
| 265 |
+
"# 4. For each model:\n",
|
| 266 |
+
"for model_name, model in models.items():\n",
|
| 267 |
+
" print(f\"\\nTraining and evaluating {model_name}...\")\n",
|
| 268 |
+
" fold_losses = [] # List to store loss from each fold\n",
|
| 269 |
+
"\n",
|
| 270 |
+
" for fold, (train_index, val_index) in enumerate(kf.split(X)):\n",
|
| 271 |
+
" # Split X_train and y_train into training and validation sets for the current fold\n",
|
| 272 |
+
" X_train_fold, X_val_fold = X.iloc[train_index], X.iloc[val_index]\n",
|
| 273 |
+
" y_train_fold, y_val_fold = y[train_index], y[val_index]\n",
|
| 274 |
+
"\n",
|
| 275 |
+
" # Train the current model\n",
|
| 276 |
+
" model.fit(X_train_fold, y_train_fold)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" # Generate predictions (probabilities) on the validation set\n",
|
| 279 |
+
" y_pred_proba = model.predict_proba(X_val_fold)\n",
|
| 280 |
+
"\n",
|
| 281 |
+
" # Calculate the average loss for the model\n",
|
| 282 |
+
" avg_loss = np.mean(fold_losses)\n",
|
| 283 |
+
" model_losses[model_name] = avg_loss\n",
|
| 284 |
+
"\n",
|
| 285 |
+
" # Print the average cross-validation loss for the current model\n",
|
| 286 |
+
" print(f\"{model_name} - Average Cross-Validation Loss: {avg_loss:.4f}\")\n",
|
| 287 |
+
"\n",
|
| 288 |
+
"print(\"\\nAll models trained and evaluated. Stored average losses:\")\n",
|
| 289 |
+
"print(model_losses)\n",
|
| 290 |
+
"\n",
|
| 291 |
+
"\n",
|
| 292 |
+
"sklearn_models = {\n",
|
| 293 |
+
" \"Random Forest\": RandomForestClassifier(\n",
|
| 294 |
+
" n_estimators=320, # Number of trees\n",
|
| 295 |
+
" max_depth=4\n",
|
| 296 |
+
" )\n",
|
| 297 |
+
"}\n",
|
| 298 |
+
"all_results = {}\n"
|
| 299 |
+
],
|
| 300 |
+
"execution_count": null,
|
| 301 |
+
"outputs": []
|
| 302 |
+
},
|
| 303 |
+
{
|
| 304 |
+
"cell_type": "code",
|
| 305 |
+
"metadata": {},
|
| 306 |
+
"source": [
|
| 307 |
+
"# Task 1: Write your code here:\n",
|
| 308 |
+
"# Gather importances from the models (from the last fold)\n",
|
| 309 |
+
"importances = {}\n",
|
| 310 |
+
"\n",
|
| 311 |
+
"importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
|
| 312 |
+
"# Create a 1x3 plot\n",
|
| 313 |
+
"fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
|
| 314 |
+
"axes = axes.flatten()\n",
|
| 315 |
+
"features = X.columns\n",
|
| 316 |
+
"\n",
|
| 317 |
+
"for i, (model_name, imp) in enumerate(importances.items()):\n",
|
| 318 |
+
" # Sort features by importance for a cleaner plot\n",
|
| 319 |
+
" sorted_idx = np.argsort(imp)\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" ax = axes[i]\n",
|
| 322 |
+
" ax.barh(features[sorted_idx], imp[sorted_idx])\n",
|
| 323 |
+
" ax.set_title(f\"{model_name} Feature Importance\")\n",
|
| 324 |
+
" ax.set_xlabel(\"Importance Score\")\n",
|
| 325 |
+
"\n",
|
| 326 |
+
"plt.tight_layout()\n",
|
| 327 |
+
"plt.show()"
|
| 328 |
+
],
|
| 329 |
+
"execution_count": null,
|
| 330 |
+
"outputs": []
|
| 331 |
+
},
|
| 332 |
+
{
|
| 333 |
+
"cell_type": "code",
|
| 334 |
+
"metadata": {},
|
| 335 |
+
"source": [
|
| 336 |
+
"# Task 2: Write your code here:"
|
| 337 |
+
],
|
| 338 |
+
"execution_count": null,
|
| 339 |
+
"outputs": []
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"cell_type": "code",
|
| 343 |
+
"metadata": {},
|
| 344 |
+
"source": [
|
| 345 |
+
"# Task Bonus: Write your code here:"
|
| 346 |
+
],
|
| 347 |
+
"execution_count": null,
|
| 348 |
+
"outputs": []
|
| 349 |
+
}
|
| 350 |
+
],
|
| 351 |
+
"metadata": {
|
| 352 |
+
"kernelspec": {
|
| 353 |
+
"display_name": "Python 3",
|
| 354 |
+
"name": "python3"
|
| 355 |
+
},
|
| 356 |
+
"language_info": {
|
| 357 |
+
"name": "python"
|
| 358 |
+
}
|
| 359 |
+
},
|
| 360 |
+
"nbformat": 4,
|
| 361 |
+
"nbformat_minor": 0
|
| 362 |
+
}
|
submissions_extracted/586/Q2.ipynb
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 sklearn.model_selection import train_test_split\n",
|
| 69 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 70 |
+
"from torch.utils.data import TensorDataset\n",
|
| 71 |
+
"from torch.utils.data import DataLoader\n",
|
| 72 |
+
"import torch\n",
|
| 73 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 74 |
+
"import torch.nn as nn\n",
|
| 75 |
+
"\n",
|
| 76 |
+
"from torchvision.transforms.functional import to_tensor\n",
|
| 77 |
+
"from torch.utils.data import DataLoader\n",
|
| 78 |
+
"import matplotlib.pyplot as plt\n",
|
| 79 |
+
"import torch.nn as nn\n",
|
| 80 |
+
"import torch.nn.functional as F\n",
|
| 81 |
+
"import torch\n",
|
| 82 |
+
"from torch.optim import AdamW"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 92 |
+
"X_train = torch.tensor(X_train, dtype=torch.long)\n",
|
| 93 |
+
"X_test = torch.tensor(X_test, dtype=torch.float32)\n",
|
| 94 |
+
"y_train = torch.tensor(y_train, dtype=torch.float32)\n",
|
| 95 |
+
"y_test = torch.tensor(y_test, dtype=torch.float32)"
|
| 96 |
+
],
|
| 97 |
+
"execution_count": null,
|
| 98 |
+
"outputs": []
|
| 99 |
+
},
|
| 100 |
+
{
|
| 101 |
+
"cell_type": "code",
|
| 102 |
+
"metadata": {},
|
| 103 |
+
"source": [
|
| 104 |
+
"# 2. Create TensorDataset objects\n",
|
| 105 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 106 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 107 |
+
],
|
| 108 |
+
"execution_count": null,
|
| 109 |
+
"outputs": []
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"cell_type": "code",
|
| 113 |
+
"metadata": {},
|
| 114 |
+
"source": [
|
| 115 |
+
"# 3. Create DataLoaders\n",
|
| 116 |
+
"from torch.utils.data import DataLoader\n",
|
| 117 |
+
"\n",
|
| 118 |
+
"# DataLoader for training data\n",
|
| 119 |
+
"train_loader = DataLoader(\n",
|
| 120 |
+
" train_dataset,\n",
|
| 121 |
+
" batch_size=32,\n",
|
| 122 |
+
" shuffle=True,\n",
|
| 123 |
+
" num_workers=2\n",
|
| 124 |
+
")\n",
|
| 125 |
+
"# DataLoader for test/validation data\n",
|
| 126 |
+
"test_loader = DataLoader(\n",
|
| 127 |
+
" test_dataset,\n",
|
| 128 |
+
" batch_size=32,\n",
|
| 129 |
+
" shuffle=False,\n",
|
| 130 |
+
" num_workers=2\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 |
+
"# Get the first batch from the training DataLoader\n",
|
| 142 |
+
"X_batch, y_batch = next(iter(train_loader))\n",
|
| 143 |
+
"print(f\"Training batch input shape: {X_batch.shape}\")\n",
|
| 144 |
+
"print(f\"Training batch labels shape: {y_batch.shape}\")\n"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# 5. Display sample images\n",
|
| 154 |
+
"# Get one batch of images and labels\n",
|
| 155 |
+
"images, labels = next(iter(train_loader))\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"# Display the first 6 images in the batch\n",
|
| 158 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 159 |
+
"\n",
|
| 160 |
+
"for i in range(6):\n",
|
| 161 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 162 |
+
"\n",
|
| 163 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 164 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 165 |
+
"\n",
|
| 166 |
+
" plt.imshow(img)\n",
|
| 167 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 168 |
+
" plt.axis('off')\n",
|
| 169 |
+
"\n",
|
| 170 |
+
"plt.tight_layout()\n",
|
| 171 |
+
"plt.show()"
|
| 172 |
+
],
|
| 173 |
+
"execution_count": null,
|
| 174 |
+
"outputs": []
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"cell_type": "code",
|
| 178 |
+
"metadata": {},
|
| 179 |
+
"source": [
|
| 180 |
+
"# Task 1: Write your model class here:\n",
|
| 181 |
+
"class NN4Layer(nn.Module):\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" def __init__(self, input_dim, hidden_dim, output_dim):\n",
|
| 184 |
+
" super(NN4Layer, self).__init__()\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 187 |
+
"\n",
|
| 188 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 189 |
+
"\n",
|
| 190 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 191 |
+
"\n",
|
| 192 |
+
" self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
|
| 193 |
+
"\n",
|
| 194 |
+
" # activation function for non-linearity\n",
|
| 195 |
+
" self.relu = nn.ReLU()\n",
|
| 196 |
+
"\n",
|
| 197 |
+
" # Defines how input data flows through the network\n",
|
| 198 |
+
" def forward(self, x):\n",
|
| 199 |
+
" z1 = self.layer1(x)\n",
|
| 200 |
+
" a1 = self.relu(z1)\n",
|
| 201 |
+
"\n",
|
| 202 |
+
" z2 = self.layer2(a1)\n",
|
| 203 |
+
" a2 = self.relu(z2)\n",
|
| 204 |
+
"\n",
|
| 205 |
+
" z3 = self.layer3(a2)\n",
|
| 206 |
+
" a3 = self.relu(z3)\n",
|
| 207 |
+
"\n",
|
| 208 |
+
" z4 = self.layer4(a3)\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" return z4"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"# Task 2: Write your training loop here:\n",
|
| 220 |
+
"def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
|
| 221 |
+
" # Set the model to training mode\n",
|
| 222 |
+
" model.train()\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" running_loss = 0.0\n",
|
| 225 |
+
"\n",
|
| 226 |
+
" for X_batch, y_batch in train_loader:\n",
|
| 227 |
+
" # Move batch to the selected device\n",
|
| 228 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 229 |
+
" y_batch = y_batch.to(device)\n",
|
| 230 |
+
"\n",
|
| 231 |
+
" # Forward pass\n",
|
| 232 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 233 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 234 |
+
"\n",
|
| 235 |
+
" # Backward pass & optimization\n",
|
| 236 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 237 |
+
" loss.backward() # Compute gradients\n",
|
| 238 |
+
" optimizer.step() # Update model parameters\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" running_loss += loss.item()\n",
|
| 241 |
+
"\n",
|
| 242 |
+
" # Average loss over all batches\n",
|
| 243 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 244 |
+
"\n",
|
| 245 |
+
" return avg_loss"
|
| 246 |
+
],
|
| 247 |
+
"execution_count": null,
|
| 248 |
+
"outputs": []
|
| 249 |
+
},
|
| 250 |
+
{
|
| 251 |
+
"cell_type": "code",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"# Task 3: Write your validation loop here:\n",
|
| 255 |
+
"import torch.nn.functional as F\n",
|
| 256 |
+
"\n",
|
| 257 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 258 |
+
" # Set the model to evaluation mode\n",
|
| 259 |
+
" model.eval()\n",
|
| 260 |
+
"\n",
|
| 261 |
+
" running_loss = 0.0\n",
|
| 262 |
+
" correct = 0\n",
|
| 263 |
+
" total = 0\n",
|
| 264 |
+
"\n",
|
| 265 |
+
" with torch.no_grad():\n",
|
| 266 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 267 |
+
" # Move data to device\n",
|
| 268 |
+
" X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
|
| 269 |
+
" y_batch = y_batch.to(device)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" # Forward pass\n",
|
| 272 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 273 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 274 |
+
" running_loss += loss.item()\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" probabilities = F.softmax(outputs, dim=1)\n",
|
| 277 |
+
"\n",
|
| 278 |
+
" predicted = torch.argmax(probabilities, dim=1)\n",
|
| 279 |
+
"\n",
|
| 280 |
+
" # Accuracy calculation\n",
|
| 281 |
+
" correct += (predicted == y_batch).sum().item()\n",
|
| 282 |
+
" total += y_batch.size(0)\n",
|
| 283 |
+
"\n",
|
| 284 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 285 |
+
" accuracy = correct / total\n",
|
| 286 |
+
"\n",
|
| 287 |
+
" return avg_loss, accuracy"
|
| 288 |
+
],
|
| 289 |
+
"execution_count": null,
|
| 290 |
+
"outputs": []
|
| 291 |
+
},
|
| 292 |
+
{
|
| 293 |
+
"cell_type": "code",
|
| 294 |
+
"metadata": {},
|
| 295 |
+
"source": [
|
| 296 |
+
"# Task 4: Define device, model, loss, optimizer:\n",
|
| 297 |
+
"# Device setup\n",
|
| 298 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"# Model parameters\n",
|
| 301 |
+
"input_dim = 3 * 36 * 36\n",
|
| 302 |
+
"\n",
|
| 303 |
+
"hidden_dim = 32 # Design choice\n",
|
| 304 |
+
"\n",
|
| 305 |
+
"output_dim = 32\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
|
| 308 |
+
"\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}\")\n"
|
| 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 |
+
"from torch.optim import AdamW\n",
|
| 325 |
+
"num_epochs = 20\n",
|
| 326 |
+
"\n",
|
| 327 |
+
"learning_rate = 0.001\n",
|
| 328 |
+
"\n",
|
| 329 |
+
"criterion = nn.CrossEntropyLoss()\n",
|
| 330 |
+
"\n",
|
| 331 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
"# Run Training\n",
|
| 334 |
+
"train_losses = []\n",
|
| 335 |
+
"val_losses = []\n",
|
| 336 |
+
"val_accuracies = []\n",
|
| 337 |
+
"\n",
|
| 338 |
+
"print('Starting Training...')\n",
|
| 339 |
+
"for epoch in range(num_epochs):\n",
|
| 340 |
+
" # Train one epoch\n",
|
| 341 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 342 |
+
"\n",
|
| 343 |
+
" # Validate\n",
|
| 344 |
+
" val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
|
| 345 |
+
"\n",
|
| 346 |
+
" train_losses.append(train_loss)\n",
|
| 347 |
+
" val_losses.append(val_loss)\n",
|
| 348 |
+
" val_accuracies.append(val_accuracy)\n",
|
| 349 |
+
"\n",
|
| 350 |
+
" print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
|
| 351 |
+
"\n",
|
| 352 |
+
"print('Training Complete!')"
|
| 353 |
+
],
|
| 354 |
+
"execution_count": null,
|
| 355 |
+
"outputs": []
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"source": [
|
| 361 |
+
"# Task 1: Write your code here:\n",
|
| 362 |
+
"# Plotting results\n",
|
| 363 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 364 |
+
"\n",
|
| 365 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 366 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 367 |
+
"plt.title('Loss over Epochs')\n",
|
| 368 |
+
"plt.xlabel('Epoch')\n",
|
| 369 |
+
"plt.ylabel('Loss')\n",
|
| 370 |
+
"plt.legend()\n",
|
| 371 |
+
"\n",
|
| 372 |
+
"plt.tight_layout()\n",
|
| 373 |
+
"plt.show()"
|
| 374 |
+
],
|
| 375 |
+
"execution_count": null,
|
| 376 |
+
"outputs": []
|
| 377 |
+
},
|
| 378 |
+
{
|
| 379 |
+
"cell_type": "code",
|
| 380 |
+
"metadata": {},
|
| 381 |
+
"source": [
|
| 382 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 383 |
+
],
|
| 384 |
+
"execution_count": null,
|
| 385 |
+
"outputs": []
|
| 386 |
+
},
|
| 387 |
+
{
|
| 388 |
+
"cell_type": "code",
|
| 389 |
+
"metadata": {},
|
| 390 |
+
"source": [],
|
| 391 |
+
"execution_count": null,
|
| 392 |
+
"outputs": []
|
| 393 |
+
}
|
| 394 |
+
],
|
| 395 |
+
"metadata": {
|
| 396 |
+
"kernelspec": {
|
| 397 |
+
"display_name": "Python 3",
|
| 398 |
+
"name": "python3"
|
| 399 |
+
},
|
| 400 |
+
"language_info": {
|
| 401 |
+
"name": "python"
|
| 402 |
+
}
|
| 403 |
+
},
|
| 404 |
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n"
|
| 8 |
+
],
|
| 9 |
+
"execution_count": null,
|
| 10 |
+
"outputs": []
|
| 11 |
+
},
|
| 12 |
+
{
|
| 13 |
+
"cell_type": "code",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"import numpy as np # Numerical computations\n",
|
| 17 |
+
"import pandas as pd # Data manipulation (DataFrames)\n",
|
| 18 |
+
"import matplotlib.pyplot as plt # Plotting and visualization\n",
|
| 19 |
+
"import os # Operating system utilities"
|
| 20 |
+
],
|
| 21 |
+
"execution_count": null,
|
| 22 |
+
"outputs": []
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"cell_type": "code",
|
| 26 |
+
"metadata": {},
|
| 27 |
+
"source": [
|
| 28 |
+
"import kagglehub\n",
|
| 29 |
+
"\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"# Download latest version\n",
|
| 33 |
+
"\n",
|
| 34 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"\n",
|
| 37 |
+
"\n",
|
| 38 |
+
"print(\"Path to dataset files:\", path)"
|
| 39 |
+
],
|
| 40 |
+
"execution_count": null,
|
| 41 |
+
"outputs": []
|
| 42 |
+
},
|
| 43 |
+
{
|
| 44 |
+
"cell_type": "code",
|
| 45 |
+
"metadata": {},
|
| 46 |
+
"source": [
|
| 47 |
+
"# Task 1: Write your code here:\n",
|
| 48 |
+
"\n",
|
| 49 |
+
"data_path = os.path.join(path, 'Q3_data.csv') # Create full path to CSV file\n",
|
| 50 |
+
"df_Q3 = pd.read_csv(data_path) # Read CSV into DataFrame\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"print(f\"Dataset shape: {df_Q3.shape}\")"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 2: Write your code here:\n",
|
| 62 |
+
"df_Q3.head()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 3: Write your code here:\n",
|
| 72 |
+
"df_Q3.info() # Display dataset information"
|
| 73 |
+
],
|
| 74 |
+
"execution_count": null,
|
| 75 |
+
"outputs": []
|
| 76 |
+
},
|
| 77 |
+
{
|
| 78 |
+
"cell_type": "code",
|
| 79 |
+
"metadata": {},
|
| 80 |
+
"source": [
|
| 81 |
+
"# Task 4: Write your code here:\n",
|
| 82 |
+
"df_Q3.describe() # Show statistical description using"
|
| 83 |
+
],
|
| 84 |
+
"execution_count": null,
|
| 85 |
+
"outputs": []
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"cell_type": "code",
|
| 89 |
+
"metadata": {},
|
| 90 |
+
"source": [
|
| 91 |
+
"# Task 1: Write your code here:\n",
|
| 92 |
+
"# 2. Do we have missing values?\n",
|
| 93 |
+
"def check_missing_values(df_Q3):\n",
|
| 94 |
+
"\n",
|
| 95 |
+
" # Get missing values using pandas\n",
|
| 96 |
+
" missing_values = df_Q3.isnull().sum()\n",
|
| 97 |
+
"\n",
|
| 98 |
+
" print(\"Missing Values per Column:\")\n",
|
| 99 |
+
" print(missing_values[missing_values > 0])\n",
|
| 100 |
+
"\n",
|
| 101 |
+
" if missing_values.any():\n",
|
| 102 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 103 |
+
" else:\n",
|
| 104 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 105 |
+
"\n",
|
| 106 |
+
"check_missing_values(df_Q3)"
|
| 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 |
+
"# 4. Check for duplicates\n",
|
| 117 |
+
"def check_duplicates(df_Q3):\n",
|
| 118 |
+
"\n",
|
| 119 |
+
" #TODO: get duplicated data using pandas\n",
|
| 120 |
+
" duplicates = df_Q3.duplicated().sum()\n",
|
| 121 |
+
"\n",
|
| 122 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 123 |
+
" if duplicates > 0:\n",
|
| 124 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 125 |
+
" df_Q3.drop_duplicates(inplace=True)\n",
|
| 126 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 127 |
+
" else:\n",
|
| 128 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 129 |
+
"\n",
|
| 130 |
+
"check_duplicates(df_Q3)"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# Task 3: Write your code here:\n",
|
| 140 |
+
"# 3. Do we have categorical columns?\n",
|
| 141 |
+
"categorical_cols = df_Q3.select_dtypes(include=[\"object\"]).columns\n",
|
| 142 |
+
"\n",
|
| 143 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 144 |
+
"# no need for labelencoder"
|
| 145 |
+
],
|
| 146 |
+
"execution_count": null,
|
| 147 |
+
"outputs": []
|
| 148 |
+
},
|
| 149 |
+
{
|
| 150 |
+
"cell_type": "code",
|
| 151 |
+
"metadata": {},
|
| 152 |
+
"source": [
|
| 153 |
+
"# Task 4: Write your code here:\n",
|
| 154 |
+
"df_clean = df_Q3.copy()\n",
|
| 155 |
+
"df_clean.head()\n",
|
| 156 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 157 |
+
"\n",
|
| 158 |
+
"numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # no need to scale target\n",
|
| 159 |
+
"scaler = StandardScaler()\n",
|
| 160 |
+
"df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
|
| 161 |
+
"df_clean.head()"
|
| 162 |
+
],
|
| 163 |
+
"execution_count": null,
|
| 164 |
+
"outputs": []
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"cell_type": "code",
|
| 168 |
+
"metadata": {},
|
| 169 |
+
"source": [
|
| 170 |
+
"# Task 5: Write your code here: 5. **Check for target imbalance and state if it is imbalanced or not**\n",
|
| 171 |
+
"\n",
|
| 172 |
+
"def check_target_imbalance(df_clean, target_column):\n",
|
| 173 |
+
" print(\"Target Distribution:\")\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" df_clean[target_column].hist()\n",
|
| 176 |
+
" plt.show()\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"check_target_imbalance(df_clean, \"Target\")"
|
| 179 |
+
],
|
| 180 |
+
"execution_count": null,
|
| 181 |
+
"outputs": []
|
| 182 |
+
},
|
| 183 |
+
{
|
| 184 |
+
"cell_type": "code",
|
| 185 |
+
"metadata": {},
|
| 186 |
+
"source": [
|
| 187 |
+
"# it is impalanced"
|
| 188 |
+
],
|
| 189 |
+
"execution_count": null,
|
| 190 |
+
"outputs": []
|
| 191 |
+
},
|
| 192 |
+
{
|
| 193 |
+
"cell_type": "code",
|
| 194 |
+
"metadata": {},
|
| 195 |
+
"source": [
|
| 196 |
+
"# Task 1: Write your code here:\n",
|
| 197 |
+
"# Task 1: Write your code here: 1. Split the dataset into features (X) and target (y)\n",
|
| 198 |
+
"X = df_clean.drop('Target', axis=1)\n",
|
| 199 |
+
"y = df_clean['Target']"
|
| 200 |
+
],
|
| 201 |
+
"execution_count": null,
|
| 202 |
+
"outputs": []
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"cell_type": "code",
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"source": [
|
| 208 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 209 |
+
"from sklearn.model_selection import StratifiedKFold #cuz data is impalanced\n",
|
| 210 |
+
"from sklearn.metrics import accuracy_score, f1_score\n"
|
| 211 |
+
],
|
| 212 |
+
"execution_count": null,
|
| 213 |
+
"outputs": []
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"cell_type": "code",
|
| 217 |
+
"metadata": {},
|
| 218 |
+
"source": [
|
| 219 |
+
"# Task 1: Write your code here:\n"
|
| 220 |
+
],
|
| 221 |
+
"execution_count": null,
|
| 222 |
+
"outputs": []
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"cell_type": "code",
|
| 226 |
+
"metadata": {},
|
| 227 |
+
"source": [
|
| 228 |
+
"# Task 2: Write your code here:"
|
| 229 |
+
],
|
| 230 |
+
"execution_count": null,
|
| 231 |
+
"outputs": []
|
| 232 |
+
},
|
| 233 |
+
{
|
| 234 |
+
"cell_type": "code",
|
| 235 |
+
"metadata": {},
|
| 236 |
+
"source": [
|
| 237 |
+
"# Task Bonus: Write your code here:"
|
| 238 |
+
],
|
| 239 |
+
"execution_count": null,
|
| 240 |
+
"outputs": []
|
| 241 |
+
}
|
| 242 |
+
],
|
| 243 |
+
"metadata": {
|
| 244 |
+
"kernelspec": {
|
| 245 |
+
"display_name": "Python 3",
|
| 246 |
+
"name": "python3"
|
| 247 |
+
},
|
| 248 |
+
"language_info": {
|
| 249 |
+
"name": "python"
|
| 250 |
+
}
|
| 251 |
+
},
|
| 252 |
+
"nbformat": 4,
|
| 253 |
+
"nbformat_minor": 0
|
| 254 |
+
}
|
submissions_extracted/587/Q1.ipynb
ADDED
|
@@ -0,0 +1,485 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
"# 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 |
+
"# i read the data and iported os\n",
|
| 26 |
+
"import os\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"q1_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 29 |
+
"df = pd.read_csv(q1_path)\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 32 |
+
"df.head()"
|
| 33 |
+
],
|
| 34 |
+
"execution_count": null,
|
| 35 |
+
"outputs": []
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"cell_type": "code",
|
| 39 |
+
"metadata": {},
|
| 40 |
+
"source": [
|
| 41 |
+
"# Task 2: Write your code here:\n",
|
| 42 |
+
"df.head()"
|
| 43 |
+
],
|
| 44 |
+
"execution_count": null,
|
| 45 |
+
"outputs": []
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"cell_type": "code",
|
| 49 |
+
"metadata": {},
|
| 50 |
+
"source": [
|
| 51 |
+
"# Task 3: Write your code here:\n",
|
| 52 |
+
"df.info()"
|
| 53 |
+
],
|
| 54 |
+
"execution_count": null,
|
| 55 |
+
"outputs": []
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"cell_type": "code",
|
| 59 |
+
"metadata": {},
|
| 60 |
+
"source": [
|
| 61 |
+
"# Task 4: Write your code here:\n",
|
| 62 |
+
"df.describe()"
|
| 63 |
+
],
|
| 64 |
+
"execution_count": null,
|
| 65 |
+
"outputs": []
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"cell_type": "code",
|
| 69 |
+
"metadata": {},
|
| 70 |
+
"source": [
|
| 71 |
+
"# Task 5: Write your code here:\n",
|
| 72 |
+
"# Attack distribution\n",
|
| 73 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 74 |
+
"plt.hist(df['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
|
| 75 |
+
"plt.title('Delivery_Time Tistribution')\n",
|
| 76 |
+
"plt.xlabel('Time')\n",
|
| 77 |
+
"plt.ylabel('Frequency')\n",
|
| 78 |
+
"plt.show()"
|
| 79 |
+
],
|
| 80 |
+
"execution_count": null,
|
| 81 |
+
"outputs": []
|
| 82 |
+
},
|
| 83 |
+
{
|
| 84 |
+
"cell_type": "code",
|
| 85 |
+
"metadata": {},
|
| 86 |
+
"source": [
|
| 87 |
+
"# Task 1: Write your code here:\n",
|
| 88 |
+
"df.drop(columns=[\"Order_ID\"],inplace=True)"
|
| 89 |
+
],
|
| 90 |
+
"execution_count": null,
|
| 91 |
+
"outputs": []
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"cell_type": "code",
|
| 95 |
+
"metadata": {},
|
| 96 |
+
"source": [
|
| 97 |
+
"# before doing task 2 i prefer seeing if there is missing values or no\n",
|
| 98 |
+
"\n",
|
| 99 |
+
"# 2. Do we have missing values?\n",
|
| 100 |
+
"def check_missing_values(df):\n",
|
| 101 |
+
" missing_values = df.isnull().sum()\n",
|
| 102 |
+
" print(\"Missing Values per Column:\")\n",
|
| 103 |
+
" print(missing_values[missing_values > 0])\n",
|
| 104 |
+
" if missing_values.any():\n",
|
| 105 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 106 |
+
" else:\n",
|
| 107 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"check_missing_values(df)\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"#as we can see there is mltiple missing values in diffrent columns and we should handle it"
|
| 112 |
+
],
|
| 113 |
+
"execution_count": null,
|
| 114 |
+
"outputs": []
|
| 115 |
+
},
|
| 116 |
+
{
|
| 117 |
+
"cell_type": "code",
|
| 118 |
+
"metadata": {},
|
| 119 |
+
"source": [
|
| 120 |
+
"# Task 2: Write your code here:\n",
|
| 121 |
+
"# first there are rows with missing target so these are useless so we should delete them\n",
|
| 122 |
+
"df.dropna(subset=['Delivery_Time'],inplace=True)"
|
| 123 |
+
],
|
| 124 |
+
"execution_count": null,
|
| 125 |
+
"outputs": []
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "code",
|
| 129 |
+
"metadata": {},
|
| 130 |
+
"source": [
|
| 131 |
+
"df['Weather']=df['Weather'].fillna(df['Weather'].mode()[0])\n"
|
| 132 |
+
],
|
| 133 |
+
"execution_count": null,
|
| 134 |
+
"outputs": []
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"metadata": {},
|
| 139 |
+
"source": [
|
| 140 |
+
"df['Traffic_Level']=df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])"
|
| 141 |
+
],
|
| 142 |
+
"execution_count": null,
|
| 143 |
+
"outputs": []
|
| 144 |
+
},
|
| 145 |
+
{
|
| 146 |
+
"cell_type": "code",
|
| 147 |
+
"metadata": {},
|
| 148 |
+
"source": [
|
| 149 |
+
"df['Time_of_Day']=df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])"
|
| 150 |
+
],
|
| 151 |
+
"execution_count": null,
|
| 152 |
+
"outputs": []
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"cell_type": "code",
|
| 156 |
+
"metadata": {},
|
| 157 |
+
"source": [
|
| 158 |
+
"df['Courier_Experience_yrs']=df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())"
|
| 159 |
+
],
|
| 160 |
+
"execution_count": null,
|
| 161 |
+
"outputs": []
|
| 162 |
+
},
|
| 163 |
+
{
|
| 164 |
+
"cell_type": "code",
|
| 165 |
+
"metadata": {},
|
| 166 |
+
"source": [
|
| 167 |
+
"# before doing task 2 i prefer seeing if there is missing values or no\n",
|
| 168 |
+
"\n",
|
| 169 |
+
"# 2. Do we have missing values?\n",
|
| 170 |
+
"def check_missing_values(df):\n",
|
| 171 |
+
" missing_values = df.isnull().sum()\n",
|
| 172 |
+
" print(\"Missing Values per Column:\")\n",
|
| 173 |
+
" print(missing_values[missing_values > 0])\n",
|
| 174 |
+
" if missing_values.any():\n",
|
| 175 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 176 |
+
" else:\n",
|
| 177 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 178 |
+
"\n",
|
| 179 |
+
"check_missing_values(df)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"#as we can see there is mltiple missing values in diffrent columns and we should handle it"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 3: Write your code here:\n",
|
| 191 |
+
"# 4. Do we have duplicate samples?\n",
|
| 192 |
+
"def check_duplicates(df):\n",
|
| 193 |
+
" duplicates = df.duplicated().sum()\n",
|
| 194 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 195 |
+
" if duplicates > 0:\n",
|
| 196 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 197 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 198 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 199 |
+
" else:\n",
|
| 200 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 201 |
+
"\n",
|
| 202 |
+
"check_duplicates(df)\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"\n",
|
| 205 |
+
"#yes there is duplicates and i dropped it"
|
| 206 |
+
],
|
| 207 |
+
"execution_count": null,
|
| 208 |
+
"outputs": []
|
| 209 |
+
},
|
| 210 |
+
{
|
| 211 |
+
"cell_type": "code",
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"source": [],
|
| 214 |
+
"execution_count": null,
|
| 215 |
+
"outputs": []
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"cell_type": "code",
|
| 219 |
+
"metadata": {},
|
| 220 |
+
"source": [
|
| 221 |
+
"# Task 4: Write your code here:\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n",
|
| 224 |
+
"\n",
|
| 225 |
+
"\n",
|
| 226 |
+
"from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"categorical_cols =df.select_dtypes(include=[\"object\"]).columns\n",
|
| 229 |
+
"for col in categorical_cols:\n",
|
| 230 |
+
" print(f\"Encoding column: {col}\")\n",
|
| 231 |
+
" le = LabelEncoder()\n",
|
| 232 |
+
" df[col] = le.fit_transform(df[col])\n",
|
| 233 |
+
"df"
|
| 234 |
+
],
|
| 235 |
+
"execution_count": null,
|
| 236 |
+
"outputs": []
|
| 237 |
+
},
|
| 238 |
+
{
|
| 239 |
+
"cell_type": "code",
|
| 240 |
+
"metadata": {},
|
| 241 |
+
"source": [
|
| 242 |
+
"# Task 5: Write your code here:\n",
|
| 243 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
|
| 246 |
+
"\n",
|
| 247 |
+
"scaler = StandardScaler()\n",
|
| 248 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 249 |
+
"df.head()"
|
| 250 |
+
],
|
| 251 |
+
"execution_count": null,
|
| 252 |
+
"outputs": []
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"cell_type": "code",
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"source": [
|
| 258 |
+
"# Task 6: Write your code here:\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"# 1. What does our target variable (charges) look like?\n",
|
| 261 |
+
"def check_target_distribution(df, target_column):\n",
|
| 262 |
+
" df[target_column].hist(bins=30, edgecolor='black')\n",
|
| 263 |
+
"\n",
|
| 264 |
+
" plt.title(f\"Target Distribution ({target_column})\")\n",
|
| 265 |
+
" plt.xlabel(target_column)\n",
|
| 266 |
+
" plt.ylabel(\"Frequency\")\n",
|
| 267 |
+
" plt.grid(False)\n",
|
| 268 |
+
"\n",
|
| 269 |
+
" plt.show()\n",
|
| 270 |
+
"\n",
|
| 271 |
+
"check_target_distribution(df, \"Delivery_Time\")\n",
|
| 272 |
+
"\n",
|
| 273 |
+
"# it is slightly skwed to the right bu not to much"
|
| 274 |
+
],
|
| 275 |
+
"execution_count": null,
|
| 276 |
+
"outputs": []
|
| 277 |
+
},
|
| 278 |
+
{
|
| 279 |
+
"cell_type": "code",
|
| 280 |
+
"metadata": {},
|
| 281 |
+
"source": [
|
| 282 |
+
"# Task 1: Write your code here:\n",
|
| 283 |
+
"X = df.drop(\"Delivery_Time\",axis=1).astype(float)\n",
|
| 284 |
+
"y = df['Delivery_Time'].astype(float)"
|
| 285 |
+
],
|
| 286 |
+
"execution_count": null,
|
| 287 |
+
"outputs": []
|
| 288 |
+
},
|
| 289 |
+
{
|
| 290 |
+
"cell_type": "code",
|
| 291 |
+
"metadata": {},
|
| 292 |
+
"source": [
|
| 293 |
+
"# Storage for logistic regression results for each fold\n",
|
| 294 |
+
"lr_losses = []\n",
|
| 295 |
+
"\n",
|
| 296 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 297 |
+
"from sklearn.model_selection import KFold\n",
|
| 298 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 299 |
+
"\n",
|
| 300 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 301 |
+
"\n",
|
| 302 |
+
"# **K-folds**:\n",
|
| 303 |
+
"models = {\n",
|
| 304 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 305 |
+
"}\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"# Storage for results\n",
|
| 308 |
+
"all_results = {}\n",
|
| 309 |
+
"\n",
|
| 310 |
+
"for name in models:\n",
|
| 311 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 312 |
+
"\n",
|
| 313 |
+
" kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 314 |
+
"n_splits = 5\n",
|
| 315 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 316 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 317 |
+
"\n",
|
| 318 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 319 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 320 |
+
"\n",
|
| 321 |
+
" for model_name, model in models.items():\n",
|
| 322 |
+
" print(f\"Training {model_name}...\")\n",
|
| 323 |
+
"\n",
|
| 324 |
+
" # Train\n",
|
| 325 |
+
" model.fit(X_train, y_train)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" # Predict\n",
|
| 328 |
+
" y_pred = model.predict(X_test)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" # Calculate metrics\n",
|
| 331 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 332 |
+
" rmse = np.sqrt(mse)\n",
|
| 333 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 334 |
+
"\n",
|
| 335 |
+
" # Store results\n",
|
| 336 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 337 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 338 |
+
" all_results[model_name][\"r2\"].append(r2)\n",
|
| 339 |
+
""
|
| 340 |
+
],
|
| 341 |
+
"execution_count": null,
|
| 342 |
+
"outputs": []
|
| 343 |
+
},
|
| 344 |
+
{
|
| 345 |
+
"cell_type": "code",
|
| 346 |
+
"metadata": {},
|
| 347 |
+
"source": [
|
| 348 |
+
"for model_name in all_results:\n",
|
| 349 |
+
" print(f\"\\n{model_name}:\")\n",
|
| 350 |
+
" print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
|
| 351 |
+
" print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
|
| 352 |
+
" print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
|
| 353 |
+
],
|
| 354 |
+
"execution_count": null,
|
| 355 |
+
"outputs": []
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"metadata": {},
|
| 360 |
+
"source": [
|
| 361 |
+
"df.columns.to_list()"
|
| 362 |
+
],
|
| 363 |
+
"execution_count": null,
|
| 364 |
+
"outputs": []
|
| 365 |
+
},
|
| 366 |
+
{
|
| 367 |
+
"cell_type": "code",
|
| 368 |
+
"metadata": {},
|
| 369 |
+
"source": [
|
| 370 |
+
"features=['Distance_km',\n",
|
| 371 |
+
" 'Weather',\n",
|
| 372 |
+
" 'Traffic_Level',\n",
|
| 373 |
+
" 'Time_of_Day',\n",
|
| 374 |
+
" 'Vehicle_Type',\n",
|
| 375 |
+
" 'Preparation_Time_min',\n",
|
| 376 |
+
" 'Courier_Experience_yrs',\n",
|
| 377 |
+
" ]\n",
|
| 378 |
+
"# Task 1: Write your code here:\n",
|
| 379 |
+
"# Feature importance\n",
|
| 380 |
+
"importance = pd.DataFrame({\n",
|
| 381 |
+
" 'feature': features,\n",
|
| 382 |
+
" 'importance': model.feature_importances_\n",
|
| 383 |
+
"}).sort_values('importance', ascending=False)\n",
|
| 384 |
+
"\n",
|
| 385 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 386 |
+
"plt.barh(importance['feature'], importance['importance'], color='purple')\n",
|
| 387 |
+
"plt.xlabel('Importance')\n",
|
| 388 |
+
"plt.title('Feature Importance')\n",
|
| 389 |
+
"plt.gca().invert_yaxis()\n",
|
| 390 |
+
"plt.show()"
|
| 391 |
+
],
|
| 392 |
+
"execution_count": null,
|
| 393 |
+
"outputs": []
|
| 394 |
+
},
|
| 395 |
+
{
|
| 396 |
+
"cell_type": "code",
|
| 397 |
+
"metadata": {},
|
| 398 |
+
"source": [
|
| 399 |
+
"# Task 2: Write your code here:"
|
| 400 |
+
],
|
| 401 |
+
"execution_count": null,
|
| 402 |
+
"outputs": []
|
| 403 |
+
},
|
| 404 |
+
{
|
| 405 |
+
"cell_type": "code",
|
| 406 |
+
"metadata": {},
|
| 407 |
+
"source": [
|
| 408 |
+
"pip install catboost"
|
| 409 |
+
],
|
| 410 |
+
"execution_count": null,
|
| 411 |
+
"outputs": []
|
| 412 |
+
},
|
| 413 |
+
{
|
| 414 |
+
"cell_type": "code",
|
| 415 |
+
"metadata": {},
|
| 416 |
+
"source": [
|
| 417 |
+
"# Task Bonus: Write your code here:\n",
|
| 418 |
+
"from catboost import CatBoostRegressor\n",
|
| 419 |
+
"\n",
|
| 420 |
+
"# Storage for logistic regression results for each fold\n",
|
| 421 |
+
"lr_losses = []\n",
|
| 422 |
+
"\n",
|
| 423 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 424 |
+
"from sklearn.model_selection import KFold\n",
|
| 425 |
+
"from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
|
| 426 |
+
"\n",
|
| 427 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 428 |
+
"\n",
|
| 429 |
+
"# **K-folds**:\n",
|
| 430 |
+
"models = {\n",
|
| 431 |
+
" \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
|
| 432 |
+
" \"CatBoost\": CatBoostRegressor(verbose=0)\n",
|
| 433 |
+
"}\n",
|
| 434 |
+
"\n",
|
| 435 |
+
"# Storage for results\n",
|
| 436 |
+
"all_results = {}\n",
|
| 437 |
+
"\n",
|
| 438 |
+
"for name in models:\n",
|
| 439 |
+
" all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
|
| 440 |
+
"\n",
|
| 441 |
+
" kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
|
| 442 |
+
"n_splits = 5\n",
|
| 443 |
+
"for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
|
| 444 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 445 |
+
"\n",
|
| 446 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 447 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 448 |
+
"\n",
|
| 449 |
+
" for model_name, model in models.items():\n",
|
| 450 |
+
" print(f\"Training {model_name}...\")\n",
|
| 451 |
+
"\n",
|
| 452 |
+
" # Train\n",
|
| 453 |
+
" model.fit(X_train, y_train)\n",
|
| 454 |
+
"\n",
|
| 455 |
+
" # Predict\n",
|
| 456 |
+
" y_pred = model.predict(X_test)\n",
|
| 457 |
+
"\n",
|
| 458 |
+
" # Calculate metrics\n",
|
| 459 |
+
" mse = sklearn_mse(y_test, y_pred)\n",
|
| 460 |
+
" rmse = np.sqrt(mse)\n",
|
| 461 |
+
" r2 = r2_score(y_test, y_pred)\n",
|
| 462 |
+
" mae=\n",
|
| 463 |
+
"\n",
|
| 464 |
+
" # Store results\n",
|
| 465 |
+
" all_results[model_name][\"mse\"].append(mse)\n",
|
| 466 |
+
" all_results[model_name][\"rmse\"].append(rmse)\n",
|
| 467 |
+
" all_results[model_name][\"r2\"].append(r2)\n",
|
| 468 |
+
""
|
| 469 |
+
],
|
| 470 |
+
"execution_count": null,
|
| 471 |
+
"outputs": []
|
| 472 |
+
}
|
| 473 |
+
],
|
| 474 |
+
"metadata": {
|
| 475 |
+
"kernelspec": {
|
| 476 |
+
"display_name": "Python 3",
|
| 477 |
+
"name": "python3"
|
| 478 |
+
},
|
| 479 |
+
"language_info": {
|
| 480 |
+
"name": "python"
|
| 481 |
+
}
|
| 482 |
+
},
|
| 483 |
+
"nbformat": 4,
|
| 484 |
+
"nbformat_minor": 0
|
| 485 |
+
}
|
submissions_extracted/587/Q2.ipynb
ADDED
|
@@ -0,0 +1,387 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 kagglehub\n",
|
| 22 |
+
"import pandas as pd\n",
|
| 23 |
+
"import numpy as np\n",
|
| 24 |
+
"import torch\n",
|
| 25 |
+
"import torch.nn as nn\n",
|
| 26 |
+
"from torch.optim import AdamW\n",
|
| 27 |
+
"import matplotlib.pyplot as plt\n",
|
| 28 |
+
"from torch.utils.data import DataLoader, TensorDataset\n",
|
| 29 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 30 |
+
"from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
|
| 31 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 32 |
+
"\n",
|
| 33 |
+
"print(f\"PyTorch version: {torch.__version__}\")\n",
|
| 34 |
+
"print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
|
| 35 |
+
"\n",
|
| 36 |
+
"# Load Labels\n",
|
| 37 |
+
"labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
|
| 38 |
+
"img_dir = os.path.join(path, \"images\")\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"images = []\n",
|
| 41 |
+
"ages = []\n",
|
| 42 |
+
"\n",
|
| 43 |
+
"# Load Images and Resize\n",
|
| 44 |
+
"print(\"Loading images...\")\n",
|
| 45 |
+
"for index, row in labels_df.iterrows():\n",
|
| 46 |
+
" img_name = row.iloc[0]\n",
|
| 47 |
+
" age = row.iloc[1]\n",
|
| 48 |
+
" img_path = os.path.join(img_dir, img_name)\n",
|
| 49 |
+
"\n",
|
| 50 |
+
" if os.path.exists(img_path):\n",
|
| 51 |
+
" img = Image.open(img_path).convert('RGB')\n",
|
| 52 |
+
" img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
|
| 53 |
+
" images.append(img_array)\n",
|
| 54 |
+
" ages.append(age)\n",
|
| 55 |
+
"\n",
|
| 56 |
+
"X = np.array(images)\n",
|
| 57 |
+
"y = np.array(ages)\n",
|
| 58 |
+
"\n",
|
| 59 |
+
"# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
|
| 60 |
+
"X = np.transpose(X, (0, 3, 1, 2))\n",
|
| 61 |
+
"\n",
|
| 62 |
+
"# Split Data\n",
|
| 63 |
+
"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
|
| 64 |
+
"\n",
|
| 65 |
+
"print(f\"X_train shape: {X_train.shape}\")\n",
|
| 66 |
+
"print(f\"X_test shape: {X_test.shape}\")\n",
|
| 67 |
+
"print(f\"y_train shape: {y_train.shape}\")\n",
|
| 68 |
+
"print(f\"y_test shape: {y_test.shape}\")"
|
| 69 |
+
],
|
| 70 |
+
"execution_count": null,
|
| 71 |
+
"outputs": []
|
| 72 |
+
},
|
| 73 |
+
{
|
| 74 |
+
"cell_type": "code",
|
| 75 |
+
"metadata": {},
|
| 76 |
+
"source": [
|
| 77 |
+
"# 1. Convert Numpy arrays to PyTorch Tensors\n",
|
| 78 |
+
"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 |
+
"\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 |
+
"\n",
|
| 93 |
+
"\n",
|
| 94 |
+
"# Create TensorDatasets for training and testing\n",
|
| 95 |
+
"train_dataset = TensorDataset(X_train, y_train)\n",
|
| 96 |
+
"test_dataset = TensorDataset(X_test, y_test)\n"
|
| 97 |
+
],
|
| 98 |
+
"execution_count": null,
|
| 99 |
+
"outputs": []
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"cell_type": "code",
|
| 103 |
+
"metadata": {},
|
| 104 |
+
"source": [
|
| 105 |
+
"# 3. Create DataLoaders\n",
|
| 106 |
+
"\n",
|
| 107 |
+
"# Create Dataloaders to train and test data in batches\n",
|
| 108 |
+
"train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
|
| 109 |
+
"test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
|
| 110 |
+
"\n",
|
| 111 |
+
"\n",
|
| 112 |
+
"\n"
|
| 113 |
+
],
|
| 114 |
+
"execution_count": null,
|
| 115 |
+
"outputs": []
|
| 116 |
+
},
|
| 117 |
+
{
|
| 118 |
+
"cell_type": "code",
|
| 119 |
+
"metadata": {},
|
| 120 |
+
"source": [
|
| 121 |
+
"# 4. Print shape of one batch\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"# Print dataset sizes\n",
|
| 124 |
+
"print(\"Train dataset:\", len(train_dataset))\n",
|
| 125 |
+
"print(\"Test dataset:\", len(test_dataset))\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}\")"
|
| 131 |
+
],
|
| 132 |
+
"execution_count": null,
|
| 133 |
+
"outputs": []
|
| 134 |
+
},
|
| 135 |
+
{
|
| 136 |
+
"cell_type": "code",
|
| 137 |
+
"metadata": {},
|
| 138 |
+
"source": [
|
| 139 |
+
"# 5. Display sample images\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"# Get one batch of images and labels\n",
|
| 142 |
+
"images, labels = next(iter(train_loader))\n",
|
| 143 |
+
"\n",
|
| 144 |
+
"# Display the first 6 images in the batch\n",
|
| 145 |
+
"plt.figure(figsize=(8, 4))\n",
|
| 146 |
+
"\n",
|
| 147 |
+
"for i in range(6):\n",
|
| 148 |
+
" plt.subplot(2, 3, i + 1)\n",
|
| 149 |
+
"\n",
|
| 150 |
+
" # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
|
| 151 |
+
" img = images[i].permute(1, 2, 0)\n",
|
| 152 |
+
"\n",
|
| 153 |
+
" plt.imshow(img)\n",
|
| 154 |
+
" plt.title(f\"Label: {labels[i].item()}\")\n",
|
| 155 |
+
" plt.axis('off')\n",
|
| 156 |
+
"\n",
|
| 157 |
+
"plt.tight_layout()\n",
|
| 158 |
+
"plt.show()"
|
| 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 |
+
"\n",
|
| 169 |
+
"class NN4Layer(nn.Module):\n",
|
| 170 |
+
"\n",
|
| 171 |
+
" def __init__(self, input_dim, hidden_dim):\n",
|
| 172 |
+
" super(NN4Layer, self).__init__()\n",
|
| 173 |
+
"\n",
|
| 174 |
+
"\n",
|
| 175 |
+
" self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
|
| 176 |
+
"\n",
|
| 177 |
+
"\n",
|
| 178 |
+
" self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 179 |
+
"\n",
|
| 180 |
+
" # TODO: What are the dimensions from previous and next layer?\n",
|
| 181 |
+
" self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
|
| 182 |
+
"\n",
|
| 183 |
+
" # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n",
|
| 184 |
+
" self.layer4 = nn.Linear(hidden_dim, 1)\n",
|
| 185 |
+
"\n",
|
| 186 |
+
" # activation function for non-linearity\n",
|
| 187 |
+
" self.relu = nn.ReLU()\n",
|
| 188 |
+
"\n",
|
| 189 |
+
" # Defines how input data flows through the network\n",
|
| 190 |
+
" def forward(self, x):\n",
|
| 191 |
+
" # Layer 1: TODO\n",
|
| 192 |
+
" z1 = self.layer1(x)\n",
|
| 193 |
+
" a1 = self.relu(z1)\n",
|
| 194 |
+
"\n",
|
| 195 |
+
" # Layer 2 TODO\n",
|
| 196 |
+
" z2 = self.layer2(a1)\n",
|
| 197 |
+
" a2 = self.relu(z2)\n",
|
| 198 |
+
"\n",
|
| 199 |
+
" # Layer 3 TODO\n",
|
| 200 |
+
" z3 = self.layer3(a2)\n",
|
| 201 |
+
" a3 = self.relu(z3)\n",
|
| 202 |
+
"\n",
|
| 203 |
+
" # Output layer TODO\n",
|
| 204 |
+
" z4 = self.layer5(a3)\n",
|
| 205 |
+
"\n",
|
| 206 |
+
" return z4"
|
| 207 |
+
],
|
| 208 |
+
"execution_count": null,
|
| 209 |
+
"outputs": []
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"cell_type": "code",
|
| 213 |
+
"metadata": {},
|
| 214 |
+
"source": [
|
| 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\n",
|
| 223 |
+
"\n",
|
| 224 |
+
" X_batch = X_batch.view.to(device)\n",
|
| 225 |
+
" y_batch = y_batch.view(-1, 1).to(device)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
" # Forward pass\n",
|
| 228 |
+
" # TODO: make predictions\n",
|
| 229 |
+
" outputs = model(X_batch) # shape: (batch_size, 10)\n",
|
| 230 |
+
" # TODO: compute loss\n",
|
| 231 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 232 |
+
"\n",
|
| 233 |
+
" # Backward pass & optimization\n",
|
| 234 |
+
" optimizer.zero_grad() # Clear previous gradients\n",
|
| 235 |
+
" loss.backward() # Compute gradients\n",
|
| 236 |
+
" optimizer.step() # Update model parameters\n",
|
| 237 |
+
"\n",
|
| 238 |
+
" running_loss += loss.item()\n",
|
| 239 |
+
"\n",
|
| 240 |
+
" # Average loss over all batches\n",
|
| 241 |
+
" avg_loss = running_loss / len(train_loader)\n",
|
| 242 |
+
"\n",
|
| 243 |
+
" return avg_loss"
|
| 244 |
+
],
|
| 245 |
+
"execution_count": null,
|
| 246 |
+
"outputs": []
|
| 247 |
+
},
|
| 248 |
+
{
|
| 249 |
+
"cell_type": "code",
|
| 250 |
+
"metadata": {},
|
| 251 |
+
"source": [
|
| 252 |
+
"# Task 3: Write your validation loop here:\n",
|
| 253 |
+
"def validate(model, criterion, test_loader, device):\n",
|
| 254 |
+
" # Set the model to evaluation mode\n",
|
| 255 |
+
" model.eval()\n",
|
| 256 |
+
"\n",
|
| 257 |
+
" running_loss = 0.0\n",
|
| 258 |
+
"\n",
|
| 259 |
+
" with torch.no_grad():\n",
|
| 260 |
+
" for X_batch, y_batch in test_loader:\n",
|
| 261 |
+
" # Move data to device\n",
|
| 262 |
+
" print(X_batch)\n",
|
| 263 |
+
" print(y_batch)\n",
|
| 264 |
+
" X_batch = X_batch.to(device)\n",
|
| 265 |
+
" y_batch = y_batch.to(device)\n",
|
| 266 |
+
"\n",
|
| 267 |
+
" # Forward pass (continuous output)\n",
|
| 268 |
+
" outputs = model(X_batch)\n",
|
| 269 |
+
" loss = criterion(outputs, y_batch)\n",
|
| 270 |
+
"\n",
|
| 271 |
+
" running_loss += loss.item()\n",
|
| 272 |
+
"\n",
|
| 273 |
+
" # Average loss over all batches\n",
|
| 274 |
+
" avg_loss = running_loss / len(test_loader)\n",
|
| 275 |
+
"\n",
|
| 276 |
+
" return avg_loss"
|
| 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 |
+
"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
|
| 287 |
+
"input_dim = X_train.shape[1] # Number of tabular features\n",
|
| 288 |
+
"hidden_dim = 64 # Design choice\n",
|
| 289 |
+
"\n",
|
| 290 |
+
"# Instantiate regression model\n",
|
| 291 |
+
"model = NN4Layer(input_dim, hidden_dim).to(device)\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"# Print the model architecture\n",
|
| 294 |
+
"print(\"Model Architecture:\\n\")\n",
|
| 295 |
+
"print(model)\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"# Calculate the total number of trainable parameters\n",
|
| 298 |
+
"total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
|
| 299 |
+
"print(f\"\\nTotal trainable parameters: {total_params}\")"
|
| 300 |
+
],
|
| 301 |
+
"execution_count": null,
|
| 302 |
+
"outputs": []
|
| 303 |
+
},
|
| 304 |
+
{
|
| 305 |
+
"cell_type": "code",
|
| 306 |
+
"metadata": {},
|
| 307 |
+
"source": [
|
| 308 |
+
"# Task 5: Start training for 20 epochs:\n",
|
| 309 |
+
"# Hyperparameters (feel free to experiment!)\n",
|
| 310 |
+
"num_epochs = 20\n",
|
| 311 |
+
"learning_rate = 0.001\n",
|
| 312 |
+
"\n",
|
| 313 |
+
"# Define criterion (loss function)\n",
|
| 314 |
+
"criterion = nn.MSELoss()\n",
|
| 315 |
+
"# Define optimizer\n",
|
| 316 |
+
"optimizer = AdamW(model.parameters(), learning_rate)\n",
|
| 317 |
+
"\n",
|
| 318 |
+
"# Run Training\n",
|
| 319 |
+
"train_losses = []\n",
|
| 320 |
+
"val_losses = []\n",
|
| 321 |
+
"\n",
|
| 322 |
+
"print('Starting Training...')\n",
|
| 323 |
+
"for epoch in range(num_epochs):\n",
|
| 324 |
+
" # Train one epoch\n",
|
| 325 |
+
" train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
|
| 326 |
+
"\n",
|
| 327 |
+
" # Validate\n",
|
| 328 |
+
" val_loss = validate(model, criterion, test_loader, device)\n",
|
| 329 |
+
"\n",
|
| 330 |
+
" train_losses.append(train_loss)\n",
|
| 331 |
+
" val_losses.append(val_loss)\n",
|
| 332 |
+
"\n",
|
| 333 |
+
" if (epoch + 1) % 5 == 0:\n",
|
| 334 |
+
" print(\n",
|
| 335 |
+
" f'Epoch [{epoch+1}/{num_epochs}], '\n",
|
| 336 |
+
" f'Train Loss: {train_loss:.4f}, '\n",
|
| 337 |
+
" f'Val Loss: {val_loss:.4f}'\n",
|
| 338 |
+
" )\n",
|
| 339 |
+
"\n",
|
| 340 |
+
"print('Training Complete!')"
|
| 341 |
+
],
|
| 342 |
+
"execution_count": null,
|
| 343 |
+
"outputs": []
|
| 344 |
+
},
|
| 345 |
+
{
|
| 346 |
+
"cell_type": "code",
|
| 347 |
+
"metadata": {},
|
| 348 |
+
"source": [
|
| 349 |
+
"# Task 1: Write your code here:\n",
|
| 350 |
+
"# Plotting results\n",
|
| 351 |
+
"plt.figure(figsize=(7, 5))\n",
|
| 352 |
+
"\n",
|
| 353 |
+
"plt.plot(train_losses, label='Train Loss')\n",
|
| 354 |
+
"plt.plot(val_losses, label='Validation Loss')\n",
|
| 355 |
+
"plt.title('Loss over Epochs')\n",
|
| 356 |
+
"plt.xlabel('Epoch')\n",
|
| 357 |
+
"plt.ylabel('Loss')\n",
|
| 358 |
+
"plt.legend()\n",
|
| 359 |
+
"\n",
|
| 360 |
+
"plt.tight_layout()\n",
|
| 361 |
+
"plt.show()"
|
| 362 |
+
],
|
| 363 |
+
"execution_count": null,
|
| 364 |
+
"outputs": []
|
| 365 |
+
},
|
| 366 |
+
{
|
| 367 |
+
"cell_type": "code",
|
| 368 |
+
"metadata": {},
|
| 369 |
+
"source": [
|
| 370 |
+
"# Task 2 (Bonus): Write your code here:"
|
| 371 |
+
],
|
| 372 |
+
"execution_count": null,
|
| 373 |
+
"outputs": []
|
| 374 |
+
}
|
| 375 |
+
],
|
| 376 |
+
"metadata": {
|
| 377 |
+
"kernelspec": {
|
| 378 |
+
"display_name": "Python 3",
|
| 379 |
+
"name": "python3"
|
| 380 |
+
},
|
| 381 |
+
"language_info": {
|
| 382 |
+
"name": "python"
|
| 383 |
+
}
|
| 384 |
+
},
|
| 385 |
+
"nbformat": 4,
|
| 386 |
+
"nbformat_minor": 0
|
| 387 |
+
}
|
submissions_extracted/587/Q3.ipynb
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "code",
|
| 5 |
+
"metadata": {},
|
| 6 |
+
"source": [
|
| 7 |
+
"import kagglehub\n",
|
| 8 |
+
"\n",
|
| 9 |
+
"\n",
|
| 10 |
+
"\n",
|
| 11 |
+
"# Download latest version\n",
|
| 12 |
+
"\n",
|
| 13 |
+
"path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
|
| 14 |
+
"\n",
|
| 15 |
+
"\n",
|
| 16 |
+
"\n",
|
| 17 |
+
"print(\"Path to dataset files:\", path)"
|
| 18 |
+
],
|
| 19 |
+
"execution_count": null,
|
| 20 |
+
"outputs": []
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"cell_type": "code",
|
| 24 |
+
"metadata": {},
|
| 25 |
+
"source": [
|
| 26 |
+
"# Task 1: Write your code here:\n",
|
| 27 |
+
"import os\n",
|
| 28 |
+
"import pandas as pd\n",
|
| 29 |
+
"q3_path = os.path.join(path, 'Q3_data.csv')\n",
|
| 30 |
+
"df = pd.read_csv(q3_path)\n",
|
| 31 |
+
"\n",
|
| 32 |
+
"print(f\"Shape: {df.shape}\")\n",
|
| 33 |
+
"df.head()"
|
| 34 |
+
],
|
| 35 |
+
"execution_count": null,
|
| 36 |
+
"outputs": []
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"cell_type": "code",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"source": [
|
| 42 |
+
"# Task 2: Write your code here:\n",
|
| 43 |
+
"df.head()"
|
| 44 |
+
],
|
| 45 |
+
"execution_count": null,
|
| 46 |
+
"outputs": []
|
| 47 |
+
},
|
| 48 |
+
{
|
| 49 |
+
"cell_type": "code",
|
| 50 |
+
"metadata": {},
|
| 51 |
+
"source": [
|
| 52 |
+
"# Task 3: Write your code here:\n",
|
| 53 |
+
"df.info()"
|
| 54 |
+
],
|
| 55 |
+
"execution_count": null,
|
| 56 |
+
"outputs": []
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"cell_type": "code",
|
| 60 |
+
"metadata": {},
|
| 61 |
+
"source": [
|
| 62 |
+
"# Task 4: Write your code here:\n",
|
| 63 |
+
"df.describe()"
|
| 64 |
+
],
|
| 65 |
+
"execution_count": null,
|
| 66 |
+
"outputs": []
|
| 67 |
+
},
|
| 68 |
+
{
|
| 69 |
+
"cell_type": "code",
|
| 70 |
+
"metadata": {},
|
| 71 |
+
"source": [
|
| 72 |
+
"# Task 1: Write your code here:\n",
|
| 73 |
+
"# before doing task 2 i prefer seeing if there is missing values or no\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"# 2. Do we have missing values?\n",
|
| 76 |
+
"def check_missing_values(df):\n",
|
| 77 |
+
" missing_values = df.isnull().sum()\n",
|
| 78 |
+
" print(\"Missing Values per Column:\")\n",
|
| 79 |
+
" print(missing_values[missing_values > 0])\n",
|
| 80 |
+
" if missing_values.any():\n",
|
| 81 |
+
" print(\"\\nHandle Missing Values as needed.\")\n",
|
| 82 |
+
" else:\n",
|
| 83 |
+
" print(\"\\nNo Missing Values Found.\")\n",
|
| 84 |
+
"\n",
|
| 85 |
+
"check_missing_values(df)\n",
|
| 86 |
+
"\n",
|
| 87 |
+
"#as we can see there is mltiple missing values in diffrent columns and we should handle it\n",
|
| 88 |
+
"\n",
|
| 89 |
+
"df = df.fillna(df.mean())"
|
| 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 |
+
"# 4. Do we have duplicate samples?\n",
|
| 100 |
+
"def check_duplicates(df):\n",
|
| 101 |
+
" duplicates = df.duplicated().sum()\n",
|
| 102 |
+
" print(f\"Number of Duplicate Samples: {duplicates}\")\n",
|
| 103 |
+
" if duplicates > 0:\n",
|
| 104 |
+
" print(\"Dropping Duplicates...\")\n",
|
| 105 |
+
" df.drop_duplicates(inplace=True)\n",
|
| 106 |
+
" print(\"Duplicates Dropped.\")\n",
|
| 107 |
+
" else:\n",
|
| 108 |
+
" print(\"No Duplicate Samples Found.\")\n",
|
| 109 |
+
"\n",
|
| 110 |
+
"check_duplicates(df)"
|
| 111 |
+
],
|
| 112 |
+
"execution_count": null,
|
| 113 |
+
"outputs": []
|
| 114 |
+
},
|
| 115 |
+
{
|
| 116 |
+
"cell_type": "code",
|
| 117 |
+
"metadata": {},
|
| 118 |
+
"source": [
|
| 119 |
+
"# Task 3: Write your code here:\n",
|
| 120 |
+
"\n",
|
| 121 |
+
"# 3. Do we have categorical columns?\n",
|
| 122 |
+
"categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
|
| 123 |
+
"\n",
|
| 124 |
+
"print(\"Categorical Columns:\", list(categorical_cols))\n",
|
| 125 |
+
"\n",
|
| 126 |
+
"#no categorical values"
|
| 127 |
+
],
|
| 128 |
+
"execution_count": null,
|
| 129 |
+
"outputs": []
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"cell_type": "code",
|
| 133 |
+
"metadata": {},
|
| 134 |
+
"source": [
|
| 135 |
+
"# Task 4: Write your code here:\n",
|
| 136 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 137 |
+
"\n",
|
| 138 |
+
"\n",
|
| 139 |
+
"numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
|
| 140 |
+
"\n",
|
| 141 |
+
"scaler = StandardScaler()\n",
|
| 142 |
+
"df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
|
| 143 |
+
"df.head()"
|
| 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 |
+
"# 1. Is the target imbalanced?\n",
|
| 154 |
+
"import matplotlib.pyplot as plt\n",
|
| 155 |
+
"def check_target_imbalance(df, target_column):\n",
|
| 156 |
+
" print(\"Target Distribution:\")\n",
|
| 157 |
+
"\n",
|
| 158 |
+
" df[target_column].hist() # Yeah you can just do this :)\n",
|
| 159 |
+
" plt.show()\n",
|
| 160 |
+
"\n",
|
| 161 |
+
"check_target_imbalance(df, \"Target\")\n",
|
| 162 |
+
"\n",
|
| 163 |
+
"#slightly inbalnaced"
|
| 164 |
+
],
|
| 165 |
+
"execution_count": null,
|
| 166 |
+
"outputs": []
|
| 167 |
+
},
|
| 168 |
+
{
|
| 169 |
+
"cell_type": "code",
|
| 170 |
+
"metadata": {},
|
| 171 |
+
"source": [
|
| 172 |
+
"# Task 1: Write your code here:\n",
|
| 173 |
+
"X = df.drop(\"Target\",axis=1).astype(float)\n",
|
| 174 |
+
"y = df['Target'].astype(float)"
|
| 175 |
+
],
|
| 176 |
+
"execution_count": null,
|
| 177 |
+
"outputs": []
|
| 178 |
+
},
|
| 179 |
+
{
|
| 180 |
+
"cell_type": "code",
|
| 181 |
+
"metadata": {},
|
| 182 |
+
"source": [
|
| 183 |
+
"pip install catboost"
|
| 184 |
+
],
|
| 185 |
+
"execution_count": null,
|
| 186 |
+
"outputs": []
|
| 187 |
+
},
|
| 188 |
+
{
|
| 189 |
+
"cell_type": "code",
|
| 190 |
+
"metadata": {},
|
| 191 |
+
"source": [
|
| 192 |
+
"from catboost import CatBoostClassifier\n",
|
| 193 |
+
"from sklearn.model_selection import StratifiedKFold\n",
|
| 194 |
+
"from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
|
| 195 |
+
"sklearn_models = {\n",
|
| 196 |
+
" \"CatBoost\": CatBoostClassifier(\n",
|
| 197 |
+
" verbose=0,\n",
|
| 198 |
+
" n_estimators=320,\n",
|
| 199 |
+
" max_depth=4\n",
|
| 200 |
+
" )\n",
|
| 201 |
+
"}\n",
|
| 202 |
+
"\n",
|
| 203 |
+
"\n",
|
| 204 |
+
"all_results = {}\n",
|
| 205 |
+
"\n",
|
| 206 |
+
"for name in sklearn_models:\n",
|
| 207 |
+
" all_results[name] = {'accuracy': [],'f1': []}\n",
|
| 208 |
+
"\n",
|
| 209 |
+
"\n",
|
| 210 |
+
" n_splits = 5 # K\n",
|
| 211 |
+
"\n",
|
| 212 |
+
"# Stratified 5-Fold Cross-Validation, shuffled\n",
|
| 213 |
+
"skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
|
| 214 |
+
"\n",
|
| 215 |
+
"for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
|
| 216 |
+
" print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
|
| 217 |
+
"\n",
|
| 218 |
+
" # 1. Split data\n",
|
| 219 |
+
" X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
|
| 220 |
+
" y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
|
| 221 |
+
"\n",
|
| 222 |
+
" # 2. Train & Validate sklearn models\n",
|
| 223 |
+
" for model_name, model in sklearn_models.items():\n",
|
| 224 |
+
" print(f\"Training {model_name}...\")\n",
|
| 225 |
+
" model.fit(X_train, y_train) # train\n",
|
| 226 |
+
" y_pred = model.predict(X_test) # validate\n",
|
| 227 |
+
"\n",
|
| 228 |
+
" # 3. Save metrics for that model in this fold\n",
|
| 229 |
+
" accuracy = accuracy_score(y_test, y_pred)\n",
|
| 230 |
+
" precision = precision_score(y_test, y_pred, zero_division=0)\n",
|
| 231 |
+
" recall = recall_score(y_test, y_pred, zero_division=0)\n",
|
| 232 |
+
" f1 = f1_score(y_test, y_pred, zero_division=0)\n",
|
| 233 |
+
"\n",
|
| 234 |
+
" all_results[model_name]['accuracy'].append(accuracy)\n",
|
| 235 |
+
" all_results[model_name]['f1'].append(f1)"
|
| 236 |
+
],
|
| 237 |
+
"execution_count": null,
|
| 238 |
+
"outputs": []
|
| 239 |
+
},
|
| 240 |
+
{
|
| 241 |
+
"cell_type": "code",
|
| 242 |
+
"metadata": {},
|
| 243 |
+
"source": [
|
| 244 |
+
"# Task 1: Write your code here:\n",
|
| 245 |
+
"# Plot feature importance\n",
|
| 246 |
+
"features = [col for col in df.columns if col != 'Target']\n",
|
| 247 |
+
"importance = pd.DataFrame({\n",
|
| 248 |
+
" 'feature': features,\n",
|
| 249 |
+
" 'importance': model.feature_importances_\n",
|
| 250 |
+
"})\n",
|
| 251 |
+
"importance = importance.sort_values('importance', ascending=True).tail(10)\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"plt.figure(figsize=(10, 6))\n",
|
| 254 |
+
"plt.barh(importance['feature'], importance['importance'])\n",
|
| 255 |
+
"plt.title('Top 10 Feature Importance')\n",
|
| 256 |
+
"plt.xlabel('Importance')\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 |
+
"# Task 2: Write your code here:\n",
|
| 268 |
+
"print(\"the best feature is : \"+ \"P_2\")\n"
|
| 269 |
+
],
|
| 270 |
+
"execution_count": null,
|
| 271 |
+
"outputs": []
|
| 272 |
+
},
|
| 273 |
+
{
|
| 274 |
+
"cell_type": "code",
|
| 275 |
+
"metadata": {},
|
| 276 |
+
"source": [
|
| 277 |
+
"# Task Bonus: Write your code here:"
|
| 278 |
+
],
|
| 279 |
+
"execution_count": null,
|
| 280 |
+
"outputs": []
|
| 281 |
+
}
|
| 282 |
+
],
|
| 283 |
+
"metadata": {
|
| 284 |
+
"kernelspec": {
|
| 285 |
+
"display_name": "Python 3",
|
| 286 |
+
"name": "python3"
|
| 287 |
+
},
|
| 288 |
+
"language_info": {
|
| 289 |
+
"name": "python"
|
| 290 |
+
}
|
| 291 |
+
},
|
| 292 |
+
"nbformat": 4,
|
| 293 |
+
"nbformat_minor": 0
|
| 294 |
+
}
|
submissions_extracted/588/Q1.ipynb
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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/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 |
+
"# Load the CSV file\n",
|
| 24 |
+
"import numpy as np\n",
|
| 25 |
+
"import pandas as pd\n",
|
| 26 |
+
"import os\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"fd_path = os.path.join(path, 'Q1_data.csv')\n",
|
| 29 |
+
"df_fd = pd.read_csv(fd_path)\n"
|
| 30 |
+
],
|
| 31 |
+
"execution_count": null,
|
| 32 |
+
"outputs": []
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"cell_type": "code",
|
| 36 |
+
"metadata": {},
|
| 37 |
+
"source": [
|
| 38 |
+
"# Task 2: Write your code here:\n",
|
| 39 |
+
"\n",
|
| 40 |
+
"print(f\"Shape: {df_fd.shape}\")\n",
|
| 41 |
+
"df_fd.head()"
|
| 42 |
+
],
|
| 43 |
+
"execution_count": null,
|
| 44 |
+
"outputs": []
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
"cell_type": "code",
|
| 48 |
+
"metadata": {},
|
| 49 |
+
"source": [
|
| 50 |
+
"# Task 3: Write your code here:\n",
|
| 51 |
+
"\n",
|
| 52 |
+
"df_fd.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 |
+
"\n",
|
| 63 |
+
"# Descriptive statistics for numerical columns\n",
|
| 64 |
+
"df_fd.describe()"
|
| 65 |
+
],
|
| 66 |
+
"execution_count": null,
|
| 67 |
+
"outputs": []
|
| 68 |
+
},
|
| 69 |
+
{
|
| 70 |
+
"cell_type": "code",
|
| 71 |
+
"metadata": {},
|
| 72 |
+
"source": [
|
| 73 |
+
"# Task 5: Write your code here:\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"import matplotlib.pyplot as plt\n",
|
| 76 |
+
"# Price distribution (target variable)\n",
|
| 77 |
+
"plt.figure(figsize=(10, 5))\n",
|
| 78 |
+
"plt.plot(df_fd['Delivery_Time'].dropna())\n",
|
| 79 |
+
"plt.title('delivery_time Distribution')\n",
|
| 80 |
+
"plt.show()"
|
| 81 |
+
],
|
| 82 |
+
"execution_count": null,
|
| 83 |
+
"outputs": []
|
| 84 |
+
},
|
| 85 |
+
{
|
| 86 |
+
"cell_type": "code",
|
| 87 |
+
"metadata": {},
|
| 88 |
+
"source": [
|
| 89 |
+
"# Task 1: Write your code here:\n",
|
| 90 |
+
"\n",
|
| 91 |
+
"df_clean = df_fd.drop(columns=['Order_ID']).copy()\n",
|
| 92 |
+
"df_clean.head()"
|
| 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 |
+
"df_clean = df_fd.drop(columns=['Order_ID']).copy()\n",
|
| 104 |
+
"df_clean.head()"
|
| 105 |
+
],
|
| 106 |
+
"execution_count": null,
|
| 107 |
+
"outputs": []
|
| 108 |
+
},
|
| 109 |
+
{
|
| 110 |
+
"cell_type": "code",
|
| 111 |
+
"metadata": {},
|
| 112 |
+
"source": [
|
| 113 |
+
"# Task 3: Write your code here:\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"df_clean = df_fd.drop_duplicates()\n",
|
| 116 |
+
"df_clean.head()\n"
|
| 117 |
+
],
|
| 118 |
+
"execution_count": null,
|
| 119 |
+
"outputs": []
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"cell_type": "code",
|
| 123 |
+
"metadata": {},
|
| 124 |
+
"source": [
|
| 125 |
+
"# Task 4: Write your code here:\n",
|
| 126 |
+
"\n",
|
| 127 |
+
"from sklearn.preprocessing import LabelEncoder\n",
|
| 128 |
+
"\n",
|
| 129 |
+
"# Encode type columns\n",
|
| 130 |
+
"le = LabelEncoder()\n",
|
| 131 |
+
"df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n",
|
| 132 |
+
"df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n",
|
| 133 |
+
"df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n",
|
| 134 |
+
"df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n",
|
| 135 |
+
"df_clean.head()\n"
|
| 136 |
+
],
|
| 137 |
+
"execution_count": null,
|
| 138 |
+
"outputs": []
|
| 139 |
+
},
|
| 140 |
+
{
|
| 141 |
+
"cell_type": "code",
|
| 142 |
+
"metadata": {},
|
| 143 |
+
"source": [
|
| 144 |
+
"# Task 5: Write your code here:\n",
|
| 145 |
+
"\n",
|
| 146 |
+
"from sklearn.preprocessing import StandardScaler\n",
|
| 147 |
+
"\n",
|
| 148 |
+
"# Scale features\n",
|
| 149 |
+
"scaler = StandardScaler()\n",
|
| 150 |
+
"x = scaler.fit_transform(df_clean)\n",
|
| 151 |
+
"print(x)\n"
|
| 152 |
+
],
|
| 153 |
+
"execution_count": null,
|
| 154 |
+
"outputs": []
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"cell_type": "code",
|
| 158 |
+
"metadata": {},
|
| 159 |
+
"source": [
|
| 160 |
+
"# Task 6: Write your code here:"
|
| 161 |
+
],
|
| 162 |
+
"execution_count": null,
|
| 163 |
+
"outputs": []
|
| 164 |
+
},
|
| 165 |
+
{
|
| 166 |
+
"cell_type": "code",
|
| 167 |
+
"metadata": {},
|
| 168 |
+
"source": [
|
| 169 |
+
"# Task 1: Write your code here:\n",
|
| 170 |
+
"\n",
|
| 171 |
+
"from sklearn.model_selection import train_test_split\n",
|
| 172 |
+
"\n",
|
| 173 |
+
"# Split the dataset into training and testing sets\n",
|
| 174 |
+
"\n",
|
| 175 |
+
"X = df_clean.data\n",
|
| 176 |
+
"y = df_clean.target\n",
|
| 177 |
+
"\n",
|
| 178 |
+
"X_train, X_test, y_train, y_test = train_test_split(\n",
|
| 179 |
+
" X, y, test_size=0.2, random_state=42, stratify=y)\n",
|
| 180 |
+
"\n",
|
| 181 |
+
"print(X_train, X_test, y_train, y_test)\n"
|
| 182 |
+
],
|
| 183 |
+
"execution_count": null,
|
| 184 |
+
"outputs": []
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"cell_type": "code",
|
| 188 |
+
"metadata": {},
|
| 189 |
+
"source": [
|
| 190 |
+
"# Task 2,3,4,5: Write your code here:\n",
|
| 191 |
+
"from sklearn.ensemble import RandomForestClassifier\n",
|
| 192 |
+
"from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
|
| 193 |
+
"\n",
|
| 194 |
+
"# Train RandomForestClassifier\n",
|
| 195 |
+
"model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
|
| 196 |
+
" class_weight='balanced', random_state=42)\n",
|
| 197 |
+
"model.fit(X_train_scaled, y_train)\n",
|
| 198 |
+
"print(\"Model trained!\")\n",
|
| 199 |
+
"mae = mean_absolute_error(y_test.numpy(), predictions)\n",
|
| 200 |
+
"\n"
|
| 201 |
+
],
|
| 202 |
+
"execution_count": null,
|
| 203 |
+
"outputs": []
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
"cell_type": "code",
|
| 207 |
+
"metadata": {},
|
| 208 |
+
"source": [
|
| 209 |
+
"# Task 1: Write your code here:"
|
| 210 |
+
],
|
| 211 |
+
"execution_count": null,
|
| 212 |
+
"outputs": []
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"cell_type": "code",
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"source": [
|
| 218 |
+
"# Task 2: Write your code here:"
|
| 219 |
+
],
|
| 220 |
+
"execution_count": null,
|
| 221 |
+
"outputs": []
|
| 222 |
+
},
|
| 223 |
+
{
|
| 224 |
+
"cell_type": "code",
|
| 225 |
+
"metadata": {},
|
| 226 |
+
"source": [
|
| 227 |
+
"# Task Bonus: Write your code here:\n",
|
| 228 |
+
"from sklearn.ensemble import RandomForestRegressor\n",
|
| 229 |
+
"from catboost import CatBoostRegressor\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"\n"
|
| 232 |
+
],
|
| 233 |
+
"execution_count": null,
|
| 234 |
+
"outputs": []
|
| 235 |
+
}
|
| 236 |
+
],
|
| 237 |
+
"metadata": {
|
| 238 |
+
"kernelspec": {
|
| 239 |
+
"display_name": "Python 3",
|
| 240 |
+
"name": "python3"
|
| 241 |
+
},
|
| 242 |
+
"language_info": {
|
| 243 |
+
"name": "python"
|
| 244 |
+
}
|
| 245 |
+
},
|
| 246 |
+
"nbformat": 4,
|
| 247 |
+
"nbformat_minor": 0
|
| 248 |
+
}
|