ALLIA12 commited on
Commit
f5c196f
·
verified ·
1 Parent(s): e7ac985

Intro to AI Stage 2 practical exam: 1038 dual-graded students, rubric, solutions (part 7)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. submissions_extracted/820/Q1.ipynb +432 -0
  2. submissions_extracted/820/Q2.ipynb +424 -0
  3. submissions_extracted/820/Q3.ipynb +279 -0
  4. submissions_extracted/821/Q1.ipynb +258 -0
  5. submissions_extracted/821/Q2.ipynb +394 -0
  6. submissions_extracted/821/Q3.ipynb +200 -0
  7. submissions_extracted/822/Q1.ipynb +369 -0
  8. submissions_extracted/822/Q2.ipynb +421 -0
  9. submissions_extracted/822/Q3.ipynb +217 -0
  10. submissions_extracted/823/Q1.ipynb +343 -0
  11. submissions_extracted/823/Q2.ipynb +407 -0
  12. submissions_extracted/823/Q3.ipynb +285 -0
  13. submissions_extracted/824/Q1.ipynb +517 -0
  14. submissions_extracted/824/Q2.ipynb +478 -0
  15. submissions_extracted/824/Q3.ipynb +592 -0
  16. submissions_extracted/825/Q1.ipynb +263 -0
  17. submissions_extracted/825/Q2.ipynb +384 -0
  18. submissions_extracted/825/Q3.ipynb +249 -0
  19. submissions_extracted/826/Q1.ipynb +278 -0
  20. submissions_extracted/826/Q2.ipynb +360 -0
  21. submissions_extracted/826/Q3.ipynb +288 -0
  22. submissions_extracted/827/Q1.ipynb +265 -0
  23. submissions_extracted/827/Q2.ipynb +382 -0
  24. submissions_extracted/827/Q3.ipynb +177 -0
  25. submissions_extracted/828/Q1.ipynb +354 -0
  26. submissions_extracted/828/Q2.ipynb +414 -0
  27. submissions_extracted/828/Q3.ipynb +315 -0
  28. submissions_extracted/829/Q1.ipynb +347 -0
  29. submissions_extracted/829/Q2.ipynb +390 -0
  30. submissions_extracted/829/Q3.ipynb +322 -0
  31. submissions_extracted/83/Q1.ipynb +250 -0
  32. submissions_extracted/83/Q2.ipynb +209 -0
  33. submissions_extracted/83/Q3.ipynb +266 -0
  34. submissions_extracted/830/Q1.ipynb +322 -0
  35. submissions_extracted/830/Q2.ipynb +362 -0
  36. submissions_extracted/830/Q3.ipynb +177 -0
  37. submissions_extracted/831/Q1.ipynb +272 -0
  38. submissions_extracted/831/Q2.ipynb +433 -0
  39. submissions_extracted/831/Q3.ipynb +197 -0
  40. submissions_extracted/832/Q1.ipynb +405 -0
  41. submissions_extracted/832/Q2.ipynb +332 -0
  42. submissions_extracted/832/Q3.ipynb +186 -0
  43. submissions_extracted/833/Q1.ipynb +317 -0
  44. submissions_extracted/833/Q2.ipynb +370 -0
  45. submissions_extracted/833/Q3.ipynb +176 -0
  46. submissions_extracted/834/Q1.ipynb +263 -0
  47. submissions_extracted/834/Q2.ipynb +372 -0
  48. submissions_extracted/834/Q3.ipynb +255 -0
  49. submissions_extracted/835/Q1.ipynb +283 -0
  50. submissions_extracted/835/Q2.ipynb +351 -0
submissions_extracted/820/Q1.ipynb ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, KFold\n",
28
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
29
+ "from sklearn.ensemble import RandomForestRegressor\n",
30
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# Task 1: Write your code here:\n",
40
+ "new_path = os.path.join(path, 'Q1_data.csv')\n",
41
+ "df = pd.read_csv(new_path)\n",
42
+ "\n",
43
+ "print(f\"Dataset shape: {df.shape}\")\n"
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.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.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.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
+ "# Price distribution (target variable)\n",
84
+ "plt.figure(figsize=(10, 5))\n",
85
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
86
+ "plt.title('Delivery_Time Distribution')\n",
87
+ "plt.xlabel('Delivery_Time')\n",
88
+ "plt.ylabel('Frequency')\n",
89
+ "plt.show()"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 1: Write your code here:\n",
99
+ "df = df.drop(\"Order_ID\", axis=1)\n",
100
+ "\n",
101
+ "df.head()"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# Task 2: Write your code here:\n",
111
+ "# Analyze missing values\n",
112
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
113
+ "missing_data = pd.DataFrame({\n",
114
+ " 'Column': missing_percentage.index,\n",
115
+ " 'Missing_Percentage': missing_percentage.values\n",
116
+ "})\n",
117
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
118
+ "\n",
119
+ "print(\"Missing Data Analysis:\")\n",
120
+ "missing_data.head(10)\n",
121
+ "df_cars.describe()\n",
122
+ "\n",
123
+ "\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)"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 3: Write your code here:\n",
143
+ "def check_duplicates(df):\n",
144
+ " duplicates = df.duplicated().sum()\n",
145
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
146
+ " if duplicates > 0:\n",
147
+ " print(\"Dropping Duplicates...\")\n",
148
+ " df.drop_duplicates(inplace=True)\n",
149
+ " print(\"Duplicates Dropped.\")\n",
150
+ " else:\n",
151
+ " print(\"No Duplicate Samples Found.\")\n",
152
+ "\n",
153
+ "check_duplicates(df)\n",
154
+ "\n",
155
+ "df.head()"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 4: Write your code here:\n",
165
+ "\n",
166
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
167
+ "\n",
168
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
169
+ "\n",
170
+ "label_encoders = {}\n",
171
+ "for col in categorical_cols:\n",
172
+ " le = LabelEncoder()\n",
173
+ " df[col] = le.fit_transform(df[col])\n",
174
+ " label_encoders[col] = le\n",
175
+ "\n",
176
+ "df"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 5: Write your code here:\n",
186
+ "import numpy as np\n",
187
+ "import pandas as pd\n",
188
+ "import matplotlib.pyplot as plt\n",
189
+ "import kagglehub\n",
190
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
191
+ "from sklearn.model_selection import KFold\n",
192
+ "from sklearn.linear_model import LinearRegression\n",
193
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
194
+ "target_column = \"Delivery_Time\"\n",
195
+ "\n",
196
+ "X = df.drop(target_column, axis=1)\n",
197
+ "y = df[target_column]\n",
198
+ "\n",
199
+ "print(\"\\nDataset Shapes\")\n",
200
+ "print(\"X:\", X.shape)\n",
201
+ "print(\"y:\", y.shape)\n",
202
+ "\n",
203
+ "\n",
204
+ "# Feature Scaling\n",
205
+ "scaler = StandardScaler()\n",
206
+ "X_scaled = scaler.fit_transform(X)\n"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 6: Write your code here:\n",
216
+ "import pandas as pd\n",
217
+ "import numpy as np\n",
218
+ "import matplotlib.pyplot as plt\n",
219
+ "import seaborn as sns\n",
220
+ "import kagglehub\n",
221
+ "import os\n",
222
+ "from tqdm import tqdm\n",
223
+ "\n",
224
+ "%matplotlib inline\n",
225
+ "def check_target_imbalance(df, target_column):\n",
226
+ " print(\"Target Distribution:\")\n",
227
+ " print(df[target_column].value_counts(normalize=True))\n",
228
+ " sns.countplot(x=df[target_column])\n",
229
+ " plt.title(\"Target Distribution\")\n",
230
+ " plt.show()\n",
231
+ "\n",
232
+ "check_target_imbalance(df, target_column)\n",
233
+ "\n",
234
+ "###Target is numeric not classes so we don't need to worry!!"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Define Model\n",
244
+ "model = LinearRegression()\n",
245
+ "\n",
246
+ "# K-Fold Cross Validation\n",
247
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
248
+ "\n",
249
+ "mse_scores = []\n",
250
+ "mae_scores = []\n",
251
+ "\n",
252
+ "for train_idx, test_idx in kf.split(X_scaled):\n",
253
+ " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n",
254
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
255
+ "\n",
256
+ " # Train model\n",
257
+ " model.fit(X_train, y_train)\n",
258
+ "\n",
259
+ " # Predict\n",
260
+ " y_pred = model.predict(X_test)\n",
261
+ "\n",
262
+ " # Evaluation metrics\n",
263
+ " mse_scores.append(mean_squared_error(y_test, y_pred))\n",
264
+ " mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
265
+ "\n",
266
+ "\n",
267
+ "# Print Evaluation Metrics\n",
268
+ "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*40)\n",
269
+ "print(f\"MSE : {np.mean(mse_scores):.2f}\")\n",
270
+ "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n",
271
+ "print(f\"RMSE: {np.sqrt(np.mean(mse_scores)):.2f}\")\n",
272
+ "print(\"-\"*40)\n",
273
+ "\n",
274
+ "# Plot Predictions vs Ground Truth\n",
275
+ "plt.figure(figsize=(6, 4))\n",
276
+ "plt.scatter(y_test, y_pred, alpha=0.6)\n",
277
+ "plt.plot(\n",
278
+ " [y_test.min(), y_test.max()],\n",
279
+ " [y_test.min(), y_test.max()],\n",
280
+ " \"r--\",\n",
281
+ " linewidth=2\n",
282
+ ")\n",
283
+ "\n",
284
+ "plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n",
285
+ "plt.ylabel(\"Predicted Exam Scores\")\n",
286
+ "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
287
+ "plt.grid(True)\n",
288
+ "\n",
289
+ "plt.tight_layout()\n",
290
+ "plt.show()\n"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "# Task 1: Write your code here:\n",
300
+ "# Define Model\n",
301
+ "\n",
302
+ "X = df.drop(target_column, axis=1)\n",
303
+ "y = df[target_column]\n",
304
+ "\n",
305
+ "\n"
306
+ ],
307
+ "execution_count": null,
308
+ "outputs": []
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "metadata": {},
313
+ "source": [
314
+ "# Task 2,3,4,5: Write your code here:\n",
315
+ "#From sklearn.metrics import mean_absolute_error\n",
316
+ "models = {\n",
317
+ "\n",
318
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
319
+ "}\n",
320
+ "\n",
321
+ "\n",
322
+ "# Handle NaN\n",
323
+ "if isinstance(y, pd.Series):\n",
324
+ " nan_indices = y.index[y.isna()] # Get indices where y is NaN in Series\n",
325
+ " y = y.dropna()\n",
326
+ "\n",
327
+ "\n",
328
+ "n_splits = 5 # K=5 Folds\n",
329
+ "\n",
330
+ "# Storage for results\n",
331
+ "all_results = {}\n",
332
+ "\n",
333
+ "for name in models:\n",
334
+ " all_results[name] = {'mae': []}\n",
335
+ "\n",
336
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
337
+ "\n",
338
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
339
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
340
+ "\n",
341
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
342
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
343
+ "\n",
344
+ " print(f\"Training {model}...\")\n",
345
+ "\n",
346
+ " # Train\n",
347
+ " model.fit(X_train, y_train)\n",
348
+ "\n",
349
+ " # Predict\n",
350
+ " y_pred = model.predict(X_test)\n",
351
+ "\n",
352
+ " # Calculate metrics\n",
353
+ " mae = mean_absolute_error(y_test, y_pred)\n",
354
+ "\n",
355
+ " # Store results\n",
356
+ " all_results[model_name][\"mse\"].append(mse)\n",
357
+ "\n",
358
+ " #idk what is the error\n"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [],
367
+ "execution_count": null,
368
+ "outputs": []
369
+ },
370
+ {
371
+ "cell_type": "code",
372
+ "metadata": {},
373
+ "source": [
374
+ "# Task 1: Write your code here:\n",
375
+ "from sklearn.linear_model import Ridge, Lasso\n",
376
+ "\n",
377
+ "coeffs = {}\n",
378
+ "\n",
379
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
380
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
381
+ "\n",
382
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
383
+ "axes = axes.flatten()\n",
384
+ "features = X.columns\n",
385
+ "\n",
386
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
387
+ " # Sort features by absolute coefficient value\n",
388
+ " absolute_coef = np.abs(coef)\n",
389
+ " sorted_idx = np.argsort(absolute_coef)\n",
390
+ "\n",
391
+ " ax = axes[i]\n",
392
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
393
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
394
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
395
+ "\n",
396
+ "plt.tight_layout()\n",
397
+ "plt.show()"
398
+ ],
399
+ "execution_count": null,
400
+ "outputs": []
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "metadata": {},
405
+ "source": [
406
+ "# Task 2: Write your code here:\n"
407
+ ],
408
+ "execution_count": null,
409
+ "outputs": []
410
+ },
411
+ {
412
+ "cell_type": "code",
413
+ "metadata": {},
414
+ "source": [
415
+ "# Task Bonus: Write your code here:"
416
+ ],
417
+ "execution_count": null,
418
+ "outputs": []
419
+ }
420
+ ],
421
+ "metadata": {
422
+ "kernelspec": {
423
+ "display_name": "Python 3",
424
+ "name": "python3"
425
+ },
426
+ "language_info": {
427
+ "name": "python"
428
+ }
429
+ },
430
+ "nbformat": 4,
431
+ "nbformat_minor": 0
432
+ }
submissions_extracted/820/Q2.ipynb ADDED
@@ -0,0 +1,424 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
70
+ "import torch\n",
71
+ "from sklearn.preprocessing import StandardScaler\n",
72
+ "from torch.utils.data import TensorDataset\n",
73
+ "from torch.utils.data import DataLoader\n",
74
+ "import torch\n",
75
+ "from torchvision.datasets import MNIST\n",
76
+ "from torchvision.transforms.functional import to_tensor\n",
77
+ "from torch.utils.data import DataLoader\n",
78
+ "import torch\n",
79
+ "import torch.nn as nn"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
89
+ "\n",
90
+ "\n",
91
+ "# transform to tensors\n",
92
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\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)\n",
96
+ "\n",
97
+ "# Create TensorDatasets for training and testing\n",
98
+ "train_dataset = TensorDataset(X_train, y_train)\n",
99
+ "test_dataset = TensorDataset(X_test, y_test)\n",
100
+ "\n",
101
+ "# Create Dataloaders to train and test data in batches\n",
102
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
103
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# 2. Create TensorDataset objects\n",
113
+ "\n",
114
+ "train_dataset = TensorDataset(X_train, y_train)\n",
115
+ "test_dataset = TensorDataset(X_test, y_test)\n",
116
+ "\n",
117
+ "first_sample, _ = train_dataset[0]\n",
118
+ "print(f\"Shape of one sample: {first_sample.shape}\")"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# 3. Create DataLoaders\n",
128
+ "\n",
129
+ "\n",
130
+ "train_loader = DataLoader(\n",
131
+ " train_dataset,\n",
132
+ " batch_size=32,\n",
133
+ " shuffle=True,\n",
134
+ " num_workers=2\n",
135
+ ")\n",
136
+ "# DataLoader for test/validation data\n",
137
+ "test_loader = DataLoader(\n",
138
+ " test_dataset,\n",
139
+ " batch_size=32,\n",
140
+ " shuffle=False,\n",
141
+ " num_workers=2\n",
142
+ ")\n"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# 4. Print shape of one batch\n",
152
+ "\n",
153
+ "# Get the first batch from the training DataLoader\n",
154
+ "X_batch, y_batch = next(iter(train_loader))\n",
155
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
156
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# 5. Display sample images\n",
166
+ "import matplotlib.pyplot as plt\n",
167
+ "images, labels = next(iter(train_loader))\n",
168
+ "\n",
169
+ "# Display the first 6 images in the batch\n",
170
+ "plt.figure(figsize=(8, 4))\n",
171
+ "\n",
172
+ "for i in range(6):\n",
173
+ " plt.subplot(2, 3, i + 1)\n",
174
+ "\n",
175
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
176
+ " img = images[i].permute(1, 2, 0)\n",
177
+ "\n",
178
+ " plt.imshow(img)\n",
179
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
180
+ " plt.axis('off')\n",
181
+ "\n",
182
+ "plt.tight_layout()\n",
183
+ "plt.show()"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "# Task 1: Write your model class here:\n",
193
+ "\n",
194
+ "class NN4Layer(nn.Module):\n",
195
+ "\n",
196
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
197
+ " super(NN4Layer, self).__init__()\n",
198
+ "\n",
199
+ " # First linear layer: input features -> hidden layer\n",
200
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
201
+ "\n",
202
+ " # Second linear layer: hidden layer -> hidden layer\n",
203
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
204
+ "\n",
205
+ " # Third linear layer: hidden layer -> hidden layer\n",
206
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
207
+ "\n",
208
+ " # Output layer: hidden layer -> number of classes (logits)\n",
209
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
210
+ "\n",
211
+ " # ReLU activation for non-linearity\n",
212
+ " self.relu = nn.ReLU()\n",
213
+ "\n",
214
+ " # Defines how input data flows through the network\n",
215
+ " def forward(self, x):\n",
216
+ " # First hidden layer\n",
217
+ " a1 = self.relu(self.layer1(x))\n",
218
+ "\n",
219
+ " # Second hidden layer\n",
220
+ " a2 = self.relu(self.layer2(a1))\n",
221
+ "\n",
222
+ " # Third hidden layer\n",
223
+ " a3 = self.relu(self.layer3(a2))\n",
224
+ "\n",
225
+ " # Output layer\n",
226
+ " output = self.layer4(a3)\n",
227
+ " return output"
228
+ ],
229
+ "execution_count": null,
230
+ "outputs": []
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "metadata": {},
235
+ "source": [
236
+ "# Task 2: Write your training loop here:\n",
237
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
238
+ " # Set the model to training mode\n",
239
+ " model.train()\n",
240
+ "\n",
241
+ " running_loss = 0.0\n",
242
+ "\n",
243
+ " for X_batch, y_batch in train_loader:\n",
244
+ " # Move batch to the selected device\n",
245
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
246
+ " y_batch = y_batch.to(device)\n",
247
+ "\n",
248
+ " # Forward pass\n",
249
+ " # TODO: make predictions\n",
250
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
251
+ " # TODO: compute loss\n",
252
+ " loss = criterion(outputs, y_batch)\n",
253
+ "\n",
254
+ " # Backward pass & optimization\n",
255
+ " optimizer.zero_grad() # Clear previous gradients\n",
256
+ " loss.backward() # Compute gradients\n",
257
+ " optimizer.step() # Update model parameters\n",
258
+ "\n",
259
+ " running_loss += loss.item()\n",
260
+ "\n",
261
+ " # Average loss over all batches\n",
262
+ " avg_loss = running_loss / len(train_loader)\n",
263
+ "\n",
264
+ " return avg_loss"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "metadata": {},
272
+ "source": [
273
+ "# Task 3: Write your validation loop here:\n",
274
+ "def validate(model, criterion, test_loader, device):\n",
275
+ " # Set the model to evaluation mode\n",
276
+ " model.eval()\n",
277
+ "\n",
278
+ " running_loss = 0.0\n",
279
+ " correct = 0\n",
280
+ " total = 0\n",
281
+ "\n",
282
+ " with torch.no_grad():\n",
283
+ " for X_batch, y_batch in test_loader:\n",
284
+ " # Move data to device\n",
285
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
286
+ " y_batch = y_batch.to(device)\n",
287
+ "\n",
288
+ " # Forward pass\n",
289
+ " # TODO: make predictions\n",
290
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
291
+ " # TODO: compute loss\n",
292
+ " loss = criterion(outputs, y_batch)\n",
293
+ " running_loss += loss.item()\n",
294
+ "\n",
295
+ " # TODO: Apply Softmax to get probabilities\n",
296
+ " probabilities = F.softmax(outputs, dim=1)\n",
297
+ "\n",
298
+ " # TODO: Multiclass predictions\n",
299
+ " predicted = torch.argmax(probabilities, dim=1)\n",
300
+ "\n",
301
+ " # Accuracy calculation\n",
302
+ " correct += (predicted == y_batch).sum().item()\n",
303
+ " total += y_batch.size(0)\n",
304
+ "\n",
305
+ " avg_loss = running_loss / len(test_loader)\n",
306
+ " # TODO: how do we calculate accuracy?\n",
307
+ " accuracy = correct / total\n",
308
+ "\n",
309
+ " return avg_loss, accuracy\n"
310
+ ],
311
+ "execution_count": null,
312
+ "outputs": []
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "metadata": {},
317
+ "source": [
318
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
319
+ "\n",
320
+ "# Model parameters\n",
321
+ "# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
322
+ "input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n",
323
+ "\n",
324
+ "# TODO: choose number of hidden neurons\n",
325
+ "hidden_dim = 64 # Design choice\n",
326
+ "\n",
327
+ "# TODO: what are the number of classes ?\n",
328
+ "output_dim = 10 # CIFAR-10 classes\n",
329
+ "\n",
330
+ "# TODO: Instantiate model (what are the model class inputs?)\n",
331
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
332
+ "\n",
333
+ "# TODO: Print the model architecture\n",
334
+ "print(\"Model Architecture:\\n\")\n",
335
+ "print(model)\n",
336
+ "\n",
337
+ "# Calculate the total number of trainable parameters\n",
338
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
339
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
340
+ "\n",
341
+ "num_epochs = 20\n",
342
+ "# TODO: choose a learning rate (try different values and evaluate results)\n",
343
+ "learning_rate = 0.001\n",
344
+ "\n",
345
+ "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
346
+ "criterion = nn.CrossEntropyLoss()\n",
347
+ "# TODO: Define optimizer(what is updated during training?)\n",
348
+ "from torch.optim import AdamW\n",
349
+ "optimizer = AdamW(model.parameters(), learning_rate)\n"
350
+ ],
351
+ "execution_count": null,
352
+ "outputs": []
353
+ },
354
+ {
355
+ "cell_type": "code",
356
+ "metadata": {},
357
+ "source": [
358
+ "# Task 5: Start training for 20 epochs:\n",
359
+ "# Run Training\n",
360
+ "train_losses = []\n",
361
+ "val_losses = []\n",
362
+ "val_accuracies = []\n",
363
+ "\n",
364
+ "print('Starting Training...')\n",
365
+ "for epoch in range(num_epochs):\n",
366
+ " # Train one epoch\n",
367
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
368
+ "\n",
369
+ " # Validate\n",
370
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
371
+ "\n",
372
+ " train_losses.append(train_loss)\n",
373
+ " val_losses.append(val_loss)\n",
374
+ " val_accuracies.append(val_accuracy)\n",
375
+ "\n",
376
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
377
+ "\n",
378
+ "print('Training Complete!')"
379
+ ],
380
+ "execution_count": null,
381
+ "outputs": []
382
+ },
383
+ {
384
+ "cell_type": "code",
385
+ "metadata": {},
386
+ "source": [
387
+ "# Task 1: Write your code here:\n",
388
+ "plt.figure(figsize=(7, 5))\n",
389
+ "\n",
390
+ "plt.plot(train_losses, label='Train Loss')\n",
391
+ "plt.plot(val_losses, label='Validation Loss')\n",
392
+ "plt.title('Loss over Epochs')\n",
393
+ "plt.xlabel('Epoch')\n",
394
+ "plt.ylabel('Loss')\n",
395
+ "plt.legend()\n",
396
+ "\n",
397
+ "plt.tight_layout()\n",
398
+ "plt.show()"
399
+ ],
400
+ "execution_count": null,
401
+ "outputs": []
402
+ },
403
+ {
404
+ "cell_type": "code",
405
+ "metadata": {},
406
+ "source": [
407
+ "# Task 2 (Bonus): Write your code here:"
408
+ ],
409
+ "execution_count": null,
410
+ "outputs": []
411
+ }
412
+ ],
413
+ "metadata": {
414
+ "kernelspec": {
415
+ "display_name": "Python 3",
416
+ "name": "python3"
417
+ },
418
+ "language_info": {
419
+ "name": "python"
420
+ }
421
+ },
422
+ "nbformat": 4,
423
+ "nbformat_minor": 0
424
+ }
submissions_extracted/820/Q3.ipynb ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import numpy as np\n",
27
+ "import pandas as pd\n",
28
+ "import matplotlib.pyplot as plt\n",
29
+ "import os\n",
30
+ "import kagglehub\n",
31
+ "\n",
32
+ "from sklearn.model_selection import train_test_split, KFold\n",
33
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
34
+ "from sklearn.ensemble import RandomForestRegressor\n",
35
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 1: Write your code here:\n",
45
+ "new_path = os.path.join(path, 'Q3_data.csv')\n",
46
+ "df = pd.read_csv(new_path)\n",
47
+ "\n",
48
+ "print(f\"Dataset shape: {df.shape}\")"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 2: Write your code here:\n",
58
+ "df.head()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 3: Write your code here:\n",
68
+ "df.info()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 4: Write your code here:\n",
78
+ "df.describe()"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "import pandas as pd\n",
88
+ "import numpy as np\n",
89
+ "import matplotlib.pyplot as plt\n",
90
+ "import seaborn as sns\n",
91
+ "import kagglehub\n",
92
+ "import os\n",
93
+ "import numpy as np\n",
94
+ "import pandas as pd\n",
95
+ "import matplotlib.pyplot as plt\n",
96
+ "import os\n",
97
+ "\n",
98
+ "from sklearn.model_selection import train_test_split, KFold\n",
99
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n"
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
+ "# Missing values\n",
110
+ "print(\"Missing values:\")\n",
111
+ "print(df.isnull().sum())\n",
112
+ "\n",
113
+ "df = df.dropna()"
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
+ "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)\n",
134
+ "\n",
135
+ "df.head()"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Task 3: Write your code here:\n",
145
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
146
+ "\n",
147
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
148
+ "\n",
149
+ "label_encoders = {}\n",
150
+ "for col in categorical_cols:\n",
151
+ " le = LabelEncoder()\n",
152
+ " df[col] = le.fit_transform(df[col])\n",
153
+ " label_encoders[col] = le\n",
154
+ "\n",
155
+ "df"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 4: Write your code here:"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 5: Write your code here:"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task 1: Write your code here:\n",
183
+ "X = df.drop('Target', axis=1)\n",
184
+ "y = df['Target']"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [],
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
+ "from sklearn.model_selection import KFold\n",
202
+ "from catboost import CatBoostClassifier\n",
203
+ "from sklearn.linear_model import Ridge, Lasso\n",
204
+ "from sklearn.svm import SVR\n",
205
+ "from sklearn.tree import DecisionTreeRegressor\n",
206
+ "from sklearn.ensemble import RandomForestRegressor\n",
207
+ "from lightgbm import LGBMRegressor\n",
208
+ "\n",
209
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
210
+ "scores = []\n",
211
+ "\n",
212
+ "for train, test in kf.split(X):\n",
213
+ " model = CatBoostClassifier(verbose=0,\n",
214
+ " n_estimators=200,\n",
215
+ " max_depth=4)\n",
216
+ " model.fit(X.iloc[train], y.iloc[train])\n",
217
+ " scores.append(model.score(X.iloc[test], y.iloc[test]))\n",
218
+ "\n",
219
+ "print('Accuracy:', sum(scores)/len(scores))\n",
220
+ "\n",
221
+ "model.fit(X, y)\n"
222
+ ],
223
+ "execution_count": null,
224
+ "outputs": []
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "metadata": {},
229
+ "source": [
230
+ "# Task 1: Write your code here:\n",
231
+ "feature_cols = [\"P_2\", \"D_39\", \"B_1\"]\n",
232
+ "feature_importance = pd.DataFrame({\n",
233
+ " 'feature': feature_cols,\n",
234
+ " 'importance': model.feature_importances_\n",
235
+ "}).sort_values('importance', ascending=False)\n",
236
+ "\n",
237
+ "plt.figure(figsize=(10, 6))\n",
238
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
239
+ "plt.xlabel('Importance')\n",
240
+ "plt.title('Feature Importance')\n",
241
+ "plt.gca().invert_yaxis()\n",
242
+ "plt.show()"
243
+ ],
244
+ "execution_count": null,
245
+ "outputs": []
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "metadata": {},
250
+ "source": [
251
+ "# Task 2: Write your code here:\n",
252
+ "golden_feature = feature_importance.index[0]\n",
253
+ "print(golden_feature)"
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": "python3"
272
+ },
273
+ "language_info": {
274
+ "name": "python"
275
+ }
276
+ },
277
+ "nbformat": 4,
278
+ "nbformat_minor": 0
279
+ }
submissions_extracted/821/Q1.ipynb ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "import kagglehub\n",
13
+ "from sklearn.metrics import mean_absolute_error\n",
14
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
15
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
16
+ "from sklearn.ensemble import RandomForestClassifier\n",
17
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
18
+ "\n",
19
+ "import warnings\n",
20
+ "warnings.filterwarnings('ignore')\n",
21
+ "\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
+ "#reading the file\n",
36
+ "food_path = os.path.join(path, 'Q1_data.csv')\n",
37
+ "df_food = pd.read_csv(food_path)\n",
38
+ "\n",
39
+ "print(f\"Dataset shape: {df_food.shape}\")\n",
40
+ "\n",
41
+ "\n",
42
+ "\n"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "#Inspect the first few rows using the head function\n",
53
+ "df_food.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
+ "#displaying some datasets\n",
64
+ "df_food.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 4: Write your code here:\n",
74
+ "# Descriptive statistics for numerical columns\n",
75
+ "df_food.describe()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 5: Write your code here:\n",
85
+ "# delivery_time distribution (target variable)\n",
86
+ "plt.figure(figsize=(10, 5))\n",
87
+ "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
88
+ "plt.title('delivery time Distribution')\n",
89
+ "plt.xlabel('delivery_time')\n",
90
+ "plt.ylabel('Frequency')\n",
91
+ "plt.show()"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 1: Write your code here:\n",
101
+ "#df_clean = df_food.drop(df_food['Order_ID']).copy()\n",
102
+ "df_food.drop(\"Order_ID\",axis=1)"
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
+ "# Missing values\n",
113
+ "print(\"Missing values:\")\n",
114
+ "print(df_food.isnull().sum())\n",
115
+ "\n",
116
+ "\n",
117
+ "# Drop rows where target (delivery time) or key features are missing - can't predict without them\n",
118
+ "print(f\"Before: {df_food.shape}\")\n",
119
+ "df_food = df_food.dropna(subset=['Weather','Traffic_Level', 'Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n",
120
+ "print(f\"After dropping missing values: {df_food.shape}\")\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 3: Write your code here:"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 4: Write your code here:\n",
139
+ "# Encode categorical columns - converts text to integers\n",
140
+ "categorical_cols = ['Weather','Traffic_Level','Time_of_Day','Vehicle_Type']\n",
141
+ "for col in categorical_cols:\n",
142
+ " le = LabelEncoder()\n",
143
+ " df_food[col] = le.fit_transform(df_food[col].astype(str))\n",
144
+ "\n",
145
+ "df_food.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
+ "feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
156
+ "X = df_food[feature_cols]\n",
157
+ "y = df_food['Delivery_Time']\n",
158
+ "\n",
159
+ "# Train-test split (80% train, 20% test)\n",
160
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
161
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
162
+ "\n",
163
+ "# Scale features - fit on train, transform both\n",
164
+ "scaler = StandardScaler()\n",
165
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
166
+ "X_test_scaled = scaler.transform(X_test)\n",
167
+ "\n",
168
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
169
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 6: Write your code here:"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 1: Write your code here:"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Task 2,3,4,5: Write your code here:\n",
197
+ "# k fold split\n",
198
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, )\n",
199
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
200
+ "print(f\"Legendary in train: {y_train.sum()}, in test: {y_test.sum()}\")\n",
201
+ "\n",
202
+ "# Train RandomForestClassifier\n",
203
+ "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
204
+ " class_weight='balanced', random_state=42)\n",
205
+ "model.fit(X_train_scaled, y_train)\n",
206
+ "print(\"Model trained!\")\n",
207
+ "# Predictions and metrics\n",
208
+ "# Predict and evaluate\n",
209
+ "y_pred = model.predict(X_test_scaled)\n",
210
+ "\n",
211
+ "mae = mean_absolute_error(y_test, y_pred)\n",
212
+ "\n",
213
+ "\n",
214
+ "print(f\"MAE: ${mae:,.2f}\")\n"
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"
251
+ },
252
+ "language_info": {
253
+ "name": "python"
254
+ }
255
+ },
256
+ "nbformat": 4,
257
+ "nbformat_minor": 0
258
+ }
submissions_extracted/821/Q2.ipynb ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "import kagglehub\n",
27
+ "import pandas as pd\n",
28
+ "import numpy as np\n",
29
+ "import torch\n",
30
+ "import torch.nn as nn\n",
31
+ "from torch.optim import AdamW\n",
32
+ "import matplotlib.pyplot as plt\n",
33
+ "from torch.utils.data import DataLoader, TensorDataset\n",
34
+ "from sklearn.model_selection import train_test_split\n",
35
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
36
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
37
+ "\n",
38
+ "print(f\"PyTorch version: {torch.__version__}\")\n",
39
+ "print(f\"CUDA available: {torch.cuda.is_available()}\")\n",
40
+ "\n",
41
+ "# Load Labels\n",
42
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
43
+ "img_dir = os.path.join(path, \"images\")\n",
44
+ "\n",
45
+ "images = []\n",
46
+ "ages = []\n",
47
+ "\n",
48
+ "# Load Images and Resize\n",
49
+ "print(\"Loading images...\")\n",
50
+ "for index, row in labels_df.iterrows():\n",
51
+ " img_name = row.iloc[0]\n",
52
+ " age = row.iloc[1]\n",
53
+ " img_path = os.path.join(img_dir, img_name)\n",
54
+ "\n",
55
+ " if os.path.exists(img_path):\n",
56
+ " img = Image.open(img_path).convert('RGB')\n",
57
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
58
+ " images.append(img_array)\n",
59
+ " ages.append(age)\n",
60
+ "\n",
61
+ "X = np.array(images)\n",
62
+ "y = np.array(ages)\n",
63
+ "\n",
64
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
65
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
66
+ "\n",
67
+ "# Split Data\n",
68
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
69
+ "\n",
70
+ "print(f\"X_train shape: {X_train.shape}\")\n",
71
+ "print(f\"X_test shape: {X_test.shape}\")\n",
72
+ "print(f\"y_train shape: {y_train.shape}\")\n",
73
+ "print(f\"y_test shape: {y_test.shape}\")\n"
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
+ "\n",
85
+ "# transform to tensors\n",
86
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
87
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
88
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
89
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
90
+ "\n"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# 2. Create TensorDataset objects\n",
100
+ "# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
101
+ "# Each item in the dataset is returned as (X[i], y[i])\n",
102
+ "train_dataset = TensorDataset(X_train, y_train)\n",
103
+ "test_dataset = TensorDataset(X_test, y_test)\n",
104
+ "\n",
105
+ "\n"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# 3. Create DataLoaders\n",
115
+ "\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
+ "\n"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# 4. Print shape of one batch\n",
142
+ "\n",
143
+ "# Get the first batch from the training DataLoader\n",
144
+ "X_batch, y_batch = next(iter(train_loader))\n",
145
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
146
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# 5. Display sample images\n",
156
+ "# Display the first 5 images in the batch\n",
157
+ "plt.figure(figsize=(8, 4))\n",
158
+ "\n",
159
+ "for i in range(5):\n",
160
+ " plt.subplot(2, 3, i + 1)\n",
161
+ "\n",
162
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
163
+ " img = images[i]#.permute(1, 2, 0)\n",
164
+ "\n",
165
+ " plt.imshow(img)\n",
166
+ " plt.title(f\"Label: {ages[i]}\")\n",
167
+ " plt.axis('off')\n",
168
+ "\n",
169
+ "plt.tight_layout()\n",
170
+ "plt.show()\n"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 1: Write your model class here:\n",
180
+ "class NN4Layer(nn.Module):\n",
181
+ "\n",
182
+ " def __init__(self, input_dim,hidden_dim):\n",
183
+ " super(NN4Layer, self).__init__()\n",
184
+ "\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
+ "\n",
193
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
194
+ "\n",
195
+ "\n",
196
+ " self.relu = nn.ReLU()\n",
197
+ "\n",
198
+ " # Defines how input data flows through the network\n",
199
+ " def forward(self, x):\n",
200
+ " # Layer 1: TODO\n",
201
+ " z1 = self.layer1(x)\n",
202
+ " a1 = self.relu(z1)\n",
203
+ "\n",
204
+ " # Layer 2 TODO\n",
205
+ " z2 = self.layer2(a1)\n",
206
+ " a2 = self.relu(z2)\n",
207
+ "\n",
208
+ " # Layer 3 TODO\n",
209
+ " z3 = self.layer3(a2)\n",
210
+ " a3 = self.relu(z3)\n",
211
+ "\n",
212
+ " # Layer 4 TODO\n",
213
+ " z4 = self.layer4(a3)\n",
214
+ " a4=self.relu(z4)\n",
215
+ "\n",
216
+ "\n",
217
+ " return a4"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 2: Write your training loop here:\n",
227
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
228
+ " # Set the model to training mode\n",
229
+ " model.train()\n",
230
+ "\n",
231
+ " running_loss = 0.0\n",
232
+ "\n",
233
+ " for X_batch, y_batch in train_loader:\n",
234
+ " # Move batch to the selected device\n",
235
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
236
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
237
+ "\n",
238
+ " # Forward pass (continuous output)\n",
239
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
240
+ " loss = criterion(outputs, y_batch)\n",
241
+ "\n",
242
+ " # Backward pass & optimization\n",
243
+ " optimizer.zero_grad() # Clear previous gradients\n",
244
+ " loss.backward() # Compute gradients\n",
245
+ " optimizer.step() # Update model parameters\n",
246
+ "\n",
247
+ " running_loss += loss.item()\n",
248
+ "\n",
249
+ " # Average loss over all batches\n",
250
+ " avg_loss = running_loss / len(train_loader)\n",
251
+ "\n",
252
+ " return avg_loss"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 3: Write your validation loop here:\n",
262
+ "def validate(model, criterion, test_loader, device):\n",
263
+ " # Set the model to evaluation mode\n",
264
+ " model.eval()\n",
265
+ "\n",
266
+ " running_loss = 0.0\n",
267
+ " correct = 0\n",
268
+ " total = 0\n",
269
+ "\n",
270
+ " with torch.no_grad():\n",
271
+ " for X_batch, y_batch in test_loader:\n",
272
+ " # Move data to device\n",
273
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
274
+ " y_batch = y_batch.to(device)\n",
275
+ "\n",
276
+ " # Forward pass\n",
277
+ " # TODO: make predictions\n",
278
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
279
+ " # TODO: compute loss\n",
280
+ " loss = criterion(outputs, y_batch)\n",
281
+ " running_loss += loss.item()\n",
282
+ "\n",
283
+ " # TODO: Apply Softmax to get probabilities\n",
284
+ " probabilities = F.softmax(outputs, dim=1)\n",
285
+ "\n",
286
+ " # TODO: Multiclass predictions\n",
287
+ " predicted = torch.argmax(probabilities, dim=1)\n",
288
+ "\n",
289
+ " # Accuracy calculation\n",
290
+ " correct += (predicted == y_batch).sum().item()\n",
291
+ " total += y_batch.size(0)\n",
292
+ "\n",
293
+ " avg_loss = running_loss / len(test_loader)\n",
294
+ " # TODO: how do we calculate accuracy?\n",
295
+ " accuracy = correct / total\n",
296
+ "\n",
297
+ " return avg_loss, accuracy\n"
298
+ ],
299
+ "execution_count": null,
300
+ "outputs": []
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "metadata": {},
305
+ "source": [
306
+ "# Task 4: Define device, model, loss, optimizer:\n",
307
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
308
+ "\n",
309
+ "# Model parameters\n",
310
+ "input_dim =3888\n",
311
+ "hidden_dim =24 # Design choice\n",
312
+ "\n",
313
+ "# Instantiate regression model\n",
314
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
315
+ "\n",
316
+ "# Print the model architecture\n",
317
+ "print(\"Model Architecture:\\n\")\n",
318
+ "print(model)\n",
319
+ "\n",
320
+ "num_epochs = 20\n",
321
+ "learning_rate = 0.001\n",
322
+ "\n",
323
+ "# Define criterion (loss function)\n",
324
+ "criterion = nn.MSELoss()\n",
325
+ "# Define optimizer\n",
326
+ "optimizer = AdamW(model.parameters(), learning_rate)"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "# Task 5: Start training for 20 epochs:\n",
336
+ "\n",
337
+ "# Run Training\n",
338
+ "train_losses = []\n",
339
+ "val_losses = []\n",
340
+ "\n",
341
+ "print('Starting Training...')\n",
342
+ "for epoch in range(num_epochs):\n",
343
+ " # Train one epoch\n",
344
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
345
+ "\n",
346
+ " # Validate\n",
347
+ " val_loss = validate(model, criterion, test_loader, device)\n",
348
+ "\n",
349
+ " train_losses.append(train_loss)\n",
350
+ " val_losses.append(val_loss)\n",
351
+ "\n",
352
+ " if (epoch + 1) % 5 == 0:\n",
353
+ " print(\n",
354
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
355
+ " f'Train Loss: {train_loss:.4f}, '\n",
356
+ " f'Val Loss: {val_loss:.4f}'\n",
357
+ " )\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:"
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/821/Q3.ipynb ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import kagglehub\n",
9
+ "import numpy as np\n",
10
+ "import pandas as pd\n",
11
+ "import matplotlib.pyplot as plt\n",
12
+ "import os\n",
13
+ "import kagglehub\n",
14
+ "from sklearn.metrics import mean_absolute_error\n",
15
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
17
+ "from sklearn.ensemble import RandomForestClassifier\n",
18
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
19
+ "\n",
20
+ "import os\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
+ "q3_path = os.path.join(path,'Q3_data.csv')\n",
39
+ "df_data = pd.read_csv(q3_path)"
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
+ "# inspecting few rows\n",
50
+ "print(f\"Dataset shape: {df_data.shape}\")\n",
51
+ "#Inspect the first few rows using the head function\n",
52
+ "df_data.head()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 3: Write your code here:\n",
62
+ "# displaying using info\n",
63
+ "df_data.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_data.describe()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 1: Write your code here:\n",
83
+ "# Fill missing type2\n",
84
+ "# Analyze missing values\n",
85
+ "missing_percentage = (df_data.isnull().sum() / len(df_data)) * 100\n",
86
+ "missing_data = pd.DataFrame({\n",
87
+ " 'Column': missing_percentage.index,\n",
88
+ " 'Missing_Percentage': missing_percentage.values\n",
89
+ "})\n",
90
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
91
+ "\n",
92
+ "print(\"Missing Data Analysis:\")\n",
93
+ "missing_data.head(10)\n",
94
+ "#filled with one\n",
95
+ "\n",
96
+ "df_data = df_data.dropna(subset=['D_137', 'D_138', 'D_139'])\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 2: Write your code here:\n",
106
+ "# Encode categorical columns - converts text to integers\n",
107
+ " #no need to encod\n",
108
+ ""
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
+ "# Scale features - fit on train, transform both\n",
119
+ "# Train-test split (80% train, 20% test)\n",
120
+ "\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 4: Write your code here:"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 5: Write your code here:"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 1: Write your code here:"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 2,3,4,5: Write your code here:"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 1: Write your code here:"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 2: Write your code here:"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "# Task Bonus: Write your code here:"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ }
188
+ ],
189
+ "metadata": {
190
+ "kernelspec": {
191
+ "display_name": "Python 3",
192
+ "name": "python3"
193
+ },
194
+ "language_info": {
195
+ "name": "python"
196
+ }
197
+ },
198
+ "nbformat": 4,
199
+ "nbformat_minor": 0
200
+ }
submissions_extracted/822/Q1.ipynb ADDED
@@ -0,0 +1,369 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, KFold\n",
28
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
29
+ "from sklearn.ensemble import RandomForestRegressor\n",
30
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
31
+ "\n",
32
+ "import warnings\n",
33
+ "warnings.filterwarnings('ignore')"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 1: Write your code here:\n",
43
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
44
+ "df_data = pd.read_csv(data_path)"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# Task 2: Write your code here:\n",
54
+ "print(f\"Dataset shape: {df_data.shape}\")\n",
55
+ "df_data.head()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 3: Write your code here:\n",
65
+ "df_data.info()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 4: Write your code here:\n",
75
+ "df_data.describe()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 5: Write your code here:\n",
85
+ "df_data.Delivery_Time.hist()"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 1: Write your code here:\n",
95
+ "data = df_data.drop('Order_ID', axis=1)"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "data"
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
+ "# Check missing values\n",
115
+ "missing_values = data.isnull().sum()\n",
116
+ "print(\"Columns with missing values:\")\n",
117
+ "print(missing_values[missing_values > 0])\n",
118
+ "\n",
119
+ "# Fill categorical columns with 'unknown' for categorical columns\n",
120
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
121
+ " data[col] = data[col].fillna('unknown')\n",
122
+ "\n",
123
+ "# # Fill missing values with mean for numerical columns\n",
124
+ "data['Courier_Experience_yrs'] = data['Courier_Experience_yrs'].fillna(data['Courier_Experience_yrs'].mean())\n",
125
+ "data['Delivery_Time'] = data['Delivery_Time'].fillna(data['Delivery_Time'].mean())\n",
126
+ "\n",
127
+ "print(\"Missing values remaining:\", data.isnull().sum().sum())\n",
128
+ "\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 3: Write your code here:\n",
138
+ "# 4. Do we have duplicate samples?\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(data)\n",
150
+ "data"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 4: Write your code here:\n",
160
+ "categorical_cols = data.select_dtypes(include=[\"object\"]).columns\n",
161
+ "for col in categorical_cols:\n",
162
+ " le = LabelEncoder()\n",
163
+ " data[col] = le.fit_transform(data[col].astype(str))\n",
164
+ "\n",
165
+ "data.head()\n"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 5: Write your code here:\n",
175
+ "from sklearn.preprocessing import StandardScaler\n",
176
+ "\n",
177
+ "features = data.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
178
+ "\n",
179
+ "scaler = StandardScaler()\n",
180
+ "data[features] = scaler.fit_transform(data[features])\n",
181
+ "data.head()"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 6: Write your code here:\n",
191
+ "data[\"Delivery_Time\"].hist()"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task 1: Write your code here:\n",
201
+ "X = data.drop(\"Delivery_Time\", axis=1).astype(float)\n",
202
+ "y = data['Delivery_Time'].astype(float)"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# BCE in NumPy\n",
212
+ "def binary_cross_entropy(y, y_hat):\n",
213
+ " epsilon = 1e-15 # Very small number to prevent log(0)\n",
214
+ " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
215
+ "\n",
216
+ " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
217
+ " return loss"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "from tqdm import tqdm\n",
227
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
228
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
229
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
230
+ " losses = []\n",
231
+ "\n",
232
+ " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
233
+ " z = np.dot(X, theta)\n",
234
+ " y_hat = sigmoid(z)\n",
235
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
236
+ " theta -= learning_rate * gradient\n",
237
+ "\n",
238
+ " loss = binary_cross_entropy(y, y_hat)\n",
239
+ " losses.append(loss)\n",
240
+ "\n",
241
+ " return theta, losses"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# sigmoid in NumPy\n",
251
+ "def sigmoid(z):\n",
252
+ " return 1 / (1 + np.exp(-z))"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 2,3,4,5: Write your code here:\n",
262
+ "from sklearn.ensemble import RandomForestClassifier\n",
263
+ "from sklearn.model_selection import StratifiedKFold\n",
264
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
265
+ "\n",
266
+ "\n",
267
+ "n_splits = 5 # K=5 Folds\n",
268
+ "\n",
269
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
270
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
271
+ "\n",
272
+ "model = RandomForestClassifier(\n",
273
+ " n_estimators=320, # Number of trees\n",
274
+ " max_depth=4\n",
275
+ " )\n",
276
+ "\n",
277
+ "lr_losses = []\n",
278
+ "\n",
279
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
280
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
281
+ "\n",
282
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
283
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
284
+ "\n",
285
+ " # Train\n",
286
+ " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
287
+ "\n",
288
+ " # # Validate\n",
289
+ " # y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
290
+ " # y_pred = (y_pred_proba >= 0.5).astype(int)\n",
291
+ " # # y_pred = model.predict(X_test_scaled)\n",
292
+ " # mae = mean_absolute_error(y_test, y_pred)\n",
293
+ " # Validate\n",
294
+ " y_pred = np.dot(X_test.values, theta)\n",
295
+ "\n",
296
+ " # Calculate evaluation metrics\n",
297
+ " mse = sklearn_mse(y_test, y_pred)\n",
298
+ "\n",
299
+ " # Store results\n",
300
+ " lr_losses.append(losses)\n",
301
+ "\n",
302
+ "# Calculate average loss across folds\n",
303
+ "avg_loss = np.mean(lr_losses, axis=0)\n",
304
+ "\n",
305
+ "plt.figure(figsize=(10, 6))\n",
306
+ "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
307
+ "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
308
+ "plt.xlabel('Iteration')\n",
309
+ "plt.ylabel('Binary Cross-Entropy Loss')\n",
310
+ "plt.legend()\n",
311
+ "plt.grid(True, alpha=0.3)\n",
312
+ "plt.show()\n"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "metadata": {},
320
+ "source": [
321
+ "# Task 1: Write your code here:\n",
322
+ "# Feature importance\n",
323
+ "feature_importance = pd.DataFrame({\n",
324
+ " 'feature': X,\n",
325
+ " 'importance': model.feature_importances_\n",
326
+ "}).sort_values('importance', ascending=False)\n",
327
+ "\n",
328
+ "plt.figure(figsize=(10, 6))\n",
329
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
330
+ "plt.xlabel('Importance')\n",
331
+ "plt.title('Feature Importance')\n",
332
+ "plt.gca().invert_yaxis()\n",
333
+ "plt.show()"
334
+ ],
335
+ "execution_count": null,
336
+ "outputs": []
337
+ },
338
+ {
339
+ "cell_type": "code",
340
+ "metadata": {},
341
+ "source": [
342
+ "# Task 2: Write your code here:\n",
343
+ "data.Delivery_Time.hist()"
344
+ ],
345
+ "execution_count": null,
346
+ "outputs": []
347
+ },
348
+ {
349
+ "cell_type": "code",
350
+ "metadata": {},
351
+ "source": [
352
+ "# Task Bonus: Write your code here:"
353
+ ],
354
+ "execution_count": null,
355
+ "outputs": []
356
+ }
357
+ ],
358
+ "metadata": {
359
+ "kernelspec": {
360
+ "display_name": "Python 3",
361
+ "name": "python3"
362
+ },
363
+ "language_info": {
364
+ "name": "python"
365
+ }
366
+ },
367
+ "nbformat": 4,
368
+ "nbformat_minor": 0
369
+ }
submissions_extracted/822/Q2.ipynb ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.datasets import load_breast_cancer\n",
69
+ "from sklearn.model_selection import train_test_split\n",
70
+ "from sklearn.preprocessing import StandardScaler\n",
71
+ "from torch.utils.data import TensorDataset\n",
72
+ "from torch.utils.data import DataLoader\n",
73
+ "import torch"
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.long)\n",
87
+ "y_test = torch.tensor(y_test, dtype=torch.long)\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
+ "# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
99
+ "# Each item in the dataset is returned as (X[i], y[i])\n",
100
+ "train_dataset = TensorDataset(X_train, y_train)\n",
101
+ "test_dataset = TensorDataset(X_test, y_test)\n"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# 3. Create DataLoaders\n",
111
+ "\n",
112
+ "# Create Dataloaders to train and test data in batches\n",
113
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
114
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# 4. Print shape of one batch\n",
124
+ "# 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}\")\n"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# 5. Display sample images\n",
137
+ "import matplotlib.pyplot as plt\n",
138
+ "# Get one batch of images and labels\n",
139
+ "images, labels = next(iter(train_loader))\n",
140
+ "\n",
141
+ "# Display the first 6 images in the batch\n",
142
+ "plt.figure(figsize=(8, 4))\n",
143
+ "\n",
144
+ "for i in range(6):\n",
145
+ " plt.subplot(2, 3, i + 1)\n",
146
+ "\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
+ "from torchvision.datasets import CIFAR10\n",
165
+ "from torchvision.transforms.functional import to_tensor\n",
166
+ "from torch.utils.data import DataLoader\n",
167
+ "import matplotlib.pyplot as plt\n",
168
+ "import torch.nn as nn\n",
169
+ "import torch.nn.functional as F\n",
170
+ "import torch\n",
171
+ "from torch.optim import AdamW"
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):\n",
184
+ " super(NN4Layer, self).__init__()\n",
185
+ "\n",
186
+ " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
187
+ " self.layer1 = nn.Linear(input_dim, hidden_dim) # <YOUR CODE HERE> input_dim -> 3*32*32\n",
188
+ "\n",
189
+ " # TODO: What are the dimensions from previous and next layer?\n",
190
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim) # <YOUR CODE HERE> hidden_dim -> 14\n",
191
+ "\n",
192
+ " # TODO: What are the dimensions from previous and next layer?\n",
193
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim) # <YOUR CODE HERE>\n",
194
+ "\n",
195
+ " # TODO: What are the dimensions from previous and next layer?\n",
196
+ " self.layer4 = nn.Linear(hidden_dim, 1) # <YOUR CODE HERE>\n",
197
+ "\n",
198
+ " # activation function for non-linearity\n",
199
+ " self.relu = nn.ReLU()\n",
200
+ "\n",
201
+ " # Defines how input data flows through the network\n",
202
+ " def forward(self, x):\n",
203
+ " # Layer 1: TODO\n",
204
+ " z1 = self.layer1(x)\n",
205
+ " a1 = self.relu(z1)\n",
206
+ "\n",
207
+ " # Layer 2 TODO\n",
208
+ " z2 = self.layer2(a1)\n",
209
+ " a2 = self.relu(z2)\n",
210
+ "\n",
211
+ " # Layer 3 TODO\n",
212
+ " z3 = self.layer3(a2)\n",
213
+ " a3 = self.relu(z3)\n",
214
+ "\n",
215
+ " # Output layer TODO\n",
216
+ " z4 = self.layer4(a3)\n",
217
+ "\n",
218
+ " # TODO: are we missing output activation function? (hint: Loss Function)\n",
219
+ "\n",
220
+ " return z4"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "metadata": {},
228
+ "source": [
229
+ "# Task 2: Write your training loop here:\n",
230
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
231
+ " # Set the model to training mode\n",
232
+ " model.train()\n",
233
+ "\n",
234
+ " running_loss = 0.0\n",
235
+ "\n",
236
+ " for X_batch, y_batch in train_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.to(device)\n",
240
+ "\n",
241
+ " # Forward pass\n",
242
+ " # TODO: make predictions\n",
243
+ " outputs = model(X_batch) # <YOUR CODE HERE>\n",
244
+ " # TODO: compute loss\n",
245
+ " loss = criterion(outputs, y_batch) # <YOUR CODE HERE>\n",
246
+ "\n",
247
+ " # Backward pass & optimization\n",
248
+ " optimizer.zero_grad() # Clear previous gradients\n",
249
+ " loss.backward() # Compute gradients\n",
250
+ " optimizer.step() # Update model parameters\n",
251
+ "\n",
252
+ " running_loss += loss.item()\n",
253
+ "\n",
254
+ " # Average loss over all batches\n",
255
+ " avg_loss = running_loss / len(train_loader)\n",
256
+ "\n",
257
+ " return avg_loss"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task 3: Write your validation loop here:\n",
267
+ "def validate(model, criterion, test_loader, device):\n",
268
+ " # Set the model to evaluation mode\n",
269
+ " model.eval()\n",
270
+ "\n",
271
+ " running_loss = 0.0\n",
272
+ " correct = 0\n",
273
+ " total = 0\n",
274
+ "\n",
275
+ " with torch.no_grad():\n",
276
+ " for X_batch, y_batch in test_loader:\n",
277
+ " # Move data to device\n",
278
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
279
+ " y_batch = y_batch.to(device)\n",
280
+ "\n",
281
+ " # Forward pass\n",
282
+ " # TODO: make predictions\n",
283
+ " outputs = model(X_batch) # <YOUR CODE HERE>\n",
284
+ " # TODO: compute loss\n",
285
+ " loss = criterion(outputs, y_batch) # <YOUR CODE HERE>\n",
286
+ " running_loss += loss.item()\n",
287
+ "\n",
288
+ " # TODO: Apply Softmax to get probabilities\n",
289
+ " probabilities = F.softmax(outputs, dim=1)\n",
290
+ "\n",
291
+ " # TODO: Multiclass predictions\n",
292
+ " predicted = torch.argmax(probabilities, dim=1)\n",
293
+ "\n",
294
+ " # Accuracy calculation\n",
295
+ " correct += (predicted == y_batch).sum().item()\n",
296
+ " total += y_batch.size(0)\n",
297
+ "\n",
298
+ " avg_loss = running_loss / len(test_loader)\n",
299
+ " # TODO: how do we calculate accuracy?\n",
300
+ " accuracy = correct / total # <YOUR CODE HERE>\n",
301
+ "\n",
302
+ " return avg_loss, accuracy\n"
303
+ ],
304
+ "execution_count": null,
305
+ "outputs": []
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "metadata": {},
310
+ "source": [
311
+ "torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n"
312
+ ],
313
+ "execution_count": null,
314
+ "outputs": []
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "metadata": {},
319
+ "source": [
320
+ "# Task 4: Define device, model, loss, optimizer:\n",
321
+ "# Device setup\n",
322
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
323
+ "\n",
324
+ "# Model parameters\n",
325
+ "input_dim = 3*36*36\n",
326
+ "hidden_dim = 14 # Design choice\n",
327
+ "# output_dim = 1\n",
328
+ "\n",
329
+ "# Instantiate model\n",
330
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
331
+ "\n",
332
+ "# Print the model architecture\n",
333
+ "print(\"Model Architecture:\\n\")\n",
334
+ "print(model)\n",
335
+ "\n",
336
+ "# Calculate the total number of trainable parameters\n",
337
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
338
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
339
+ "\n",
340
+ "num_epochs = 20\n",
341
+ "learning_rate = 0.001\n",
342
+ "\n",
343
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
344
+ "criterion = nn.CrossEntropyLoss()\n",
345
+ "# Define optimizer\n",
346
+ "optimizer = AdamW(model.parameters(), learning_rate)"
347
+ ],
348
+ "execution_count": null,
349
+ "outputs": []
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "metadata": {},
354
+ "source": [
355
+ "# Task 5: Start training for 20 epochs:\n",
356
+ "# Run Training\n",
357
+ "train_losses = []\n",
358
+ "val_losses = []\n",
359
+ "val_accuracies = []\n",
360
+ "\n",
361
+ "print('Starting Training...')\n",
362
+ "for epoch in range(num_epochs):\n",
363
+ " # Train one epoch\n",
364
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
365
+ "\n",
366
+ " # Validate\n",
367
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
368
+ "\n",
369
+ " train_losses.append(train_loss)\n",
370
+ " val_losses.append(val_loss)\n",
371
+ " val_accuracies.append(val_accuracy)\n",
372
+ "\n",
373
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
374
+ "\n",
375
+ "print('Training Complete!')"
376
+ ],
377
+ "execution_count": null,
378
+ "outputs": []
379
+ },
380
+ {
381
+ "cell_type": "code",
382
+ "metadata": {},
383
+ "source": [
384
+ "# Task 1: Write your code here:\n",
385
+ "plt.figure(figsize=(7, 5))\n",
386
+ "\n",
387
+ "plt.plot(train_losses, label='Train Loss')\n",
388
+ "plt.plot(val_losses, label='Validation Loss')\n",
389
+ "plt.title('Loss over Epochs')\n",
390
+ "plt.xlabel('Epoch')\n",
391
+ "plt.ylabel('Loss')\n",
392
+ "plt.legend()\n",
393
+ "\n",
394
+ "plt.tight_layout()\n",
395
+ "plt.show()"
396
+ ],
397
+ "execution_count": null,
398
+ "outputs": []
399
+ },
400
+ {
401
+ "cell_type": "code",
402
+ "metadata": {},
403
+ "source": [
404
+ "# Task 2 (Bonus): Write your code here:\n"
405
+ ],
406
+ "execution_count": null,
407
+ "outputs": []
408
+ }
409
+ ],
410
+ "metadata": {
411
+ "kernelspec": {
412
+ "display_name": "Python 3",
413
+ "name": "python3"
414
+ },
415
+ "language_info": {
416
+ "name": "python"
417
+ }
418
+ },
419
+ "nbformat": 4,
420
+ "nbformat_minor": 0
421
+ }
submissions_extracted/822/Q3.ipynb ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import numpy as np\n",
27
+ "import pandas as pd\n",
28
+ "import matplotlib.pyplot as plt\n",
29
+ "import os\n",
30
+ "import kagglehub\n",
31
+ "\n",
32
+ "from sklearn.model_selection import train_test_split, KFold\n",
33
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
34
+ "from sklearn.ensemble import RandomForestRegressor\n",
35
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
36
+ "\n",
37
+ "import warnings\n",
38
+ "warnings.filterwarnings('ignore')"
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
+ "data_path = os.path.join(path, 'Q3_data.csv')\n",
49
+ "df_data = pd.read_csv(data_path)"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 2: Write your code here:\n",
59
+ "print(f\"Dataset shape: {df_data.shape}\")\n",
60
+ "df_data.head()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 3: Write your code here:\n",
70
+ "df_data.info()"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# Task 4: Write your code here:\n",
80
+ "df_data.describe()"
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
+ "missing_values = df_data.isnull().sum()\n",
91
+ "print(\"Columns with missing values:\")\n",
92
+ "print(missing_values[missing_values > 0])\n",
93
+ "\n",
94
+ "df_data.fillna(df_data.mean())\n",
95
+ "\n"
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
+ "# Task 3: Write your code here:\n",
106
+ "# 4. Do we have duplicate samples?\n",
107
+ "def check_duplicates(df):\n",
108
+ " duplicates = df.duplicated().sum()\n",
109
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
110
+ " if duplicates > 0:\n",
111
+ " print(\"Dropping Duplicates...\")\n",
112
+ " df.drop_duplicates(inplace=True)\n",
113
+ " print(\"Duplicates Dropped.\")\n",
114
+ " else:\n",
115
+ " print(\"No Duplicate Samples Found.\")\n",
116
+ "\n",
117
+ "check_duplicates(df_data)\n",
118
+ "df_data"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# Task 3: Write your code here:\n"
128
+ ],
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
+ "features = df_data.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
140
+ "\n",
141
+ "scaler = StandardScaler()\n",
142
+ "df_data[features] = scaler.fit_transform(df_data[features])\n",
143
+ "df_data.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
+ "df_data['Target'].hist()\n",
154
+ "\n",
155
+ "#it's imblanaced"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 1: Write your code here:"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 2,3,4,5: Write your code here:"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task 1: Write your code here:"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "# Task 2: Write your code here:"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task Bonus: Write your code here:"
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ }
205
+ ],
206
+ "metadata": {
207
+ "kernelspec": {
208
+ "display_name": "Python 3",
209
+ "name": "python3"
210
+ },
211
+ "language_info": {
212
+ "name": "python"
213
+ }
214
+ },
215
+ "nbformat": 4,
216
+ "nbformat_minor": 0
217
+ }
submissions_extracted/823/Q1.ipynb ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import pandas as pd\n",
23
+ "import os\n",
24
+ "data_path = os.path.join(path, \"Q1_data.csv\")\n",
25
+ "df = pd.read_csv(data_path)\n",
26
+ "\n",
27
+ "\n"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 2: Write your code here:\n",
37
+ "df.head()"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 3: Write your code here:\n",
47
+ "df.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 4: Write your code here:\n",
57
+ "df.describe()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 5: Write your code here:\n",
67
+ "import matplotlib.pyplot as plt\n",
68
+ "\n",
69
+ "plt.figure(figsize=(10, 5))\n",
70
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
71
+ "plt.title('delivery time Distribution')\n",
72
+ "plt.xlabel('delivery time')\n",
73
+ "plt.ylabel('Frequency')\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
+ "df_clean = df.copy()\n",
85
+ "\n",
86
+ "df_clean = df_clean.drop(columns=['Order_ID'])\n"
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
+ "\n",
97
+ "\n",
98
+ "\n",
99
+ "df_clean = df_clean.dropna(subset=['Distance_km', 'Traffic_Level', 'Delivery_Time', 'Weather','Time_of_Day'])\n",
100
+ "df_clean['Courier_Experience_yrs'] = df_clean['Courier_Experience_yrs'].fillna(df_clean['Courier_Experience_yrs'].mode()[0])\n",
101
+ "\n",
102
+ "df_clean.isnull().sum()\n",
103
+ "\n"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "df_clean.info()"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 3: Write your code here:\n",
122
+ "\n",
123
+ "def check_duplicates(df):\n",
124
+ " duplicates = df.duplicated().sum()\n",
125
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
126
+ " if duplicates > 0:\n",
127
+ " print(\"Dropping Duplicates...\")\n",
128
+ " df.drop_duplicates(inplace=True)\n",
129
+ " print(\"Duplicates Dropped.\")\n",
130
+ " else:\n",
131
+ " print(\"No Duplicate Samples Found.\")\n",
132
+ "\n",
133
+ "check_duplicates(df_clean)\n",
134
+ "\n",
135
+ "df_clean.drop_duplicates(inplace=True) #we drop the duplicated"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Task 4: Write your code here:\n",
145
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
146
+ "\n",
147
+ "categorical_cols = ['Traffic_Level', 'Weather', 'Time_of_Day', 'Vehicle_Type']\n",
148
+ "for col in categorical_cols:\n",
149
+ " le = LabelEncoder()\n",
150
+ " df_clean[col] = le.fit_transform(df_clean[col])"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "df_clean.info()"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 5: Write your code here:\n",
176
+ "\n",
177
+ "all_col = df_clean.drop('Delivery_Time', axis = 1)\n",
178
+ "scaler = StandardScaler()\n",
179
+ "x= scaler.fit_transform(all_col)\n",
180
+ "\n",
181
+ "df_clean.head()\n"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 6: Write your code here:\n"
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
+ "\n",
201
+ "X = df_clean.drop('Delivery_Time', axis = 1)\n",
202
+ "Y = df_clean['Delivery_Time']"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 2,3,4,5: Write your code here:\n",
212
+ "import numpy as np\n",
213
+ "from sklearn.ensemble import RandomForestRegressor\n",
214
+ "from sklearn.model_selection import KFold, StratifiedKFold\n",
215
+ "\n",
216
+ "from sklearn.metrics import mean_squared_error\n",
217
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
218
+ "model = model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
219
+ "\n",
220
+ "mse_scores = []\n",
221
+ "\n",
222
+ "for train_idx, val_idx in kfold.split(X):\n",
223
+ " X_fold_train, X_fold_val = X.iloc[train_idx], X.iloc[val_idx]\n",
224
+ " y_fold_train, y_fold_val = Y.iloc[train_idx], Y.iloc[val_idx]\n",
225
+ "\n",
226
+ " # Train and predict\n",
227
+ " model.fit(X_fold_train, y_fold_train)\n",
228
+ " y_fold_pred = model.predict(X_fold_val)\n",
229
+ "\n",
230
+ " # Calculate metrics\n",
231
+ " mse_scores.append(mean_squared_error(y_fold_val, y_fold_pred))\n",
232
+ "\n",
233
+ "\n",
234
+ "\n",
235
+ "print(f\"5-Fold CV Results:\")\n",
236
+ "\n",
237
+ "print(np.mean(mse_scores))\n",
238
+ "\n",
239
+ ""
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
+ "feature_importance = pd.DataFrame({\n",
250
+ " 'feature': all_col,\n",
251
+ " 'importance': model.feature_importances_\n",
252
+ "}).sort_values('importance', ascending=False)\n",
253
+ "\n",
254
+ "plt.figure(figsize=(10, 6))\n",
255
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
256
+ "plt.xlabel('Importance')\n",
257
+ "plt.title('Feature Importance')\n",
258
+ "plt.gca().invert_yaxis()\n",
259
+ "plt.show()"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task 2: Write your code here:\n"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task Bonus: Write your code here:\n",
278
+ "from catboost import CatBoostClassifier\n",
279
+ "from sklearn.ensemble import RandomForestRegressor\n",
280
+ "\n",
281
+ "\n",
282
+ "sklearn_models = {\n",
283
+ "\n",
284
+ " \"Random Forest\": RandomForestRegressor(\n",
285
+ " n_estimators=320, # Number of trees\n",
286
+ " max_depth=4\n",
287
+ " ),\n",
288
+ "\n",
289
+ " \"CatBoost\": CatBoostRe(\n",
290
+ " verbose=0,\n",
291
+ " n_estimators=320,\n",
292
+ " max_depth=4\n",
293
+ " )\n",
294
+ "}\n",
295
+ "\n",
296
+ "\n",
297
+ "results = {}\n",
298
+ "\n",
299
+ "for model_name in models:\n",
300
+ " results[model_name] = {'mse': []}\n",
301
+ "\n",
302
+ "\n",
303
+ " or 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
+ " # Get the train & test split for this fold\n",
307
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
308
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
309
+ "\n",
310
+ " # Train & Validate Models\n",
311
+ " for model_name, model in models.items():\n",
312
+ "\n",
313
+ " print(f\"Training {model_name}...\")\n",
314
+ "\n",
315
+ " # Fit the model on train data\n",
316
+ " model.fit(X_train, y_train)\n",
317
+ "\n",
318
+ " # Use the model to predict the test data\n",
319
+ " y_pred = model.predict(X_test)\n",
320
+ "\n",
321
+ " # Calculate evaluation metrics\n",
322
+ " mse = mean_squared_error(y_test, y_pred)\n",
323
+ "\n",
324
+ "\n",
325
+ " results[model_name]['mse'].append(mse)\n",
326
+ ""
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ }
331
+ ],
332
+ "metadata": {
333
+ "kernelspec": {
334
+ "display_name": "Python 3",
335
+ "name": "python3"
336
+ },
337
+ "language_info": {
338
+ "name": "python"
339
+ }
340
+ },
341
+ "nbformat": 4,
342
+ "nbformat_minor": 0
343
+ }
submissions_extracted/823/Q2.ipynb ADDED
@@ -0,0 +1,407 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 kagglehub\n",
69
+ "import pandas as pd\n",
70
+ "import torch\n",
71
+ "import torch.nn as nn\n",
72
+ "from torch.optim import AdamW\n",
73
+ "import matplotlib.pyplot as plt\n",
74
+ "import torch.nn.functional as F\n",
75
+ "from torch.utils.data import DataLoader, TensorDataset\n",
76
+ "from sklearn.model_selection import train_test_split\n",
77
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder"
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
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
88
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
89
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
90
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
91
+ "\n"
92
+ ],
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
+ "\n",
105
+ "\n"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# 3. Create DataLoaders\n",
115
+ "\n",
116
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
117
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
118
+ "\n",
119
+ "# Print dataset sizes\n",
120
+ "print(\"Train dataset:\", len(train_dataset))\n",
121
+ "print(\"Test dataset:\", len(test_dataset))\n",
122
+ "\n"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# 4. Print shape of one batch\n",
132
+ "X_batch, y_batch = next(iter(train_loader))\n",
133
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
134
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
135
+ "\n",
136
+ "\n"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# 5. Display sample images\n",
146
+ "\n",
147
+ "model.eval()\n",
148
+ "# Get one batch from the test DataLoader\n",
149
+ "images, labels = next(iter(test_loader))\n",
150
+ "# Move images to device\n",
151
+ "images = images.to(device)\n",
152
+ "labels = labels.to(device)\n",
153
+ "\n",
154
+ "with torch.no_grad():\n",
155
+ " # Flatten images before passing to the model\n",
156
+ " outputs = model(images.view(images.size(0), -1))\n",
157
+ " predictions = torch.argmax(outputs, dim=1)\n",
158
+ "\n",
159
+ "# Move tensors back to CPU for plotting\n",
160
+ "images = images.cpu()\n",
161
+ "labels = labels.cpu()\n",
162
+ "predictions = predictions.cpu()\n",
163
+ "\n",
164
+ "# Plot first 6 predictions\n",
165
+ "plt.figure(figsize=(8, 4))\n",
166
+ "for i in range(6):\n",
167
+ " plt.subplot(2, 3, i + 1)\n",
168
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
169
+ " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
170
+ " plt.axis('off')\n",
171
+ "\n",
172
+ "plt.tight_layout()\n",
173
+ "plt.show()"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task 1: Write your model class here:\n",
183
+ "\n",
184
+ "class NN4Layer(nn.Module):\n",
185
+ "\n",
186
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
187
+ " super(NN4Layer, self).__init__()\n",
188
+ "\n",
189
+ " # First linear layer: input features -> hidden layer\n",
190
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
191
+ "\n",
192
+ " # Second linear layer: hidden layer -> hidden layer\n",
193
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
194
+ "\n",
195
+ " # Third linear layer: hidden layer -> hidden layer\n",
196
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
197
+ "\n",
198
+ " # Output layer: hidden layer -> number of classes (logits)\n",
199
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
200
+ "\n",
201
+ " # ReLU activation for non-linearity\n",
202
+ " self.relu = nn.ReLU()\n",
203
+ "\n",
204
+ " # Defines how input data flows through the network\n",
205
+ " def forward(self, x):\n",
206
+ " # First hidden layer\n",
207
+ " a1 = self.relu(self.layer1(x))\n",
208
+ "\n",
209
+ " # Second hidden layer\n",
210
+ " a2 = self.relu(self.layer2(a1))\n",
211
+ "\n",
212
+ " # Third hidden layer\n",
213
+ " a3 = self.relu(self.layer3(a2))\n",
214
+ "\n",
215
+ " # Output layer (raw scores / logits)\n",
216
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
217
+ "\n",
218
+ " return output\n"
219
+ ],
220
+ "execution_count": null,
221
+ "outputs": []
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "metadata": {},
226
+ "source": [
227
+ "# Task 2: Write your training loop here:\n",
228
+ "\n",
229
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
230
+ " # Set the model to training mode\n",
231
+ " model.train()\n",
232
+ "\n",
233
+ " running_loss = 0.0\n",
234
+ "\n",
235
+ " for X_batch, y_batch in train_loader:\n",
236
+ " # Move batch to the selected device\n",
237
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
238
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
239
+ "\n",
240
+ " # Forward pass (continuous output)\n",
241
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
242
+ " loss = criterion(outputs, y_batch)\n",
243
+ "\n",
244
+ " # Backward pass & optimization\n",
245
+ " optimizer.zero_grad() # Clear previous gradients\n",
246
+ " loss.backward() # Compute gradients\n",
247
+ " optimizer.step() # Update model parameters\n",
248
+ "\n",
249
+ " running_loss += loss.item()\n",
250
+ "\n",
251
+ " # Average loss over all batches\n",
252
+ " avg_loss = running_loss / len(train_loader)\n",
253
+ "\n",
254
+ " return avg_loss"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# Task 3: Write your validation loop here:\n",
264
+ "def validate(model, criterion, test_loader, device):\n",
265
+ " # Set the model to evaluation mode\n",
266
+ " model.eval()\n",
267
+ "\n",
268
+ " running_loss = 0.0\n",
269
+ "\n",
270
+ " with torch.no_grad():\n",
271
+ " for X_batch, y_batch in test_loader:\n",
272
+ " # Move data to device\n",
273
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
274
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
275
+ "\n",
276
+ " # Forward pass (continuous output)\n",
277
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
278
+ " loss = criterion(outputs, y_batch)\n",
279
+ "\n",
280
+ " running_loss += loss.item()\n",
281
+ "\n",
282
+ " # Average loss over all batches\n",
283
+ " avg_loss = running_loss / len(test_loader)\n",
284
+ "\n",
285
+ " return avg_loss\n",
286
+ "\n",
287
+ "\n",
288
+ "\n",
289
+ "\n",
290
+ "\n",
291
+ "\n",
292
+ "\n"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "metadata": {},
300
+ "source": [
301
+ "# Task 4: Define device, model, loss, optimizer:\n",
302
+ "\n",
303
+ "# Device setup\n",
304
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
305
+ "\n",
306
+ "# Model parameters\n",
307
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
308
+ "hidden_dim = 64 # Design choice\n",
309
+ "output_dim = 1 #\n",
310
+ "\n",
311
+ "# Instantiate model\n",
312
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
313
+ "\n",
314
+ "# Print the model architecture\n",
315
+ "print(\"Model Architecture:\\n\")\n",
316
+ "print(model)\n",
317
+ "\n",
318
+ "# Calculate the total number of trainable parameters\n",
319
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
320
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
321
+ ],
322
+ "execution_count": null,
323
+ "outputs": []
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "metadata": {},
328
+ "source": [
329
+ "# Task 5: Start training for 20 epochs:\n",
330
+ "num_epochs = 20\n",
331
+ "learning_rate = 0.001\n",
332
+ "criterion = nn.MSELoss()\n",
333
+ "# Define optimizer\n",
334
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
335
+ "\n",
336
+ "\n",
337
+ "train_losses = []\n",
338
+ "val_losses = []\n",
339
+ "\n",
340
+ "print('Starting Training...')\n",
341
+ "for epoch in range(num_epochs):\n",
342
+ " # Train one epoch\n",
343
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
344
+ "\n",
345
+ " # Validate\n",
346
+ " val_loss = validate(model, criterion, test_loader, device)\n",
347
+ "\n",
348
+ " train_losses.append(train_loss)\n",
349
+ " val_losses.append(val_loss)\n",
350
+ "\n",
351
+ " if (epoch + 1) % 5 == 0:\n",
352
+ " print(\n",
353
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
354
+ " f'Train Loss: {train_loss:.4f}, '\n",
355
+ " f'Val Loss: {val_loss:.4f}'\n",
356
+ " )\n",
357
+ "\n",
358
+ "print('Training Complete!')"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [
367
+ "# Task 1: Write your code here:\n",
368
+ "\n",
369
+ "# Plotting results\n",
370
+ "plt.figure(figsize=(7, 5))\n",
371
+ "\n",
372
+ "plt.plot(train_losses, label='Train Loss')\n",
373
+ "plt.plot(val_losses, label='Validation Loss')\n",
374
+ "plt.title('Loss over Epochs')\n",
375
+ "plt.xlabel('Epoch')\n",
376
+ "plt.ylabel('Loss (MSE)')\n",
377
+ "plt.legend()\n",
378
+ "\n",
379
+ "plt.tight_layout()\n",
380
+ "plt.show()"
381
+ ],
382
+ "execution_count": null,
383
+ "outputs": []
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "metadata": {},
388
+ "source": [
389
+ "# Task 2 (Bonus): Write your code here:\n",
390
+ "\n"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ }
395
+ ],
396
+ "metadata": {
397
+ "kernelspec": {
398
+ "display_name": "Python 3",
399
+ "name": "python3"
400
+ },
401
+ "language_info": {
402
+ "name": "python"
403
+ }
404
+ },
405
+ "nbformat": 4,
406
+ "nbformat_minor": 0
407
+ }
submissions_extracted/823/Q3.ipynb ADDED
@@ -0,0 +1,285 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
28
+ "import pandas as pd\n",
29
+ "import os\n",
30
+ "data_path = os.path.join(path, \"Q3_data.csv\")\n",
31
+ "df = pd.read_csv(data_path)\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "df.head()"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 3: Write your code here:\n",
51
+ "df.info()"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 4: Write your code here:\n",
61
+ "df.describe()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 1: Write your code here:\n",
71
+ "\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
+ " else:\n",
79
+ " print(\"\\nNo Missing Values Found.\")\n",
80
+ "\n",
81
+ "check_missing_values(df)\n",
82
+ "\n",
83
+ "df.drop('')\n",
84
+ "df.drop(subset = )"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Task 2: Write your code here:\n",
94
+ "def check_duplicates(df):\n",
95
+ " duplicates = df.duplicated().sum()\n",
96
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
97
+ " if duplicates > 0:\n",
98
+ " print(\"Dropping Duplicates...\")\n",
99
+ " df.drop_duplicates(inplace=True)\n",
100
+ " print(\"Duplicates Dropped.\")\n",
101
+ " else:\n",
102
+ " print(\"No Duplicate Samples Found.\")\n",
103
+ "\n",
104
+ "check_duplicates(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
+ "from sklearn.preprocessing import LabelEncoder\n",
115
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
116
+ "\n",
117
+ "for col in categorical_cols:\n",
118
+ " print(f\"Encoding column: {col}\")\n",
119
+ " le = LabelEncoder()\n",
120
+ " # TODO: Apply fit_transform to encode the column\n",
121
+ " df[col] = le.fit_transform(df[col])\n",
122
+ "\n",
123
+ "df.head()"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 4: Write your code here:\n",
133
+ "from sklearn.preprocessing import StandardScaler\n",
134
+ "\n",
135
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop('Target') # DON'T SCALE THE TARGET\n",
136
+ "\n",
137
+ "scaler = StandardScaler()\n",
138
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
139
+ "df.head()\n"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 5: Write your code here:\n",
149
+ "import matplotlib.pyplot as plt\n",
150
+ "import seaborn as sns\n",
151
+ "def check_target_imbalance(df, target_column):\n",
152
+ " print(\"Target Distribution:\")\n",
153
+ " print(df[target_column].value_counts(normalize=True))\n",
154
+ " sns.countplot(x=df[target_column])\n",
155
+ " plt.title(\"Target Distribution\")\n",
156
+ " plt.show()\n",
157
+ "\n",
158
+ "check_target_imbalance(df, \"Target\")"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 1: Write your code here:\n",
168
+ "X = df.drop('Target', axis = 1)\n",
169
+ "Y = df['Target']"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "pip install catboost"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 2,3,4,5: Write your code here:\n",
188
+ "\n",
189
+ "import numpy as np\n",
190
+ "from catboost import CatBoostClassifier\n",
191
+ "from sklearn.model_selection import KFold\n",
192
+ "from sklearn.metrics import accuracy_score, f1_score\n",
193
+ "\n",
194
+ "\n",
195
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
196
+ "model = CatBoostClassifier(verbose=0,\n",
197
+ " n_estimators=320,\n",
198
+ " max_depth=4)\n",
199
+ "\n",
200
+ "all_results = []\n",
201
+ "\n",
202
+ "for train_idx, val_idx in kfold.split(X):\n",
203
+ " X_fold_train, X_fold_val = X.iloc[train_idx], X.iloc[val_idx]\n",
204
+ " y_fold_train, y_fold_val = Y.iloc[train_idx], Y.iloc[val_idx]\n",
205
+ "\n",
206
+ " # Train and predict\n",
207
+ " model.fit(X_fold_train, y_fold_train)\n",
208
+ " y_fold_pred = model.predict(X_fold_val)\n",
209
+ "\n",
210
+ " # Calculate metrics\n",
211
+ " accuracy = accuracy_score(y_fold_val, y_fold_pred)\n",
212
+ " f1 = f1_score(y_fold_val, y_fold_pred, zero_division=0)\n",
213
+ "\n",
214
+ " all_results[model]['accuracy'].append(accuracy)\n",
215
+ " all_results[model]['f1'].append(f1)\n",
216
+ "\n",
217
+ "\n",
218
+ "\n",
219
+ "\n",
220
+ "\n",
221
+ "\n",
222
+ "\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:\n",
232
+ "\n",
233
+ "\n",
234
+ "\n",
235
+ "# Create a 1x3 plot\n",
236
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
237
+ "axes = axes.flatten()\n",
238
+ "features = X.columns\n",
239
+ "\n",
240
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
241
+ " # Sort features by importance for a cleaner plot\n",
242
+ " sorted_idx = np.argsort(imp)\n",
243
+ "\n",
244
+ " ax = axes[i]\n",
245
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
246
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
247
+ " ax.set_xlabel(\"Importance Score\")\n",
248
+ "\n",
249
+ "plt.tight_layout()\n",
250
+ "plt.show()"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "metadata": {},
258
+ "source": [
259
+ "# Task 2: Write your code here:"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task Bonus: Write your code here:"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ }
273
+ ],
274
+ "metadata": {
275
+ "kernelspec": {
276
+ "display_name": "Python 3",
277
+ "name": "python3"
278
+ },
279
+ "language_info": {
280
+ "name": "python"
281
+ }
282
+ },
283
+ "nbformat": 4,
284
+ "nbformat_minor": 0
285
+ }
submissions_extracted/824/Q1.ipynb ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import pandas as pd\n",
22
+ "import numpy as np\n",
23
+ "import matplotlib.pyplot as plt\n",
24
+ "import seaborn as sns\n",
25
+ "import kagglehub\n",
26
+ "import os\n",
27
+ "from tqdm import tqdm\n",
28
+ "\n",
29
+ "%matplotlib inline"
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
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
40
+ "\n",
41
+ "df = pd.read_csv(csv_path)\n",
42
+ "\n",
43
+ "\n",
44
+ "# print(\"data shape:\", df.shape)"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# Task 2: Write your code here\n",
54
+ "df.head()\n"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "# Task 3: Write your code here:\n",
64
+ "df.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 4: Write your code here:\n",
74
+ "df.describe()"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 5: Write your code here:\n",
84
+ "plt.figure(figsize=(10, 5))\n",
85
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
86
+ "plt.title('delivery_time Distribution')\n",
87
+ "plt.xlabel('delivery_time')\n",
88
+ "plt.ylabel('count')\n",
89
+ "plt.show()"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 1: Write your code here:\n",
99
+ "df = df.drop('Order_ID', axis= 1)\n",
100
+ "df.head()"
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
+ "# 2. Do we have missing values?\n",
111
+ "def check_missing_values(df):\n",
112
+ " missing_values = df.isnull().sum()\n",
113
+ " print(\"Missing Values per Column:\")\n",
114
+ " print(missing_values[missing_values > 0])\n",
115
+ " if missing_values.any():\n",
116
+ " print(\"\\nHandle Missing Values as needed.\")\n",
117
+ " else:\n",
118
+ " print(\"\\nNo Missing Values Found.\")\n",
119
+ "\n",
120
+ "check_missing_values(df)\n",
121
+ "\n",
122
+ "print(\"=\" * 40)\n",
123
+ "\n",
124
+ "df_clean = df.dropna().copy() # YOUR CODE HERE\n",
125
+ "print(f\"Shape after cleaning: {df_clean.shape}\")\n",
126
+ "\n",
127
+ "\n",
128
+ "check_missing_values(df_clean)\n",
129
+ "\n",
130
+ "\n",
131
+ "df_clean.info()"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 3: Write your code here:\n",
141
+ "\n",
142
+ "def check_duplicates(df):\n",
143
+ " duplicates = df.duplicated().sum()\n",
144
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
145
+ " if duplicates > 0:\n",
146
+ " print(\"Dropping Duplicates...\")\n",
147
+ " df.drop_duplicates(inplace=True)\n",
148
+ " print(\"Duplicates Dropped.\")\n",
149
+ " else:\n",
150
+ " print(\"No Duplicate Samples Found.\")\n",
151
+ "\n",
152
+ "check_duplicates(df_clean)"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "df_clean.info()"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 4: Write your code here:\n",
171
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
172
+ "\n",
173
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns # <Replace None with your code>\n",
174
+ "\n",
175
+ "for col in categorical_cols:\n",
176
+ " print(f\"Encoding column: {col}\")\n",
177
+ " le = LabelEncoder()\n",
178
+ " # TODO: Apply fit_transform to encode the column\n",
179
+ " df_clean[col] = le.fit_transform(df_clean[col]) # <Replace None with your code>"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "df= df_clean.copy()"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 5: Write your code here:\n",
198
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # <Replace None with your code>\n",
199
+ "\n",
200
+ "scaler = StandardScaler()\n",
201
+ "\n",
202
+ "# TODO: Apply fit_transform to scale the numerical columns\n",
203
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols]) # <Replace None with your code>\n",
204
+ "\n",
205
+ "df.head()"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "df.info()"
215
+ ],
216
+ "execution_count": null,
217
+ "outputs": []
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "# Task 6: Write your code here:\n",
224
+ "def check_target_imbalance(df, target_column):\n",
225
+ " print(\"Target Distribution:\")\n",
226
+ " print(df[target_column].value_counts(normalize=True))\n",
227
+ " sns.countplot(x=df[target_column])\n",
228
+ " plt.title(\"Target Distribution\")\n",
229
+ " plt.show()\n",
230
+ "\n",
231
+ "check_target_imbalance(df, \"Delivery_Time\")"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 1: Write your code here:\n",
241
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
242
+ "y = df['Delivery_Time'].astype(float)"
243
+ ],
244
+ "execution_count": null,
245
+ "outputs": []
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "metadata": {},
250
+ "source": [
251
+ "from sklearn.model_selection import KFold\n",
252
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 2,3,4,5: Write your code here:\n",
262
+ "\n",
263
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
264
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
265
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
266
+ " losses = []\n",
267
+ "\n",
268
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
269
+ " y_hat = np.dot(X, theta)\n",
270
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
271
+ " theta -= learning_rate * gradient\n",
272
+ "\n",
273
+ " loss = mean_absolute_error(y, y_hat)\n",
274
+ " losses.append(loss)\n",
275
+ "\n",
276
+ " return theta, losses\n",
277
+ "\n"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "n_splits = 5 # K=5 Folds\n",
287
+ "\n",
288
+ "# 5-Fold Cross-Validation, shuffled\n",
289
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Storage for linear regression results for each fold\n",
299
+ "lr_losses = []\n",
300
+ "lr_mae = []"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
310
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
311
+ "\n",
312
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
313
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
314
+ "\n",
315
+ "\n",
316
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
317
+ "\n",
318
+ " # Validate\n",
319
+ " y_pred = np.dot(X_test.values, theta)\n",
320
+ "\n",
321
+ " mae = mean_absolute_error(y_test, y_pred)\n",
322
+ "\n",
323
+ " lr_losses.append(losses)\n",
324
+ " lr_mae.append(mae)\n"
325
+ ],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "average_losses = np.mean(lr_losses, axis=0)\n",
334
+ "\n",
335
+ "plt.figure(figsize=(10, 6))\n",
336
+ "plt.plot(average_losses, label='Average Loss')\n",
337
+ "plt.xlabel('Iteration')\n",
338
+ "plt.ylabel('MAE Loss')\n",
339
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
340
+ "plt.legend()\n",
341
+ "plt.grid(True, alpha=0.3)\n",
342
+ "plt.show()"
343
+ ],
344
+ "execution_count": null,
345
+ "outputs": []
346
+ },
347
+ {
348
+ "cell_type": "code",
349
+ "metadata": {},
350
+ "source": [
351
+ "print(\"Linear Regression Results\")\n",
352
+ "print(f\" Average MAE: {np.mean(lr_mae):.4f}\")"
353
+ ],
354
+ "execution_count": null,
355
+ "outputs": []
356
+ },
357
+ {
358
+ "cell_type": "code",
359
+ "metadata": {},
360
+ "source": [
361
+ "# Storage for linear regression results for each fold\n",
362
+ "print('Fold 1= ', lr_mae[0])\n",
363
+ "print('Fold 2= ', lr_mae[1])\n",
364
+ "print('Fold 3= ', lr_mae[2])\n",
365
+ "print('Fold 4= ', lr_mae[3])\n",
366
+ "print('Fold 5= ', lr_mae[4])"
367
+ ],
368
+ "execution_count": null,
369
+ "outputs": []
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "metadata": {},
374
+ "source": [
375
+ "from sklearn.ensemble import RandomForestRegressor\n",
376
+ "models = {\n",
377
+ "\n",
378
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
379
+ "\n",
380
+ "}"
381
+ ],
382
+ "execution_count": null,
383
+ "outputs": []
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "metadata": {},
388
+ "source": [
389
+ "# Storage for results\n",
390
+ "all_results = {}\n",
391
+ "\n",
392
+ "for name in models:\n",
393
+ " all_results[name] = {'mae': []}"
394
+ ],
395
+ "execution_count": null,
396
+ "outputs": []
397
+ },
398
+ {
399
+ "cell_type": "code",
400
+ "metadata": {},
401
+ "source": [
402
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
403
+ "\n",
404
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
405
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
406
+ "\n",
407
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
408
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
409
+ "\n",
410
+ " for model_name, model in models.items():\n",
411
+ " print(f\"Training {model_name}...\")\n",
412
+ "\n",
413
+ " # Train\n",
414
+ " model.fit(X_train, y_train)\n",
415
+ "\n",
416
+ " # Predict\n",
417
+ " y_pred = model.predict(X_test)\n",
418
+ "\n",
419
+ " # Calculate metrics\n",
420
+ " mae = mean_absolute_error(y_test, y_pred)\n",
421
+ "\n",
422
+ "\n",
423
+ " # Store results\n",
424
+ " all_results[model_name][\"mae\"].append(mae)\n"
425
+ ],
426
+ "execution_count": null,
427
+ "outputs": []
428
+ },
429
+ {
430
+ "cell_type": "code",
431
+ "metadata": {},
432
+ "source": [
433
+ "for model_name in all_results:\n",
434
+ " print(f\"\\n{model_name}:\")\n",
435
+ " print(f\" MAE: {np.mean(all_results[model_name]['mae']):.4f}\")\n"
436
+ ],
437
+ "execution_count": null,
438
+ "outputs": []
439
+ },
440
+ {
441
+ "cell_type": "code",
442
+ "metadata": {},
443
+ "source": [],
444
+ "execution_count": null,
445
+ "outputs": []
446
+ },
447
+ {
448
+ "cell_type": "code",
449
+ "metadata": {},
450
+ "source": [
451
+ "# Gather importances from the models (from the last fold)\n",
452
+ "importances = {}\n",
453
+ "\n",
454
+ "importances['RF'] = models['Random Forest Regressor'].feature_importances_\n",
455
+ "\n",
456
+ "# Create a 1x3 plot\n",
457
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
458
+ "axes = axes.flatten()\n",
459
+ "features = X.columns\n",
460
+ "\n",
461
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
462
+ " # Sort features by importance for a cleaner plot\n",
463
+ " sorted_idx = np.argsort(imp)\n",
464
+ "\n",
465
+ " ax = axes[i]\n",
466
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
467
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
468
+ " ax.set_xlabel(\"Importance Score\")\n",
469
+ "\n",
470
+ "plt.tight_layout()\n",
471
+ "plt.show()"
472
+ ],
473
+ "execution_count": null,
474
+ "outputs": []
475
+ },
476
+ {
477
+ "cell_type": "code",
478
+ "metadata": {},
479
+ "source": [
480
+ "# Task 2: Write your code here:\n",
481
+ "\n",
482
+ "plt.figure(figsize=(6, 4))\n",
483
+ "plt.scatter(y_test, y_pred, alpha=0.7) # model\n",
484
+ "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2) # Actual data\n",
485
+ "plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
486
+ "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n",
487
+ "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n",
488
+ "plt.grid(True)\n",
489
+ "\n",
490
+ "plt.tight_layout()\n",
491
+ "plt.show()"
492
+ ],
493
+ "execution_count": null,
494
+ "outputs": []
495
+ },
496
+ {
497
+ "cell_type": "code",
498
+ "metadata": {},
499
+ "source": [
500
+ "# Task Bonus: Write your code here:"
501
+ ],
502
+ "execution_count": null,
503
+ "outputs": []
504
+ }
505
+ ],
506
+ "metadata": {
507
+ "kernelspec": {
508
+ "display_name": "Python 3",
509
+ "name": "python3"
510
+ },
511
+ "language_info": {
512
+ "name": "python"
513
+ }
514
+ },
515
+ "nbformat": 4,
516
+ "nbformat_minor": 0
517
+ }
submissions_extracted/824/Q2.ipynb ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# 2. Create TensorDataset objects\n",
78
+ "\n",
79
+ "\n"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# 3. Create DataLoaders\n",
89
+ "\n",
90
+ "\n"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# 4. Print shape of one batch\n",
100
+ "\n"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 5. Display sample images\n",
110
+ "\n"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "import torch\n",
120
+ "import numpy as np\n",
121
+ "\n",
122
+ "# --- Convert to tensors (safe if already tensors) ---\n",
123
+ "X_train = torch.as_tensor(X_train)\n",
124
+ "y_train = torch.as_tensor(y_train)\n",
125
+ "X_test = torch.as_tensor(X_test)\n",
126
+ "y_test = torch.as_tensor(y_test)\n",
127
+ "\n",
128
+ "# --- Fix common label shapes ---\n",
129
+ "# Case: labels are shape (N,1) -> make (N,)\n",
130
+ "if y_train.dim() > 1 and y_train.shape[-1] == 1:\n",
131
+ " y_train = y_train.squeeze(-1)\n",
132
+ "if y_test.dim() > 1 and y_test.shape[-1] == 1:\n",
133
+ " y_test = y_test.squeeze(-1)\n",
134
+ "\n",
135
+ "# Case: labels are one-hot (N, num_classes) -> convert to class indices\n",
136
+ "if y_train.dim() == 2 and y_train.size(1) > 1:\n",
137
+ " y_train = y_train.argmax(dim=1)\n",
138
+ "if y_test.dim() == 2 and y_test.size(1) > 1:\n",
139
+ " y_test = y_test.argmax(dim=1)\n",
140
+ "\n",
141
+ "# --- Combine labels to analyze full dataset classes ---\n",
142
+ "y_all = torch.cat([y_train, y_test], dim=0)\n",
143
+ "\n",
144
+ "# 1) Number of unique labels\n",
145
+ "unique_labels = torch.unique(y_all)\n",
146
+ "num_unique_labels = unique_labels.numel()\n",
147
+ "\n",
148
+ "# 2) Shape of input data\n",
149
+ "input_shape_train = tuple(X_train.shape)\n",
150
+ "input_shape_test = tuple(X_test.shape)\n",
151
+ "\n",
152
+ "# Per-sample shape (excluding N)\n",
153
+ "per_sample_shape = tuple(X_train.shape[1:])\n",
154
+ "\n",
155
+ "# 3) Max / 4) Min across the FULL dataset (train+test)\n",
156
+ "X_all = torch.cat([X_train.reshape(X_train.size(0), -1),\n",
157
+ " X_test.reshape(X_test.size(0), -1)], dim=0)\n",
158
+ "max_val = X_all.max().item()\n",
159
+ "min_val = X_all.min().item()\n",
160
+ "\n",
161
+ "print(\" Task 1 Results\")\n",
162
+ "print(\"-\" * 60)\n",
163
+ "print(f\"1) Unique labels count: {num_unique_labels}\")\n",
164
+ "print(f\" Unique labels: {unique_labels.tolist()}\")\n",
165
+ "print(f\"2) Train input shape: {input_shape_train}\")\n",
166
+ "print(f\" Test input shape: {input_shape_test}\")\n",
167
+ "print(f\" Per-sample shape: {per_sample_shape}\")\n",
168
+ "print(f\"3) Max value in dataset: {max_val}\")\n",
169
+ "print(f\"4) Min value in dataset: {min_val}\")\n"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 1: Write your model class here:\n",
186
+ "\n"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "# Task 2: Write your training loop here:"
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:"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "metadata": {},
212
+ "source": [
213
+ "# Task 4: Define device, model, loss, optimizer:"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 5: Start training for 20 epochs:"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "from sklearn.model_selection import train_test_split\n",
232
+ "from torch.utils.data import TensorDataset, DataLoader\n",
233
+ "\n",
234
+ "# Convert types for NN training\n",
235
+ "X_train = X_train.float()\n",
236
+ "X_test = X_test.float()\n",
237
+ "y_train = y_train.float()\n",
238
+ "y_test = y_test.float()\n",
239
+ "\n",
240
+ "# If input is (N, H, W), add channel -> (N, 1, H, W)\n",
241
+ "if X_train.dim() == 3:\n",
242
+ " X_train = X_train.unsqueeze(1)\n",
243
+ " X_test = X_test.unsqueeze(1)\n",
244
+ "\n",
245
+ "# --- Normalize using TRAIN stats only (important!) ---\n",
246
+ "train_mean = X_train.mean()\n",
247
+ "train_std = X_train.std() + 1e-8\n",
248
+ "\n",
249
+ "X_train = (X_train - train_mean) / train_std\n",
250
+ "X_test = (X_test - train_mean) / train_std\n",
251
+ "\n",
252
+ "# Create validation split from training set (so test remains \"final exam evaluation\")\n",
253
+ "\n",
254
+ "batch_size = 64\n",
255
+ "\n",
256
+ "train_loader = DataLoader(TensorDataset(X_train, y_train), batch_size=batch_size, shuffle=True)\n",
257
+ "val_loader = DataLoader(TensorDataset(X_train, X_train), batch_size=batch_size, shuffle=False)\n",
258
+ "test_loader = DataLoader(TensorDataset(X_test, y_test), batch_size=batch_size, shuffle=False)\n",
259
+ "\n",
260
+ "print(\"Loaders ready\")\n",
261
+ "print(\"Train batches:\", len(train_loader))\n",
262
+ "print(\"Val batches: \", len(val_loader))\n",
263
+ "print(\"Test batches: \", len(test_loader))\n",
264
+ "print(\"Example batch X shape:\", next(iter(train_loader))[0].shape)\n"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "metadata": {},
272
+ "source": [],
273
+ "execution_count": null,
274
+ "outputs": []
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "metadata": {},
279
+ "source": [
280
+ "import torch.nn as nn\n",
281
+ "import torch.nn.functional as F\n",
282
+ "import torch\n",
283
+ "\n",
284
+ "num_classes = int(torch.unique(torch.cat([y_train, y_test])).numel())\n",
285
+ "in_shape = tuple(X_train.shape[1:]) # use train split after channel fix\n",
286
+ "\n",
287
+ "class CompactNet(nn.Module):\n",
288
+ " \"\"\"\n",
289
+ " Max 5 LEARNABLE layers.\n",
290
+ " CNN version (4 learnable layers):\n",
291
+ " 1) Conv2d\n",
292
+ " 2) Conv2d\n",
293
+ " 3) Linear\n",
294
+ " 4) Linear\n",
295
+ " \"\"\"\n",
296
+ " def __init__(self, in_shape, num_classes):\n",
297
+ " super().__init__()\n",
298
+ " C, H, W = in_shape\n",
299
+ "\n",
300
+ " self.conv1 = nn.Conv2d(C, 16, kernel_size=3, padding=1) # (1)\n",
301
+ " self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1) # (2)\n",
302
+ " self.pool = nn.AdaptiveAvgPool2d((1, 1))\n",
303
+ "\n",
304
+ " self.fc1 = nn.Linear(32, 64) # (3)\n",
305
+ " self.fc2 = nn.Linear(64, num_classes) # (4)\n",
306
+ "\n",
307
+ " def forward(self, x):\n",
308
+ " x = F.relu(self.conv1(x))\n",
309
+ " x = F.relu(self.conv2(x))\n",
310
+ " x = self.pool(x)\n",
311
+ " x = x.view(x.size(0), -1)\n",
312
+ " x = F.relu(self.fc1(x))\n",
313
+ " return self.fc2(x)\n",
314
+ "\n",
315
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
316
+ "model = CompactNet(in_shape, num_classes).to(device)\n",
317
+ "\n",
318
+ "print(model)\n",
319
+ "print(\" Device:\", device)\n"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {},
327
+ "source": [
328
+ "from sklearn.metrics import f1_score, accuracy_score\n",
329
+ "\n",
330
+ "# Handle imbalance with class weights (from y_tr only)\n",
331
+ "class_counts = torch.bincount(y_train)\n",
332
+ "class_weights = (class_counts.sum() / (class_counts + 1e-8))\n",
333
+ "class_weights = class_weights / class_weights.sum()\n",
334
+ "class_weights = class_weights.to(device)\n",
335
+ "\n",
336
+ "criterion = nn.CrossEntropyLoss(weight=class_weights)\n",
337
+ "optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n",
338
+ "\n",
339
+ "def eval_loader(model, loader):\n",
340
+ " model.eval()\n",
341
+ " total_loss = 0.0\n",
342
+ " total = 0\n",
343
+ " correct = 0\n",
344
+ " all_preds, all_true = [], []\n",
345
+ "\n",
346
+ " with torch.no_grad():\n",
347
+ " for xb, yb in loader:\n",
348
+ " xb, yb = xb.to(device), yb.to(device)\n",
349
+ " logits = model(xb)\n",
350
+ " loss = criterion(logits, yb)\n",
351
+ "\n",
352
+ " total_loss += loss.item() * xb.size(0)\n",
353
+ " total += xb.size(0)\n",
354
+ "\n",
355
+ " preds = logits.argmax(dim=1)\n",
356
+ " correct += (preds == yb).sum().item()\n",
357
+ "\n",
358
+ " all_preds.append(preds.cpu())\n",
359
+ " all_true.append(yb.cpu())\n",
360
+ "\n",
361
+ " avg_loss = total_loss / total\n",
362
+ " acc = correct / total\n",
363
+ "\n",
364
+ " all_preds = torch.cat(all_preds).numpy()\n",
365
+ " all_true = torch.cat(all_true).numpy()\n",
366
+ " macro_f1 = f1_score(all_true, all_preds, average=\"macro\")\n",
367
+ "\n",
368
+ " return avg_loss, acc, macro_f1\n",
369
+ "\n",
370
+ "\n",
371
+ "epochs = 15\n",
372
+ "for epoch in range(1, epochs + 1):\n",
373
+ " model.train()\n",
374
+ " running_loss = 0.0\n",
375
+ " total_train = 0\n",
376
+ "\n",
377
+ " for xb, yb in train_loader:\n",
378
+ " xb, yb = xb.to(device), yb.to(device)\n",
379
+ "\n",
380
+ " optimizer.zero_grad()\n",
381
+ " logits = model(xb)\n",
382
+ " loss = criterion(logits, yb)\n",
383
+ " loss.backward()\n",
384
+ " optimizer.step()\n",
385
+ "\n",
386
+ " running_loss += loss.item() * xb.size(0)\n",
387
+ " total_train += xb.size(0)\n",
388
+ "\n",
389
+ " train_loss = running_loss / total_train\n",
390
+ " val_loss, val_acc, val_f1 = eval_loader(model, val_loader)\n",
391
+ "\n",
392
+ " print(f\"Epoch {epoch:02d}/{epochs} | \"\n",
393
+ " f\"Train Loss: {train_loss:.4f} | \"\n",
394
+ " f\"Val Loss: {val_loss:.4f} | \"\n",
395
+ " f\"Val Acc: {val_acc:.4f} | \"\n",
396
+ " f\"Val Macro-F1: {val_f1:.4f}\")\n",
397
+ "\n",
398
+ "# Final test evaluation\n",
399
+ "test_loss, test_acc, test_f1 = eval_loader(model, test_loader)\n",
400
+ "print(\"\\n FINAL TEST RESULTS\")\n",
401
+ "print(f\"Test Loss: {test_loss:.4f}\")\n",
402
+ "print(f\"Test Acc: {test_acc:.4f}\")\n",
403
+ "print(f\"Test Macro-F1: {test_f1:.4f}\")\n"
404
+ ],
405
+ "execution_count": null,
406
+ "outputs": []
407
+ },
408
+ {
409
+ "cell_type": "code",
410
+ "metadata": {},
411
+ "source": [],
412
+ "execution_count": null,
413
+ "outputs": []
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "metadata": {},
418
+ "source": [],
419
+ "execution_count": null,
420
+ "outputs": []
421
+ },
422
+ {
423
+ "cell_type": "code",
424
+ "metadata": {},
425
+ "source": [],
426
+ "execution_count": null,
427
+ "outputs": []
428
+ },
429
+ {
430
+ "cell_type": "code",
431
+ "metadata": {},
432
+ "source": [],
433
+ "execution_count": null,
434
+ "outputs": []
435
+ },
436
+ {
437
+ "cell_type": "code",
438
+ "metadata": {},
439
+ "source": [
440
+ "# Task 1: Write your code here:\n",
441
+ "# Plotting results\n",
442
+ "plt.figure(figsize=(7, 5))\n",
443
+ "\n",
444
+ "plt.plot(train_losses, label='Train Loss')\n",
445
+ "plt.plot(val_losses, label='Validation Loss')\n",
446
+ "plt.title('Loss over Epochs')\n",
447
+ "plt.xlabel('Epoch')\n",
448
+ "plt.ylabel('Loss')\n",
449
+ "plt.legend()\n",
450
+ "\n",
451
+ "plt.tight_layout()\n",
452
+ "plt.show()"
453
+ ],
454
+ "execution_count": null,
455
+ "outputs": []
456
+ },
457
+ {
458
+ "cell_type": "code",
459
+ "metadata": {},
460
+ "source": [
461
+ "# Task 2 (Bonus): Write your code here:"
462
+ ],
463
+ "execution_count": null,
464
+ "outputs": []
465
+ }
466
+ ],
467
+ "metadata": {
468
+ "kernelspec": {
469
+ "display_name": "Python 3",
470
+ "name": "python3"
471
+ },
472
+ "language_info": {
473
+ "name": "python"
474
+ }
475
+ },
476
+ "nbformat": 4,
477
+ "nbformat_minor": 0
478
+ }
submissions_extracted/824/Q3.ipynb ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "from IPython.display import clear_output\n",
8
+ "\n",
9
+ "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n",
10
+ "\n",
11
+ "clear_output()\n"
12
+ ],
13
+ "execution_count": null,
14
+ "outputs": []
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "metadata": {},
19
+ "source": [
20
+ "import kagglehub\n",
21
+ "\n",
22
+ "\n",
23
+ "\n",
24
+ "# Download latest version\n",
25
+ "\n",
26
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
27
+ "\n",
28
+ "\n",
29
+ "\n",
30
+ "print(\"Path to dataset files:\", path)"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "import os\n",
40
+ "import numpy as np\n",
41
+ "import pandas as pd\n",
42
+ "import matplotlib.pyplot as plt\n",
43
+ "\n",
44
+ "from sklearn.model_selection import StratifiedKFold\n",
45
+ "from sklearn.metrics import f1_score, accuracy_score\n"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 1: Write your code here:\n",
55
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
56
+ "df = pd.read_csv(csv_path)"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 2: Write your code here:\n",
66
+ "df.head()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 3: Write your code here:\n",
76
+ "df.info()"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 4: Write your code here:\n",
86
+ "df.describe()"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 1: Write your code here:\n",
96
+ "def check_missing_values(df):\n",
97
+ " missing_values = df.isnull().sum()\n",
98
+ " print(\"Missing Values per Column:\")\n",
99
+ " print(missing_values[missing_values > 0])\n",
100
+ " if missing_values.any():\n",
101
+ " print(\"\\nHandle Missing Values as needed.\")\n",
102
+ " else:\n",
103
+ " print(\"\\nNo Missing Values Found.\")\n",
104
+ "\n",
105
+ "check_missing_values(df)\n",
106
+ "\n",
107
+ "print(\"=\" * 40)\n",
108
+ "\n",
109
+ "stat_cols = df.columns\n",
110
+ "\n",
111
+ "df_clean = df[stat_cols].fillna(0) # YOUR CODE HERE\n",
112
+ "\n",
113
+ "\n",
114
+ "check_missing_values(df_clean)\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# Task 2: Write your code here:\n",
124
+ "\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)\n",
136
+ "\n",
137
+ "df_clean.head()"
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
+ "\n",
148
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
149
+ "\n",
150
+ "print(\"Categorical Columns:\", list(categorical_cols))"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 4: Write your code here:\n",
160
+ "\n",
161
+ "from sklearn.preprocessing import StandardScaler\n",
162
+ "\n",
163
+ "# Pick only the numerical columns, NOT the target\n",
164
+ "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
165
+ "\n",
166
+ "scaler = StandardScaler()\n",
167
+ "\n",
168
+ "# scale the `numerical_cols`\n",
169
+ "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
170
+ "\n",
171
+ "df_clean.head()"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "import seaborn as sns\n"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "# Task 5: Write your code here\n",
190
+ "\n",
191
+ "def check_target_imbalance(df, target_column):\n",
192
+ " print(\"Target Distribution:\")\n",
193
+ " print(df[target_column].value_counts(normalize=True))\n",
194
+ " sns.countplot(x=df[target_column])\n",
195
+ " plt.title(\"Target Distribution\")\n",
196
+ " plt.show()\n",
197
+ "\n",
198
+ "check_target_imbalance(df_clean, \"Target\")"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "import os\n",
208
+ "import numpy as np\n",
209
+ "import pandas as pd\n",
210
+ "import matplotlib.pyplot as plt\n",
211
+ "\n",
212
+ "from sklearn.model_selection import StratifiedKFold\n",
213
+ "from sklearn.metrics import f1_score, accuracy_score\n"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "from sklearn.model_selection import KFold\n",
223
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score"
224
+ ],
225
+ "execution_count": null,
226
+ "outputs": []
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "# Task 1: Write your code here:\n",
233
+ "X = df_clean.drop(\"Target\", axis=1).astype(float)\n",
234
+ "y = df_clean['Target'].astype(float)\n"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "from tqdm import tqdm\n"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "metadata": {},
251
+ "source": [
252
+ "# sigmoid in NumPy\n",
253
+ "def sigmoid(z):\n",
254
+ " return 1 / (1 + np.exp(-z))"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# BCE in NumPy\n",
264
+ "def binary_cross_entropy(y, y_hat):\n",
265
+ " epsilon = 1e-15 # Very small number to prevent log(0)\n",
266
+ " y_hat = np.clip(y_hat, epsilon, 1 - epsilon) # np.clip(value, min, max)\n",
267
+ "\n",
268
+ " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
269
+ " return loss"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "metadata": {},
277
+ "source": [
278
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
279
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
280
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
281
+ " losses = []\n",
282
+ "\n",
283
+ " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
284
+ " z = np.dot(X, theta)\n",
285
+ " y_hat = sigmoid(z)\n",
286
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
287
+ " theta -= learning_rate * gradient\n",
288
+ "\n",
289
+ " loss = binary_cross_entropy(y, y_hat)\n",
290
+ " losses.append(loss)\n",
291
+ "\n",
292
+ " return theta, losses"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "metadata": {},
300
+ "source": [
301
+ "from sklearn.model_selection import StratifiedKFold\n",
302
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
303
+ ],
304
+ "execution_count": null,
305
+ "outputs": []
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "metadata": {},
310
+ "source": [
311
+ "n_splits = 5 # K=5 Folds\n",
312
+ "\n",
313
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
314
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
315
+ ],
316
+ "execution_count": null,
317
+ "outputs": []
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "metadata": {},
322
+ "source": [
323
+ "# Storage for logistic regression results for each fold\n",
324
+ "lr_losses = []\n",
325
+ "\n",
326
+ "lr_f1 = []"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
336
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
337
+ "\n",
338
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
339
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
340
+ "\n",
341
+ " # Train\n",
342
+ " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
343
+ "\n",
344
+ " # Validate\n",
345
+ " y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
346
+ "\n",
347
+ "# something here\n",
348
+ "\n",
349
+ " y_pred = (y_pred_proba >= 0.5).astype(int)\n",
350
+ "\n",
351
+ " # Calculate evaluation metrics\n",
352
+ " accuracy = accuracy_score(y_test, y_pred)\n",
353
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
354
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
355
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
356
+ "\n",
357
+ " # Store results\n",
358
+ " lr_losses.append(losses)\n",
359
+ "\n",
360
+ " lr_f1.append(f1)"
361
+ ],
362
+ "execution_count": null,
363
+ "outputs": []
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "metadata": {},
368
+ "source": [
369
+ "# Calculate average loss across folds\n",
370
+ "avg_loss = np.mean(lr_losses, axis=0)\n",
371
+ "\n",
372
+ "plt.figure(figsize=(10, 6))\n",
373
+ "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
374
+ "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
375
+ "plt.xlabel('Iteration')\n",
376
+ "plt.ylabel('Binary Cross-Entropy Loss')\n",
377
+ "plt.legend()\n",
378
+ "plt.grid(True, alpha=0.3)\n",
379
+ "plt.show()"
380
+ ],
381
+ "execution_count": null,
382
+ "outputs": []
383
+ },
384
+ {
385
+ "cell_type": "code",
386
+ "metadata": {},
387
+ "source": [
388
+ "print(\"LOGISTIC REGRESSION Performance:\")\n",
389
+ "\n",
390
+ "print(f\" F1-Score: {np.mean(lr_f1):.4f}\")"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "metadata": {},
398
+ "source": [
399
+ "# Import models\n",
400
+ "from sklearn.neighbors import KNeighborsClassifier\n",
401
+ "from sklearn.svm import SVC\n",
402
+ "from sklearn.tree import DecisionTreeClassifier\n",
403
+ "from sklearn.ensemble import RandomForestClassifier\n",
404
+ "from xgboost import XGBClassifier\n",
405
+ "from catboost import CatBoostClassifier"
406
+ ],
407
+ "execution_count": null,
408
+ "outputs": []
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "metadata": {},
413
+ "source": [
414
+ "sklearn_models = {\n",
415
+ " \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
416
+ " n_neighbors=3, # Number of neighbors to consider\n",
417
+ " ),\n",
418
+ " \"Support Vector Machine\": SVC(\n",
419
+ " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
420
+ " C=0.75 # Regularization parameter\n",
421
+ " ),\n",
422
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
423
+ " max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
424
+ " ),\n",
425
+ " \"Random Forest\": RandomForestClassifier(\n",
426
+ " n_estimators=320, # Number of trees\n",
427
+ " max_depth=4\n",
428
+ " ),\n",
429
+ " \"XGBoost\": XGBClassifier(\n",
430
+ " verbosity=0,\n",
431
+ " n_estimators=300, # Number of boosting rounds\n",
432
+ " max_depth=5,\n",
433
+ " learning_rate=0.05 # Step size shrinkage\n",
434
+ " ),\n",
435
+ " \"CatBoost\": CatBoostClassifier(\n",
436
+ " verbose=0,\n",
437
+ " n_estimators=320,\n",
438
+ " max_depth=4\n",
439
+ " )\n",
440
+ "}"
441
+ ],
442
+ "execution_count": null,
443
+ "outputs": []
444
+ },
445
+ {
446
+ "cell_type": "code",
447
+ "metadata": {},
448
+ "source": [
449
+ "all_results = {}\n",
450
+ "\n",
451
+ "for name in sklearn_models:\n",
452
+ " all_results[name] = {'f1': []}"
453
+ ],
454
+ "execution_count": null,
455
+ "outputs": []
456
+ },
457
+ {
458
+ "cell_type": "code",
459
+ "metadata": {},
460
+ "source": [
461
+ "n_splits = 5 # K\n",
462
+ "\n",
463
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
464
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
465
+ ],
466
+ "execution_count": null,
467
+ "outputs": []
468
+ },
469
+ {
470
+ "cell_type": "code",
471
+ "metadata": {},
472
+ "source": [
473
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
474
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
475
+ "\n",
476
+ " # 1. Split data\n",
477
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
478
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
479
+ "\n",
480
+ " # 2. Train & Validate sklearn models\n",
481
+ " for model_name, model in sklearn_models.items():\n",
482
+ " print(f\"Training {model_name}...\")\n",
483
+ " model.fit(X_train, y_train) # train\n",
484
+ " y_pred = model.predict(X_test) # validate\n",
485
+ "\n",
486
+ " # 3. Save metrics for that model in this fold\n",
487
+ " accuracy = accuracy_score(y_test, y_pred)\n",
488
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
489
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
490
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
491
+ "\n",
492
+ " all_results[model_name]['f1'].append(f1)"
493
+ ],
494
+ "execution_count": null,
495
+ "outputs": []
496
+ },
497
+ {
498
+ "cell_type": "code",
499
+ "metadata": {},
500
+ "source": [
501
+ "for model_name in all_results:\n",
502
+ " print(f\"\\n{model_name}:\")\n",
503
+ " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
504
+ ],
505
+ "execution_count": null,
506
+ "outputs": []
507
+ },
508
+ {
509
+ "cell_type": "code",
510
+ "metadata": {},
511
+ "source": [],
512
+ "execution_count": null,
513
+ "outputs": []
514
+ },
515
+ {
516
+ "cell_type": "code",
517
+ "metadata": {},
518
+ "source": [],
519
+ "execution_count": null,
520
+ "outputs": []
521
+ },
522
+ {
523
+ "cell_type": "code",
524
+ "metadata": {},
525
+ "source": [],
526
+ "execution_count": null,
527
+ "outputs": []
528
+ },
529
+ {
530
+ "cell_type": "code",
531
+ "metadata": {},
532
+ "source": [
533
+ "# Task 1: Write your code here:\n",
534
+ "# Gather importances from the models (from the last fold)\n",
535
+ "importances = {}\n",
536
+ "\n",
537
+ "importances['RF'] = sklearn_models['CatBoost'].feature_importances_\n",
538
+ "\n",
539
+ "# Create a 1x3 plot\n",
540
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
541
+ "axes = axes.flatten()\n",
542
+ "features = X.columns\n",
543
+ "\n",
544
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
545
+ " # Sort features by importance for a cleaner plot\n",
546
+ " sorted_idx = np.argsort(imp)\n",
547
+ "\n",
548
+ " ax = axes[i]\n",
549
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
550
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
551
+ " ax.set_xlabel(\"Importance Score\")\n",
552
+ "\n",
553
+ "plt.tight_layout()\n",
554
+ "plt.show()"
555
+ ],
556
+ "execution_count": null,
557
+ "outputs": []
558
+ },
559
+ {
560
+ "cell_type": "code",
561
+ "metadata": {},
562
+ "source": [
563
+ "# Task 2: Write your code here:\n",
564
+ "golden_feat = print(sorted_idx[0]) # 14\n",
565
+ "\n",
566
+ "print(features[14])"
567
+ ],
568
+ "execution_count": null,
569
+ "outputs": []
570
+ },
571
+ {
572
+ "cell_type": "code",
573
+ "metadata": {},
574
+ "source": [
575
+ "# Task Bonus: Write your code here:"
576
+ ],
577
+ "execution_count": null,
578
+ "outputs": []
579
+ }
580
+ ],
581
+ "metadata": {
582
+ "kernelspec": {
583
+ "display_name": "Python 3",
584
+ "name": "python3"
585
+ },
586
+ "language_info": {
587
+ "name": "python"
588
+ }
589
+ },
590
+ "nbformat": 4,
591
+ "nbformat_minor": 0
592
+ }
submissions_extracted/825/Q1.ipynb ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import numpy as np\n",
23
+ "import pandas as pd\n",
24
+ "import matplotlib.pyplot as plt\n",
25
+ "import os\n",
26
+ "food_path = os.path.join(path,'Q1_data.csv')\n",
27
+ "df_food = pd.read_csv(food_path)\n"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 2: Write your code here:\n",
37
+ "df_food.head()"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 3: Write your code here:\n",
47
+ "df_food.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 4: Write your code here:\n",
57
+ "df_food.describe()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 5: Write your code here:\n",
67
+ "plt.figure(figsize=(10, 5))\n",
68
+ "plt.hist(df_food['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
69
+ "plt.title('Delivery Time Distribution')\n",
70
+ "plt.xlabel('Delivery Time')\n",
71
+ "plt.ylabel('Frequency')\n",
72
+ "plt.show()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 1: Write your code here:\n",
82
+ "df_food = df_food.drop(columns=['Order_ID'],axis =1)\n",
83
+ "df_food.head()"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 2: Write your code here:\n",
93
+ "missing_value = df_food.isnull().sum()\n",
94
+ "print(missing_value)\n",
95
+ "mis_cols = ['Weather','Traffic_Level','Time_of_Day','Courier_Experience_yrs','Delivery_Time'] # mis_cols is miising values columns\n",
96
+ "df_food = df_food.dropna(subset=mis_cols)\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 3: Write your code here:\n",
106
+ "def check_duplicates(df):\n",
107
+ " duplicates = df.duplicated().sum()\n",
108
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
109
+ " if duplicates > 0:\n",
110
+ " print(\"Dropping Duplicates...\")\n",
111
+ " df.drop_duplicates(inplace=True)\n",
112
+ " print(\"Duplicates Dropped.\")\n",
113
+ " else:\n",
114
+ " print(\"No Duplicate Samples Found.\")\n",
115
+ "\n",
116
+ "check_duplicates(df_food)\n",
117
+ "df_food.info()"
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.model_selection import train_test_split, KFold\n",
128
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
129
+ "\n",
130
+ "\n",
131
+ "cols = df_food.select_dtypes(include=[\"object\"]).columns\n",
132
+ "print(cols)\n",
133
+ "label_encoders = {}\n",
134
+ "for col in cols:\n",
135
+ " le = LabelEncoder()\n",
136
+ " df_food[col] = le.fit_transform(df_food[col])\n",
137
+ " label_encoders[col] = le\n",
138
+ "df_food.info()"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 5: Write your code here:\n",
148
+ "numerical_cols = df_food.select_dtypes(include=['int64',\"float64\"]).columns\n",
149
+ "scaler = StandardScaler()\n",
150
+ "df_food[numerical_cols] = scaler.fit_transform(df_food[numerical_cols])\n",
151
+ "df_food.head()"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 6: Write your code here:\n",
161
+ "df_food['Delivery_Time'].value_counts() # imbalcnced"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 1: Write your code here:\n",
171
+ "from sklearn.model_selection import StratifiedKFold\n",
172
+ "from sklearn.ensemble import RandomForestRegressor\n",
173
+ "from sklearn.metrics import mean_absolute_error\n",
174
+ "X = df_food.drop('Delivery_Time',axis=1)\n",
175
+ "y = df_food['Delivery_Time']\n",
176
+ "X.head()\n"
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
+ "from sklearn.model_selection import StratifiedKFold,KFold\n",
187
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
188
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
189
+ "\n",
190
+ "mae_scores = []\n",
191
+ "n_splits = 5\n",
192
+ "for fold_idx, (train_index, test_index) in enumerate(kfold.split(X)):\n",
193
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
194
+ "\n",
195
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
196
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
197
+ "\n",
198
+ "\n",
199
+ " # Train and predict\n",
200
+ " model.fit(X_train, y_train)\n",
201
+ " y_fold_pred = model.predict(X_test)\n",
202
+ "\n",
203
+ " # Calculate metrics\n",
204
+ " mae_scores.append(mean_absolute_error(y_test, y_fold_pred))\n",
205
+ " print(f\"MAE: ${mae_scores[fold_idx]:,.2f}\")\n",
206
+ "mae_scores = np.array(mae_scores)\n",
207
+ "\n",
208
+ "print(f\"5-Fold CV Results:\")\n",
209
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "# Task 1: Write your code here:\n",
219
+ "average_losses = np.mean(lr_losses, axis=0)\n",
220
+ "\n",
221
+ "plt.figure(figsize=(10, 6))\n",
222
+ "plt.plot(average_losses, label='Average Loss')\n",
223
+ "plt.xlabel('Iteration')\n",
224
+ "plt.ylabel('MSE Loss')\n",
225
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
226
+ "plt.legend()\n",
227
+ "plt.grid(True, alpha=0.3)\n",
228
+ "plt.show()"
229
+ ],
230
+ "execution_count": null,
231
+ "outputs": []
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "metadata": {},
236
+ "source": [
237
+ "# Task 2: Write your code here:"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task Bonus: Write your code here:"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ }
251
+ ],
252
+ "metadata": {
253
+ "kernelspec": {
254
+ "display_name": "Python 3",
255
+ "name": "python3"
256
+ },
257
+ "language_info": {
258
+ "name": "python"
259
+ }
260
+ },
261
+ "nbformat": 4,
262
+ "nbformat_minor": 0
263
+ }
submissions_extracted/825/Q2.ipynb ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import torch\n",
26
+ "import torch.nn as nn\n",
27
+ "from torch.optim import AdamW\n",
28
+ "import matplotlib.pyplot as plt\n",
29
+ "import torch.nn.functional as F\n",
30
+ "from torch.utils.data import DataLoader, TensorDataset\n",
31
+ "from sklearn.model_selection import train_test_split\n",
32
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
33
+ "from sklearn.model_selection import train_test_split\n",
34
+ "\n",
35
+ "# Load Labels\n",
36
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
37
+ "img_dir = os.path.join(path, \"images\")\n",
38
+ "\n",
39
+ "images = []\n",
40
+ "ages = []\n",
41
+ "\n",
42
+ "# Load Images and Resize\n",
43
+ "print(\"Loading images...\")\n",
44
+ "for index, row in labels_df.iterrows():\n",
45
+ " img_name = row.iloc[0]\n",
46
+ " age = row.iloc[1]\n",
47
+ " img_path = os.path.join(img_dir, img_name)\n",
48
+ "\n",
49
+ " if os.path.exists(img_path):\n",
50
+ " img = Image.open(img_path).convert('RGB')\n",
51
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
52
+ " images.append(img_array)\n",
53
+ " ages.append(age)\n",
54
+ "\n",
55
+ "X = np.array(images)\n",
56
+ "y = np.array(ages)\n",
57
+ "\n",
58
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
59
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
60
+ "\n",
61
+ "# Split Data\n",
62
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
63
+ "\n",
64
+ "print(f\"X_train shape: {X_train.shape}\")\n",
65
+ "print(f\"X_test shape: {X_test.shape}\")\n",
66
+ "print(f\"y_train shape: {y_train.shape}\")\n",
67
+ "print(f\"y_test shape: {y_test.shape}\")"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
77
+ "X_train = torch.tensor(X_train,dtype=torch.float32)\n",
78
+ "X_test = torch.tensor(X_test,dtype=torch.float32)\n",
79
+ "y_train = torch.tensor(y_train,dtype=torch.float32)\n",
80
+ "y_test = torch.tensor(y_test,dtype=torch.float32)\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 2. Create TensorDataset objects\n",
91
+ "\n",
92
+ "train_dataset = TensorDataset(X_train, y_train)\n",
93
+ "test_dataset = TensorDataset(X_test, y_test)\n"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# 3. Create DataLoaders\n",
103
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
104
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 4. Print shape of one batch\n",
114
+ "X_batch, y_batch = next(iter(train_loader))\n",
115
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# 5. Display sample images\n",
125
+ "import matplotlib.pyplot as plt\n",
126
+ "images, labels = next(iter(train_loader))\n",
127
+ "\n",
128
+ "# Display the first 6 images in the batch\n",
129
+ "plt.figure(figsize=(8, 4))\n",
130
+ "\n",
131
+ "for i in range(6):\n",
132
+ " plt.subplot(2, 3, i + 1)\n",
133
+ "\n",
134
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
135
+ " img = images[i].permute(1, 2, 0)\n",
136
+ "\n",
137
+ " plt.imshow(img)\n",
138
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
139
+ " plt.axis('off')\n",
140
+ "\n",
141
+ "plt.tight_layout()\n",
142
+ "plt.show()"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 1: Write your model class here:\n",
152
+ "class NN4Layer(nn.Module):\n",
153
+ "\n",
154
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
155
+ " super(NN4Layer, self).__init__()\n",
156
+ "\n",
157
+ " # First linear layer: input features -> hidden layer\n",
158
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
159
+ "\n",
160
+ " # Second linear layer: hidden layer -> hidden layer\n",
161
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
162
+ "\n",
163
+ " # third layer: hidden layer -> number of classes (logits)\n",
164
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
165
+ " # output layer: hidden layer -> number of classes (logits)\n",
166
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\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
+ " # Layer 1: TODO\n",
173
+ " z1 = self.layer1(x)\n",
174
+ " a1 = self.relu(z1)\n",
175
+ "\n",
176
+ " # Layer 2 TODO\n",
177
+ " z2 = self.layer2(a1)\n",
178
+ " a2 = self.relu(z2)\n",
179
+ "\n",
180
+ " # Layer 3 TODO\n",
181
+ " z3 = self.layer3(a2)\n",
182
+ " a3 = self.relu(z3)\n",
183
+ "\n",
184
+ " # Layer 4 TODO\n",
185
+ " output = self.layer4(a3)\n",
186
+ "\n",
187
+ "\n",
188
+ " return output\n"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 2: Write your training loop here:\n",
198
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
199
+ " # Set the model to training mode\n",
200
+ " model.train()\n",
201
+ "\n",
202
+ " running_loss = 0.0\n",
203
+ "\n",
204
+ " for X_batch, y_batch in train_loader:\n",
205
+ " # Move batch to the selected device\n",
206
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
207
+ " y_batch = y_batch.to(device)\n",
208
+ "\n",
209
+ " # Forward pass\n",
210
+ " # TODO: make predictions\n",
211
+ " outputs = model(X_batch)\n",
212
+ " # TODO: compute loss\n",
213
+ " loss = criterion(outputs, y_batch)\n",
214
+ "\n",
215
+ " # Backward pass & optimization\n",
216
+ " optimizer.zero_grad() # Clear previous gradients\n",
217
+ " loss.backward() # Compute gradients\n",
218
+ " optimizer.step() # Update model parameters\n",
219
+ "\n",
220
+ " running_loss += loss.item()\n",
221
+ "\n",
222
+ " # Average loss over all batches\n",
223
+ " avg_loss = running_loss / len(train_loader)\n",
224
+ "\n",
225
+ " return avg_loss"
226
+ ],
227
+ "execution_count": null,
228
+ "outputs": []
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "# Task 3: Write your validation loop here:\n",
235
+ "def validate(model, criterion, test_loader, device):\n",
236
+ " # Set the model to evaluation mode\n",
237
+ " model.eval()\n",
238
+ "\n",
239
+ " running_loss = 0.0\n",
240
+ " correct = 0\n",
241
+ " total = 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 = X_batch.view(X_batch.size(0), -1).to(device)\n",
247
+ " y_batch = y_batch.to(device)\n",
248
+ "\n",
249
+ " # Forward pass\n",
250
+ " # TODO: make predictions\n",
251
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
252
+ " # TODO: compute loss\n",
253
+ " loss = criterion(outputs, y_batch)\n",
254
+ " running_loss += loss.item()\n",
255
+ "\n",
256
+ " # TODO: Apply Softmax to get probabilities\n",
257
+ " probabilities = F.softmax(outputs, dim=1)\n",
258
+ "\n",
259
+ " # TODO: Multiclass predictions\n",
260
+ " predicted = torch.argmax(probabilities, dim=1)\n",
261
+ "\n",
262
+ " # Accuracy calculation\n",
263
+ " correct += (predicted == y_batch).sum().item()\n",
264
+ " total += y_batch.size(0)\n",
265
+ "\n",
266
+ " avg_loss = running_loss / len(test_loader)\n",
267
+ " # TODO: how do we calculate accuracy?\n",
268
+ " accuracy = correct / total\n",
269
+ "\n",
270
+ " return avg_loss, accuracy\n"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "metadata": {},
278
+ "source": [
279
+ "# Task 4: Define device, model, loss, optimizer:\n",
280
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
281
+ "\n",
282
+ "# Model parameters\n",
283
+ "# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
284
+ "input_dim = 3*36*36\n",
285
+ "\n",
286
+ "# TODO: choose number of hidden neurons\n",
287
+ "hidden_dim = 32 # Design choice\n",
288
+ "\n",
289
+ "# TODO: what are the number of classes ?\n",
290
+ "output_dim = 1\n",
291
+ "\n",
292
+ "# TODO: Instantiate model (what are the model class inputs?)\n",
293
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
294
+ "\n",
295
+ "# TODO: Print the model architecture\n",
296
+ "print(\"Model Architecture:\\n\")\n",
297
+ "print(model)\n",
298
+ "\n",
299
+ "# Calculate the total number of trainable parameters\n",
300
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
301
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n"
302
+ ],
303
+ "execution_count": null,
304
+ "outputs": []
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "metadata": {},
309
+ "source": [
310
+ "# Task 5: Start training for 20 epochs:\n",
311
+ "num_epochs = 20\n",
312
+ "# TODO: choose a learning rate (try different values and evaluate results)\n",
313
+ "learning_rate = 0.001\n",
314
+ "\n",
315
+ "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
316
+ "criterion = nn.MSELoss()\n",
317
+ "# TODO: Define optimizer(what is updated during training?)\n",
318
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
319
+ "\n",
320
+ "train_losses = []\n",
321
+ "val_losses = []\n",
322
+ "val_accuracies = []\n",
323
+ "\n",
324
+ "print('Starting Training...')\n",
325
+ "for epoch in range(num_epochs):\n",
326
+ " # Train one epoch\n",
327
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
328
+ "\n",
329
+ " # Validate\n",
330
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
331
+ "\n",
332
+ " train_losses.append(train_loss)\n",
333
+ " val_losses.append(val_loss)\n",
334
+ " val_accuracies.append(val_accuracy)\n",
335
+ "\n",
336
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
337
+ "\n",
338
+ "print('Training Complete!')"
339
+ ],
340
+ "execution_count": null,
341
+ "outputs": []
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "metadata": {},
346
+ "source": [
347
+ "# Task 1: Write your code here:\n",
348
+ "plt.figure(figsize=(7, 5))\n",
349
+ "\n",
350
+ "plt.plot(train_losses, label='Train Loss')\n",
351
+ "plt.plot(val_losses, label='Validation Loss')\n",
352
+ "plt.title('Loss over Epochs')\n",
353
+ "plt.xlabel('Epoch')\n",
354
+ "plt.ylabel('Loss')\n",
355
+ "plt.legend()\n",
356
+ "\n",
357
+ "plt.tight_layout()\n",
358
+ "plt.show()"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [
367
+ "# Task 2 (Bonus): Write your code here:"
368
+ ],
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/825/Q3.ipynb ADDED
@@ -0,0 +1,249 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
28
+ "import numpy as np\n",
29
+ "import pandas as pd\n",
30
+ "import matplotlib.pyplot as plt\n",
31
+ "import os\n",
32
+ "food_path = os.path.join(path,'Q3_data.csv')\n",
33
+ "df_ano = pd.read_csv(food_path)"
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_ano.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_ano.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_ano.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
+ "missing_value = df_ano.isnull().sum()\n",
74
+ "cols = list(missing_value[missing_value>0].index)\n",
75
+ "for col in cols:\n",
76
+ " df_ano[col] = df_ano[col].fillna(df_ano[col].mean())\n",
77
+ "df_ano.info()"
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()\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)\n",
93
+ " print(\"Duplicates Dropped.\")\n",
94
+ " else:\n",
95
+ " print(\"No Duplicate Samples Found.\")\n",
96
+ "\n",
97
+ "check_duplicates(df_ano)\n",
98
+ "df_ano.info()"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# Task 3: Write your code here:\n",
108
+ "# no need all not catigorial"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ "# Task 4: Write your code here:\n",
118
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder,OneHotEncoder\n",
119
+ "\n",
120
+ "numerical_cols = df_ano.select_dtypes(include=['int64',\"float64\"]).columns\n",
121
+ "scaler = StandardScaler()\n",
122
+ "df_ano[numerical_cols] = scaler.fit_transform(df_ano[numerical_cols])\n",
123
+ "df_ano.head()"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 5: Write your code here:\n",
133
+ "df_ano['Target'].value_counts() # imbalcnced"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "import pandas as pd\n",
143
+ "import numpy as np\n",
144
+ "import matplotlib.pyplot as plt\n",
145
+ "import seaborn as sns\n",
146
+ "import kagglehub\n",
147
+ "import os\n",
148
+ "from tqdm import tqdm\n",
149
+ "from sklearn.model_selection import StratifiedKFold\n",
150
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
151
+ "%pip install catboost\n",
152
+ "from catboost import CatBoostClassifier"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 1: Write your code here:\n",
162
+ "X = df_ano.drop(\"Target\", axis=1).astype(float)\n",
163
+ "y = df_ano['Target'].astype(float)\n",
164
+ "X.info()"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "y"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task 2,3,4,5: Write your code here:\n",
183
+ " # supposed target 0 or 1 didnit make\n",
184
+ "n_splits = 5 # K\n",
185
+ "\n",
186
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
187
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
188
+ "model = CatBoostClassifier(verbose=0,n_estimators=320,max_depth=4)\n",
189
+ "\n",
190
+ "\n",
191
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
192
+ "\n",
193
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
194
+ "\n",
195
+ " # Get the train & test split for this fold\n",
196
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
197
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
198
+ "\n",
199
+ "\n",
200
+ " model.fit(X_train, y_train) # train\n",
201
+ " y_pred = model.predict(X_test) #\n",
202
+ "\n",
203
+ " # Calculate evaluation metrics\n",
204
+ " accuracy = accuracy_score(y_test, y_pred)\n",
205
+ " f1 = f1_score(y_test, y_pred, zero_division=0)"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 1: Write your code here:"
215
+ ],
216
+ "execution_count": null,
217
+ "outputs": []
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "# Task 2: Write your code here:"
224
+ ],
225
+ "execution_count": null,
226
+ "outputs": []
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "# Task Bonus: Write your code here:"
233
+ ],
234
+ "execution_count": null,
235
+ "outputs": []
236
+ }
237
+ ],
238
+ "metadata": {
239
+ "kernelspec": {
240
+ "display_name": "Python 3",
241
+ "name": "python3"
242
+ },
243
+ "language_info": {
244
+ "name": "python"
245
+ }
246
+ },
247
+ "nbformat": 4,
248
+ "nbformat_minor": 0
249
+ }
submissions_extracted/826/Q1.ipynb ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
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(\"/kaggle/input/q1-exam-data/Q1_data.csv\")\n",
38
+ "\n"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 2: Write your code here:\n",
48
+ "df.head()"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 3: Write your code here:\n",
58
+ "df.info()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 4: Write your code here:\n",
68
+ "df.describe()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 5: Write your code here:\n",
78
+ "df[\"Delivery_Time\"].hist(bins=30, edgecolor='black')\n",
79
+ "\n",
80
+ "plt.title(f\"Target Distribution ({\"delivery_time\"})\")\n",
81
+ "plt.xlabel(\"delivery_time\")\n",
82
+ "plt.ylabel(\"Frequency\")\n",
83
+ "plt.grid(False)\n",
84
+ "\n",
85
+ "\n",
86
+ "plt.show()"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 1: Write your code here:\n",
96
+ "df = df.drop(\"Order_ID\", axis=1)\n",
97
+ "df"
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
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
108
+ "missing_data = pd.DataFrame({\n",
109
+ " 'Column': missing_percentage.index,\n",
110
+ " 'Missing_Percentage': missing_percentage.values\n",
111
+ "})\n",
112
+ "\n",
113
+ "missing_data.head(5)\n",
114
+ "\n",
115
+ "print(\"--------------/n\")\n",
116
+ "print(\"handeling the missing data\")\n",
117
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs',]:\n",
118
+ " df[col] = df[col].fillna(df[col].mode()[0])\n",
119
+ "\n",
120
+ "df[\"Delivery_Time\"] = df[\"Delivery_Time\"].fillna(df[\"Delivery_Time\"].mean())\n",
121
+ "\n",
122
+ "missing_data.head(5)\n",
123
+ "\n",
124
+ "\n",
125
+ "\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 3: Write your code here:\n",
135
+ "def check_duplicates(df):\n",
136
+ " duplicates = df.duplicated().sum()\n",
137
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
138
+ " if duplicates > 0:\n",
139
+ " print(\"Dropping Duplicates...\")\n",
140
+ " df.drop_duplicates(inplace=True)\n",
141
+ " print(\"Duplicates Dropped.\")\n",
142
+ " else:\n",
143
+ " print(\"No Duplicate Samples Found.\")\n",
144
+ "\n",
145
+ "check_duplicates(df)"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 4: Write your code here:\n",
155
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
156
+ "\n",
157
+ "\n",
158
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
159
+ "for col in categorical_cols:\n",
160
+ " print(f\"Encoding column: {col}\")\n",
161
+ " le = LabelEncoder()\n",
162
+ " df[col] = le.fit_transform(df[col])\n",
163
+ "df"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 5: Write your code here:\n",
173
+ "\n",
174
+ "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
175
+ "\n",
176
+ "scaler = StandardScaler()\n",
177
+ "df[features] = scaler.fit_transform(df[features])\n",
178
+ "df.head()"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 6: Write your code here:\n",
188
+ "\n",
189
+ "#not needed because the target have conunuise value -- regration not Classifcation"
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(\"Delivery_Time\",axis=1)\n",
200
+ "y = df['Delivery_Time']\n"
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "metadata": {},
208
+ "source": [
209
+ "# Task 2,3,4,5: Writekf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
210
+ "from sklearn.ensemble import RandomForestRegressor\n",
211
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
212
+ "from sklearn.model_selection import KFold\n",
213
+ "\n",
214
+ "\n",
215
+ "MAE=[]\n",
216
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
217
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
218
+ "\n",
219
+ "\n",
220
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
221
+ "\n",
222
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
223
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
224
+ "\n",
225
+ "\n",
226
+ " print(f\"Training singe fold .....\")\n",
227
+ "\n",
228
+ " # Train\n",
229
+ " model.fit(X_train, y_train)\n",
230
+ "\n",
231
+ " # Predict\n",
232
+ " y_pred = model.predict(X_test)\n",
233
+ "\n",
234
+ " # Calculate metrics\n",
235
+ " mae = mean_absolute_error(y_test, y_pred)\n",
236
+ " MAS.append(mae)\n",
237
+ " print(f\"MAE: {mae}\")\n",
238
+ "\n"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task Bonus: Write your code here:"
262
+ ],
263
+ "execution_count": null,
264
+ "outputs": []
265
+ }
266
+ ],
267
+ "metadata": {
268
+ "kernelspec": {
269
+ "display_name": "Python 3",
270
+ "name": "python3"
271
+ },
272
+ "language_info": {
273
+ "name": "python"
274
+ }
275
+ },
276
+ "nbformat": 4,
277
+ "nbformat_minor": 0
278
+ }
submissions_extracted/826/Q2.ipynb ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 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
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
82
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
83
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
84
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# 2. Create TensorDataset objects\n",
94
+ "train_dataset = TensorDataset(X_train, y_train)\n",
95
+ "test_dataset = TensorDataset(X_test, y_test)\n",
96
+ "\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
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
108
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ "# 4. Print shape of one batch\n",
118
+ "X_batch, y_batch = next(iter(train_loader))\n",
119
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
120
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Get one batch of images and labels\n",
130
+ "images, labels = next(iter(train_loader))\n",
131
+ "\n",
132
+ "# Display the first 6 images in the batch\n",
133
+ "plt.figure(figsize=(8, 4))\n",
134
+ "\n",
135
+ "for i in range(6):\n",
136
+ " plt.subplot(2, 3, i + 1)\n",
137
+ "\n",
138
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
139
+ " img = images[i].permute(1, 2, 0)\n",
140
+ "\n",
141
+ " plt.imshow(img)\n",
142
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
143
+ " plt.axis('off')\n",
144
+ "\n",
145
+ "plt.tight_layout()\n",
146
+ "plt.show()"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Task 1: Write your model class here:\n",
156
+ "\n",
157
+ "class NN4Layer(nn.Module):\n",
158
+ "\n",
159
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
160
+ " super(NN4Layer, self).__init__()\n",
161
+ "\n",
162
+ " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
163
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
164
+ "\n",
165
+ " # TODO: What are the dimensions from previous and next layer?\n",
166
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
167
+ "\n",
168
+ " # TODO: What are the dimensions from previous and next layer?\n",
169
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
170
+ "\n",
171
+ " # TODO: What are the dimensions from previous and next layer?\n",
172
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
173
+ "\n",
174
+ " # TODO: What are the dimensions of previous and output layer? (hint: hidden neurons? num of classes?)\n",
175
+ "\n",
176
+ " # activation function for non-linearity\n",
177
+ " self.relu = nn.ReLU()\n",
178
+ "\n",
179
+ " # Defines how input data flows through the network\n",
180
+ " def forward(self, x):\n",
181
+ " # Layer 1: TODO\n",
182
+ " z1 = self.layer1(x)\n",
183
+ " a1 = self.relu(z1)\n",
184
+ "\n",
185
+ " # Layer 2 TODO\n",
186
+ " z2 = self.layer2(a1)\n",
187
+ " a2 = self.relu(z2)\n",
188
+ "\n",
189
+ " # Layer 3 TODO\n",
190
+ " z3 = self.layer3(a2)\n",
191
+ " a3 = self.relu(z3)\n",
192
+ "\n",
193
+ " # Layer 4 TODO\n",
194
+ " z4 = self.layer4(a3)\n",
195
+ "\n",
196
+ "\n",
197
+ " # TODO: are we missing output activation function? (hint: Loss Function)\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.to(device) # shape: (batch_size, num_features)\n",
218
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
219
+ "\n",
220
+ " # Forward pass\n",
221
+ " # TODO: make predictions\n",
222
+ " outputs = model(X_batch) # shape: (batch_size, 10)\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
+ " # Set the model to evaluation mode\n",
248
+ " model.eval()\n",
249
+ "\n",
250
+ " running_loss = 0.0\n",
251
+ "\n",
252
+ " with torch.no_grad():\n",
253
+ " for X_batch, y_batch in test_loader:\n",
254
+ " # Move data to device\n",
255
+ "\n",
256
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
257
+ " y_batch = y_batch.to(device)\n",
258
+ "\n",
259
+ " # Forward pass (continuous output)\n",
260
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
261
+ " loss = criterion(outputs, y_batch)\n",
262
+ "\n",
263
+ " running_loss += loss.item()\n",
264
+ "\n",
265
+ " # Average loss over all batches\n",
266
+ " avg_loss = running_loss / len(test_loader)\n",
267
+ "\n",
268
+ " return avg_loss"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task 4: Define device, model, loss, optimizer:\n",
278
+ "num_epochs = 20\n",
279
+ "learning_rate = 0.001\n",
280
+ "\n",
281
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
282
+ "\n",
283
+ "input_dim = 3*36*36\n",
284
+ "hidden_dim = 64\n",
285
+ "\n",
286
+ "model = NN4Layer(input_dim, hidden_dim,1).to(device)\n",
287
+ "\n",
288
+ "criterion = nn.MSELoss()\n",
289
+ "\n",
290
+ "optimizer = AdamW(model.parameters(), learning_rate)\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
+ "\n",
302
+ "train_losses = []\n",
303
+ "val_losses = []\n",
304
+ "\n",
305
+ "print('Starting Training...')\n",
306
+ "for epoch in range(num_epochs):\n",
307
+ " # Train one epoch\n",
308
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
309
+ "\n",
310
+ " # Validate\n",
311
+ " val_loss = validate(model, criterion, test_loader, device)\n",
312
+ "\n",
313
+ " train_losses.append(train_loss)\n",
314
+ " val_losses.append(val_loss)\n",
315
+ "\n",
316
+ " if (epoch + 1) % 5 == 0:\n",
317
+ " print(\n",
318
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
319
+ " f'Train Loss: {train_loss:.4f}, '\n",
320
+ " f'Val Loss: {val_loss:.4f}'\n",
321
+ " )\n",
322
+ "\n",
323
+ "print('Training Complete!')\n"
324
+ ],
325
+ "execution_count": null,
326
+ "outputs": []
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "metadata": {},
331
+ "source": [
332
+ "# Task 1: Write your code here:\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')\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
+ "metadata": {
350
+ "kernelspec": {
351
+ "display_name": "Python 3",
352
+ "name": "python3"
353
+ },
354
+ "language_info": {
355
+ "name": "python"
356
+ }
357
+ },
358
+ "nbformat": 4,
359
+ "nbformat_minor": 0
360
+ }
submissions_extracted/826/Q3.ipynb ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "import pandas as pd\n",
28
+ "import numpy as np\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "import seaborn as sns\n",
31
+ "import kagglehub\n",
32
+ "import os\n",
33
+ "from tqdm import tqdm\n",
34
+ "\n",
35
+ "\n",
36
+ "df = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_data.csv\")\n"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 2: Write your code here:\n",
46
+ "df.head(5)"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 3: Write your code here:\n",
56
+ "df.info()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 4: Write your code here:\n",
66
+ "df.describe()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 1: Write your code here:\n",
76
+ "# Task 2: Write your code here:\n",
77
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
78
+ "missing_data = pd.DataFrame({\n",
79
+ " 'Column': missing_percentage.index,\n",
80
+ " 'Missing_Percentage': missing_percentage.values\n",
81
+ "})\n",
82
+ "\n",
83
+ "missing_data.head(5)\n",
84
+ "\n",
85
+ "print(\"--------------/n\")\n",
86
+ "print(\"handeling the missing data\")\n",
87
+ "\n",
88
+ "for col in [df.columns]:\n",
89
+ " df[col] = df[col].fillna(df[col].mean())\n",
90
+ "\n",
91
+ "\n",
92
+ "\n",
93
+ "missing_data.head(5)\n",
94
+ "\n",
95
+ "\n",
96
+ "\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 2: Write your code here:\n",
106
+ "\n",
107
+ "def check_duplicates(df):\n",
108
+ " duplicates = df.duplicated().sum()\n",
109
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
110
+ " if duplicates > 0:\n",
111
+ " print(\"Dropping Duplicates...\")\n",
112
+ " df.drop_duplicates(inplace=True)\n",
113
+ " print(\"Duplicates Dropped.\")\n",
114
+ " else:\n",
115
+ " print(\"No Duplicate Samples Found.\")\n",
116
+ "\n",
117
+ "check_duplicates(df)"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# Task 3: Write your code here:\n",
127
+ "\n",
128
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
129
+ "\n",
130
+ "\n",
131
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
132
+ "for col in categorical_cols:\n",
133
+ " print(f\"Encoding column: {col}\")\n",
134
+ " le = LabelEncoder()\n",
135
+ " df[col] = le.fit_transform(df[col])\n",
136
+ "df"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 4: Write your code here:\n",
146
+ "\n",
147
+ "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
148
+ "\n",
149
+ "scaler = StandardScaler()\n",
150
+ "df[features] = scaler.fit_transform(df[features])\n",
151
+ "df.head()"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 5: Write your code here:\n",
161
+ "transmission_counts = df[\"Target\"].value_counts()\n",
162
+ "plt.figure(figsize=(10, 5))\n",
163
+ "plt.bar(transmission_counts.index, transmission_counts.values, color='teal')\n",
164
+ "plt.title('target Distribution')\n",
165
+ "plt.xticks(rotation=45)\n",
166
+ "plt.show()\n",
167
+ "\n",
168
+ "#there is imbalance"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 1: Write your code here:\n",
178
+ "\n",
179
+ "X = df.drop(\"Target\",axis=1)\n",
180
+ "y = df['Target']"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "! pip install catboost"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 2,3,4,5: Write your code here:\n",
199
+ "# Import models\n",
200
+ "from sklearn.neighbors import KNeighborsClassifier\n",
201
+ "from sklearn.svm import SVC\n",
202
+ "from sklearn.tree import DecisionTreeClassifier\n",
203
+ "from sklearn.ensemble import RandomForestClassifier\n",
204
+ "from xgboost import XGBClassifier\n",
205
+ "from catboost import CatBoostClassifier\n",
206
+ "\n",
207
+ "n_splits = 5 # K=5 Folds\n",
208
+ "\n",
209
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
210
+ "\n",
211
+ "Accuracy=[]\n",
212
+ "F1=[]\n",
213
+ "\n",
214
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
215
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
216
+ "\n",
217
+ " # 1. Split data\n",
218
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
219
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
220
+ "\n",
221
+ " model=CatBoostClassifier(\n",
222
+ " verbose=0,\n",
223
+ " n_estimators=320,\n",
224
+ " max_depth=4\n",
225
+ " )\n",
226
+ " model.fit(X_train, y_train)\n",
227
+ " y_pred = model.predict(X_test) # validate\n",
228
+ "\n",
229
+ " accuracy = accuracy_score(y_test, y_pred)\n",
230
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
231
+ "\n",
232
+ " Accuracy.append(accuracy)\n",
233
+ " F1.append(f1)\n",
234
+ "\n",
235
+ "\n",
236
+ "F1\n",
237
+ "ac_avrage=sum(Accuracy) / len(Accuracy)\n",
238
+ "\n",
239
+ "f1_avrage=sum(F1) / len(F1)\n",
240
+ "\n",
241
+ "print(f\"acc: {ac_avrage}\")\n",
242
+ "print(f\"F1: {f1_avrage}\")\n",
243
+ "\n",
244
+ "\n"
245
+ ],
246
+ "execution_count": null,
247
+ "outputs": []
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "metadata": {},
252
+ "source": [
253
+ "# Task 1: Write your code here:"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 2: Write your code here:"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {},
270
+ "source": [
271
+ "# Task Bonus: Write your code here:"
272
+ ],
273
+ "execution_count": null,
274
+ "outputs": []
275
+ }
276
+ ],
277
+ "metadata": {
278
+ "kernelspec": {
279
+ "display_name": "Python 3",
280
+ "name": "python3"
281
+ },
282
+ "language_info": {
283
+ "name": "python"
284
+ }
285
+ },
286
+ "nbformat": 4,
287
+ "nbformat_minor": 0
288
+ }
submissions_extracted/827/Q1.ipynb ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import numpy as np\n",
23
+ "import pandas as pd\n",
24
+ "import matplotlib.pyplot as plt\n",
25
+ "import os\n",
26
+ "import kagglehub\n",
27
+ "\n",
28
+ "path_csv = os.path.join(path, \"Q1_data.csv\")\n",
29
+ "df = pd.read_csv(path_csv)\n",
30
+ "print(df)"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# Task 2: Write your code here:\n",
40
+ "df.head()"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 3: Write your code here:\n",
50
+ "df.info()"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 4: Write your code here:\n",
60
+ "df.describe()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 5: Write your code here:\n",
70
+ "plt.figure(figsize=(10, 5))\n",
71
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
72
+ "plt.title('Target 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
+ "df = df.drop('Order_ID', axis=1)\n",
85
+ "df.head()"
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
+ "\n",
96
+ "null_col = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\"]\n",
97
+ "df[null_col]= df[null_col].fillna('unknown')\n",
98
+ "\n",
99
+ "null_nums = [\"Courier_Experience_yrs\",\t\"Delivery_Time\"]\n",
100
+ "df[null_nums]= df[null_nums].fillna(np.mean(df[null_nums]))\n",
101
+ "print(df.isnull().sum())\n"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# Task 3: Write your code here:\n",
111
+ "print(df.duplicated().sum())\n",
112
+ "df.drop_duplicates(inplace=True)\n",
113
+ "print(df.duplicated().sum())\n",
114
+ "\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# Task 4: Write your code here:\n",
124
+ "from sklearn.preprocessing import OneHotEncoder, LabelEncoder\n",
125
+ "categorical_cols=['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
126
+ "print(categorical_cols)\n",
127
+ "label = LabelEncoder()\n",
128
+ "for cate in categorical_cols:\n",
129
+ " df[cate]= label.fit_transform(df[cate])\n",
130
+ "\n",
131
+ "df.head(50)\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
+ "from sklearn.preprocessing import StandardScaler\n",
142
+ "features = df.drop('Delivery_Time', axis=1).columns\n",
143
+ "scaler = StandardScaler()\n",
144
+ "df[features] = scaler.fit_transform(df[features])\n"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 6: Write your code here:"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 1: Write your code here:\n",
163
+ "\n",
164
+ "X= df.drop('Delivery_Time', axis=1)\n",
165
+ "y= df[\"Delivery_Time\"]\n",
166
+ "\n",
167
+ "from sklearn.model_selection import KFold\n",
168
+ "\n",
169
+ "\n",
170
+ "\n",
171
+ "\n",
172
+ ""
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 2,3,4,5: Write your code here:\n",
182
+ "# Train Random Forest Regressor\n",
183
+ "from sklearn.ensemble import RandomForestRegressor\n",
184
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
185
+ "from sklearn.model_selection import KFold\n",
186
+ "\n",
187
+ "\n",
188
+ "# Define K-Fold Cross Validation\n",
189
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
190
+ "\n",
191
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
192
+ "\n",
193
+ "mae_scores=[]\n",
194
+ "# Iterate through folds\n",
195
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
196
+ " # indexing for each fold\n",
197
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
198
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
199
+ " model.fit(X_train, y_train)\n",
200
+ " pred = model.predict(X_test)\n",
201
+ "\n",
202
+ " mae_scores.append(mean_absolute_error(y_test,pred))\n",
203
+ "mae_scores = np.array(mae_scores)\n",
204
+ "print(f\"5-Fold CV Results:\")\n",
205
+ "print(f\"MAE: {mae_scores.mean():,.2f}\")\n"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 1: Write your code here:\n",
215
+ "feature_importance = pd.DataFrame({\n",
216
+ " 'feature': X.columns,\n",
217
+ " 'importance': model.feature_importances_\n",
218
+ "}).sort_values('importance', ascending=False)\n",
219
+ "\n",
220
+ "plt.figure(figsize=(10, 6))\n",
221
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
222
+ "plt.xlabel('Importance')\n",
223
+ "plt.title('Feature Importance')\n",
224
+ "plt.gca().invert_yaxis()\n",
225
+ "plt.show()"
226
+ ],
227
+ "execution_count": null,
228
+ "outputs": []
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "# Task 2: Write your code here:\n",
235
+ "plt.figure(figsize=(10, 5))\n",
236
+ "plt.hist(pred, bins=50, edgecolor='black')\n",
237
+ "plt.title('Target Distribution')\n",
238
+ "\n",
239
+ "plt.show()"
240
+ ],
241
+ "execution_count": null,
242
+ "outputs": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "metadata": {},
247
+ "source": [
248
+ "# Task Bonus: Write your code here:"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": []
252
+ }
253
+ ],
254
+ "metadata": {
255
+ "kernelspec": {
256
+ "display_name": "Python 3",
257
+ "name": "python3"
258
+ },
259
+ "language_info": {
260
+ "name": "python"
261
+ }
262
+ },
263
+ "nbformat": 4,
264
+ "nbformat_minor": 0
265
+ }
submissions_extracted/827/Q2.ipynb ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 kagglehub\n",
70
+ "import pandas as pd\n",
71
+ "import torch\n",
72
+ "import torch.nn as nn\n",
73
+ "from torch.optim import AdamW\n",
74
+ "import matplotlib.pyplot as plt\n",
75
+ "import torch.nn.functional as F\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
+ "\n",
80
+ "\n",
81
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
82
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
83
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
84
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
85
+ "\n",
86
+ "labels_df.head()\n",
87
+ "target= labels_df['age']"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# 2. Create TensorDataset objects\n",
97
+ "train_dataset = TensorDataset(X_train, y_train)\n",
98
+ "test_dataset = TensorDataset(X_test, y_test)\n",
99
+ "\n"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# 3. Create DataLoaders\n",
109
+ "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
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# 4. Print shape of one batch\n",
122
+ "X_batch, y_batch = next(iter(train_loader))\n",
123
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
124
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# 5. Display sample images\n",
134
+ "# Get one batch of images and labels\n",
135
+ "images, labels = next(iter(train_loader))\n",
136
+ "\n",
137
+ "# Display the first 6 images in the batch\n",
138
+ "plt.figure(figsize=(8, 4))\n",
139
+ "\n",
140
+ "for i in range(6):\n",
141
+ " plt.subplot(2, 3, i + 1)\n",
142
+ "\n",
143
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
144
+ " img = images[i].permute(1, 2, 0)\n",
145
+ "\n",
146
+ " plt.imshow(img)\n",
147
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
148
+ " plt.axis('off')\n",
149
+ "\n",
150
+ "plt.tight_layout()\n",
151
+ "plt.show()"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 1: Write your model class here:\n",
161
+ "class NN4Layer(nn.Module):\n",
162
+ "\n",
163
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
164
+ " super(NN4Layer, self).__init__()\n",
165
+ "\n",
166
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
167
+ "\n",
168
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
169
+ "\n",
170
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
171
+ "\n",
172
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
173
+ "\n",
174
+ " self.relu = nn.ReLU()\n",
175
+ "\n",
176
+ " def forward(self, x):\n",
177
+ " # Layer 1: TODO\n",
178
+ " z1 = self.layer1(x)\n",
179
+ " a1 = self.relu(z1)\n",
180
+ "\n",
181
+ " # Layer 2 TODO\n",
182
+ " z2 = self.layer2(a1)\n",
183
+ " a2 = self.relu(z2)\n",
184
+ "\n",
185
+ " # Layer 3 TODO\n",
186
+ " z3 = self.layer3(a2)\n",
187
+ " a3 = self.relu(z3)\n",
188
+ "\n",
189
+ " # Output layer TODO\n",
190
+ " z4 = self.layer4(a3)\n",
191
+ "\n",
192
+ "\n",
193
+ " return z4"
194
+ ],
195
+ "execution_count": null,
196
+ "outputs": []
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "metadata": {},
201
+ "source": [
202
+ "# Task 2: Write your training loop here:\n",
203
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\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
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
210
+ " y_batch = y_batch.view(y_batch.size(0), 1).to(device)\n",
211
+ "\n",
212
+ " # Forward pass\n",
213
+ " # TODO: make predictions\n",
214
+ " outputs = model(X_batch)\n",
215
+ " # TODO: compute loss\n",
216
+ " loss = criterion(outputs, y_batch)\n",
217
+ "\n",
218
+ " # Backward pass & optimization\n",
219
+ " optimizer.zero_grad() # Clear previous gradients\n",
220
+ " loss.backward() # Compute gradients\n",
221
+ " optimizer.step() # Update model parameters\n",
222
+ "\n",
223
+ " running_loss += loss.item()\n",
224
+ "\n",
225
+ " # Average loss over all batches\n",
226
+ " avg_loss = running_loss / len(train_loader)\n",
227
+ "\n",
228
+ " return avg_loss"
229
+ ],
230
+ "execution_count": null,
231
+ "outputs": []
232
+ },
233
+ {
234
+ "cell_type": "code",
235
+ "metadata": {},
236
+ "source": [
237
+ "# Task 3: Write your validation loop here:\n",
238
+ "def validate(model, criterion, test_loader, device):\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.view(y_batch.size(0), 1).to(device)\n",
250
+ "\n",
251
+ " # Forward pass\n",
252
+ " # TODO: make predictions\n",
253
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
254
+ " # TODO: compute loss\n",
255
+ " loss = criterion(outputs, y_batch)\n",
256
+ " running_loss += loss.item()\n",
257
+ "\n",
258
+ " # TODO: Apply Softmax to get probabilities\n",
259
+ " probabilities = F.mse_loss(outputs,target)\n",
260
+ "\n",
261
+ " # TODO: Multiclass predictions\n",
262
+ "\n",
263
+ " # Accuracy calculation\n",
264
+ " total += y_batch.size(0)\n",
265
+ "\n",
266
+ " avg_loss = running_loss / len(test_loader)\n",
267
+ "\n",
268
+ " return avg_loss, probabilities\n"
269
+ ],
270
+ "execution_count": null,
271
+ "outputs": []
272
+ },
273
+ {
274
+ "cell_type": "code",
275
+ "metadata": {},
276
+ "source": [
277
+ "# Task 4: Define device, model, loss, optimizer:\n",
278
+ "# Device setup\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 # flattened (RGB)\n",
284
+ "\n",
285
+ "# TODO: choose number of hidden neurons\n",
286
+ "hidden_dim = 40 # Design choice\n",
287
+ "\n",
288
+ "# TODO: what are the number of classes ?\n",
289
+ "output_dim = 1 # CIFAR-10 classes\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}\")\n",
301
+ "\n",
302
+ "# TODO: choose number of epochs, increase it if you have gpus :)\n",
303
+ "num_epochs = 20\n",
304
+ "# TODO: choose a learning rate (try different values and evaluate results)\n",
305
+ "learning_rate = 0.001\n",
306
+ "\n",
307
+ "criterion = nn.MSELoss()\n",
308
+ "optimizer = AdamW(model.parameters(), learning_rate)"
309
+ ],
310
+ "execution_count": null,
311
+ "outputs": []
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "metadata": {},
316
+ "source": [
317
+ "# Task 5: Start training for 20 epochs:\n",
318
+ "# 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
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.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
+ "# Plotting results\n",
346
+ "plt.figure(figsize=(7, 5))\n",
347
+ "\n",
348
+ "plt.plot(train_losses, label='Train Loss')\n",
349
+ "plt.plot(val_losses, label='Validation Loss')\n",
350
+ "plt.title('Loss over Epochs')\n",
351
+ "plt.xlabel('Epoch')\n",
352
+ "plt.ylabel('Loss')\n",
353
+ "plt.legend()\n",
354
+ "\n",
355
+ "plt.tight_layout()\n",
356
+ "plt.show()"
357
+ ],
358
+ "execution_count": null,
359
+ "outputs": []
360
+ },
361
+ {
362
+ "cell_type": "code",
363
+ "metadata": {},
364
+ "source": [
365
+ "# Task 2 (Bonus): Write your code here:"
366
+ ],
367
+ "execution_count": null,
368
+ "outputs": []
369
+ }
370
+ ],
371
+ "metadata": {
372
+ "kernelspec": {
373
+ "display_name": "Python 3",
374
+ "name": "python3"
375
+ },
376
+ "language_info": {
377
+ "name": "python"
378
+ }
379
+ },
380
+ "nbformat": 4,
381
+ "nbformat_minor": 0
382
+ }
submissions_extracted/827/Q3.ipynb ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "\n",
13
+ "\n",
14
+ "# Download latest version\n",
15
+ "\n",
16
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
17
+ "\n",
18
+ "\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "# Task 1: Write your code here:\n",
30
+ "path_csv = os.path.join(path,'Q3_data.csv')\n",
31
+ "df = pd.read_csv(path_csv)\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "df.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
+ "print(df.info())"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 4: Write your code here:\n",
61
+ "df.describe()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 1: Write your code here:\n",
71
+ "print(df.isna().sum())\n",
72
+ "col = df.isna().columns\n",
73
+ "print(col)\n",
74
+ "df[col] = df[col].fillna(np.mean(df[col]))"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 2: Write your code here:\n",
84
+ "print(df.duplicated().sum())\n",
85
+ "df.drop_duplicates(inplace=True)\n",
86
+ "print(df.duplicated().sum())"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 3: Write your code here:\n",
96
+ "obj = df.select_dtypes(include=['object']).columns\n",
97
+ "print(obj)"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 4: Write your code here:"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 5: Write your code here:"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# Task 1: Write your code here:"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 2,3,4,5: Write your code here:"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 1: Write your code here:"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 2: Write your code here:"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task Bonus: Write your code here:"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ }
165
+ ],
166
+ "metadata": {
167
+ "kernelspec": {
168
+ "display_name": "Python 3",
169
+ "name": "python3"
170
+ },
171
+ "language_info": {
172
+ "name": "python"
173
+ }
174
+ },
175
+ "nbformat": 4,
176
+ "nbformat_minor": 0
177
+ }
submissions_extracted/828/Q1.ipynb ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "import matplotlib.pyplot as plt\n",
25
+ "import seaborn as sns\n",
26
+ "import kagglehub\n",
27
+ "import os\n",
28
+ "\n",
29
+ "print(os.listdir(path))\n",
30
+ "csv_path = os.path.join(path,\"Q1_data.csv\")\n",
31
+ "df = pd.read_csv(csv_path)\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "df.head()"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 3: Write your code here:\n",
51
+ "df.info()"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 4: Write your code here:\n",
61
+ "df.describe()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 5: Write your code here:\n",
71
+ "def check_target_distribution(df, target_column):\n",
72
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
73
+ "\n",
74
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
75
+ " plt.xlabel(target_column)\n",
76
+ " plt.ylabel(\"Frequency\")\n",
77
+ " plt.grid(False)\n",
78
+ "\n",
79
+ " plt.show()\n",
80
+ "\n",
81
+ "check_target_distribution(df, \"Delivery_Time\")\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 1: Write your code here:\n",
91
+ "df.drop(columns=['Order_ID'], inplace=True)"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 2: Write your code here:\n",
101
+ "def check_missing_values(df):\n",
102
+ " missing_values = df.isnull().sum()\n",
103
+ " print(\"Missing Values per Column:\")\n",
104
+ " missing_data = missing_values[missing_values > 0]\n",
105
+ "\n",
106
+ " if not missing_data.empty:\n",
107
+ " percentage = (missing_data / len(df)) * 100\n",
108
+ " result = pd.concat([missing_data, percentage], axis=1, keys=['Count', 'Percentage'])\n",
109
+ " print(result[result['Count'] > 0].round(2))\n",
110
+ " print(\"\\nHandle Missing Values as needed.\")\n",
111
+ " else:\n",
112
+ " print(\"\\nNo Missing Values Found.\")\n",
113
+ "check_missing_values(df)"
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
+ "df['Weather'].fillna(df['Weather'].mode()[0], inplace=True)\n",
124
+ "df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0], inplace=True)\n",
125
+ "df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0], inplace=True)\n",
126
+ "df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean(), inplace=True)\n",
127
+ "df['Delivery_Time'].fillna(df['Delivery_Time'].mean(), inplace=True)\n"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "df.isnull().sum()"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 3: Write your code here:\n",
146
+ "# Do we have duplicate samples?\n",
147
+ "def check_duplicates(df):\n",
148
+ " duplicates = df.duplicated().sum()\n",
149
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
150
+ " if duplicates > 0:\n",
151
+ " print(\"Dropping Duplicates...\")\n",
152
+ " df.drop_duplicates(inplace=True)\n",
153
+ " print(\"Duplicates Dropped.\")\n",
154
+ " else:\n",
155
+ " print(\"No Duplicate Samples Found.\")\n",
156
+ "\n",
157
+ "\n",
158
+ "check_duplicates(df)"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 4: Write your code here:\n",
168
+ "from sklearn.preprocessing import OneHotEncoder\n",
169
+ "# Do we have categorical columns?\n",
170
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
171
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
172
+ "\n",
173
+ "\n"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "pd.get_dummies(df, columns=['Weather','Traffic_Level','Time_of_Day','Vehicle_Type'], drop_first=True)"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "df.head()"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task 5: Write your code here:\n",
201
+ "from sklearn.preprocessing import MinMaxScaler\n",
202
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
203
+ "scaler = MinMaxScaler()\n",
204
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
205
+ "df"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 6: Write your code here:\n",
215
+ "# 1. Is the target imbalanced?\n",
216
+ "def check_target_imbalance(df, target_column):\n",
217
+ " print(\"Target Distribution:\")\n",
218
+ "\n",
219
+ " df[target_column].hist() # Yeah you can just do this :)\n",
220
+ " plt.show()\n",
221
+ "\n",
222
+ "check_target_imbalance(df, \"Delivery_Time\")\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:\n",
232
+ "X = df.drop(\"Delivery_Time\",axis=1)\n",
233
+ "y = df['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
+ "from sklearn.model_selection import KFold\n",
244
+ "from sklearn.metrics import mean_absolute_error\n",
245
+ "from sklearn.ensemble import RandomForestRegressor\n",
246
+ "\n",
247
+ "model = RandomForestRegressor(n_estimators=200)\n",
248
+ "# 5-Fold Cross-Validation, shuffled\n",
249
+ "\n",
250
+ "scores_mae=[]\n",
251
+ "n_splits = 5 # K=5 Folds\n",
252
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
253
+ "\n",
254
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
255
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
256
+ "\n",
257
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
258
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
259
+ "\n",
260
+ "\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
+ "\n",
270
+ " scores_mae.append(mean_absolute_error(y_test, y_pred))\n",
271
+ "\n",
272
+ "\n",
273
+ " # Store results\n",
274
+ " print(f\"{model} MAE Score: {np.mean(scores_mae)}\")\n",
275
+ "\n",
276
+ "\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
+ "\n",
287
+ "\n",
288
+ "importances = {}\n",
289
+ "\n",
290
+ "importances['Random Forest'] = model.feature_importances_\n",
291
+ "# Create a 1x3 plot\n",
292
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
293
+ "axes = axes.flatten()\n",
294
+ "features = X.columns\n",
295
+ "\n",
296
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
297
+ " # Sort features by importance for a cleaner plot\n",
298
+ " sorted_idx = np.argsort(imp)\n",
299
+ "\n",
300
+ " ax = axes[i]\n",
301
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
302
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
303
+ " ax.set_xlabel(\"Importance Score\")\n",
304
+ "\n",
305
+ "plt.tight_layout()\n",
306
+ "plt.show()"
307
+ ],
308
+ "execution_count": null,
309
+ "outputs": []
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "metadata": {},
314
+ "source": [],
315
+ "execution_count": null,
316
+ "outputs": []
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "metadata": {},
321
+ "source": [
322
+ "# Task Bonus: Write your code here:"
323
+ ],
324
+ "execution_count": null,
325
+ "outputs": []
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "metadata": {},
330
+ "source": [
331
+ "# Calculate the baseline predictions (mean of the target)\n",
332
+ "baseline_pred = np.full_like(y, y.mean())\n",
333
+ "\n",
334
+ "# Evaluate the baseline\n",
335
+ "baseline_mae = mean_absolute_error(y, baseline_pred)\n",
336
+ "\n",
337
+ "print(f\"Baseline MAE (using mean target): {baseline_mae:.4f}\")"
338
+ ],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ }
342
+ ],
343
+ "metadata": {
344
+ "kernelspec": {
345
+ "display_name": "Python 3",
346
+ "name": "python3"
347
+ },
348
+ "language_info": {
349
+ "name": "python"
350
+ }
351
+ },
352
+ "nbformat": 4,
353
+ "nbformat_minor": 0
354
+ }
submissions_extracted/828/Q2.ipynb ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 kagglehub\n",
69
+ "import pandas as pd\n",
70
+ "import torch\n",
71
+ "import torch.nn as nn\n",
72
+ "from torch.optim import AdamW\n",
73
+ "import matplotlib.pyplot as plt\n",
74
+ "import torch.nn.functional as F\n",
75
+ "from torch.utils.data import DataLoader, TensorDataset\n",
76
+ "from sklearn.model_selection import train_test_split\n",
77
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
78
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
79
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
80
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
81
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
82
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# 2. Create TensorDataset objects\n",
92
+ "train_dataset = TensorDataset(X_train, y_train)\n",
93
+ "test_dataset = TensorDataset(X_test, y_test)\n",
94
+ "\n",
95
+ "\n"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# 3. Create DataLoaders\n",
105
+ "\n",
106
+ "from torch.utils.data import DataLoader\n",
107
+ "\n",
108
+ "# DataLoader for training data\n",
109
+ "train_loader = DataLoader(\n",
110
+ " train_dataset,\n",
111
+ " batch_size=32,\n",
112
+ " shuffle=True,\n",
113
+ " num_workers=2\n",
114
+ ")\n",
115
+ "# DataLoader for test/validation data\n",
116
+ "test_loader = DataLoader(\n",
117
+ " test_dataset,\n",
118
+ " batch_size=32,\n",
119
+ " shuffle=False,\n",
120
+ " num_workers=2\n",
121
+ ")\n",
122
+ "\n"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# 4. Print shape of one batch\n",
132
+ "\n",
133
+ "# Get the first batch from the training DataLoader\n",
134
+ "X_batch, y_batch = next(iter(train_loader))\n",
135
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
136
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# 5. Display sample images\n",
146
+ "# Get one batch of images and labels\n",
147
+ "images, labels = next(iter(train_loader))\n",
148
+ "\n",
149
+ "# Display the first 6 images in the batch\n",
150
+ "plt.figure(figsize=(8, 4))\n",
151
+ "\n",
152
+ "for i in range(6):\n",
153
+ " plt.subplot(2, 3, i + 1)\n",
154
+ " plt.imshow(images[i].permute(1, 2, 0))\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()\n"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "class NN4Layer(nn.Module):\n",
169
+ "\n",
170
+ " def __init__(self, input_dim, hidden_dim):\n",
171
+ " super(NN4Layer, self).__init__()\n",
172
+ "\n",
173
+ " # First linear layer: input features -> hidden layer\n",
174
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
175
+ "\n",
176
+ " # Second linear layer: hidden layer -> hidden layer\n",
177
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
178
+ "\n",
179
+ " # Third linear layer: hidden layer -> hidden layer\n",
180
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
181
+ "\n",
182
+ " # Output layer: hidden layer -> number of classes (logits)\n",
183
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
184
+ "\n",
185
+ " # ReLU activation for non-linearity\n",
186
+ " self.relu = nn.ReLU()\n",
187
+ "\n",
188
+ " # Defines how input data flows through the network\n",
189
+ " def forward(self, x):\n",
190
+ " # First hidden layer\n",
191
+ " a1 = self.relu(self.layer1(x))\n",
192
+ "\n",
193
+ " # Second hidden layer\n",
194
+ " a2 = self.relu(self.layer2(a1))\n",
195
+ "\n",
196
+ " # Third hidden layer\n",
197
+ " a3 = self.relu(self.layer3(a2))\n",
198
+ "\n",
199
+ " # Output layer (linear output)\n",
200
+ " output = self.layer4(a3)\n",
201
+ "\n",
202
+ " return output"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
212
+ " # Set the model to training mode\n",
213
+ " model.train()\n",
214
+ "\n",
215
+ " running_loss = 0.0\n",
216
+ "\n",
217
+ " for X_batch, y_batch in train_loader:\n",
218
+ " # Move batch to the selected device\n",
219
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
220
+ " y_batch = y_batch.to(device)\n",
221
+ "\n",
222
+ " # Forward pass (continuous output)\n",
223
+ " outputs = model(X_batch) # shape: (batch_size, 1)\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
+ " # Set the model to evaluation mode\n",
248
+ " model.eval()\n",
249
+ "\n",
250
+ " running_loss = 0.0\n",
251
+ "\n",
252
+ " with torch.no_grad():\n",
253
+ " for X_batch, y_batch in test_loader:\n",
254
+ " # Move data to device\n",
255
+ " X_batch = X_batch.to(device).view(X_batch.size(0), -1).to(device) # shape: (batch_size, num_features)\n",
256
+ " y_batch = y_batch.to(device) # shape: (batch_size, 1)\n",
257
+ "\n",
258
+ " # Forward pass (continuous output)\n",
259
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
260
+ " loss = criterion(outputs, y_batch)\n",
261
+ "\n",
262
+ " running_loss += loss.item()\n",
263
+ "\n",
264
+ " # Average loss over all batches\n",
265
+ " avg_loss = running_loss / len(test_loader)\n",
266
+ "\n",
267
+ " return avg_loss"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task 4: Define device, model, loss, optimizer:\n",
277
+ "\n",
278
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
279
+ "\n",
280
+ "input_dim = 3*36*36 # Number of tabular features\n",
281
+ "hidden_dim = 256 # Design choice\n",
282
+ "\n",
283
+ "# Instantiate regression model\n",
284
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
285
+ "\n",
286
+ "# Print the model architecture\n",
287
+ "print(\"Model Architecture:\\n\")\n",
288
+ "print(model)\n",
289
+ "\n",
290
+ "# Calculate the total number of trainable parameters\n",
291
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
292
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
293
+ "\n",
294
+ "# Hyperparameters\n",
295
+ "num_epochs = 80\n",
296
+ "learning_rate = 0.0001\n",
297
+ "\n",
298
+ "# criterion (loss function)\n",
299
+ "criterion = nn.MSELoss()\n",
300
+ "# optimizer\n",
301
+ "optimizer = AdamW(model.parameters(), learning_rate)"
302
+ ],
303
+ "execution_count": null,
304
+ "outputs": []
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "metadata": {},
309
+ "source": [
310
+ "# Task 5: Start training for 20 epochs:\n",
311
+ "# Run Training\n",
312
+ "train_losses = []\n",
313
+ "val_losses = []\n",
314
+ "\n",
315
+ "print('Starting Training...')\n",
316
+ "for epoch in range(num_epochs):\n",
317
+ " # Train one epoch\n",
318
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
319
+ "\n",
320
+ " # Validate\n",
321
+ " val_loss = validate(model, criterion, test_loader, device)\n",
322
+ "\n",
323
+ " train_losses.append(train_loss)\n",
324
+ " val_losses.append(val_loss)\n",
325
+ "\n",
326
+ " if (epoch + 1) % 5 == 0:\n",
327
+ " print(\n",
328
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
329
+ " f'Train Loss: {train_loss:.4f}, '\n",
330
+ " f'Val Loss: {val_loss:.4f}'\n",
331
+ " )\n",
332
+ "\n",
333
+ "print('Training Complete!')"
334
+ ],
335
+ "execution_count": null,
336
+ "outputs": []
337
+ },
338
+ {
339
+ "cell_type": "code",
340
+ "metadata": {},
341
+ "source": [
342
+ "# Task 1: Write your code here:\n",
343
+ "# Plotting results\n",
344
+ "plt.figure(figsize=(7, 5))\n",
345
+ "\n",
346
+ "plt.plot(train_losses, label='Train Loss')\n",
347
+ "plt.plot(val_losses, label='Validation Loss')\n",
348
+ "plt.title('Loss over Epochs')\n",
349
+ "plt.xlabel('Epoch')\n",
350
+ "plt.ylabel('Loss')\n",
351
+ "plt.legend()\n",
352
+ "\n",
353
+ "plt.tight_layout()\n",
354
+ "plt.show()"
355
+ ],
356
+ "execution_count": null,
357
+ "outputs": []
358
+ },
359
+ {
360
+ "cell_type": "code",
361
+ "metadata": {},
362
+ "source": [
363
+ "# Task 2 (Bonus): Write your code here:\n",
364
+ "# Set model to evaluation mode\n",
365
+ "model.eval()\n",
366
+ "# Get one batch from the test DataLoader\n",
367
+ "images, labels = next(iter(test_loader))\n",
368
+ "# Move images to device\n",
369
+ "images = images.to(device)\n",
370
+ "labels = labels.to(device)\n",
371
+ "\n",
372
+ "with torch.no_grad():\n",
373
+ " # Flatten images before passing to the model\n",
374
+ " prediction = model(images.view(images.size(0), -1))\n",
375
+ "\n",
376
+ "# Move tensors back to CPU for plotting\n",
377
+ "images = images.cpu()\n",
378
+ "labels = labels.cpu()\n",
379
+ "prediction = prediction.cpu()\n",
380
+ "\n",
381
+ "# Plot first 6 predictions\n",
382
+ "plt.figure(figsize=(8, 4))\n",
383
+ "for i in range(6):\n",
384
+ " plt.subplot(2, 3, i + 1)\n",
385
+ " plt.imshow(images[i].permute(1, 2, 0))\n",
386
+ " plt.title(f\"True: {labels[i]} | Pred: {prediction[i]}\")\n",
387
+ " plt.axis('off')\n",
388
+ "\n",
389
+ "plt.tight_layout()\n",
390
+ "plt.show()"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "metadata": {},
398
+ "source": [],
399
+ "execution_count": null,
400
+ "outputs": []
401
+ }
402
+ ],
403
+ "metadata": {
404
+ "kernelspec": {
405
+ "display_name": "Python 3",
406
+ "name": "python3"
407
+ },
408
+ "language_info": {
409
+ "name": "python"
410
+ }
411
+ },
412
+ "nbformat": 4,
413
+ "nbformat_minor": 0
414
+ }
submissions_extracted/828/Q3.ipynb ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "!pip install catboost\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "import pandas as pd\n",
28
+ "import numpy as np\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "import seaborn as sns\n",
31
+ "import kagglehub\n",
32
+ "import os\n",
33
+ "\n",
34
+ "print(os.listdir(path))\n",
35
+ "csv_path = os.path.join(path,\"Q3_data.csv\")\n",
36
+ "df = pd.read_csv(csv_path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 2: Write your code here:\n",
46
+ "df.head()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "df.shape"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 3: Write your code here:\n",
65
+ "df.info()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 4: Write your code here:\n",
75
+ "df.describe()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 1: Write your code here:\n",
85
+ "def check_missing_values(df):\n",
86
+ " missing_values = df.isnull().sum()\n",
87
+ " print(\"Missing Values per Column:\")\n",
88
+ " missing_data = missing_values[missing_values > 1000]\n",
89
+ " print(missing_data.index)\n",
90
+ "\n",
91
+ " if not missing_data.empty:\n",
92
+ " percentage = (missing_data / len(df)) * 100\n",
93
+ " result = pd.concat([missing_data, percentage], axis=1, keys=['Count', 'Percentage'])\n",
94
+ " print(result[result['Count'] > 0].round(2))\n",
95
+ " print(\"\\nHandle Missing Values as needed.\")\n",
96
+ " else:\n",
97
+ " print(\"\\nNo Missing Values Found.\")\n",
98
+ "check_missing_values(df)\n",
99
+ "\n",
100
+ "\n"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "\n",
110
+ "for col in df.columns:\n",
111
+ " if df[col].isnull().any():\n",
112
+ " df[col] = df[col].fillna(df[col].median())"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "df.shape"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your code here:\n",
131
+ "def check_duplicates(df):\n",
132
+ " duplicates = df.duplicated().sum()\n",
133
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
134
+ " if duplicates > 0:\n",
135
+ " print(\"Dropping Duplicates...\")\n",
136
+ " df.drop_duplicates(inplace=True)\n",
137
+ " print(\"Duplicates Dropped.\")\n",
138
+ " else:\n",
139
+ " print(\"No Duplicate Samples Found.\")\n",
140
+ "\n",
141
+ "\n",
142
+ "check_duplicates(df)"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 3: Write your code here:\n",
152
+ "from sklearn.preprocessing import LabelEncoder\n",
153
+ "\n",
154
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
155
+ "for col in categorical_cols:\n",
156
+ " print(f\"Encoding column: {col}\")\n",
157
+ " le = LabelEncoder()\n",
158
+ " df[col] = le.fit_transform(df[col])\n",
159
+ "df.head()"
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 StandardScaler\n",
170
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
171
+ "scaler = StandardScaler()\n",
172
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
173
+ "df.head()\n"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task 5: Write your code here:\n",
183
+ "#The target is imbalance\n",
184
+ "def check_target_imbalance(df, target_column):\n",
185
+ " print(\"Target Distribution:\")\n",
186
+ "\n",
187
+ " df[target_column].hist() # Yeah you can just do this :)\n",
188
+ " plt.show()\n",
189
+ "\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
+ "# Task 2,3,4,5: Write your code here:\n",
211
+ "from sklearn.model_selection import StratifiedKFold\n",
212
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
213
+ "from catboost import CatBoostClassifier\n",
214
+ "\n",
215
+ "model = CatBoostClassifier(\n",
216
+ " verbose=0,\n",
217
+ " n_estimators=320,\n",
218
+ " max_depth=4\n",
219
+ ")\n",
220
+ "# 5-Fold Cross-Validation, shuffled\n",
221
+ "\n",
222
+ "accuracys=[]\n",
223
+ "f1s=[]\n",
224
+ "n_splits = 5 # K=5 Folds\n",
225
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
226
+ "\n",
227
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X)):\n",
228
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
229
+ "\n",
230
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
231
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
232
+ "\n",
233
+ "\n",
234
+ "\n",
235
+ " # Train\n",
236
+ " model.fit(X_train, y_train)\n",
237
+ "\n",
238
+ " # Predict\n",
239
+ " y_pred = model.predict(X_test)\n",
240
+ "\n",
241
+ " # Calculate metrics\n",
242
+ "\n",
243
+ " accuracy = accuracy_score(y_test, y_pred)\n",
244
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
245
+ " accuracys.append(accuracy)\n",
246
+ " f1s.append(f1)\n",
247
+ " # Store results\n",
248
+ " print(f\"{model} Accuracy: {np.mean(accuracys)}\")\n",
249
+ " print(f\"{model} F1-Score: {np.mean(f1s)}\")"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "metadata": {},
257
+ "source": [
258
+ "# Task 1: Write your code here:\n",
259
+ "# Task 1: Write your code here:\n",
260
+ "\n",
261
+ "\n",
262
+ "importances = {}\n",
263
+ "\n",
264
+ "importances['CatBoost'] = model.feature_importances_\n",
265
+ "# Create a 1x3 plot\n",
266
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
267
+ "axes = axes.flatten()\n",
268
+ "features = X.columns\n",
269
+ "\n",
270
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
271
+ " # Sort features by importance for a cleaner plot\n",
272
+ " sorted_idx = np.argsort(imp)\n",
273
+ "\n",
274
+ " ax = axes[i]\n",
275
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
276
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
277
+ " ax.set_xlabel(\"Importance Score\")\n",
278
+ "\n",
279
+ "plt.tight_layout()\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:"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Task Bonus: Write your code here:"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ }
303
+ ],
304
+ "metadata": {
305
+ "kernelspec": {
306
+ "display_name": "Python 3",
307
+ "name": "python3"
308
+ },
309
+ "language_info": {
310
+ "name": "python"
311
+ }
312
+ },
313
+ "nbformat": 4,
314
+ "nbformat_minor": 0
315
+ }
submissions_extracted/829/Q1.ipynb ADDED
@@ -0,0 +1,347 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Import Libraries\n",
8
+ "%pip install catboost\n",
9
+ "import kagglehub\n",
10
+ "import pandas as pd\n",
11
+ "import os\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "import seaborn as sns\n",
14
+ "import numpy as np\n",
15
+ "from sklearn.preprocessing import StandardScaler, OneHotEncoder\n",
16
+ "from sklearn.model_selection import train_test_split, KFold\n",
17
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error\n",
18
+ "from sklearn.ensemble import RandomForestRegressor\n",
19
+ "from catboost import CatBoostRegressor\n",
20
+ "# Download latest version\n",
21
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
22
+ "\n",
23
+ "print(\"Path to dataset files:\", path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 1: Write your code here:\n",
33
+ "\n",
34
+ "df_path = os.path.join(path, 'Q1_data.csv')\n",
35
+ "df = pd.read_csv(df_path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 2: Write your code here:\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 3: Write your code here:\n",
55
+ "df.info()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 4: Write your code here:\n",
65
+ "df.describe()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 5: Write your code here:\n",
75
+ "plt.figure(figsize=(10, 5))\n",
76
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
77
+ "plt.title('Delivery Time Distribution')\n",
78
+ "plt.xlabel('Delivery Time')\n",
79
+ "plt.ylabel('Frequency')\n",
80
+ "plt.show()"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 1: Write your code here:\n",
90
+ "print(f\"Before: {df.shape}\")\n",
91
+ "\n",
92
+ "df = df.drop('Order_ID', axis=1)\n",
93
+ "print(f\"After dropping the column: {df.shape}\")"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 2: Write your code here:\n",
103
+ "missing_values = df.isnull().sum()\n",
104
+ "print(\"Columns with missing values:\")\n",
105
+ "print(missing_values[missing_values > 0])\n",
106
+ "# Fill catogorical columns missing values\n",
107
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
108
+ " df[col] = df[col].fillna(df[col].mode()[0])\n",
109
+ "\n",
110
+ "# Fill neumerical columns missing values\n",
111
+ "for col in ['Courier_Experience_yrs', 'Delivery_Time']:\n",
112
+ " df[col] = df[col].fillna(df[col].mean())\n",
113
+ "\n",
114
+ "# Check if any missing value remains\n",
115
+ "print(\"Missing values remaining:\", df.isnull().sum().sum())"
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(duplicates)\n",
128
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
129
+ " if duplicates > 0:\n",
130
+ " print(\"Dropping Duplicates...\")\n",
131
+ " df.drop_duplicates(inplace=True)\n",
132
+ " print(\"Duplicates Dropped.\")\n",
133
+ " else:\n",
134
+ " print(\"No Duplicate Samples Found.\")\n",
135
+ "\n",
136
+ "check_duplicates(df)\n",
137
+ "# Check if any duplicates value remains\n",
138
+ "print(\"Duplicates values remaining:\", df.duplicated().sum())"
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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
149
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
150
+ "\n",
151
+ "oe = OneHotEncoder(sparse_output=False)\n",
152
+ "encoded = oe.fit_transform(df[categorical_cols])\n",
153
+ "# Convert the encoded data into a DataFrame with proper column names\n",
154
+ "encoded_df = pd.DataFrame(\n",
155
+ " encoded,\n",
156
+ " columns=oe.get_feature_names_out(categorical_cols),\n",
157
+ " index=df.index\n",
158
+ ")\n",
159
+ "# Drop the original categorical columns\n",
160
+ "df = df.drop(columns=categorical_cols)\n",
161
+ "\n",
162
+ "# Concatenate the encoded columns back into the DataFrame\n",
163
+ "df = pd.concat([df, encoded_df], axis=1)\n",
164
+ "\n",
165
+ "# Check the result\n",
166
+ "df.head()"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 5: Write your code here:\n",
176
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET, that's why we drop it\n",
177
+ "scaler = StandardScaler()\n",
178
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
179
+ "df.head()"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 6: Write your code here:\n",
189
+ "# 1. What does our target variable (charges) look like?\n",
190
+ "def check_target_distribution(df, target_column):\n",
191
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
192
+ "\n",
193
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
194
+ " plt.xlabel(target_column)\n",
195
+ " plt.ylabel(\"Frequency\")\n",
196
+ " plt.grid(False)\n",
197
+ "\n",
198
+ " plt.show()\n",
199
+ "\n",
200
+ "check_target_distribution(df, \"Delivery_Time\")\n",
201
+ "# cuz the most data is in the middle, it's normally distributed"
202
+ ],
203
+ "execution_count": null,
204
+ "outputs": []
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "metadata": {},
209
+ "source": [
210
+ "# Task 1: Write your code here:\n",
211
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float) # for safety\n",
212
+ "y = df['Delivery_Time'].astype(float)"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# Task 2,3,4,5: Write your code here:\n",
222
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)# YOUR CODE HERE\n",
223
+ "\n",
224
+ "n_splits = 5\n",
225
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
226
+ "\n",
227
+ "all_results = {'mae': []}\n",
228
+ "# Initialize and train model\n",
229
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1) # n_estimators=100 = 100 decision Trees\n",
230
+ "\n",
231
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
232
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
233
+ "\n",
234
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
235
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
236
+ " # Train\n",
237
+ " model.fit(X_train, y_train)\n",
238
+ " # Predict\n",
239
+ " y_pred = model.predict(X_test)\n",
240
+ " # Calculate metrics\n",
241
+ " mae = mean_absolute_error(y_test, y_pred)\n",
242
+ " # Store results\n",
243
+ " all_results[\"mae\"].append(mae)\n",
244
+ "\n",
245
+ "print(\"\\nModel trained!\")\n",
246
+ "\n",
247
+ "print(f\" Average MAE: {np.mean(all_results['mae']):.4f}\")\n"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task 1: Write your code here:\n",
257
+ "feature_cols = [col for col in df.columns if col != 'Delivery_Time']\n",
258
+ "\n",
259
+ "# Feature importance\n",
260
+ "importance = pd.DataFrame({\n",
261
+ " 'feature': feature_cols,\n",
262
+ " 'importance': model.feature_importances_\n",
263
+ "})\n",
264
+ "importance = importance.sort_values('importance', ascending=True).tail(10)\n",
265
+ "\n",
266
+ "plt.figure(figsize=(10, 6))\n",
267
+ "plt.barh(importance['feature'], importance['importance'])\n",
268
+ "plt.title('Top Feature Importance')\n",
269
+ "plt.xlabel('Importance')\n",
270
+ "plt.tight_layout()\n",
271
+ "plt.show()"
272
+ ],
273
+ "execution_count": null,
274
+ "outputs": []
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "metadata": {},
279
+ "source": [
280
+ "# Task 2: Write your code here:\n",
281
+ "valid_pred = model.predict(X_test)\n",
282
+ "plt.figure(figsize=(10, 6))\n",
283
+ "plt.hist(valid_pred, bins=30, edgecolor='black')\n",
284
+ "plt.title('Distribution of Predictions')\n",
285
+ "plt.xlabel('Predicted Delivery Time')\n",
286
+ "plt.ylabel('Count')\n",
287
+ "plt.show()"
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
+ "models = {\n",
298
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
299
+ " \"CatBoost\": CatBoostRegressor(verbose=0)\n",
300
+ "}\n",
301
+ "all_results = {}\n",
302
+ "\n",
303
+ "for name in models:\n",
304
+ " all_results[name] = {'mae': []}\n",
305
+ "\n",
306
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
307
+ "\n",
308
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
309
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
310
+ "\n",
311
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
312
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
313
+ "\n",
314
+ " for model_name, model in models.items():\n",
315
+ " print(f\"Training {model_name}...\")\n",
316
+ "\n",
317
+ " # Train\n",
318
+ " model.fit(X_train, y_train)\n",
319
+ "\n",
320
+ " # Predict\n",
321
+ " y_pred = model.predict(X_test)\n",
322
+ "\n",
323
+ " # Calculate metrics\n",
324
+ " mae = mean_absolute_error(y_test, y_pred)\n",
325
+ " # Store results\n",
326
+ " all_results[model_name][\"mae\"].append(mae)\n",
327
+ "\n",
328
+ "for model_name in all_results:\n",
329
+ " print(f\"\\n{model_name}:\")\n",
330
+ " print(f\" MSE: {np.mean(all_results[model_name]['mae']):.4f}\")\n"
331
+ ],
332
+ "execution_count": null,
333
+ "outputs": []
334
+ }
335
+ ],
336
+ "metadata": {
337
+ "kernelspec": {
338
+ "display_name": "Python 3",
339
+ "name": "python3"
340
+ },
341
+ "language_info": {
342
+ "name": "python"
343
+ }
344
+ },
345
+ "nbformat": 4,
346
+ "nbformat_minor": 0
347
+ }
submissions_extracted/829/Q2.ipynb ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torchvision.transforms.functional import to_tensor\n",
26
+ "from torchvision.datasets import MNIST\n",
27
+ "import torch.nn as nn\n",
28
+ "from sklearn.model_selection import train_test_split\n",
29
+ "from sklearn.datasets import load_breast_cancer\n",
30
+ "from sklearn.model_selection import train_test_split\n",
31
+ "from sklearn.preprocessing import StandardScaler\n",
32
+ "from torch.utils.data import TensorDataset\n",
33
+ "from torch.utils.data import DataLoader\n",
34
+ "from torch.optim import AdamW\n",
35
+ "import torch\n",
36
+ "import matplotlib.pyplot as plt\n",
37
+ "\n",
38
+ "# Load Labels\n",
39
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
40
+ "img_dir = os.path.join(path, \"images\")\n",
41
+ "\n",
42
+ "images = []\n",
43
+ "ages = []\n",
44
+ "\n",
45
+ "# Load Images and Resize\n",
46
+ "print(\"Loading images...\")\n",
47
+ "for index, row in labels_df.iterrows():\n",
48
+ " img_name = row.iloc[0]\n",
49
+ " age = row.iloc[1]\n",
50
+ " img_path = os.path.join(img_dir, img_name)\n",
51
+ "\n",
52
+ " if os.path.exists(img_path):\n",
53
+ " img = Image.open(img_path).convert('RGB')\n",
54
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
55
+ " images.append(img_array)\n",
56
+ " ages.append(age)\n",
57
+ "\n",
58
+ "X = np.array(images)\n",
59
+ "y = np.array(ages)\n",
60
+ "\n",
61
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
62
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
63
+ "\n",
64
+ "# Split Data\n",
65
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
66
+ "\n",
67
+ "print(f\"X_train shape: {X_train.shape}\")\n",
68
+ "print(f\"X_test shape: {X_test.shape}\")\n",
69
+ "print(f\"y_train shape: {y_train.shape}\")\n",
70
+ "print(f\"y_test shape: {y_test.shape}\")"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
80
+ "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
+ "# You can copy paste this\n",
94
+ "# Training dataset\n",
95
+ "train_dataset = MNIST(\n",
96
+ " root='./datasets', # Dataset storage path, Path where the dataset will be stored\n",
97
+ " train=True, # Use training data\n",
98
+ " transform=to_tensor, # Convert images to tensors\n",
99
+ " download=True # Downloads the dataset if it's not already present\n",
100
+ ")\n",
101
+ "\n",
102
+ "# Testing dataset\n",
103
+ "test_dataset = MNIST(\n",
104
+ " root='./datasets', # Dataset storage path\n",
105
+ " train=False, # Use test data\n",
106
+ " transform=to_tensor, # Convert images to tensors\n",
107
+ " download=True # Download if not available\n",
108
+ ")"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ "# 3. Create DataLoaders\n",
118
+ "train_loader = DataLoader(\n",
119
+ " train_dataset,\n",
120
+ " batch_size=32,\n",
121
+ " shuffle=True,\n",
122
+ " num_workers=2 # No. Cores inside the CPU, you can delete it, if u have more than 2 cores this may work faster, u can delete it\n",
123
+ ")\n",
124
+ "# DataLoader for test/validation data\n",
125
+ "test_loader = DataLoader(\n",
126
+ " test_dataset,\n",
127
+ " batch_size=32,\n",
128
+ " shuffle=False,\n",
129
+ " num_workers=2\n",
130
+ ")"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# 4. Print shape of one batch\n",
140
+ "X_batch, y_batch = next(iter(train_loader))\n",
141
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
142
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# 5. Display sample images\n",
152
+ "\n",
153
+ "sample_image, sample_label = train_dataset[0] # images first (image), then corresponding labels dim 1 is the labels (image, its label)\n",
154
+ "\n",
155
+ "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
156
+ "print(f\"Label: {sample_label}\")"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 1: Write your model class here:\n",
166
+ "class NN4Layer(nn.Module):\n",
167
+ "\n",
168
+ " def __init__(self, input_dim, hidden_dim):\n",
169
+ " super(NN4Layer, self).__init__()\n",
170
+ "\n",
171
+ " # First linear layer: input features -> hidden layer\n",
172
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
173
+ "\n",
174
+ " # Second linear layer: hidden layer -> hidden layer\n",
175
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
176
+ "\n",
177
+ " # Output layer: hidden layer -> number of classes (logits)\n",
178
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
179
+ "\n",
180
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
181
+ "\n",
182
+ " # ReLU activation for non-linearity\n",
183
+ " self.relu = nn.ReLU()\n",
184
+ "\n",
185
+ " # Defines how input data flows through the network\n",
186
+ " def forward(self, x):\n",
187
+ " # First hidden layer\n",
188
+ " a1 = self.relu(self.layer1(x))\n",
189
+ "\n",
190
+ " # Second hidden layer\n",
191
+ " a2 = self.relu(self.layer2(a1))\n",
192
+ "\n",
193
+ " a3 = self.relu(self.layer3(a2))\n",
194
+ " # Output layer (raw scores / logits)\n",
195
+ " output = self.layer4(a3) # there is something missing here, remember? :), Cross-Entropy Loss we dont use it here, we will use it in validation\n",
196
+ "\n",
197
+ " return output\n"
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.to(device) # shape: (batch_size, num_features)\n",
216
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
217
+ "\n",
218
+ " # Forward pass\n",
219
+ " outputs = model(X_batch) # shape: (batch_size, 10) # outputs are logits not probabilites\n",
220
+ " loss = criterion(outputs, y_batch) # criterion is the loss function\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.to(device) # shape: (batch_size, num_features)\n",
252
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
253
+ "\n",
254
+ " # Forward pass\n",
255
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
256
+ " loss = criterion(outputs, y_batch)\n",
257
+ "\n",
258
+ " running_loss += loss.item()\n",
259
+ "\n",
260
+ " avg_loss = running_loss / len(test_loader)\n",
261
+ "\n",
262
+ " return avg_loss\n"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {},
270
+ "source": [
271
+ "# Task 4: Define device, model, loss, optimizer:\n",
272
+ "# Device setup\n",
273
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
274
+ "\n",
275
+ "# Model parameters\n",
276
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
277
+ "hidden_dim = 14 # Design choice\n",
278
+ "learning_rate = 0.001\n",
279
+ "# Instantiate model\n",
280
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
281
+ "criterion = nn.MSELoss() #\n",
282
+ "\n",
283
+ "\n",
284
+ "optimizer = AdamW(model.parameters(), learning_rate) # You can use AdamW too\n",
285
+ "# Print the model architecture\n",
286
+ "print(\"Model Architecture:\\n\")\n",
287
+ "print(model)\n",
288
+ "\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
+ "num_epochs = 20\n",
301
+ "\n",
302
+ "# Run Training\n",
303
+ "train_losses = []\n",
304
+ "val_losses = []\n",
305
+ "\n",
306
+ "print('Starting Training...')\n",
307
+ "for epoch in range(num_epochs):\n",
308
+ " # Train one epoch\n",
309
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
310
+ "\n",
311
+ " # Validate\n",
312
+ " val_loss = validate(model, criterion, test_loader, device)\n",
313
+ "\n",
314
+ " train_losses.append(train_loss)\n",
315
+ " val_losses.append(val_loss)\n",
316
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
317
+ "\n",
318
+ "print('Training Complete!')"
319
+ ],
320
+ "execution_count": null,
321
+ "outputs": []
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "metadata": {},
326
+ "source": [
327
+ "# Task 1: Write your code here:\n",
328
+ "plt.figure(figsize=(7, 5))\n",
329
+ "\n",
330
+ "plt.plot(train_losses, label='Train Loss')\n",
331
+ "plt.plot(val_losses, label='Validation Loss')\n",
332
+ "plt.title('Loss over Epochs')\n",
333
+ "plt.xlabel('Epoch')\n",
334
+ "plt.ylabel('Loss')\n",
335
+ "plt.legend()\n",
336
+ "\n",
337
+ "plt.tight_layout()\n",
338
+ "plt.show()"
339
+ ],
340
+ "execution_count": null,
341
+ "outputs": []
342
+ },
343
+ {
344
+ "cell_type": "code",
345
+ "metadata": {},
346
+ "source": [
347
+ "# Task 2 (Bonus): Write your code here:\n",
348
+ "# Set model to evaluation mode\n",
349
+ "model.eval()\n",
350
+ "# Get one batch from the test DataLoader\n",
351
+ "images, labels = next(iter(test_loader))\n",
352
+ "# Move images to device\n",
353
+ "images = images.to(device)\n",
354
+ "labels = labels.to(device)\n",
355
+ "\n",
356
+ "with torch.no_grad():\n",
357
+ " # Flatten images before passing to the model\n",
358
+ " outputs = model(images.view(images.size(0), -1))\n",
359
+ "\n",
360
+ "# Move tensors back to CPU for plotting, matplot doesnt accept any tensors, we should convert them to CPUs\n",
361
+ "images = images.cpu()\n",
362
+ "labels = labels.cpu()\n",
363
+ "\n",
364
+ "# Plot first 6 predictions\n",
365
+ "plt.figure(figsize=(8, 4))\n",
366
+ "for i in range(6):\n",
367
+ " plt.subplot(2, 3, i + 1)\n",
368
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
369
+ " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
370
+ " plt.axis('off')\n",
371
+ "\n",
372
+ "plt.tight_layout()\n",
373
+ "plt.show()"
374
+ ],
375
+ "execution_count": null,
376
+ "outputs": []
377
+ }
378
+ ],
379
+ "metadata": {
380
+ "kernelspec": {
381
+ "display_name": "Python 3",
382
+ "name": "python3"
383
+ },
384
+ "language_info": {
385
+ "name": "python"
386
+ }
387
+ },
388
+ "nbformat": 4,
389
+ "nbformat_minor": 0
390
+ }
submissions_extracted/829/Q3.ipynb ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Import libraries\n",
8
+ "from IPython.display import clear_output\n",
9
+ "\n",
10
+ "%pip install kagglehub catboost xgboost tqdm -q\n",
11
+ "\n",
12
+ "clear_output()\n",
13
+ "import kagglehub\n",
14
+ "import pandas as pd\n",
15
+ "import numpy as np\n",
16
+ "import matplotlib.pyplot as plt\n",
17
+ "import seaborn as sns\n",
18
+ "import kagglehub\n",
19
+ "import os\n",
20
+ "from tqdm import tqdm\n",
21
+ "from sklearn.preprocessing import StandardScaler\n",
22
+ "from sklearn.model_selection import StratifiedKFold\n",
23
+ "from sklearn.metrics import accuracy_score, f1_score\n",
24
+ "\n",
25
+ "from catboost import CatBoostClassifier\n",
26
+ "%matplotlib inline\n",
27
+ "\n",
28
+ "# Download latest version\n",
29
+ "\n",
30
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
31
+ "\n",
32
+ "\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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
45
+ "\n",
46
+ "df = pd.read_csv(csv_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
+ "print(f\"Shape: {df.shape}\")\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
+ "from re import M\n",
87
+ "# Task 1: Write your code here:\n",
88
+ "# 2. Do we have missing values?\n",
89
+ "def check_missing_values(df):\n",
90
+ " missing_values = df.isnull().sum()\n",
91
+ " print(\"Missing Values per Column:\")\n",
92
+ " print(missing_values[missing_values > 0])\n",
93
+ " if missing_values.any():\n",
94
+ " print(\"\\nHandle Missing Values as needed.\")\n",
95
+ " else:\n",
96
+ " print(\"\\nNo Missing Values Found.\")\n",
97
+ "\n",
98
+ "# check_missing_values(df)\n",
99
+ "\n",
100
+ "# Fill missing values\n",
101
+ "df = df.fillna(df.median())"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# Task 2: Write your code here:\n",
111
+ "def check_duplicates(df):\n",
112
+ " duplicates = df.duplicated().sum()\n",
113
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
114
+ " if duplicates > 0:\n",
115
+ " print(\"Dropping Duplicates...\")\n",
116
+ " df.drop_duplicates(inplace=True)\n",
117
+ " print(\"Duplicates Dropped.\")\n",
118
+ " else:\n",
119
+ " print(\"No Duplicate Samples Found.\")\n",
120
+ "\n",
121
+ "check_duplicates(df)"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 3: Write your code here:\n",
131
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
132
+ "\n",
133
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET, that's why we drop it\n",
144
+ "scaler = StandardScaler()\n",
145
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])"
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
+ "# 1. Is the target imbalanced?\n",
156
+ "def check_target_imbalance(df, target_column):\n",
157
+ " print(\"Target Distribution:\")\n",
158
+ " print(df[target_column].value_counts(normalize=True)) # True --> gives percentage, False -> gives counts\n",
159
+ " sns.countplot(x=df[target_column])\n",
160
+ " plt.title(\"Target Distribution\")\n",
161
+ " plt.show()\n",
162
+ "\n",
163
+ "check_target_imbalance(df, \"Target\")"
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) # for safety\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
+ "# Task 2,3,4,5: Write your code here:\n",
184
+ "\n",
185
+ "n_splits = 5 # K=5 Folds\n",
186
+ "\n",
187
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
188
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
189
+ "\n",
190
+ "model = CatBoostClassifier(verbose=0,n_estimators=100,max_depth=4)\n",
191
+ "# Storage for logistic regression results for each fold\n",
192
+ "# To get the average later\n",
193
+ "all_results = {'accuracy': [], 'f1': []}\n",
194
+ "lr_losses = []\n",
195
+ "lr_accuracy = []\n",
196
+ "lr_f1 = []\n",
197
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
198
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
199
+ "\n",
200
+ " # 1. Split data\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
+ " # 2. Train & Validate sklearn models\n",
205
+ "\n",
206
+ " model.fit(X_train, y_train) # train\n",
207
+ " y_pred = model.predict(X_test) # validate\n",
208
+ "\n",
209
+ " # 3. Save metrics for that model in this fold\n",
210
+ " accuracy = accuracy_score(y_test, y_pred)\n",
211
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
212
+ "\n",
213
+ " all_results['accuracy'].append(accuracy)\n",
214
+ " all_results['f1'].append(f1)\n",
215
+ "\n",
216
+ "for model_name in all_results:\n",
217
+ " print(f\"\\n{model_name}:\")\n",
218
+ " print(f\" Accuracy: {np.mean(all_results['accuracy']):.4f}\")\n",
219
+ " print(f\" F1-Score: {np.mean(all_results['f1']):.4f}\")"
220
+ ],
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "metadata": {},
227
+ "source": [
228
+ "# Task 1: Write your code here:\n",
229
+ "feature_cols = [col for col in df.columns if col != 'Target']\n",
230
+ "\n",
231
+ "# Feature importance\n",
232
+ "importance = pd.DataFrame({\n",
233
+ " 'feature': feature_cols,\n",
234
+ " 'importance': model.feature_importances_\n",
235
+ "})\n",
236
+ "importance = importance.sort_values('importance', ascending=True).tail(10)\n",
237
+ "\n",
238
+ "plt.figure(figsize=(10, 6))\n",
239
+ "plt.barh(importance['feature'], importance['importance'])\n",
240
+ "plt.title('Top 10 Feature Importance')\n",
241
+ "plt.xlabel('Importance')\n",
242
+ "plt.tight_layout()\n",
243
+ "plt.show()"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ },
248
+ {
249
+ "cell_type": "code",
250
+ "metadata": {},
251
+ "source": [
252
+ "# Task 2: Write your code here:\n",
253
+ "importance = importance.sort_values('importance', ascending=True).tail(10)\n",
254
+ "print(f'The Golden feature is: {importance.tail(1)}')"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# Task Bonus: Write your code here:\n",
264
+ "# Task 1: Write your code here:\n",
265
+ "X = df[\"P_2\"].astype(float) # for safety\n",
266
+ "# Task 2,3,4,5: Write your code here:\n",
267
+ "\n",
268
+ "n_splits = 5 # K=5 Folds\n",
269
+ "\n",
270
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
271
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
272
+ "\n",
273
+ "model = CatBoostClassifier(verbose=0,n_estimators=100,max_depth=4)\n",
274
+ "# Storage for logistic regression results for each fold\n",
275
+ "# To get the average later\n",
276
+ "all_results = {'accuracy': [], 'f1': []}\n",
277
+ "lr_losses = []\n",
278
+ "lr_accuracy = []\n",
279
+ "lr_f1 = []\n",
280
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
281
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
282
+ "\n",
283
+ " # 2. Train & Validate sklearn models\n",
284
+ "\n",
285
+ " model.fit(X_train, y_train) # train\n",
286
+ " y_pred = model.predict(X_test) # validate\n",
287
+ "\n",
288
+ " # 3. Save metrics for that model in this fold\n",
289
+ " accuracy = accuracy_score(y_test, y_pred)\n",
290
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
291
+ "\n",
292
+ " all_results['accuracy'].append(accuracy)\n",
293
+ " all_results['f1'].append(f1)\n",
294
+ "\n",
295
+ "for model_name in all_results:\n",
296
+ " print(f\"\\n{model_name}:\")\n",
297
+ " print(f\" Accuracy: {np.mean(all_results['accuracy']):.4f}\")\n",
298
+ " print(f\" F1-Score: {np.mean(all_results['f1']):.4f}\")"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [],
307
+ "execution_count": null,
308
+ "outputs": []
309
+ }
310
+ ],
311
+ "metadata": {
312
+ "kernelspec": {
313
+ "display_name": "Python 3",
314
+ "name": "python3"
315
+ },
316
+ "language_info": {
317
+ "name": "python"
318
+ }
319
+ },
320
+ "nbformat": 4,
321
+ "nbformat_minor": 0
322
+ }
submissions_extracted/83/Q1.ipynb ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import pandas as pd\n",
23
+ "import os\n",
24
+ "\n",
25
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
26
+ "df = pd.read_csv(csv_path)\n",
27
+ "\n",
28
+ "df\n",
29
+ "\n",
30
+ "\n",
31
+ "\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "\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
+ "\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
+ "\n",
64
+ "df.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
+ "import matplotlib.pyplot as plt\n",
75
+ "\n",
76
+ "plt.plot(df.Delivery_Time)\n",
77
+ "plt.title('Delivery Time Distribution')\n"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 1: Write your code here:\n",
87
+ "df = df.drop('Order_ID', axis = 1)\n",
88
+ "\n",
89
+ "df\n"
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
+ "# Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
100
+ "\n",
101
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
102
+ "missing_data = pd.DataFrame({\n",
103
+ " 'Column': missing_percentage.index,\n",
104
+ " 'Missing_Percentage': missing_percentage.values\n",
105
+ "})\n",
106
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
107
+ "\n",
108
+ "print(\"Missing Data Analysis:\")\n",
109
+ "print(missing_data.head(10))\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
+ "# Task 3: Write your code here:\n",
122
+ "\n",
123
+ "\n",
124
+ "\n",
125
+ "def check_duplicates(df):\n",
126
+ " duplicates = df.duplicated().sum()\n",
127
+ "\n",
128
+ " if duplicates > 0:\n",
129
+ " df.drop_duplicates(inplace=True)\n",
130
+ "\n",
131
+ "check_duplicates(df)\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4: Write your code here:\n",
141
+ "# Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
142
+ "\n",
143
+ "from sklearn.preprocessing import LabelEncoder\n",
144
+ "\n",
145
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
146
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
147
+ "\n",
148
+ "for col in categorical_cols:\n",
149
+ " le = LabelEncoder()\n",
150
+ " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
151
+ "\n",
152
+ "df_clean.head()"
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
+ "# Define features (X) and target (y)\n",
165
+ "feature_cols = ['Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs',\t'Delivery_Time']\n",
166
+ "X = df_clean[feature_cols]\n",
167
+ "y = df_clean['price']\n",
168
+ "\n",
169
+ "# Train-test split (80% train, 20% test)\n",
170
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
171
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
172
+ "\n",
173
+ "\n",
174
+ "scaler = StandardScaler()\n",
175
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
176
+ "X_test_scaled = scaler.transform(X_test)\n",
177
+ "\n",
178
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
179
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 6: Write your code here:"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 1: Write your code here:"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 2,3,4,5: Write your code here:"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 1: Write your code here:"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Task 2: Write your code here:"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Task Bonus: Write your code here:"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ }
238
+ ],
239
+ "metadata": {
240
+ "kernelspec": {
241
+ "display_name": "Python 3",
242
+ "name": "python3"
243
+ },
244
+ "language_info": {
245
+ "name": "python"
246
+ }
247
+ },
248
+ "nbformat": 4,
249
+ "nbformat_minor": 0
250
+ }
submissions_extracted/83/Q2.ipynb ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n",
71
+ "\n",
72
+ "\n"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# 2. Create TensorDataset objects\n",
82
+ "\n",
83
+ "\n"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# 3. Create DataLoaders\n",
93
+ "\n",
94
+ "\n"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# 4. Print shape of one batch\n",
104
+ "\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 5. Display sample images\n",
114
+ "\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# Task 1: Write your model class here:"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 2: Write your training loop here:"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 3: Write your validation loop here:"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 4: Define device, model, loss, optimizer:"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 5: Start training for 20 epochs:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:\n",
169
+ "# Plotting results\n",
170
+ "\n",
171
+ "import matplotlib.pyplot as plt\n",
172
+ "\n",
173
+ "plt.figure(figsize=(7, 5))\n",
174
+ "\n",
175
+ "plt.plot(train_losses, label='Train Loss')\n",
176
+ "plt.plot(val_losses, label='Validation Loss')\n",
177
+ "plt.title('Loss over Epochs')\n",
178
+ "plt.xlabel('Epoch')\n",
179
+ "plt.ylabel('Loss')\n",
180
+ "plt.legend()\n",
181
+ "\n",
182
+ "plt.tight_layout()\n",
183
+ "plt.show()"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "# Task 2 (Bonus): Write your code here:"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ }
197
+ ],
198
+ "metadata": {
199
+ "kernelspec": {
200
+ "display_name": "Python 3",
201
+ "name": "python3"
202
+ },
203
+ "language_info": {
204
+ "name": "python"
205
+ }
206
+ },
207
+ "nbformat": 4,
208
+ "nbformat_minor": 0
209
+ }
submissions_extracted/83/Q3.ipynb ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
28
+ "import pandas as pd\n",
29
+ "import os\n",
30
+ "\n",
31
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
32
+ "df = pd.read_csv(csv_path)\n",
33
+ "\n",
34
+ "df"
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
+ "\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 3: Write your code here:\n",
55
+ "\n",
56
+ "df.info()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 4: Write your code here:\n",
66
+ "\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
+ "\n",
78
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
79
+ "missing_data = pd.DataFrame({\n",
80
+ " 'Column': missing_percentage.index,\n",
81
+ " 'Missing_Percentage': missing_percentage.values\n",
82
+ "})\n",
83
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
84
+ "\n",
85
+ "print(\"Missing Data Analysis:\")\n",
86
+ "print(missing_data.head(10))"
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
+ "\n",
97
+ "\n",
98
+ "def check_duplicates(df):\n",
99
+ " duplicates = df.duplicated().sum()\n",
100
+ "\n",
101
+ " if duplicates > 0:\n",
102
+ " df.drop_duplicates(inplace=True)\n",
103
+ "\n",
104
+ "check_duplicates(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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
116
+ "print(\"Categorical Columns:\", list(categorical_cols))\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
+ "print(f\"\\nFeature ranges - Min: {X_train.min().min():.2f}, Max: {X_train.max().max():.2f}\")\n",
128
+ "X_train.head(3)\n",
129
+ "scaler = StandardScaler()\n",
130
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
131
+ "X_test_scaled = scaler.transform(X_test)\n",
132
+ "\n",
133
+ "\n"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 5: Write your code here:\n",
143
+ "\n",
144
+ "df['status'] = df['status'].map({'Placed': 1, 'Not Placed': 0})\n",
145
+ "\n",
146
+ "# Drop unnecessary columns\n",
147
+ "df = df.drop(['salary', 'sl_no'], axis=1)\n",
148
+ "df.head()\n",
149
+ "\n",
150
+ "def check_target_imbalance(df, target_column):\n",
151
+ " print(\"Target Distribution:\")\n",
152
+ " print(df[target_column].value_counts(normalize=True))\n",
153
+ " sns.countplot(x=df[target_column])\n",
154
+ " plt.title(\"Target Distribution\")\n",
155
+ " plt.show()\n",
156
+ "\n",
157
+ "check_target_imbalance(df, \"status\")"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:\n",
167
+ "X = df.drop(\"status\", axis=1).astype(float)\n",
168
+ "y = df['status'].astype(float)"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "pip install catboost"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 2,3,4,5: Write your code here:\n",
187
+ "from sklearn.model_selection import StratifiedKFold\n",
188
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
189
+ "from catboost import CatBoostClassifier\n",
190
+ "\n",
191
+ "n_splits = 5 # K=5 Folds\n",
192
+ "sklearn_models = {\n",
193
+ " \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
194
+ " n_neighbors=3, # Number of neighbors to consider\n",
195
+ " ),\n",
196
+ " \"Support Vector Machine\": SVC(\n",
197
+ " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
198
+ " C=0.75 # Regularization parameter\n",
199
+ " ),\n",
200
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
201
+ " max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
202
+ " ),\n",
203
+ " \"Random Forest\": RandomForestClassifier(\n",
204
+ " n_estimators=320, # Number of trees\n",
205
+ " max_depth=4\n",
206
+ " ),\n",
207
+ " \"XGBoost\": XGBClassifier(\n",
208
+ " verbosity=0,\n",
209
+ " n_estimators=300, # Number of boosting rounds\n",
210
+ " max_depth=5,\n",
211
+ " learning_rate=0.05 # Step size shrinkage\n",
212
+ " ),\n",
213
+ " \"CatBoost\": CatBoostClassifier(\n",
214
+ " verbose=0,\n",
215
+ " n_estimators=320,\n",
216
+ " max_depth=4\n",
217
+ " )\n",
218
+ "}\n",
219
+ "\n",
220
+ "\n",
221
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
222
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "# Task 1: Write your code here:"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 2: Write your code here:"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {},
248
+ "source": [
249
+ "# Task Bonus: Write your code here:"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ }
254
+ ],
255
+ "metadata": {
256
+ "kernelspec": {
257
+ "display_name": "Python 3",
258
+ "name": "python3"
259
+ },
260
+ "language_info": {
261
+ "name": "python"
262
+ }
263
+ },
264
+ "nbformat": 4,
265
+ "nbformat_minor": 0
266
+ }
submissions_extracted/830/Q1.ipynb ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "from sklearn.model_selection import train_test_split, KFold\n",
12
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
13
+ "from sklearn.ensemble import RandomForestRegressor\n",
14
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "import kagglehub\n",
24
+ "\n",
25
+ "# Download latest version\n",
26
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
27
+ "\n",
28
+ "print(\"Path to dataset files:\", path)"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "# Task 1: Write your code here:\n",
38
+ "df_path = os.path.join(path, 'Q1_data.csv')\n",
39
+ "df = pd.read_csv(df_path)\n",
40
+ "\n"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 2: Write your code here:\n",
50
+ "df.head()"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 3: Write your code here:\n",
60
+ "df.info()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 4: Write your code here:\n",
70
+ "df.describe()"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# Task 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.drop(columns=['Order_ID'])"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "print(\"Missing values:\")\n",
110
+ "print(df.isnull().sum())\n",
111
+ "# filling Weather, Traffic_Level, Time_of_Day with the mode\n",
112
+ "# filing Courier_Experience_yrs, Delivery_Time with the median"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 2: Write your code here:\n",
122
+ "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
123
+ "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
124
+ "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
125
+ "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].median())\n",
126
+ "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].median())"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 3: Write your code here:\n",
143
+ "def check_duplicates(df):\n",
144
+ " duplicates = df.duplicated().sum()\n",
145
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
146
+ " if duplicates > 0:\n",
147
+ " print(\"Dropping Duplicates...\")\n",
148
+ " df.drop_duplicates(inplace=True)\n",
149
+ " print(\"Duplicates Dropped.\")\n",
150
+ " else:\n",
151
+ " print(\"No Duplicate Samples Found.\")\n",
152
+ "\n",
153
+ "check_duplicates(df)"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
163
+ "\n",
164
+ "print(\"Categorical Columns:\", list(categorical_cols))"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 4: Write your code here:\n",
174
+ "from sklearn.preprocessing import LabelEncoder\n",
175
+ "\n",
176
+ "label_encoders = {}\n",
177
+ "for col in categorical_cols:\n",
178
+ " le = LabelEncoder()\n",
179
+ " df[col] = le.fit_transform(df[col])\n",
180
+ " label_encoders[col] = le\n",
181
+ "df"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 5: Write your code here:\n",
191
+ "from sklearn.preprocessing import StandardScaler\n",
192
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")\n",
193
+ "\n",
194
+ "scaler = StandardScaler()\n",
195
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
196
+ "df.head()"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 6: Write your code here:\n",
206
+ "def check_target_imbalance(df, target_column):\n",
207
+ " print(\"Target Distribution:\")\n",
208
+ "\n",
209
+ " df[target_column].hist()\n",
210
+ " plt.show()\n",
211
+ "\n",
212
+ "check_target_imbalance(df, \"Delivery_Time\")"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "#It is imbalanced because distributions are not equal"
222
+ ],
223
+ "execution_count": null,
224
+ "outputs": []
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "metadata": {},
229
+ "source": [
230
+ "# Task 1: Write your code here:\n",
231
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
232
+ "y = df['Delivery_Time'].astype(float)"
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
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
243
+ "model.fit(X, y)\n",
244
+ "print(\"Model trained!\")\n",
245
+ "\n",
246
+ "y_pred = model.predict(X)\n",
247
+ "\n",
248
+ "mae = mean_absolute_error(y, y_pred)\n",
249
+ "\n",
250
+ "print(mae)"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "metadata": {},
258
+ "source": [
259
+ "# Task 1: Write your code here:\n",
260
+ "# Gather importances from the models (from the last fold)\n",
261
+ "importances = {}\n",
262
+ "\n",
263
+ "importances['Random Forest'] = model.feature_importances_\n",
264
+ "\n",
265
+ "# Create a 1x3 plot\n",
266
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
267
+ "axes = axes.flatten()\n",
268
+ "features = X.columns\n",
269
+ "\n",
270
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
271
+ " # Sort features by importance for a cleaner plot\n",
272
+ " sorted_idx = np.argsort(imp)\n",
273
+ "\n",
274
+ " ax = axes[i]\n",
275
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
276
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
277
+ " ax.set_xlabel(\"Importance Score\")\n",
278
+ "\n",
279
+ "plt.tight_layout()\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
+ "def check_target_imbalance(y, target_column):\n",
291
+ " print(\"Target Distribution:\")\n",
292
+ "\n",
293
+ " df[target_column].hist()\n",
294
+ " plt.show()\n",
295
+ "\n",
296
+ "check_target_imbalance(y, \"Delivery_Time\")"
297
+ ],
298
+ "execution_count": null,
299
+ "outputs": []
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "metadata": {},
304
+ "source": [
305
+ "# Task Bonus: Write your code here:"
306
+ ],
307
+ "execution_count": null,
308
+ "outputs": []
309
+ }
310
+ ],
311
+ "metadata": {
312
+ "kernelspec": {
313
+ "display_name": "Python 3",
314
+ "name": "python3"
315
+ },
316
+ "language_info": {
317
+ "name": "python"
318
+ }
319
+ },
320
+ "nbformat": 4,
321
+ "nbformat_minor": 0
322
+ }
submissions_extracted/830/Q2.ipynb ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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, dtype=torch.float32)\n",
73
+ "X_test = torch.tensor(X_test, 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)"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# 2. Create TensorDataset objects\n",
85
+ "from sklearn.datasets import load_breast_cancer\n",
86
+ "from sklearn.model_selection import train_test_split\n",
87
+ "from sklearn.preprocessing import StandardScaler\n",
88
+ "from torch.utils.data import TensorDataset\n",
89
+ "from torch.utils.data import DataLoader\n",
90
+ "import torch\n",
91
+ "train_dataset = TensorDataset(X_train, y_train)\n",
92
+ "test_dataset = TensorDataset(X_test, y_test)\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 3. Create DataLoaders\n",
102
+ "\n",
103
+ "\n",
104
+ "from torch.utils.data import DataLoader\n",
105
+ "\n",
106
+ "# DataLoader for training data\n",
107
+ "train_loader = DataLoader(\n",
108
+ " train_dataset,\n",
109
+ " batch_size=32,\n",
110
+ " shuffle=True,\n",
111
+ " num_workers=2\n",
112
+ ")\n",
113
+ "# DataLoader for test/validation data\n",
114
+ "test_loader = DataLoader(\n",
115
+ " test_dataset,\n",
116
+ " batch_size=32,\n",
117
+ " shuffle=False,\n",
118
+ " num_workers=2\n",
119
+ ")"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# 4. Print shape of one batch\n",
129
+ "\n",
130
+ "X_batch, y_batch = next(iter(train_loader))\n",
131
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
132
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# 5. Display sample images\n",
142
+ "sample_image, sample_label = train_dataset[0]\n",
143
+ "\n",
144
+ "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
145
+ "print(f\"Label: {sample_label}\")"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 1: Write your model class here:\n",
155
+ "import torch\n",
156
+ "import torch.nn as nn\n",
157
+ "import pandas as pd\n",
158
+ "import torch\n",
159
+ "import torch.nn as nn\n",
160
+ "from torch.optim import AdamW\n",
161
+ "import matplotlib.pyplot as plt\n",
162
+ "import torch.nn.functional as F\n",
163
+ "from torch.utils.data import DataLoader, TensorDataset\n",
164
+ "from sklearn.model_selection import train_test_split\n",
165
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
166
+ "\n",
167
+ "# Create a linear layer: 3 input features -> 1 output\n",
168
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
169
+ "\n",
170
+ "# Example input: batch of 4 samples, each with 3 features\n",
171
+ "x = torch.randn(4, 3)\n",
172
+ "\n",
173
+ "# Forward through the layer\n",
174
+ "y = linear(x)\n",
175
+ "\n",
176
+ "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
177
+ "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n",
178
+ "\n",
179
+ "class NN4Layer(nn.Module):\n",
180
+ "\n",
181
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
182
+ " super(NN4Layer, self).__init__()\n",
183
+ "\n",
184
+ " # First linear layer: input features -> hidden layer\n",
185
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
186
+ "\n",
187
+ " # Second linear layer: hidden layer -> hidden layer\n",
188
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
189
+ "\n",
190
+ " # Third linear layer: hidden layer -> hidden layer\n",
191
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
192
+ "\n",
193
+ " # Output layer: hidden layer -> number of classes (logits)\n",
194
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
195
+ "\n",
196
+ " # ReLU activation for non-linearity\n",
197
+ " self.relu = nn.ReLU()\n",
198
+ "\n",
199
+ " # Defines how input data flows through the network\n",
200
+ " def forward(self, x):\n",
201
+ " # First hidden layer\n",
202
+ " a1 = self.relu(self.layer1(x))\n",
203
+ "\n",
204
+ " # Second hidden layer\n",
205
+ " a2 = self.relu(self.layer2(a1))\n",
206
+ "\n",
207
+ " # Third hidden layer\n",
208
+ " a3 = self.relu(self.layer3(a2))\n",
209
+ "\n",
210
+ " # Output layer (raw scores / logits)\n",
211
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
212
+ "\n",
213
+ " return output"
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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
224
+ " # Set the model to training mode\n",
225
+ " model.train()\n",
226
+ "\n",
227
+ " running_loss = 0.0\n",
228
+ "\n",
229
+ " for X_batch, y_batch in train_loader:\n",
230
+ " # Move batch to the selected device\n",
231
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
232
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
233
+ "\n",
234
+ " # Forward pass (outputs are logits)\n",
235
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
236
+ " loss = criterion(outputs, y_batch)\n",
237
+ "\n",
238
+ " # Backward pass & optimization\n",
239
+ " optimizer.zero_grad() # Clear previous gradients\n",
240
+ " loss.backward() # Compute gradients\n",
241
+ " optimizer.step() # Update model parameters\n",
242
+ "\n",
243
+ " running_loss += loss.item()\n",
244
+ "\n",
245
+ " # Average loss over all batches\n",
246
+ " avg_loss = running_loss / len(train_loader)\n",
247
+ "\n",
248
+ " return avg_loss\n"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": []
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "metadata": {},
256
+ "source": [
257
+ "# Task 3: Write your validation loop here:\n",
258
+ "def validate(model, criterion, test_loader, device):\n",
259
+ " # Set the model to evaluation mode\n",
260
+ " model.eval()\n",
261
+ "\n",
262
+ " running_loss = 0.0\n",
263
+ " correct = 0\n",
264
+ " total = 0\n",
265
+ "\n",
266
+ " with torch.no_grad():\n",
267
+ " for X_batch, y_batch in test_loader:\n",
268
+ " # Move data to device\n",
269
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
270
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
271
+ "\n",
272
+ " # Forward pass\n",
273
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
274
+ " loss = criterion(outputs, y_batch)\n",
275
+ " running_loss += loss.item()\n",
276
+ "\n",
277
+ " # Apply Softmax to get probabilities\n",
278
+ " probabilities = F.softmax(outputs, dim=1)\n",
279
+ "\n",
280
+ " # Pick the classes with highest probabilities\n",
281
+ " predicted = torch.argmax(probabilities, dim=1)\n",
282
+ "\n",
283
+ " # Accuracy calculation\n",
284
+ " correct += (predicted == y_batch).sum().item()\n",
285
+ " total += y_batch.size(0)\n",
286
+ "\n",
287
+ " avg_loss = running_loss / len(test_loader)\n",
288
+ " accuracy = correct / total\n",
289
+ "\n",
290
+ " return avg_loss, accuracy"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "# Task 4: Define device, model, loss, optimizer:\n",
300
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n"
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
+ "\n",
313
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
314
+ "criterion = nn.CrossEntropyLoss()\n",
315
+ "# Define optimizer\n",
316
+ "optimizer = AdamW(model.parameters(), learning_rate)"
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')\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/830/Q3.ipynb ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch\n",
28
+ "import torch.nn as nn\n",
29
+ "from torchvision.datasets import MNIST\n",
30
+ "from torch.utils.data import DataLoader\n",
31
+ "from torch.optim import Adam\n",
32
+ "from torchvision.transforms.functional import to_tensor\n",
33
+ "import torch.nn.functional as F\n",
34
+ "import matplotlib.pyplot as plt\n",
35
+ "import numpy as np\n",
36
+ "import pandas as pd\n",
37
+ "import matplotlib.pyplot as plt\n",
38
+ "import os\n",
39
+ "df_path = os.path.join(path, 'Q3_data.csv')\n",
40
+ "df = pd.read_csv(df_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 1: Write your code here:"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# Task 2: Write your code here:"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# Task 3: Write your code here:"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 4: Write your code here:"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 5: Write your code here:"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# Task 1: Write your code here:"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 2,3,4,5: Write your code here:"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 1: Write your code here:"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 2: Write your code here:"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task Bonus: Write your code here:"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ }
165
+ ],
166
+ "metadata": {
167
+ "kernelspec": {
168
+ "display_name": "Python 3",
169
+ "name": "python3"
170
+ },
171
+ "language_info": {
172
+ "name": "python"
173
+ }
174
+ },
175
+ "nbformat": 4,
176
+ "nbformat_minor": 0
177
+ }
submissions_extracted/831/Q1.ipynb ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
14
+ "import seaborn as sns\n",
15
+ "from tqdm import tqdm\n",
16
+ "\n",
17
+ "%matplotlib inline\n",
18
+ "from sklearn.model_selection import train_test_split, KFold\n",
19
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
20
+ "from sklearn.ensemble import RandomForestRegressor\n",
21
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
22
+ "\n",
23
+ "import warnings\n",
24
+ "warnings.filterwarnings('ignore')\n",
25
+ "\n",
26
+ "\n",
27
+ "\n",
28
+ "# Download latest version\n",
29
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
30
+ "\n",
31
+ "print(\"Path to dataset files:\", path)"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 1: Write your code here:\n",
41
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
42
+ "df = pd.read_csv(data_path)\n",
43
+ "\n",
44
+ "print(f\"Dataset shape: {df.shape}\")"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# Task 2: Write your code here:\n",
54
+ "df.head()"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "# Task 3: Write your code here:\n",
64
+ "df.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 4: Write your code here:\n",
74
+ "df.describe()"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 5: Write your code here:\n",
84
+ "plt.figure(figsize=(10, 5))\n",
85
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
86
+ "plt.title('delivery_time Distribution')\n",
87
+ "plt.xlabel('delivery_time')\n",
88
+ "plt.ylabel('Frequency')\n",
89
+ "plt.show()"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 1: Write your code here:\n",
99
+ "df_clean = df.drop(columns = 'Order_ID')"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# Task 2: Write your code here:\n",
109
+ "# filling Null values of both String and Int features\n",
110
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
111
+ " df_clean[col] = df_clean[col].fillna('unknown')\n",
112
+ "\n",
113
+ "for col in ['Delivery_Time', 'Courier_Experience_yrs']:\n",
114
+ " df_clean[col] = df_clean[col].fillna(df_clean[col].mean())\n",
115
+ "\n",
116
+ "\n"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 3: Write your code here:\n",
126
+ "# 4. Do we have duplicate samples?\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 4: Write your code here:\n",
147
+ "# Encoding Object (str) features using Label Encoding\n",
148
+ "\n",
149
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
150
+ "for col in categorical_cols:\n",
151
+ " le = LabelEncoder()\n",
152
+ " df_clean[col] = le.fit_transform(df_clean[col].astype(str))"
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 #import StandardScaler\n",
163
+ "\n",
164
+ "print('data before scaling:\\n', df_clean) #show before scaling\n",
165
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
166
+ "df_clean = standard_scaler.fit_transform(df_clean) # Apply fit_transform\n",
167
+ "\n",
168
+ "print('\\nData after scaling:\\n', df_clean) #show after scaling"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 6: Write your code here:\n"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 1: Write your code here:\n",
187
+ "X = df_clean.drop(columns = 'Delivery_Time')\n",
188
+ "y = df_clean['Delivery_Time']\n",
189
+ "\n"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 2,3,4,5: Write your code here:\n",
199
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
200
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
201
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
202
+ " losses = []\n",
203
+ "\n",
204
+ "\n",
205
+ "# Training Random Forest\n",
206
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
207
+ "model.fit(X_train, y_train)\n",
208
+ "print(\"Model trained!\")\n",
209
+ "\n",
210
+ "# Predict and evaluate\n",
211
+ "y_pred = model.predict(X_test)\n",
212
+ "\n",
213
+ "mae = mean_absolute_error(y_test, y_pred)\n",
214
+ "print(f\"MAE: {mae:,.2f}\")\n",
215
+ "\n",
216
+ "# average loss of folds\n",
217
+ "print(np.mean(lr_losses, axis=0))\n"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 1: Write your code here:\n",
227
+ "feature_importance = pd.DataFrame({\n",
228
+ " 'feature': df_clean.drop(columns = 'Delivery_Time'),\n",
229
+ " 'importance': model.feature_importances_\n",
230
+ "}).sort_values('importance', ascending=False)\n",
231
+ "\n",
232
+ "plt.figure(figsize=(10, 6))\n",
233
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
234
+ "plt.xlabel('Importance')\n",
235
+ "plt.title('Feature Importance')\n",
236
+ "plt.gca().invert_yaxis()\n",
237
+ "plt.show()"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task 2: Write your code here:"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "# Task Bonus: Write your code here:"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ }
260
+ ],
261
+ "metadata": {
262
+ "kernelspec": {
263
+ "display_name": "Python 3",
264
+ "name": "python3"
265
+ },
266
+ "language_info": {
267
+ "name": "python"
268
+ }
269
+ },
270
+ "nbformat": 4,
271
+ "nbformat_minor": 0
272
+ }
submissions_extracted/831/Q2.ipynb ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "from torchvision.datasets import CIFAR10\n",
27
+ "from torchvision.transforms.functional import to_tensor\n",
28
+ "from torch.utils.data import DataLoader\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "import torch.nn as nn\n",
31
+ "import torch.nn.functional as F\n",
32
+ "import torch\n",
33
+ "from torch.optim import AdamW\n",
34
+ "\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
+ "from sklearn.datasets import load_breast_cancer\n",
79
+ "from sklearn.model_selection import train_test_split\n",
80
+ "from sklearn.preprocessing import StandardScaler\n",
81
+ "from torch.utils.data import TensorDataset\n",
82
+ "from torch.utils.data import DataLoader\n",
83
+ "import torch\n",
84
+ "\n",
85
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
86
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
87
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
88
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# 2. Create TensorDataset objects\n",
98
+ "\n",
99
+ "# TensorDataset pairs input features (X) with their corresponding labels (y)\n",
100
+ "# Each item in the dataset is returned as (X[i], y[i])\n",
101
+ "train_dataset = TensorDataset(X_train, y_train)\n",
102
+ "test_dataset = TensorDataset(X_test, y_test)\n",
103
+ "\n",
104
+ "# Access a single sample from the dataset\n",
105
+ "# This helps verify the shape of one data sample\n",
106
+ "first_sample, _ = train_dataset[0]\n",
107
+ "print(f\"Shape of one sample: {first_sample.shape}\")\n"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# 3. Create DataLoaders\n",
117
+ "# DataLoader for training data\n",
118
+ "train_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
119
+ "# DataLoader for test data\n",
120
+ "test_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
121
+ "\n",
122
+ "# Get the first batch from the training DataLoader\n",
123
+ "X_batch, y_batch = next(iter(train_loader))\n",
124
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
125
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# 4. Print shape of one batch\n",
135
+ "X_batch, y_batch = next(iter(train_loader))\n",
136
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
137
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# 5. Display sample images\n",
147
+ "import matplotlib.pyplot as plt\n",
148
+ "# Get one batch of images and labels\n",
149
+ "images, labels = next(iter(train_loader))\n",
150
+ "\n",
151
+ "# Display the first 6 images in the batch\n",
152
+ "plt.figure(figsize=(8, 4))\n",
153
+ "\n",
154
+ "for i in range(6):\n",
155
+ " plt.subplot(2, 3, i + 1)\n",
156
+ "\n",
157
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
158
+ " img = images[i].permute(1, 2, 0)\n",
159
+ "\n",
160
+ " plt.imshow(img)\n",
161
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
162
+ " plt.axis('off')\n",
163
+ "\n",
164
+ "plt.tight_layout()\n",
165
+ "plt.show()"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 1: Write your model class here:\n",
175
+ "import torch.nn as nn\n",
176
+ "\n",
177
+ "class NN4Layer(nn.Module):\n",
178
+ "\n",
179
+ " def __init__(self, input_dim, hidden_dim):\n",
180
+ " super(NN4Layer, self).__init__()\n",
181
+ "\n",
182
+ " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
183
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
184
+ "\n",
185
+ " # TODO: What are the dimensions from previous and next layer?\n",
186
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
187
+ "\n",
188
+ " # TODO: What are the dimensions from previous and next layer?\n",
189
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
190
+ "\n",
191
+ " # TODO: What are the dimensions from previous and next layer?\n",
192
+ " self.layer4 = nn.Linear(hidden_dim, 1)\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
+ " # Layer 1: TODO\n",
200
+ " z1 = self.layer1(x)\n",
201
+ " a1 = self.relu(z1)\n",
202
+ "\n",
203
+ " # Layer 2 TODO\n",
204
+ " z2 = self.layer2(a1)\n",
205
+ " a2 = self.relu(z2)\n",
206
+ "\n",
207
+ " # Layer 3 TODO\n",
208
+ " z3 = self.layer3(a2)\n",
209
+ " a3 = self.relu(z3)\n",
210
+ "\n",
211
+ " # Output layer TODO\n",
212
+ " z4 = self.layer4(a3)\n",
213
+ " a3 = self.relu(z4)\n",
214
+ "\n",
215
+ " # TODO: are we missing output activation function? (hint: Loss Function)\n",
216
+ "\n",
217
+ " return z4"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 2: Write your training loop here:\n",
227
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
228
+ " # Set the model to training mode\n",
229
+ " model.train()\n",
230
+ "\n",
231
+ " running_loss = 0.0\n",
232
+ "\n",
233
+ " for X_batch, y_batch in train_loader:\n",
234
+ " # Move batch to the selected device\n",
235
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
236
+ " y_batch = y_batch.to(device)\n",
237
+ "\n",
238
+ " # Forward pass\n",
239
+ " # TODO: make predictions\n",
240
+ " outputs = model(X_batch)\n",
241
+ " # TODO: compute loss\n",
242
+ " loss = criterion(outputs, y_batch)\n",
243
+ "\n",
244
+ " # Backward pass & optimization\n",
245
+ " optimizer.zero_grad() # Clear previous gradients\n",
246
+ " loss.backward() # Compute gradients\n",
247
+ " optimizer.step() # Update model parameters\n",
248
+ "\n",
249
+ " running_loss += loss.item()\n",
250
+ "\n",
251
+ " # Average loss over all batches\n",
252
+ " avg_loss = running_loss / len(train_loader)\n",
253
+ "\n",
254
+ " return avg_loss"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# Task 3: Write your validation loop here:\n",
264
+ "def validate(model, criterion, test_loader, device):\n",
265
+ " # Set the model to evaluation mode\n",
266
+ " model.eval()\n",
267
+ "\n",
268
+ " running_loss = 0.0\n",
269
+ " correct = 0\n",
270
+ " total = 0\n",
271
+ "\n",
272
+ " with torch.no_grad():\n",
273
+ " for X_batch, y_batch in test_loader:\n",
274
+ " # Move data to device\n",
275
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
276
+ " y_batch = y_batch.to(device)\n",
277
+ "\n",
278
+ " # Forward pass\n",
279
+ " # TODO: make predictions\n",
280
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
281
+ " # TODO: compute loss\n",
282
+ " loss = criterion(outputs, y_batch)\n",
283
+ " running_loss += loss.item()\n",
284
+ "\n",
285
+ " # TODO: Apply Softmax to get probabilities\n",
286
+ "\n",
287
+ " # TODO: Multiclass predictions\n",
288
+ "\n",
289
+ "\n",
290
+ " # Accuracy calculation\n",
291
+ " correct += (outputs == y_batch).sum().item()\n",
292
+ " total += y_batch.size(0)\n",
293
+ "\n",
294
+ " avg_loss = running_loss / len(test_loader)\n",
295
+ " # TODO: how do we calculate accuracy?\n",
296
+ " accuracy = correct / total\n",
297
+ "\n",
298
+ " return avg_loss, accuracy\n"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [
307
+ "# Task 4: Define device, model, loss, optimizer:\n",
308
+ "# Device setup\n",
309
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
310
+ "\n",
311
+ "# Model parameters\n",
312
+ "# TODO: What are input features ? (hint: flatten using channel, height, width)\n",
313
+ "input_dim = 3 * 36 * 36 # CIFAR-10 images flattened (RGB)\n",
314
+ "\n",
315
+ "# TODO: choose number of hidden neurons\n",
316
+ "hidden_dim = 64 # Design choice\n",
317
+ "\n",
318
+ "\n",
319
+ "# TODO: Instantiate model (what are the model class inputs?)\n",
320
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
321
+ "\n",
322
+ "# TODO: Print the model architecture\n",
323
+ "print(\"Model Architecture:\\n\")\n",
324
+ "print(model)\n",
325
+ "\n",
326
+ "# Calculate the total number of trainable parameters\n",
327
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
328
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
329
+ "\n",
330
+ "\n",
331
+ "# TODO: choose number of epochs, increase it if you have gpus :)\n",
332
+ "num_epochs = 20\n",
333
+ "# TODO: choose a learning rate (try different values and evaluate results)\n",
334
+ "learning_rate = 0.001\n",
335
+ "\n",
336
+ "# TODO: Define criterion (loss function) (hint: what loss do we use for multiclass ?)\n",
337
+ "criterion = nn.MSELoss()\n",
338
+ "# TODO: Define optimizer(what is updated during training?)\n",
339
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
340
+ "\n",
341
+ "\n"
342
+ ],
343
+ "execution_count": null,
344
+ "outputs": []
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "metadata": {},
349
+ "source": [
350
+ "# Task 5: Start training for 20 epochs:\n",
351
+ "\n",
352
+ "# Run Training\n",
353
+ "train_losses = []\n",
354
+ "val_losses = []\n",
355
+ "val_accuracies = []\n",
356
+ "\n",
357
+ "print('Starting Training...')\n",
358
+ "for epoch in range(num_epochs):\n",
359
+ " # Train one epoch\n",
360
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
361
+ "\n",
362
+ " # Validate\n",
363
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
364
+ "\n",
365
+ " train_losses.append(train_loss)\n",
366
+ " val_losses.append(val_loss)\n",
367
+ " val_accuracies.append(val_accuracy)\n",
368
+ "\n",
369
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
370
+ "\n",
371
+ "print('Training Complete!')"
372
+ ],
373
+ "execution_count": null,
374
+ "outputs": []
375
+ },
376
+ {
377
+ "cell_type": "code",
378
+ "metadata": {},
379
+ "source": [
380
+ "# Task 1: Write your code here:\n",
381
+ "# Plotting results\n",
382
+ "plt.figure(figsize=(7, 5))\n",
383
+ "\n",
384
+ "plt.plot(train_losses, label='Train Loss')\n",
385
+ "plt.plot(val_losses, label='Validation Loss')\n",
386
+ "plt.title('Loss over Epochs')\n",
387
+ "plt.xlabel('Epoch')\n",
388
+ "plt.ylabel('Loss')\n",
389
+ "plt.legend()\n",
390
+ "\n",
391
+ "plt.tight_layout()\n",
392
+ "plt.show()"
393
+ ],
394
+ "execution_count": null,
395
+ "outputs": []
396
+ },
397
+ {
398
+ "cell_type": "code",
399
+ "metadata": {},
400
+ "source": [
401
+ "# Task 2 (Bonus): Write your code here:\n",
402
+ "predictions = model(X_test.to(device)).cpu().numpy()\n",
403
+ "\n",
404
+ "# Task 1: Write your code here:\n",
405
+ "# Plotting results\n",
406
+ "plt.figure(figsize=(7, 5))\n",
407
+ "\n",
408
+ "plt.plot(predictions, label='prediction')\n",
409
+ "plt.plot(X_test, label='actual')\n",
410
+ "plt.title('Loss over Epochs')\n",
411
+ "plt.xlabel('Epoch')\n",
412
+ "plt.ylabel('Loss')\n",
413
+ "plt.legend()\n",
414
+ "\n",
415
+ "plt.tight_layout()\n",
416
+ "plt.show()\n"
417
+ ],
418
+ "execution_count": null,
419
+ "outputs": []
420
+ }
421
+ ],
422
+ "metadata": {
423
+ "kernelspec": {
424
+ "display_name": "Python 3",
425
+ "name": "python3"
426
+ },
427
+ "language_info": {
428
+ "name": "python"
429
+ }
430
+ },
431
+ "nbformat": 4,
432
+ "nbformat_minor": 0
433
+ }
submissions_extracted/831/Q3.ipynb ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "\n",
13
+ "\n",
14
+ "# Download latest version\n",
15
+ "\n",
16
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
17
+ "\n",
18
+ "\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "# Task 1: Write your code here:\n",
30
+ "data_path = os.path.join(path, 'Q3_data.csv')\n",
31
+ "df = pd.read_csv(data_path)\n",
32
+ "\n",
33
+ "print(f\"Dataset shape: {df.shape}\")"
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
+ "for col in df:\n",
74
+ " df[col] = df[col].fillna(df[col].mean())"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 2: Write your code here:\n",
84
+ "def check_duplicates(df):\n",
85
+ " duplicates = df.duplicated().sum()\n",
86
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
87
+ " if duplicates > 0:\n",
88
+ " print(\"Dropping Duplicates...\")\n",
89
+ " df.drop_duplicates(inplace=True)\n",
90
+ " print(\"Duplicates Dropped.\")\n",
91
+ " else:\n",
92
+ " print(\"No Duplicate Samples Found.\")\n",
93
+ "\n",
94
+ "check_duplicates(df)"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 3: Write your code here:\n",
104
+ "#not needed all values are ether int or float"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 4: Write your code here:\n",
114
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
115
+ "\n",
116
+ "print('data before scaling:\\n', df) #show before scaling\n",
117
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
118
+ "df_clean = standard_scaler.fit_transform(df) # Apply fit_transform\n",
119
+ "\n",
120
+ "print('\\nData after scaling:\\n', df) #show after scaling"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 5: Write your code here:\n",
130
+ "plt.figure(figsize=(10, 5))\n",
131
+ "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n",
132
+ "plt.title('delivery_time Distribution')\n",
133
+ "plt.xlabel('delivery_time')\n",
134
+ "plt.ylabel('Frequency')\n",
135
+ "plt.show()"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Task 1: Write your code here:"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 2,3,4,5: Write your code here:"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 1: Write your code here:"
163
+ ],
164
+ "execution_count": null,
165
+ "outputs": []
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "metadata": {},
170
+ "source": [
171
+ "# Task 2: Write your code here:"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "# Task Bonus: Write your code here:"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ }
185
+ ],
186
+ "metadata": {
187
+ "kernelspec": {
188
+ "display_name": "Python 3",
189
+ "name": "python3"
190
+ },
191
+ "language_info": {
192
+ "name": "python"
193
+ }
194
+ },
195
+ "nbformat": 4,
196
+ "nbformat_minor": 0
197
+ }
submissions_extracted/832/Q1.ipynb ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
23
+ "df = pd.read_csv(csv_path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 2: Write your code here:\n",
33
+ "df.head()"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 3: Write your code here:\n",
43
+ "df.info()"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 4: Write your code here:\n",
53
+ "df.describe()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 5: Write your code here:\n",
63
+ "target_column = \"Delivery_Time\"\n",
64
+ "\n",
65
+ "\n",
66
+ "X = df.drop(target_column, axis=1)\n",
67
+ "y = df[target_column]\n",
68
+ "\n",
69
+ "#print(\"\\nDataset Shapes\")\n",
70
+ "#print(\"X:\", X.shape)\n",
71
+ "#print(\"y:\", y.shape)\n",
72
+ "\n",
73
+ "plt.figure(figsize=(10, 5))\n",
74
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
75
+ "plt.title('Delivery Time Distribution')\n",
76
+ "plt.xlabel('Delivery Time')\n",
77
+ "plt.ylabel('Frequency')\n",
78
+ "plt.show()\n",
79
+ "\n",
80
+ "#or\n",
81
+ "\n",
82
+ "#def check_target_distribution(df, target_column):\n",
83
+ " # df[target_column].hist(bins=30, edgecolor='black')\n",
84
+ " # plt.title(f\"Target Distribution ({target_column})\")\n",
85
+ " # plt.xlabel(target_column)\n",
86
+ " # plt.ylabel(\"Frequency\")\n",
87
+ " # plt.grid(False)\n",
88
+ " # plt.show()\n",
89
+ "#check_target_distribution(df, \"Delivery_Time\")\n",
90
+ "\n"
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.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: Handle missing values appropriately\n",
110
+ "\n",
111
+ "#1\n",
112
+ "# Cheak if we have missing values?\n",
113
+ "def check_missing_values(df):\n",
114
+ " missing_values = df.isnull().sum()\n",
115
+ " print(\"Missing Values per Column:\")\n",
116
+ " print(missing_values[missing_values > 0])\n",
117
+ " if missing_values.any():\n",
118
+ " print(\"\\nHandle Missing Values as needed.\")\n",
119
+ " else:\n",
120
+ " print(\"\\nNo Missing Values Found.\")\n",
121
+ "\n",
122
+ "check_missing_values(df)\n",
123
+ "\n",
124
+ "\n",
125
+ " #for col in ['Time_of_Day']:\n",
126
+ " # df_clean[col] = df_clean[col].fillna('unknown')\n",
127
+ "#df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# Task 2:\n",
137
+ "\n",
138
+ "df.dropna(subset=['Delivery_Time'])\n",
139
+ "df.dropna(subset=['Courier_Experience_yrs'])"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 3: Write your code here:\n",
149
+ "def check_duplicates(df):\n",
150
+ " duplicates = df.duplicated().sum()\n",
151
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
152
+ " if duplicates > 0:\n",
153
+ " print(\"Dropping Duplicates...\")\n",
154
+ " df.drop_duplicates(inplace=True)\n",
155
+ " print(\"Duplicates Dropped.\")\n",
156
+ " else:\n",
157
+ " print(\"No Duplicate Samples Found.\")\n",
158
+ "\n",
159
+ "check_duplicates(df)"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 4: Write your code here: 4. Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
169
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
170
+ "\n",
171
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
172
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
173
+ "\n",
174
+ "\n",
175
+ "label_encoders = {}\n",
176
+ "for col in categorical_cols:\n",
177
+ " le = LabelEncoder()\n",
178
+ " df[col] = le.fit_transform(df[col])\n",
179
+ " label_encoders[col] = le\n",
180
+ "\n",
181
+ "df\n",
182
+ "\n",
183
+ "\n",
184
+ "#label_encoder = LabelEncoder()\n",
185
+ "\n",
186
+ "#for col in X.select_dtypes(include=[\"object\"]).columns:\n",
187
+ "# X[col] = label_encoder.fit_transform(X[col])\n",
188
+ "\n"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 5: Write your code here: 5. Apply feature scaling for all features (Use StandardScaler)\n",
198
+ "from sklearn.preprocessing import StandardScaler\n",
199
+ "\n",
200
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # We DON'T SCALE THE TARGET\n",
201
+ "\n",
202
+ "scaler = StandardScaler()\n",
203
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
204
+ "df.head()"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "metadata": {},
212
+ "source": [
213
+ "# Task 6: Write your code here:"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 1: Write your code here: 1. Split the dataset into features (X) and target (y)\n",
223
+ "\n",
224
+ "\n",
225
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
226
+ "y = df['Delivery_Time'].astype(float)"
227
+ ],
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "metadata": {},
234
+ "source": [
235
+ "# Task 2,3,4,5: Write your code here:\n",
236
+ "\n",
237
+ "from sklearn.model_selection import KFold\n",
238
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
239
+ "\n",
240
+ "# Mean Squared Error in NumPy (Not reqierd)\n",
241
+ "def mean_squared_error(y, y_hat):\n",
242
+ " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n",
243
+ "\n",
244
+ " def gradient_descent(X, y, learning_rate, n_iters=500):\n",
245
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
246
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
247
+ " losses = []\n",
248
+ "\n",
249
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
250
+ " y_hat = np.dot(X, theta)\n",
251
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
252
+ " theta -= learning_rate * gradient\n",
253
+ "\n",
254
+ " loss = mean_squared_error(y, y_hat)\n",
255
+ " losses.append(loss)\n",
256
+ "\n",
257
+ " return theta, losses\n",
258
+ "\n",
259
+ " n_splits = 5 # K=5 Folds\n",
260
+ "\n",
261
+ "# 5-Fold Cross-Validation, shuffled\n",
262
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
263
+ "\n",
264
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
265
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
266
+ "\n",
267
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
268
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
269
+ "\n",
270
+ " # Train\n",
271
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
272
+ "\n",
273
+ " # Validate\n",
274
+ " y_pred = np.dot(X_test.values, theta)\n",
275
+ "\n",
276
+ "\n",
277
+ "\n"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
294
+ "mae_scores = []\n",
295
+ "mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
296
+ "print(f\"MAE : {np.mean(mae_scores):.2f}\")\n",
297
+ "\n",
298
+ "\n",
299
+ "\n",
300
+ "\n",
301
+ "average_losses = np.mean(lr_losses, axis=0)\n",
302
+ "\n",
303
+ "plt.figure(figsize=(10, 6))\n",
304
+ "plt.plot(average_losses, label='Average Loss')\n",
305
+ "plt.xlabel('Iteration')\n",
306
+ "plt.ylabel('MAE Loss')\n",
307
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
308
+ "plt.legend()\n",
309
+ "plt.grid(True, alpha=0.3)\n",
310
+ "plt.show()\n"
311
+ ],
312
+ "execution_count": null,
313
+ "outputs": []
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "metadata": {},
318
+ "source": [
319
+ "# Task 1: Write your code here:\n",
320
+ "coeffs = {}\n",
321
+ "\n",
322
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
323
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
324
+ "\n",
325
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
326
+ "axes = axes.flatten()\n",
327
+ "features = X.columns\n",
328
+ "\n",
329
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
330
+ " # Sort features by absolute coefficient value\n",
331
+ " absolute_coef = np.abs(coef)\n",
332
+ " sorted_idx = np.argsort(absolute_coef)\n",
333
+ "\n",
334
+ " ax = axes[i]\n",
335
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
336
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
337
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
338
+ "\n",
339
+ "plt.tight_layout()\n",
340
+ "plt.show()"
341
+ ],
342
+ "execution_count": null,
343
+ "outputs": []
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "metadata": {},
348
+ "source": [
349
+ "# Task 2: Write your code here:\n",
350
+ "\n",
351
+ "# Plot as a linear plot\n",
352
+ "\n",
353
+ "#plt.figure(figsize=(6, 4))\n",
354
+ "#plt.scatter(y_test, y_pred, alpha=0.6)\n",
355
+ "#plt.plot(\n",
356
+ " # [y_test.min(), y_test.max()],\n",
357
+ " # [y_test.min(), y_test.max()],\n",
358
+ " # \"r--\",\n",
359
+ " # linewidth=2\n",
360
+ "#)\n",
361
+ "#plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n",
362
+ "#plt.ylabel(\"Predicted Exam Scores\")\n",
363
+ "#plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
364
+ "#plt.grid(True)\n",
365
+ "#plt.tight_layout()\n",
366
+ "#plt.show()\n",
367
+ "\n",
368
+ "\n",
369
+ "def check_target_distribution(df, y_hat):\n",
370
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
371
+ "\n",
372
+ " plt.title(f\"Target Distribution ({y_hat})\")\n",
373
+ " plt.xlabel(target_column)\n",
374
+ " plt.ylabel(\"Frequency\")\n",
375
+ " plt.grid(False)\n",
376
+ "\n",
377
+ " plt.show()\n",
378
+ "\n",
379
+ "check_target_distribution(df, \"Delivery_Time\")"
380
+ ],
381
+ "execution_count": null,
382
+ "outputs": []
383
+ },
384
+ {
385
+ "cell_type": "code",
386
+ "metadata": {},
387
+ "source": [
388
+ "# Task Bonus: Write your code here:"
389
+ ],
390
+ "execution_count": null,
391
+ "outputs": []
392
+ }
393
+ ],
394
+ "metadata": {
395
+ "kernelspec": {
396
+ "display_name": "Python 3",
397
+ "name": "python3"
398
+ },
399
+ "language_info": {
400
+ "name": "python"
401
+ }
402
+ },
403
+ "nbformat": 4,
404
+ "nbformat_minor": 0
405
+ }
submissions_extracted/832/Q2.ipynb ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 sklearn.model_selection import train_test_split\n",
70
+ "from sklearn.preprocessing import StandardScaler\n",
71
+ "from torch.utils.data import TensorDataset\n",
72
+ "from torch.utils.data import DataLoader\n",
73
+ "import torch\n",
74
+ "# transform to tensors\n",
75
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
76
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
77
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
78
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
79
+ "\n",
80
+ "\n"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# 2. Create TensorDataset objects\n",
90
+ "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 torchvision.datasets import MNIST\n",
102
+ "from torchvision.transforms.functional import to_tensor\n",
103
+ "\n",
104
+ "# Training dataset\n",
105
+ "train_dataset = MNIST(\n",
106
+ " root='./datasets',\n",
107
+ " train=True,\n",
108
+ " transform=to_tensor,\n",
109
+ " download=True\n",
110
+ ")\n",
111
+ "\n",
112
+ "# Testing dataset\n",
113
+ "test_dataset = MNIST(\n",
114
+ " root='./datasets',\n",
115
+ " train=False,\n",
116
+ " transform=to_tensor,\n",
117
+ " download=True\n",
118
+ ")\n"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# 4. Print shape of one batch\n",
128
+ "\n",
129
+ "sample_image, sample_label = train_dataset[0]"
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
+ "sample_image, sample_label = train_dataset[0]\n",
141
+ "\n",
142
+ "print(f\"\\n Image shape: {sample_image.shape}\")\n",
143
+ "print(f\"Label: {sample_label}\")"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "\n",
153
+ "import torch\n",
154
+ "import torch.nn as nn\n",
155
+ "\n",
156
+ "# Create a linear layer: 3 input features -> 1 output\n",
157
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
158
+ "\n",
159
+ "# Example input: batch of 4 samples, each with 3 features\n",
160
+ "x = torch.randn(4, 3)\n",
161
+ "\n",
162
+ "# Forward through the layer\n",
163
+ "y = linear(x)\n",
164
+ "\n",
165
+ "print(\"Input shape:\", x.shape)\n",
166
+ "print(\"Output shape:\", y.shape)\n",
167
+ "\n",
168
+ "class NN2Layer(nn.Module):\n",
169
+ "\n",
170
+ " def __init__(self, input_dim, hidden_dim):\n",
171
+ "\n",
172
+ " super(NN2Layer, self).__init__()\n",
173
+ " # input_dim = num of features, hidden_dim = num of neurons\n",
174
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
175
+ " self.layer2 = nn.Linear(4, 1)\n",
176
+ "\n",
177
+ " # non-linearity activation function\n",
178
+ " self.relu = nn.ReLU()\n",
179
+ " # output activation function\n",
180
+ " self.sigmoid = nn.Sigmoid()\n",
181
+ "\n",
182
+ " # forward pass\n",
183
+ " def forward(self, x):\n",
184
+ " z1 = self.layer1(x)\n",
185
+ " a1 = self.relu(z1)\n",
186
+ " z2 = self.layer2(a1)\n",
187
+ " a2 = self.sigmoid(z2)\n",
188
+ " return a2"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 2: Write your training loop here:"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 3: Write your validation loop here:"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 4: Define device, model, loss, optimizer:\n",
216
+ "\n",
217
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
218
+ "\n",
219
+ " model.train()\n",
220
+ "\n",
221
+ " running_loss = 0.0\n",
222
+ "\n",
223
+ " for X_batch, y_batch in train_loader:\n",
224
+ " # Move batch to the selected device\n",
225
+ " X_batch = X_batch.to(device)\n",
226
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
227
+ "\n",
228
+ " # Forward pass\n",
229
+ " outputs = model(X_batch)\n",
230
+ " loss = criterion(outputs, y_batch)\n",
231
+ "\n",
232
+ " optimizer.zero_grad()\n",
233
+ " loss.backward()\n",
234
+ " optimizer.step()\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 5: Start training for 20 epochs:\n",
251
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
252
+ "print(f\"Using device: {device}\")\n",
253
+ "\n",
254
+ "num_epochs = 50\n",
255
+ "learning_rate = 0.001\n",
256
+ "\n",
257
+ "# Model, Criterion, Optimizer\n",
258
+ "input_dim = X_train.shape[1]\n",
259
+ "hidden_dim = 10\n",
260
+ "model =NN2Layer(input_dim, hidden_dim).to(device)\n",
261
+ "criterion = nn.BCELoss()\n",
262
+ "optimizer = Adam(model.parameters(), lr=learning_rate)\n",
263
+ "\n",
264
+ "\n",
265
+ "# Run Training\n",
266
+ "train_losses = []\n",
267
+ "val_losses = []\n",
268
+ "val_accuracies = []\n",
269
+ "\n",
270
+ "print('Starting Training...')\n",
271
+ "for epoch in range(num_epochs):\n",
272
+ " # Train one epoch\n",
273
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
274
+ "\n",
275
+ " # Validate\n",
276
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
277
+ "\n",
278
+ " train_losses.append(train_loss)\n",
279
+ " val_losses.append(val_loss)\n",
280
+ " val_accuracies.append(val_accuracy)\n",
281
+ "\n",
282
+ " if (epoch + 1) % 5 == 0:\n",
283
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
284
+ "\n",
285
+ "print('Training Complete!')"
286
+ ],
287
+ "execution_count": null,
288
+ "outputs": []
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "metadata": {},
293
+ "source": [
294
+ "# Task 1: Write your code here:\n",
295
+ "# Plotting results\n",
296
+ "plt.figure(figsize=(7, 5))\n",
297
+ "\n",
298
+ "plt.plot(train_losses, label='Train Loss')\n",
299
+ "plt.plot(val_losses, label='Validation Loss')\n",
300
+ "plt.title('Loss over Epochs')\n",
301
+ "plt.xlabel('Epoch')\n",
302
+ "plt.ylabel('Loss')\n",
303
+ "plt.legend()\n",
304
+ "\n",
305
+ "plt.tight_layout()\n",
306
+ "plt.show()"
307
+ ],
308
+ "execution_count": null,
309
+ "outputs": []
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "metadata": {},
314
+ "source": [
315
+ "# Task 2 (Bonus): Write your code here:"
316
+ ],
317
+ "execution_count": null,
318
+ "outputs": []
319
+ }
320
+ ],
321
+ "metadata": {
322
+ "kernelspec": {
323
+ "display_name": "Python 3",
324
+ "name": "python3"
325
+ },
326
+ "language_info": {
327
+ "name": "python"
328
+ }
329
+ },
330
+ "nbformat": 4,
331
+ "nbformat_minor": 0
332
+ }
submissions_extracted/832/Q3.ipynb ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "# Download latest version\n",
11
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
12
+ "\n",
13
+ "\n",
14
+ "print(\"Path to dataset files:\", path)"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "# Task 1: Write your code here:\n",
24
+ "df =pd.read_csv(f\"{path}/Q3_data.csv\")\n",
25
+ "\n",
26
+ "#csv_path = os.path.join(path,\"Q3_data.csv\")\n",
27
+ "#df = pd.read_csv(csv_path)\n"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 2: Write your code here:\n",
37
+ "df.head()"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 3: Write your code here:\n",
47
+ "df.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 4: Write your code here:\n",
57
+ "df.describe()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 1: Write your code here:\n",
67
+ "def check_missing_values(df):\n",
68
+ " missing_values = df.isnull().sum()\n",
69
+ " print(\"Missing Values per Column:\")\n",
70
+ " print(missing_values[missing_values > 0])\n",
71
+ " if missing_values.any():\n",
72
+ " print(\"\\nHandle Missing Values as needed.\")\n",
73
+ " else:\n",
74
+ " print(\"\\nNo Missing Values Found.\")\n",
75
+ "\n",
76
+ "check_missing_values(df)\n",
77
+ "\n"
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()\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)\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:"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 4: Write your code here:"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# Task 5: Write your code here:"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 1: Write your code here:"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 2,3,4,5: Write your code here:"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 1: Write your code here:"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 2: Write your code here:"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task Bonus: Write your code here:"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ }
174
+ ],
175
+ "metadata": {
176
+ "kernelspec": {
177
+ "display_name": "Python 3",
178
+ "name": "python3"
179
+ },
180
+ "language_info": {
181
+ "name": "python"
182
+ }
183
+ },
184
+ "nbformat": 4,
185
+ "nbformat_minor": 0
186
+ }
submissions_extracted/833/Q1.ipynb ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import seaborn as sns\n",
27
+ "\n",
28
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
29
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
30
+ "from sklearn.ensemble import RandomForestClassifier\n",
31
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
32
+ "from sklearn.ensemble import RandomForestRegressor\n",
33
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
34
+ "\n",
35
+ "import warnings\n",
36
+ "warnings.filterwarnings('ignore')"
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
+ "# Load the CSV file\n",
47
+ "food_path = os.path.join(path, 'Q1_data.csv')\n",
48
+ "df_food = pd.read_csv(food_path)\n",
49
+ "\n",
50
+ "print(f\"Shape: {df_food.shape}\")\n"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "df_og = pd.read_csv(food_path)"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 2: Write your code here:\n",
69
+ "df_food.head()"
70
+ ],
71
+ "execution_count": null,
72
+ "outputs": []
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "metadata": {},
77
+ "source": [
78
+ "# Task 3: Write your code here:\n",
79
+ "df_food.info()"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# Task 4: Write your code here:\n",
89
+ "df_food.describe()"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 5: Write your code here:\n",
99
+ "plt.figure(figsize=(10, 5)) #Figure size\n",
100
+ "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black') # choosing what column to show\n",
101
+ "plt.title('Delivery Time Distribution')\n",
102
+ "plt.xlabel('Delivery Time')\n",
103
+ "plt.ylabel('Frequency') # Y Axis\n",
104
+ "plt.show()"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 1: Write your code here:\n",
114
+ "df_food.drop(columns=['Order_ID'])\n",
115
+ "print(f\"Shape after dropping: {df_food.shape}\")"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "df_food.info()"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 2: Write your code here:\n",
134
+ "# i dropped all the missing values from all the rows\n",
135
+ "df_food = df_food.dropna(subset=['Weather'])\n",
136
+ "df_food = df_food.dropna(subset=['Time_of_Day'])\n",
137
+ "df_food = df_food.dropna(subset=['Courier_Experience_yrs'])\n",
138
+ "df_food = df_food.dropna(subset=['Delivery_Time'])"
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
+ "\n",
149
+ "def check_duplicates(df):\n",
150
+ " duplicates = df_food.duplicated().sum() #First we track the number of dublicates\n",
151
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
152
+ " if duplicates > 0:\n",
153
+ " print(\"Dropping Duplicates...\")\n",
154
+ " df_food.drop_duplicates(inplace=True) #Then we drop all dublicates if founded\n",
155
+ "\n",
156
+ " print(\"Duplicates Dropped.\")\n",
157
+ " else:\n",
158
+ " print(\"No Duplicate Samples Found.\")\n",
159
+ "\n",
160
+ "check_duplicates(df_food)"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "df_food"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 4: Write your code here:\n",
179
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
180
+ "for col in categorical_cols:\n",
181
+ " le = LabelEncoder()\n",
182
+ " df_food[col] = le.fit_transform(df_food[col].astype(str))\n",
183
+ "\n",
184
+ "df_food.head()"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 5: Write your code here:\n",
194
+ "\n",
195
+ "# Define features (X) and target (y)\n",
196
+ "feature_cols = ['Order_ID', 'Distance_km', 'Weather', 'Traffic_Level',\n",
197
+ " 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
198
+ "X = df_food[feature_cols]\n",
199
+ "y = df_food['Delivery_Time']\n",
200
+ "\n",
201
+ "# Train-test split (80% train, 20% test)\n",
202
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
203
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
204
+ "\n",
205
+ "# scaling all the columns:\n",
206
+ "scaler = StandardScaler()\n",
207
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
208
+ "X_test_scaled = scaler.transform(X_test)\n",
209
+ "\n",
210
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
211
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(5)"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task 6: Write your code here:\n",
221
+ "#1. Is the target imbalanced?\n",
222
+ "def check_target_imbalance(df, target_column):\n",
223
+ " print(\"Target Distribution:\")\n",
224
+ " print(df[target_column].value_counts(normalize=True))\n",
225
+ " sns.countplot(x=df[target_column])\n",
226
+ " plt.title(\"Target Distribution\")\n",
227
+ " plt.show()\n",
228
+ "\n",
229
+ "check_target_imbalance(df_food, \"Delivery_Time\")"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Task 1: Write your code here:\n",
239
+ "\n",
240
+ "#((Already Done splitting in Task 5))"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {},
248
+ "source": [
249
+ "# Task 2,3,4,5: Write your code here:\n",
250
+ "\n",
251
+ "# Train Random Forest Regressor\n",
252
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
253
+ "model.fit(X_train_scaled, y_train)\n",
254
+ "print(\"Model trained!\")\n",
255
+ "\n",
256
+ "# Predict and evaluate\n",
257
+ "y_pred = model.predict(X_test_scaled)\n",
258
+ "\n",
259
+ "mae = mean_absolute_error(y_test, y_pred)\n",
260
+ "\n",
261
+ "print(f\"MAE: ${mae:,.2f}\")\n"
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
+ "# Feature importance\n",
272
+ "feature_importance = pd.DataFrame({\n",
273
+ " 'feature': feature_cols,\n",
274
+ " 'importance': model.feature_importances_\n",
275
+ "}).sort_values('importance', ascending=False)\n",
276
+ "\n",
277
+ "plt.figure(figsize=(10, 6))\n",
278
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
279
+ "plt.xlabel('Importance')\n",
280
+ "plt.title('Feature Importance')\n",
281
+ "plt.gca().invert_yaxis()\n",
282
+ "plt.show()"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "metadata": {},
290
+ "source": [
291
+ "# Task 2: Write your code here:"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "metadata": {},
299
+ "source": [
300
+ "# Task Bonus: Write your code here:"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ }
305
+ ],
306
+ "metadata": {
307
+ "kernelspec": {
308
+ "display_name": "Python 3",
309
+ "name": "python3"
310
+ },
311
+ "language_info": {
312
+ "name": "python"
313
+ }
314
+ },
315
+ "nbformat": 4,
316
+ "nbformat_minor": 0
317
+ }
submissions_extracted/833/Q2.ipynb ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch\n",
24
+ "import torch.nn as nn\n",
25
+ "from torch.optim import Adam\n",
26
+ "import matplotlib.pyplot as plt\n",
27
+ "import torch.nn.functional as F\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"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "import os\n",
40
+ "import pandas as pd\n",
41
+ "import numpy as np\n",
42
+ "from PIL import Image\n",
43
+ "from sklearn.model_selection import train_test_split\n",
44
+ "\n",
45
+ "# Load Labels\n",
46
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
47
+ "img_dir = os.path.join(path, \"images\")\n",
48
+ "\n",
49
+ "images = []\n",
50
+ "ages = []\n",
51
+ "\n",
52
+ "# Load Images and Resize\n",
53
+ "print(\"Loading images...\")\n",
54
+ "for index, row in labels_df.iterrows():\n",
55
+ " img_name = row.iloc[0]\n",
56
+ " age = row.iloc[1]\n",
57
+ " img_path = os.path.join(img_dir, img_name)\n",
58
+ "\n",
59
+ " if os.path.exists(img_path):\n",
60
+ " img = Image.open(img_path).convert('RGB')\n",
61
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
62
+ " images.append(img_array)\n",
63
+ " ages.append(age)\n",
64
+ "\n",
65
+ "X = np.array(images)\n",
66
+ "y = np.array(ages)\n",
67
+ "\n",
68
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
69
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
70
+ "\n",
71
+ "# Split Data\n",
72
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
73
+ "\n",
74
+ "print(f\"X_train shape: {X_train.shape}\")\n",
75
+ "print(f\"X_test shape: {X_test.shape}\")\n",
76
+ "print(f\"y_train shape: {y_train.shape}\")\n",
77
+ "print(f\"y_test shape: {y_test.shape}\")"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
87
+ "# 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.long)\n",
91
+ "y_test = torch.tensor(y_test, dtype=torch.long)"
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
+ "# Create TensorDatasets for training and testing\n",
103
+ "train_dataset = TensorDataset(X_train, y_train)\n",
104
+ "test_dataset = TensorDataset(X_test, y_test)\n",
105
+ "\n"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# 3. Create DataLoaders\n",
115
+ "# Create Dataloaders to train and test data in batches\n",
116
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
117
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# 4. Print shape of one batch\n",
127
+ "\n",
128
+ "# Get the first batch from the training DataLoader\n",
129
+ "X_batch, y_batch = next(iter(train_loader))\n",
130
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# 5. Display sample images\n",
140
+ "fig, axes = plt.subplots(2, 10, figsize=(16, 5))\n"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Task 1: Write your model class here:\n",
150
+ "class NN4Layer(nn.Module):\n",
151
+ "\n",
152
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
153
+ " super(NN4Layer, self).__init__()\n",
154
+ "\n",
155
+ " # 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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
195
+ " # Set the model to training mode\n",
196
+ " model.train()\n",
197
+ "\n",
198
+ " running_loss = 0.0\n",
199
+ "\n",
200
+ " for X_batch, y_batch in train_loader:\n",
201
+ " # Move batch to the selected device\n",
202
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
203
+ " y_batch = y_batch.to(device)\n",
204
+ "\n",
205
+ " # Forward pass\n",
206
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
207
+ " loss = criterion(outputs, y_batch)\n",
208
+ "\n",
209
+ " # Backward pass & optimization\n",
210
+ " optimizer.zero_grad() # Clear previous gradients\n",
211
+ " loss.backward() # Compute gradients\n",
212
+ " optimizer.step() # Update model parameters\n",
213
+ "\n",
214
+ " running_loss += loss.item()\n",
215
+ "\n",
216
+ " # Average loss over all batches\n",
217
+ " avg_loss = running_loss / len(train_loader)\n",
218
+ "\n",
219
+ " return avg_loss"
220
+ ],
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "metadata": {},
227
+ "source": [
228
+ "# Task 3: Write your validation loop here:\n",
229
+ "def validate(model, criterion, test_loader, device):\n",
230
+ " # Set the model to evaluation mode\n",
231
+ " model.eval()\n",
232
+ "\n",
233
+ " running_loss = 0.0\n",
234
+ " correct = 0\n",
235
+ " total = 0\n",
236
+ "\n",
237
+ " with torch.no_grad():\n",
238
+ " for X_batch, y_batch in test_loader:\n",
239
+ " # Move data to device\n",
240
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
241
+ " y_batch = y_batch.to(device)\n",
242
+ "\n",
243
+ " # Forward pass\n",
244
+ " outputs = model(X_batch)\n",
245
+ " loss = criterion(outputs, y_batch)\n",
246
+ " running_loss += loss.item()\n",
247
+ "\n",
248
+ " # Apply Softmax to get probabilities\n",
249
+ " probabilities = F.softmax(outputs, dim=1)\n",
250
+ "\n",
251
+ " # Multiclass predictions\n",
252
+ " predicted = torch.argmax(probabilities, dim=1)\n",
253
+ "\n",
254
+ " # Accuracy calculation\n",
255
+ " correct += (predicted == y_batch).sum().item()\n",
256
+ " total += y_batch.size(0)\n",
257
+ "\n",
258
+ " avg_loss = running_loss / len(test_loader)\n",
259
+ " accuracy = correct / total\n",
260
+ "\n",
261
+ " return avg_loss, accuracy\n"
262
+ ],
263
+ "execution_count": null,
264
+ "outputs": []
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "metadata": {},
269
+ "source": [
270
+ "# Task 4: Define device, model, loss, optimizer:\n",
271
+ "\n",
272
+ "# Device setup\n",
273
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
274
+ "\n",
275
+ "# Model parameters\n",
276
+ "input_dim = 3888\n",
277
+ "hidden_dim = 14 # Design choice\n",
278
+ "output_dim = 1\n",
279
+ "\n",
280
+ "# Instantiate model\n",
281
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
282
+ "\n",
283
+ "# Print the model architecture\n",
284
+ "print(\"Model Architecture:\\n\")\n",
285
+ "print(model)\n",
286
+ "\n",
287
+ "num_epochs = 20\n",
288
+ "learning_rate = 0.001\n",
289
+ "\n",
290
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
291
+ "criterion = nn.CrossEntropyLoss()\n",
292
+ "# Define optimizer\n",
293
+ "optimizer = Adam(model.parameters(), learning_rate)"
294
+ ],
295
+ "execution_count": null,
296
+ "outputs": []
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "metadata": {},
301
+ "source": [
302
+ "# Task 5: Start training for 20 epochs:\n",
303
+ "\n",
304
+ "# Run Training\n",
305
+ "train_losses = []\n",
306
+ "val_losses = []\n",
307
+ "val_accuracies = []\n",
308
+ "\n",
309
+ "print('Starting Training...')\n",
310
+ "for epoch in range(num_epochs):\n",
311
+ " # Train one epoch\n",
312
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
313
+ "\n",
314
+ " # Validate\n",
315
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
316
+ "\n",
317
+ " train_losses.append(train_loss)\n",
318
+ " val_losses.append(val_loss)\n",
319
+ " val_accuracies.append(val_accuracy)\n",
320
+ "\n",
321
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
322
+ "\n",
323
+ "print('Training Complete!')"
324
+ ],
325
+ "execution_count": null,
326
+ "outputs": []
327
+ },
328
+ {
329
+ "cell_type": "code",
330
+ "metadata": {},
331
+ "source": [
332
+ "# Task 1: Write your code here:\n",
333
+ "# Plotting results\n",
334
+ "plt.figure(figsize=(7, 5))\n",
335
+ "\n",
336
+ "plt.plot(train_losses, label='Train Loss')\n",
337
+ "plt.plot(val_losses, label='Validation Loss')\n",
338
+ "plt.title('Loss over Epochs')\n",
339
+ "plt.xlabel('Epoch')\n",
340
+ "plt.ylabel('Loss')\n",
341
+ "plt.legend()\n",
342
+ "\n",
343
+ "plt.tight_layout()\n",
344
+ "plt.show()"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task 2 (Bonus): Write your code here:"
354
+ ],
355
+ "execution_count": null,
356
+ "outputs": []
357
+ }
358
+ ],
359
+ "metadata": {
360
+ "kernelspec": {
361
+ "display_name": "Python 3",
362
+ "name": "python3"
363
+ },
364
+ "language_info": {
365
+ "name": "python"
366
+ }
367
+ },
368
+ "nbformat": 4,
369
+ "nbformat_minor": 0
370
+ }
submissions_extracted/833/Q3.ipynb ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import numpy as np\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import seaborn as sns\n",
12
+ "import kagglehub\n",
13
+ "import os\n",
14
+ "from tqdm import tqdm\n",
15
+ "\n",
16
+ "%matplotlib inline\n",
17
+ "\n",
18
+ "\n",
19
+ "# Download latest version\n",
20
+ "\n",
21
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
22
+ "\n",
23
+ "\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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
36
+ "\n",
37
+ "df = pd.read_csv(csv_path)\n"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df.head(20)"
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"
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
+ "# Data Frame has no values"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# Task 3: Write your code here:"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 4: Write your code here:"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# Task 5: Write your code here:"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# Task 1: Write your code here:"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 2,3,4,5: Write your code here:"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 1: Write your code here:"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 2: Write your code here:"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task Bonus: Write your code here:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ }
164
+ ],
165
+ "metadata": {
166
+ "kernelspec": {
167
+ "display_name": "Python 3",
168
+ "name": "python3"
169
+ },
170
+ "language_info": {
171
+ "name": "python"
172
+ }
173
+ },
174
+ "nbformat": 4,
175
+ "nbformat_minor": 0
176
+ }
submissions_extracted/834/Q1.ipynb ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "from sklearn.preprocessing import StandardScaler\n",
12
+ "from sklearn.preprocessing import OneHotEncoder\n",
13
+ "from sklearn.ensemble import RandomForestClassifier\n",
14
+ "from sklearn.model_selection import StratifiedKFold,train_test_split\n",
15
+ "from sklearn.metrics import mean_absolute_error\n",
16
+ "# Download latest version\n",
17
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
18
+ "print(\"Path to dataset files:\", path)"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "# Task 1: Write your code here:\n",
28
+ "df = pd.read_csv(f\"{path}/Q1_data.csv\")\n",
29
+ "# Print first 5 rows\n",
30
+ "print(df)"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# Task 2: Write your code here:\n",
40
+ "df.head() # to show first 5 columns"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 3: Write your code here:\n",
50
+ "df.info() # check info"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 4: Write your code here:\n",
60
+ "df.describe() # to show all information"
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
+ "plt.figure(figsize=(10, 5))\n",
71
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
72
+ "plt.title('Delivery Time Distribution')\n",
73
+ "plt.ylabel('Time')\n",
74
+ "plt.show()\n",
75
+ "\n",
76
+ "\n",
77
+ "\n",
78
+ "\n",
79
+ "# another way to plot\n",
80
+ "df['Delivery_Time'].hist()"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 1: Write your code here:\n",
90
+ "df= df.drop(\"Order_ID\", axis=1) # deleting Order id coulmn\n",
91
+ "print(df)"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 2: Write your code here:\n",
101
+ "df.isna().sum() # checking for missing values\n",
102
+ "df_clean = df.copy()\n",
103
+ "for col in['Delivery_Time', 'Courier_Experience_yrs', 'Traffic_Level', 'Weather']:\n",
104
+ " df_clean[col] = df_clean[col].fillna(df_clean.mode()[0])\n",
105
+ "\n",
106
+ "df"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 3: Write your code here:\n",
116
+ "df.duplicated().sum() # checking for duplicated data\n",
117
+ "# df.drop(columns=duplicated, axis=1)"
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
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
128
+ "label_encoders = {}\n",
129
+ "for col in categorical_cols:\n",
130
+ " oe = OneHotEncoder(sparse_output=False)\n",
131
+ " df_clean[col] = oe.fit_transform(df_clean[col])\n",
132
+ " label_encoders[col] = oe\n",
133
+ "\n",
134
+ "df_clean"
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
+ "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # we don't scale the target\n",
145
+ "\n",
146
+ "scaler = StandardScaler()\n",
147
+ "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
148
+ "df_clean.head()"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 6: Write your code here:\n",
158
+ "df_clean['Delivery_Time'].hist()"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 1: Write your code here:\n",
168
+ "X = df_clean.drop(\"Delivery_Time\",axis=1).astype(float)\n",
169
+ "y = df_clean[\"Delivery_Time\"].astype(float)"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 2,3,4,5: Write your code here:\n",
179
+ "n_splits = 5\n",
180
+ "skf = StratifiedKFold(n_splits=n_splits,shuffle=True,random_state=42)\n",
181
+ "model = RandomForestClassifier(n_estimators=200,max_depth=10)\n",
182
+ "mae_scores = []\n",
183
+ "# Fit the model on train data\n",
184
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
185
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
186
+ "\n",
187
+ " # Split data\n",
188
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
189
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
190
+ " mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
191
+ "\n",
192
+ " for model_name, model in model():\n",
193
+ " print(f\"Training {model_name}...\")\n",
194
+ " model.fit(X_train, y_train) # train\n",
195
+ " y_pred = model.predict(X_test) # validate\n",
196
+ "\n",
197
+ "#metric\n",
198
+ "print(f\"MAE : {np.mean(mae_scores):.2f}\")"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 1: Write your code here:\n",
208
+ "feature_cols = [\"Weather\", 'Time_of_Day', \"Traffic_Level\", \"Time_of_Day\",\t\"Vehicle_Type\",\t\"Preparation_Time_min\",\t\"Courier_Experience_yrs\"\n",
209
+ " 'importance']\n",
210
+ "feature_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(feature_importance['feature'], feature_importance['importance'])\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:\n",
230
+ "df_clean[y_test].hist()"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task Bonus: Write your code here:"
240
+ ],
241
+ "execution_count": null,
242
+ "outputs": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "metadata": {},
247
+ "source": [],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ }
251
+ ],
252
+ "metadata": {
253
+ "kernelspec": {
254
+ "display_name": "Python 3",
255
+ "name": "python3"
256
+ },
257
+ "language_info": {
258
+ "name": "python"
259
+ }
260
+ },
261
+ "nbformat": 4,
262
+ "nbformat_minor": 0
263
+ }
submissions_extracted/834/Q2.ipynb ADDED
@@ -0,0 +1,372 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 numpy as np\n",
11
+ "from PIL import Image\n",
12
+ "from sklearn.model_selection import train_test_split\n",
13
+ "import torch\n",
14
+ "import torch.nn as nn\n",
15
+ "from torch.optim import AdamW\n",
16
+ "from torch.utils.data import TensorDataset\n",
17
+ "from torch.utils.data import DataLoader\n",
18
+ "import matplotlib.pyplot as plt\n",
19
+ "from torchvision.datasets import MNIST\n",
20
+ "from torchvision.transforms.functional import to_tensor\n",
21
+ "import torch.nn.functional as F\n",
22
+ "\n",
23
+ "# Download latest version\n",
24
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
25
+ "\n",
26
+ "print(\"Path to dataset files:\", path)"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "\n",
36
+ "\n",
37
+ "\n",
38
+ "# Load Labels\n",
39
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
40
+ "img_dir = os.path.join(path, \"images\")\n",
41
+ "\n",
42
+ "images = []\n",
43
+ "ages = []\n",
44
+ "\n",
45
+ "# Load Images and Resize\n",
46
+ "print(\"Loading images...\")\n",
47
+ "for index, row in labels_df.iterrows():\n",
48
+ " img_name = row.iloc[0]\n",
49
+ " age = row.iloc[1]\n",
50
+ " img_path = os.path.join(img_dir, img_name)\n",
51
+ "\n",
52
+ " if os.path.exists(img_path):\n",
53
+ " img = Image.open(img_path).convert('RGB')\n",
54
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
55
+ " images.append(img_array)\n",
56
+ " ages.append(age)\n",
57
+ "\n",
58
+ "X = np.array(images)\n",
59
+ "y = np.array(ages)\n",
60
+ "\n",
61
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
62
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
63
+ "\n",
64
+ "# Split Data\n",
65
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
66
+ "\n",
67
+ "print(f\"X_train shape: {X_train.shape}\")\n",
68
+ "print(f\"X_test shape: {X_test.shape}\")\n",
69
+ "print(f\"y_train shape: {y_train.shape}\")\n",
70
+ "print(f\"y_test shape: {y_test.shape}\")"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
80
+ "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
+ "\n",
94
+ "train_dataset = TensorDataset(X_train, y_train)\n",
95
+ "test_dataset = TensorDataset(X_test, y_test)"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# 3. Create DataLoaders\n",
105
+ "\n",
106
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
107
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# 4. Print shape of one batch\n",
117
+ "\n",
118
+ "sample_image = train_dataset[0]\n",
119
+ "\n",
120
+ "print(f\"\\n Image shape: {sample_image.shape}\")"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# 5. Display sample images\n",
130
+ "\n",
131
+ "images= next(iter(train_loader))\n",
132
+ "\n",
133
+ "# Display the first 6 images in the batch\n",
134
+ "plt.figure(figsize=(8, 4))\n",
135
+ "\n",
136
+ "for i in range(6):\n",
137
+ " plt.subplot(2, 3, i + 1)\n",
138
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
139
+ " plt.axis('off')\n",
140
+ "\n",
141
+ "plt.tight_layout()\n",
142
+ "plt.show()"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 1: Write your model class here:\n",
152
+ "class NN4Layer(nn.Module):\n",
153
+ "\n",
154
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
155
+ " super(NN4Layer, self).__init__()\n",
156
+ "\n",
157
+ " # First linear layer: input features -> hidden layer\n",
158
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
159
+ "\n",
160
+ " # Second linear layer: hidden layer -> hidden layer\n",
161
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
162
+ "\n",
163
+ " # third layer: hidden layer -> number of classes (logits)\n",
164
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
165
+ "\n",
166
+ " # Output layer: hidden layer -> number of classes (logits)\n",
167
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
168
+ "\n",
169
+ " # ReLU activation for non-linearity\n",
170
+ " self.relu = nn.ReLU()\n",
171
+ "\n",
172
+ " # Defines how input data flows through the network\n",
173
+ " def forward(self, x):\n",
174
+ " # First hidden layer\n",
175
+ " z1 = self.layer1(x)\n",
176
+ " a1 = self.relu(z1)\n",
177
+ "\n",
178
+ " # Second hidden layer\n",
179
+ " z2 = self.layer2(a1)\n",
180
+ " a2 = self.relu(z2)\n",
181
+ " a3 = self.relu(a2)\n",
182
+ " # Output layer (raw scores / logits)\n",
183
+ " output = self.layer3(a3) # there is something missing here, remember? :)\n",
184
+ "\n",
185
+ " return output\n"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 2: Write your training loop here:\n",
195
+ "\n",
196
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
197
+ " # Set the model to training mode\n",
198
+ " model.train()\n",
199
+ "\n",
200
+ " running_loss = 0.0\n",
201
+ "\n",
202
+ " for X_batch, y_batch in train_loader:\n",
203
+ " # Move batch to the selected device\n",
204
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
205
+ " y_batch = y_batch.to(device)\n",
206
+ "\n",
207
+ " # Forward pass\n",
208
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
209
+ " loss = criterion(outputs, y_batch)\n",
210
+ "\n",
211
+ " # Backward pass & optimization\n",
212
+ " optimizer.zero_grad() # Clear previous gradients\n",
213
+ " loss.backward() # Compute gradients\n",
214
+ " optimizer.step() # Update model parameters\n",
215
+ "\n",
216
+ " running_loss += loss.item()\n",
217
+ "\n",
218
+ " # Average loss over all batches\n",
219
+ " avg_loss = running_loss / len(train_loader)\n",
220
+ "\n",
221
+ " return avg_loss"
222
+ ],
223
+ "execution_count": null,
224
+ "outputs": []
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "metadata": {},
229
+ "source": [
230
+ "# Task 3: Write your validation loop here:\n",
231
+ "\n",
232
+ "def validate(model, criterion, test_loader, device):\n",
233
+ " # Set the model to evaluation mode\n",
234
+ " model.eval()\n",
235
+ "\n",
236
+ " running_loss = 0.0\n",
237
+ " correct = 0\n",
238
+ " total = 0\n",
239
+ "\n",
240
+ " with torch.no_grad():\n",
241
+ " for X_batch, y_batch in test_loader:\n",
242
+ " # Move data to device\n",
243
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
244
+ " y_batch = y_batch.to(device)\n",
245
+ "\n",
246
+ " # Forward pass\n",
247
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
248
+ " loss = criterion(outputs, y_batch)\n",
249
+ " running_loss += loss.item()\n",
250
+ "\n",
251
+ " # Apply Softmax to get probabilities\n",
252
+ " probabilities = F.softmax(outputs, dim=1)\n",
253
+ "\n",
254
+ " # Multiclass predictions\n",
255
+ " predicted = torch.argmax(probabilities, dim=1)\n",
256
+ "\n",
257
+ " # Accuracy calculation\n",
258
+ " correct += (predicted == y_batch).sum().item()\n",
259
+ " total += y_batch.size(0)\n",
260
+ "\n",
261
+ " avg_loss = running_loss / len(test_loader)\n",
262
+ " accuracy = correct / total\n",
263
+ "\n",
264
+ " return avg_loss, accuracy\n"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "metadata": {},
272
+ "source": [
273
+ "# Task 4: Define device, model, loss, optimizer:\n",
274
+ "learning_rate = 0.001\n",
275
+ "input_dim = 3 * 36 * 36\n",
276
+ "hidden_dim = 32\n",
277
+ "output_dim = 1\n",
278
+ "\n",
279
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
280
+ "\n",
281
+ "\n",
282
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
283
+ "\n",
284
+ "\n",
285
+ "\n",
286
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
287
+ "criterion = nn.MSELoss()\n",
288
+ "# Define optimizer\n",
289
+ "optimizer = AdamW(model.parameters(), learning_rate)\n"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Task 5: Start training for 20 epochs:\n",
299
+ "num_epochs = 20\n",
300
+ "\n",
301
+ "train_losses = []\n",
302
+ "val_losses = []\n",
303
+ "val_accuracies = []\n",
304
+ "\n",
305
+ "print('Starting Training...')\n",
306
+ "for epoch in range(num_epochs):\n",
307
+ " # Train one epoch\n",
308
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
309
+ "\n",
310
+ " # Validate\n",
311
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
312
+ "\n",
313
+ " train_losses.append(train_loss)\n",
314
+ " val_losses.append(val_loss)\n",
315
+ " val_accuracies.append(val_accuracy)\n",
316
+ "\n",
317
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
318
+ "\n",
319
+ "print('Training Complete!')\n"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {},
327
+ "source": [
328
+ "# Task 1: Write your code here:\n",
329
+ "plt.figure(figsize=(7, 5))\n",
330
+ "\n",
331
+ "plt.plot(train_losses, label='Train Loss')\n",
332
+ "plt.plot(val_losses, label='Validation Loss')\n",
333
+ "plt.title('Loss over Epochs')\n",
334
+ "plt.xlabel('Epoch')\n",
335
+ "plt.ylabel('Loss')\n",
336
+ "plt.legend()\n",
337
+ "\n",
338
+ "plt.tight_layout()\n",
339
+ "plt.show()"
340
+ ],
341
+ "execution_count": null,
342
+ "outputs": []
343
+ },
344
+ {
345
+ "cell_type": "code",
346
+ "metadata": {},
347
+ "source": [
348
+ "# Task 2 (Bonus): Write your code here:"
349
+ ],
350
+ "execution_count": null,
351
+ "outputs": []
352
+ },
353
+ {
354
+ "cell_type": "code",
355
+ "metadata": {},
356
+ "source": [],
357
+ "execution_count": null,
358
+ "outputs": []
359
+ }
360
+ ],
361
+ "metadata": {
362
+ "kernelspec": {
363
+ "display_name": "Python 3",
364
+ "name": "python3"
365
+ },
366
+ "language_info": {
367
+ "name": "python"
368
+ }
369
+ },
370
+ "nbformat": 4,
371
+ "nbformat_minor": 0
372
+ }
submissions_extracted/834/Q3.ipynb ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch\n",
11
+ "import torch.nn as nn\n",
12
+ "from torch.optim import AdamW\n",
13
+ "import matplotlib.pyplot as plt\n",
14
+ "import torch.nn.functional as F\n",
15
+ "from torch.utils.data import DataLoader, TensorDataset\n",
16
+ "from sklearn.model_selection import train_test_split\n",
17
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
18
+ "import numpy as np\n",
19
+ "import seaborn as sns\n",
20
+ "import os\n",
21
+ "from tqdm import tqdm\n",
22
+ "from sklearn.model_selection import StratifiedKFold\n",
23
+ "from sklearn.metrics import accuracy_score, f1_score\n",
24
+ "from catboost import CatBoostClassifier\n",
25
+ "\n",
26
+ "# Download latest version\n",
27
+ "\n"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 1: Write your code here:\n",
37
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
38
+ "\n",
39
+ "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n",
40
+ "\n",
41
+ "\n",
42
+ "print(\"Path to dataset files:\", path)\n"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "df.head()\n"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 3: Write your code here:\n",
62
+ "df.info()\n"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 4: Write your code here:\n",
72
+ "df.describe()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 1: Write your code here:\n",
82
+ "\n",
83
+ "print(df.isnull().sum())\n",
84
+ "df = df.fillna(df.mean)\n",
85
+ "print(df.isnull().sum())"
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
+ "duplicates = df.duplicated().sum()\n",
96
+ "print(f\"Duplicates:{duplicates}\")"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 3: Write your code here:\n",
106
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
107
+ "\n",
108
+ "print(\"Categorical Columns:\", list(categorical_cols))"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ " # Task 4: Write your code here:\n",
118
+ "numerical_cols = df.select_dtypes('float32', 'number')\n",
119
+ "\n",
120
+ "scaler = StandardScaler()\n",
121
+ "\n",
122
+ "# scale the `numerical_cols`\n",
123
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
124
+ "\n",
125
+ "df.head()"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "def check_target_imbalance(df, target_column):\n",
135
+ " print(\"Target Distribution:\")\n",
136
+ "\n",
137
+ " df[target_column].hist() # Yeah you can just do this :)\n",
138
+ " plt.show()\n",
139
+ "\n",
140
+ "check_target_imbalance(df, \"P_2\")"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Task 1: Write your code here:\n",
150
+ "\n",
151
+ "X = df.drop(\"P_2\", axis=1).astype(float)\n",
152
+ "y = df['P_@'].astype(float)"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 2,3,4,5: Write your code here:\n",
162
+ "n_splits = 3 # K=3 Folds\n",
163
+ "model = CatBoostClassifier(verbose=0,n_estimators=200,max_depth=4)\n",
164
+ "\n",
165
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
166
+ "\n",
167
+ "\n",
168
+ "results = {}\n",
169
+ "\n",
170
+ "for model_name in model:\n",
171
+ " results[model_name] = {'recall': [], 'f1': []}\n",
172
+ "\n",
173
+ "\n",
174
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
175
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
176
+ "\n",
177
+ " # Get the train & test split for this fold\n",
178
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
179
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
180
+ "\n",
181
+ " # Train & Validate Models\n",
182
+ " for model_name, model in models.items():\n",
183
+ "\n",
184
+ " print(f\"Training {model_name}...\")\n",
185
+ "\n",
186
+ " # Fit the model on train data\n",
187
+ " model.fit(X_train, y_train)\n",
188
+ "\n",
189
+ " # Use the model to predict the test data\n",
190
+ " y_pred = model.predict(X_test)\n",
191
+ "\n",
192
+ " # Calculate evaluation metrics\n",
193
+ " accuracy = accuracy_score(y_test, y_pred)\n",
194
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
195
+ "\n",
196
+ " results[model_name]['accuracy'].append(accuracy)\n",
197
+ " results[model_name]['f1'].append(f1)\n",
198
+ "\n",
199
+ "print(f\" Accuracy: {np.mean(results[model_name]['accuracy']):.4f}\")\n",
200
+ "print(f\" F1-Score: {np.mean(results[model_name]['f1']):.4f}\")"
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
+ "feature_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(feature_importance['feature'], feature_importance['importance'])\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/835/Q1.ipynb ADDED
@@ -0,0 +1,283 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "import pandas as pd\n",
23
+ "data = pd.read_csv(f\"{path}/Q1_data.csv\")"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 2: Write your code here:\n",
33
+ "data.head()"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 3: Write your code here:\n",
43
+ "data.info()"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 4: Write your code here:\n",
53
+ "data.describe()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 5: Write your code here:\n",
63
+ "import matplotlib.pyplot as plt\n",
64
+ "import seaborn as sns\n",
65
+ "plt.figure(figsize=(10, 5))\n",
66
+ "plt.hist(data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
67
+ "plt.title('Delivery Time Distrbution')\n",
68
+ "plt.xlabel('Delivery Time')\n",
69
+ "plt.ylabel('Frequency')\n",
70
+ "plt.show()"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# Task 1: Write your code here:\n",
80
+ "order_dropped = data.drop('Order_ID', axis=1)\n",
81
+ "order_dropped.head()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 2: Write your code here:\n",
91
+ "missing_percentage = (order_dropped.isnull().sum() / len(order_dropped)) * 100\n",
92
+ "missing_data = pd.DataFrame({\n",
93
+ " 'Column': missing_percentage.index,\n",
94
+ " 'Missing_Percentage': missing_percentage.values\n",
95
+ "})\n",
96
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
97
+ "\n",
98
+ "print(\"Missing Data Analysis:\")\n",
99
+ "print(missing_data.head(10))\n",
100
+ "\n",
101
+ "print()\n",
102
+ "\n",
103
+ "print(f\"Before: {order_dropped.shape}\")\n",
104
+ "df_clean = order_dropped.dropna(subset=['Delivery_Time'])\n",
105
+ "print(f\"After dropping missing delivery time : {df_clean.shape}\")\n",
106
+ "\n",
107
+ "df_clean = df_clean.dropna()\n",
108
+ "print(f\"After dropping missing data in other columns: {df_clean.shape}\")\n"
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
+ "def check_duplicates(df):\n",
119
+ " duplicates = df.duplicated().sum()\n",
120
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
121
+ " if duplicates > 0:\n",
122
+ " print(\"Dropping Duplicates...\")\n",
123
+ " df.drop_duplicates(inplace=True)\n",
124
+ " print(\"Duplicates Dropped.\")\n",
125
+ " else:\n",
126
+ " print(\"No Duplicate Samples Found.\")\n",
127
+ "\n",
128
+ "check_duplicates(df_clean)"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 4: Write your code here:\n",
138
+ "from sklearn.preprocessing import OneHotEncoder\n",
139
+ "\n",
140
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
141
+ "\n",
142
+ "df_clean_cols = df_clean[categorical_cols].copy()\n",
143
+ "\n",
144
+ "encoder = OneHotEncoder(sparse_output=False)\n",
145
+ "encoded = encoder.fit_transform(df_clean)\n",
146
+ "\n",
147
+ "print(\"Original:\", df_clean_cols)\n",
148
+ "print(\"Encoded:\\n\", encoded)"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Write your code here:\n",
158
+ "from sklearn.preprocessing import StandardScaler\n",
159
+ "\n",
160
+ "numerical_cols = ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time']\n",
161
+ "df_clean_num_cols = df_clean[numerical_cols].copy()\n",
162
+ "\n",
163
+ "scaler = StandardScaler()\n",
164
+ "scaled = scaler.fit_transform(df_clean_num_cols)\n",
165
+ "\n",
166
+ "print(\"\\nScaled (mean≈0, std≈1):\\n\", scaled)\n",
167
+ "print(\"\\nMeans:\", scaled.mean(axis=0))\n",
168
+ "print(\"Stds:\", scaled.std(axis=0))"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 6: Write your code here:\n",
178
+ "\n",
179
+ "# Based on the first plotted plot then is there's a class imbalance."
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 1: Write your code here:\n",
189
+ "from sklearn.model_selection import train_test_split\n",
190
+ "\n",
191
+ "feature_cols = ['Distance_km', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
192
+ "\n",
193
+ "X = df_clean[feature_cols]\n",
194
+ "y = df_clean['Delivery_Time']\n",
195
+ "\n",
196
+ "# X.head()\n",
197
+ "# y.head()"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 2,3,4,5: Write your code here:\n",
207
+ "import numpy as np\n",
208
+ "from sklearn.model_selection import KFold\n",
209
+ "from sklearn.ensemble import RandomForestRegressor\n",
210
+ "from sklearn.metrics import mean_absolute_error\n",
211
+ "\n",
212
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
213
+ "mae_scores = []\n",
214
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
215
+ "\n",
216
+ "\n",
217
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
218
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
219
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
220
+ "\n",
221
+ " model.fit(X_train, y_train)\n",
222
+ "\n",
223
+ " y_preds = model.predict(X_test)\n",
224
+ " mae_scores.append(mean_absolute_error(y_test, y_preds))\n",
225
+ "\n",
226
+ " print(f\"Average MAE: {np.mean(mae_scores)}\")"
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
+ "plt.figure(figsize=(6, 4))\n",
237
+ "plt.scatter(y_test, y_preds, alpha=0.6)\n",
238
+ "plt.plot(\n",
239
+ " [y_test.min(), y_test.max()],\n",
240
+ " [y_test.min(), y_test.max()],\n",
241
+ " \"r--\",\n",
242
+ " linewidth=2\n",
243
+ ")\n",
244
+ "plt.grid(True)\n",
245
+ "plt.show()"
246
+ ],
247
+ "execution_count": null,
248
+ "outputs": []
249
+ },
250
+ {
251
+ "cell_type": "code",
252
+ "metadata": {},
253
+ "source": [
254
+ "# Task 2: Write your code here:\n",
255
+ "plt.figure(figsize=(6, 4))\n",
256
+ "sns.histplot(y_preds, kde=True)\n",
257
+ "plt.show()"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task Bonus: Write your code here:"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ }
271
+ ],
272
+ "metadata": {
273
+ "kernelspec": {
274
+ "display_name": "Python 3",
275
+ "name": "python3"
276
+ },
277
+ "language_info": {
278
+ "name": "python"
279
+ }
280
+ },
281
+ "nbformat": 4,
282
+ "nbformat_minor": 0
283
+ }
submissions_extracted/835/Q2.ipynb ADDED
@@ -0,0 +1,351 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch.utils.data import TensorDataset\n",
70
+ "from torch.utils.data import DataLoader\n",
71
+ "import torch\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)\n",
77
+ "\n"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# 2. Create TensorDataset objects\n",
87
+ "train_dataset = TensorDataset(X_train, y_train)\n",
88
+ "test_dataset = TensorDataset(X_test, y_test)\n",
89
+ "\n",
90
+ "sample_image, sample_label = train_dataset[0]\n",
91
+ "\n",
92
+ "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
93
+ "print(f\"Label: {sample_label}\")\n"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# 3. Create DataLoaders\n",
103
+ "from torch.utils.data import DataLoader\n",
104
+ "\n",
105
+ "train_loader = DataLoader(\n",
106
+ " train_dataset,\n",
107
+ " batch_size=32,\n",
108
+ " shuffle=True,\n",
109
+ ")\n",
110
+ "\n",
111
+ "test_loader = DataLoader(\n",
112
+ " test_dataset,\n",
113
+ " batch_size=32,\n",
114
+ " shuffle=False,\n",
115
+ ")"
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
+ "X_batch, y_batch = next(iter(train_loader))\n",
127
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
128
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# 5. Display sample images\n",
138
+ "import matplotlib.pyplot as plt\n",
139
+ "\n",
140
+ "images, labels = next(iter(train_loader))\n",
141
+ "\n",
142
+ "# Display the first 6 images in the batch\n",
143
+ "plt.figure(figsize=(32, 16))\n",
144
+ "\n",
145
+ "for i in range(6):\n",
146
+ " plt.subplot(2, 3, i + 1)\n",
147
+ " plt.imshow(images[i].squeeze())\n",
148
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
149
+ " plt.axis('off')\n",
150
+ "\n",
151
+ "plt.tight_layout()\n",
152
+ "plt.show()\n"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 1: Write your model class here:\n",
162
+ "import torch.nn as nn\n",
163
+ "class NN3Layer(nn.Module):\n",
164
+ " def __init__(self, input_dim, hidden_dim):\n",
165
+ " super(NN3Layer, self).__init__()\n",
166
+ "\n",
167
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
168
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
169
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
170
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
171
+ "\n",
172
+ " self.relu = nn.ReLU()\n",
173
+ "\n",
174
+ " def forward(self, x):\n",
175
+ " # x = x.view(x.size(0), -1)\n",
176
+ " a1 = self.relu(self.layer1(x))\n",
177
+ " a2 = self.relu(self.layer2(a1))\n",
178
+ " a3 = self.relu(self.layer2(a2))\n",
179
+ " output = self.layer3(a3)\n",
180
+ "\n",
181
+ " return output"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 2: Write your training loop here:\n",
191
+ "\n",
192
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
193
+ "\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
+ "\n",
200
+ " X_batch = X_batch.to(device)\n",
201
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
202
+ "\n",
203
+ " outputs = model(X_batch)\n",
204
+ " loss = criterion(outputs, y_batch)\n",
205
+ "\n",
206
+ " optimizer.zero_grad()\n",
207
+ " loss.backward()\n",
208
+ " optimizer.step()\n",
209
+ "\n",
210
+ " running_loss += loss.item()\n",
211
+ "\n",
212
+ "\n",
213
+ " avg_loss = running_loss / len(train_loader)\n",
214
+ "\n",
215
+ " return avg_loss"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Task 3: Write your validation loop here:\n",
225
+ "\n",
226
+ "def validate(model, criterion, test_loader, device):\n",
227
+ "\n",
228
+ " model.eval()\n",
229
+ "\n",
230
+ " running_loss = 0.0\n",
231
+ "\n",
232
+ " with torch.no_grad():\n",
233
+ " for X_batch, y_batch in test_loader:\n",
234
+ "\n",
235
+ " X_batch = X_batch.to(device)\n",
236
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
237
+ "\n",
238
+ " outputs = model(X_batch)\n",
239
+ " loss = criterion(outputs, y_batch)\n",
240
+ "\n",
241
+ " running_loss += loss.item()\n",
242
+ "\n",
243
+ "\n",
244
+ " avg_loss = running_loss / len(test_loader)\n",
245
+ "\n",
246
+ " return avg_loss\n"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "# Task 4: Define device, model, loss, optimizer:\n",
256
+ "import torch\n",
257
+ "from torch.optim import AdamW\n",
258
+ "\n",
259
+ "\n",
260
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
261
+ "\n",
262
+ "\n",
263
+ "input_dim = 3*36*36 # dim of the image equals 3888\n",
264
+ "hidden_dim = 64\n",
265
+ "\n",
266
+ "\n",
267
+ "model = NN3Layer(input_dim, hidden_dim).to(device)\n",
268
+ "\n",
269
+ "\n",
270
+ "criterion = nn.MSELoss()\n",
271
+ "\n",
272
+ "\n",
273
+ "learning_rate = 0.001\n",
274
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
275
+ "\n",
276
+ "\n",
277
+ "num_epochs = 20\n"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task 5: Start training for 20 epochs:\n",
287
+ "train_losses = []\n",
288
+ "val_losses = []\n",
289
+ "\n",
290
+ "print('Starting Training...')\n",
291
+ "for epoch in range(num_epochs):\n",
292
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
293
+ " val_loss = validate(model, criterion, test_loader, device)\n",
294
+ "\n",
295
+ " train_losses.append(train_loss)\n",
296
+ " val_losses.append(val_loss)\n",
297
+ "\n",
298
+ " if (epoch + 1) % 5 == 0:\n",
299
+ " print(\n",
300
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
301
+ " f'Train Loss: {train_loss:.4f}, '\n",
302
+ " f'Val Loss: {val_loss:.4f}'\n",
303
+ " )\n",
304
+ "\n",
305
+ "print('Training Complete!')"
306
+ ],
307
+ "execution_count": null,
308
+ "outputs": []
309
+ },
310
+ {
311
+ "cell_type": "code",
312
+ "metadata": {},
313
+ "source": [
314
+ "# Task 1: Write your code here:\n",
315
+ "plt.figure(figsize=(7, 5))\n",
316
+ "\n",
317
+ "plt.plot(train_losses, label='Train Loss')\n",
318
+ "plt.plot(val_losses, label='Validation Loss')\n",
319
+ "plt.title('Loss over Epochs')\n",
320
+ "plt.xlabel('Epoch')\n",
321
+ "plt.ylabel('Loss')\n",
322
+ "plt.legend()\n",
323
+ "\n",
324
+ "plt.tight_layout()\n",
325
+ "plt.show()"
326
+ ],
327
+ "execution_count": null,
328
+ "outputs": []
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "metadata": {},
333
+ "source": [
334
+ "# Task 2 (Bonus): Write your code here:"
335
+ ],
336
+ "execution_count": null,
337
+ "outputs": []
338
+ }
339
+ ],
340
+ "metadata": {
341
+ "kernelspec": {
342
+ "display_name": "Python 3",
343
+ "name": "python3"
344
+ },
345
+ "language_info": {
346
+ "name": "python"
347
+ }
348
+ },
349
+ "nbformat": 4,
350
+ "nbformat_minor": 0
351
+ }