ALLIA12 commited on
Commit
6740237
·
verified ·
1 Parent(s): 2c7f915

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

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/140/Q1.ipynb +507 -0
  2. submissions_extracted/140/Q2.ipynb +370 -0
  3. submissions_extracted/140/Q3.ipynb +326 -0
  4. submissions_extracted/141/Q1.ipynb +265 -0
  5. submissions_extracted/141/Q2.ipynb +406 -0
  6. submissions_extracted/141/Q3.ipynb +289 -0
  7. submissions_extracted/142/Q1.ipynb +319 -0
  8. submissions_extracted/142/Q2.ipynb +386 -0
  9. submissions_extracted/142/Q3.ipynb +194 -0
  10. submissions_extracted/143/Q1.ipynb +287 -0
  11. submissions_extracted/143/Q2.ipynb +392 -0
  12. submissions_extracted/143/Q3.ipynb +312 -0
  13. submissions_extracted/144/Q1.ipynb +223 -0
  14. submissions_extracted/144/Q2.ipynb +192 -0
  15. submissions_extracted/144/Q3.ipynb +203 -0
  16. submissions_extracted/145/Q1.ipynb +241 -0
  17. submissions_extracted/145/Q2.ipynb +192 -0
  18. submissions_extracted/145/Q3.ipynb +234 -0
  19. submissions_extracted/146/Q1.ipynb +260 -0
  20. submissions_extracted/146/Q2.ipynb +192 -0
  21. submissions_extracted/146/Q3.ipynb +222 -0
  22. submissions_extracted/147/Q1.ipynb +316 -0
  23. submissions_extracted/147/Q2.ipynb +356 -0
  24. submissions_extracted/147/Q3.ipynb +437 -0
  25. submissions_extracted/148/Q1.ipynb +414 -0
  26. submissions_extracted/148/Q2.ipynb +388 -0
  27. submissions_extracted/148/Q3.ipynb +291 -0
  28. submissions_extracted/149/Q1.ipynb +270 -0
  29. submissions_extracted/149/Q2.ipynb +340 -0
  30. submissions_extracted/149/Q3.ipynb +267 -0
  31. submissions_extracted/15/Q1.ipynb +299 -0
  32. submissions_extracted/15/Q2.ipynb +395 -0
  33. submissions_extracted/15/Q3.ipynb +209 -0
  34. submissions_extracted/150/Q1.ipynb +332 -0
  35. submissions_extracted/150/Q2.ipynb +391 -0
  36. submissions_extracted/150/Q3.ipynb +305 -0
  37. submissions_extracted/151/Q1.ipynb +225 -0
  38. submissions_extracted/151/Q2.ipynb +386 -0
  39. submissions_extracted/151/Q3.ipynb +199 -0
  40. submissions_extracted/152/Q1.ipynb +316 -0
  41. submissions_extracted/152/Q2.ipynb +380 -0
  42. submissions_extracted/152/Q3.ipynb +260 -0
  43. submissions_extracted/153/Q1.ipynb +353 -0
  44. submissions_extracted/153/Q2.ipynb +360 -0
  45. submissions_extracted/153/Q3.ipynb +237 -0
  46. submissions_extracted/154/Q1.ipynb +314 -0
  47. submissions_extracted/154/Q2.ipynb +301 -0
  48. submissions_extracted/154/Q3.ipynb +249 -0
  49. submissions_extracted/155/Q1.ipynb +173 -0
  50. submissions_extracted/155/Q2.ipynb +320 -0
submissions_extracted/140/Q1.ipynb ADDED
@@ -0,0 +1,507 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import pandas as pd\n",
8
+ "import seaborn as sns\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "from sklearn.preprocessing import OneHotEncoder,StandardScaler,MinMaxScaler,LabelEncoder\n",
11
+ "from sklearn.model_selection import StratifiedKFold\n",
12
+ "from sklearn.ensemble import RandomForestRegressor\n",
13
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
14
+ "import numpy as np"
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 = pd.read_csv(path + '/Q1_data.csv')\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
+ "df[\"Delivery_Time\"].head()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 5: Write your code here:\n",
87
+ "plt.hist(df[\"Delivery_Time\"],bins=30)"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "df.head()"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 1: Write your code here:\n",
106
+ "df.drop(\"Order_ID\",axis=1,inplace=True)"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 2: Write your code here:\n",
116
+ "df.isna().sum()"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "missing_cols = df.columns.drop([\"Distance_km\",\"Vehicle_Type\",\"Preparation_Time_min\"])\n",
126
+ "df[missing_cols]"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "#Not good to fill Target Variable's values, so better to drop them\n",
136
+ "df.dropna(subset=\"Delivery_Time\",inplace=True)"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "df[\"Courier_Experience_yrs\"].unique()"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "df[\"Courier_Experience_yrs\"].fillna(round(df[\"Courier_Experience_yrs\"].mean()),inplace=True)"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "df[\"Time_of_Day\"].unique()"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "df[\"Time_of_Day\"].fillna(df[\"Time_of_Day\"].mode()[0],inplace=True)"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "df[\"Traffic_Level\"].unique()"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "df[\"Traffic_Level\"].fillna(df[\"Traffic_Level\"].mode()[0],inplace=True)"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "df[\"Weather\"].unique()"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "df[\"Weather\"].fillna(df[\"Weather\"].mode()[0],inplace=True)"
209
+ ],
210
+ "execution_count": null,
211
+ "outputs": []
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "metadata": {},
216
+ "source": [
217
+ "df.isna().sum()"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 3: Write your code here:\n",
227
+ "print(df.duplicated().sum())\n",
228
+ "if df.duplicated().sum() > 0:\n",
229
+ " df.drop_duplicates(inplace=True)"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "df.duplicated().sum()"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "df.head()"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task 4: Write your code here:\n",
257
+ "df.select_dtypes(include=[\"object\"]).columns"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "print(df[\"Weather\"].unique())\n",
267
+ "print(df[\"Traffic_Level\"].unique())\n",
268
+ "print(df[\"Time_of_Day\"].unique())\n",
269
+ "print(df[\"Vehicle_Type\"].unique())"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "metadata": {},
277
+ "source": [
278
+ "cat_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
279
+ "ohe = OneHotEncoder()\n",
280
+ "ohe_result = ohe.fit_transform(df[['Weather', 'Time_of_Day', 'Vehicle_Type']])"
281
+ ],
282
+ "execution_count": null,
283
+ "outputs": []
284
+ },
285
+ {
286
+ "cell_type": "code",
287
+ "metadata": {},
288
+ "source": [
289
+ "temp_df = pd.DataFrame(columns=ohe.get_feature_names_out(),data=ohe_result.toarray())\n",
290
+ "temp_df.head()"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "dfOHE = pd.concat([df.drop(['Weather', 'Time_of_Day', 'Vehicle_Type'],axis=1),temp_df],axis=1)\n",
300
+ "dfOHE.head()"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "df.shape"
310
+ ],
311
+ "execution_count": null,
312
+ "outputs": []
313
+ },
314
+ {
315
+ "cell_type": "code",
316
+ "metadata": {},
317
+ "source": [
318
+ "dfOHE.shape"
319
+ ],
320
+ "execution_count": null,
321
+ "outputs": []
322
+ },
323
+ {
324
+ "cell_type": "code",
325
+ "metadata": {},
326
+ "source": [
327
+ "dfOHE.dropna(inplace=True)"
328
+ ],
329
+ "execution_count": null,
330
+ "outputs": []
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "metadata": {},
335
+ "source": [
336
+ "le = LabelEncoder()\n",
337
+ "dfOHE[\"Traffic_Level\"] = le.fit_transform(dfOHE[\"Traffic_Level\"])"
338
+ ],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "metadata": {},
345
+ "source": [
346
+ "dfOHE.head()"
347
+ ],
348
+ "execution_count": null,
349
+ "outputs": []
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "metadata": {},
354
+ "source": [
355
+ "# Task 5: Write your code here:\n",
356
+ "dcols = dfOHE.columns.drop(\"Delivery_Time\") ## desired columns (not scaling target)\n",
357
+ "sc = StandardScaler()\n",
358
+ "dfOHE[dcols] = sc.fit_transform(dfOHE[dcols])"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [
367
+ "# Task 6: Write your code here:\n",
368
+ "dfOHE[\"Delivery_Time\"].skew()"
369
+ ],
370
+ "execution_count": null,
371
+ "outputs": []
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "metadata": {},
376
+ "source": [
377
+ "plt.hist(dfOHE[\"Delivery_Time\"],bins=50)"
378
+ ],
379
+ "execution_count": null,
380
+ "outputs": []
381
+ },
382
+ {
383
+ "cell_type": "code",
384
+ "metadata": {},
385
+ "source": [
386
+ "dfOHE.head()"
387
+ ],
388
+ "execution_count": null,
389
+ "outputs": []
390
+ },
391
+ {
392
+ "cell_type": "code",
393
+ "metadata": {},
394
+ "source": [
395
+ "# Task 1: Write your code here:\n",
396
+ "X = dfOHE.drop(\"Delivery_Time\",axis=1).values\n",
397
+ "y = dfOHE[\"Delivery_Time\"].values\n"
398
+ ],
399
+ "execution_count": null,
400
+ "outputs": []
401
+ },
402
+ {
403
+ "cell_type": "code",
404
+ "metadata": {},
405
+ "source": [
406
+ "# Task 2,3,4,5: Write your code here:\n",
407
+ "kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n",
408
+ "model=RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42)\n",
409
+ "mae_scores = []\n",
410
+ "predictions = []"
411
+ ],
412
+ "execution_count": null,
413
+ "outputs": []
414
+ },
415
+ {
416
+ "cell_type": "code",
417
+ "metadata": {},
418
+ "source": [
419
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X, y), start=1):\n",
420
+ " X_fold_train, X_fold_val = X[train_idx], X[test_idx]\n",
421
+ " y_fold_train, y_fold_val = y[train_idx], y[test_idx]\n",
422
+ "\n",
423
+ " # Train and predict\n",
424
+ " model.fit(X_fold_train, y_fold_train)\n",
425
+ " y_fold_pred = model.predict(X_fold_val)\n",
426
+ " predictions.append(y_fold_pred)\n",
427
+ " # Calculate metrics\n",
428
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
429
+ "\n",
430
+ "mae_scores = np.array(mae_scores).mean()\n",
431
+ "print(f\"5-Fold CV Results:\")\n",
432
+ "print(f\"MAE: {mae_scores}\")"
433
+ ],
434
+ "execution_count": null,
435
+ "outputs": []
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "metadata": {},
440
+ "source": [
441
+ "len(model.feature_importances_)"
442
+ ],
443
+ "execution_count": null,
444
+ "outputs": []
445
+ },
446
+ {
447
+ "cell_type": "code",
448
+ "metadata": {},
449
+ "source": [
450
+ "len(dfOHE.columns.drop(\"Delivery_Time\"))"
451
+ ],
452
+ "execution_count": null,
453
+ "outputs": []
454
+ },
455
+ {
456
+ "cell_type": "code",
457
+ "metadata": {},
458
+ "source": [
459
+ "# Task 1: Write your code here:\n",
460
+ "# Feature importance\n",
461
+ "feature_importance = pd.DataFrame({\n",
462
+ " 'feature': dfOHE.columns.drop(\"Delivery_Time\"),\n",
463
+ " 'importance': model.feature_importances_\n",
464
+ "}).sort_values('importance', ascending=False)\n",
465
+ "\n",
466
+ "plt.figure(figsize=(10, 6))\n",
467
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
468
+ "plt.xlabel('Importance')\n",
469
+ "plt.title('Feature Importance')\n",
470
+ "plt.gca().invert_yaxis()\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
+ "plt.hist(predictions,bins=30)"
482
+ ],
483
+ "execution_count": null,
484
+ "outputs": []
485
+ },
486
+ {
487
+ "cell_type": "code",
488
+ "metadata": {},
489
+ "source": [
490
+ "# Task Bonus: Write your code here:"
491
+ ],
492
+ "execution_count": null,
493
+ "outputs": []
494
+ }
495
+ ],
496
+ "metadata": {
497
+ "kernelspec": {
498
+ "display_name": "Python 3",
499
+ "name": "python3"
500
+ },
501
+ "language_info": {
502
+ "name": "python"
503
+ }
504
+ },
505
+ "nbformat": 4,
506
+ "nbformat_minor": 0
507
+ }
submissions_extracted/140/Q2.ipynb ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import torch\n",
8
+ "import torch.nn as nn\n",
9
+ "from torchvision.datasets import MNIST\n",
10
+ "from torch.utils.data import DataLoader,TensorDataset\n",
11
+ "from torch.optim import Adam\n",
12
+ "from torchvision.transforms.functional import to_tensor\n",
13
+ "import torch.nn.functional as F\n",
14
+ "import matplotlib.pyplot as plt"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "import kagglehub\n",
24
+ "\n",
25
+ "# Download latest version\n",
26
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
27
+ "\n",
28
+ "print(\"Path to dataset files:\", path)"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "import os\n",
38
+ "import pandas as pd\n",
39
+ "import numpy as np\n",
40
+ "from PIL import Image\n",
41
+ "from sklearn.model_selection import train_test_split\n",
42
+ "\n",
43
+ "# Load Labels\n",
44
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
45
+ "img_dir = os.path.join(path, \"images\")\n",
46
+ "\n",
47
+ "images = []\n",
48
+ "ages = []\n",
49
+ "\n",
50
+ "# Load Images and Resize\n",
51
+ "print(\"Loading images...\")\n",
52
+ "for index, row in labels_df.iterrows():\n",
53
+ " img_name = row.iloc[0]\n",
54
+ " age = row.iloc[1]\n",
55
+ " img_path = os.path.join(img_dir, img_name)\n",
56
+ "\n",
57
+ " if os.path.exists(img_path):\n",
58
+ " img = Image.open(img_path).convert('RGB')\n",
59
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
60
+ " images.append(img_array)\n",
61
+ " ages.append(age)\n",
62
+ "\n",
63
+ "X = np.array(images)\n",
64
+ "y = np.array(ages)\n",
65
+ "\n",
66
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
67
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
68
+ "\n",
69
+ "# Split Data\n",
70
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
71
+ "\n",
72
+ "print(f\"X_train shape: {X_train.shape}\")\n",
73
+ "print(f\"X_test shape: {X_test.shape}\")\n",
74
+ "print(f\"y_train shape: {y_train.shape}\")\n",
75
+ "print(f\"y_test shape: {y_test.shape}\")"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
85
+ "X_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
+ "train_dataset = TensorDataset(X_train, y_train)\n",
99
+ "test_dataset = TensorDataset(X_test, y_test)\n",
100
+ "\n",
101
+ "\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 3. Create DataLoaders\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
+ "\n"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# 4. Print shape of one batch\n",
125
+ "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
+ "# Get one batch of images and labels\n",
137
+ "images, labels = next(iter(train_loader))\n",
138
+ "\n",
139
+ "# Display the first 6 images in the batch\n",
140
+ "plt.figure(figsize=(8, 4))\n",
141
+ "\n",
142
+ "for i in range(6):\n",
143
+ " plt.subplot(2, 3, i + 1)\n",
144
+ "\n",
145
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
146
+ " img = images[i].permute(1, 2, 0)\n",
147
+ "\n",
148
+ " plt.imshow(img)\n",
149
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
150
+ " plt.axis('off')\n",
151
+ "\n",
152
+ "plt.tight_layout()\n",
153
+ "plt.show()"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 1: Write your model class here:\n",
163
+ "class NN4Layer(nn.Module):\n",
164
+ "\n",
165
+ " def __init__(self, input_dim,hidden_dim1,hidden_dim2,hidden_dim3):\n",
166
+ " super(NN4Layer, self).__init__()\n",
167
+ " self.seq = nn.Sequential(\n",
168
+ " nn.Linear(input_dim,hidden_dim1),\n",
169
+ " nn.ReLU(),\n",
170
+ "\n",
171
+ " nn.Linear(hidden_dim1,hidden_dim2),\n",
172
+ " nn.ReLU(),\n",
173
+ "\n",
174
+ " nn.Linear(hidden_dim2,hidden_dim3),\n",
175
+ " nn.ReLU(),\n",
176
+ "\n",
177
+ " nn.Linear(hidden_dim3,1)\n",
178
+ " )\n",
179
+ "\n",
180
+ "\n",
181
+ "\n",
182
+ "\n",
183
+ " # forward pass\n",
184
+ " def forward(self, x):\n",
185
+ " y = self.seq(x)\n",
186
+ " return y"
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:\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.shape[0],-1).to(device)\n",
205
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
206
+ "\n",
207
+ " # Forward pass\n",
208
+ " outputs = model(X_batch)\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
+ "def validate(model, criterion, test_loader, device):\n",
232
+ " # Set the model to evaluation mode\n",
233
+ " model.eval()\n",
234
+ "\n",
235
+ " running_loss = 0.0\n",
236
+ " correct = 0\n",
237
+ " total = 0\n",
238
+ "\n",
239
+ " with torch.no_grad(): # Disable gradient computation\n",
240
+ " for X_batch, y_batch in test_loader:\n",
241
+ " # Move batch to the selected device\n",
242
+ " X_batch = X_batch.view(X_batch.shape[0],-1).to(device)\n",
243
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
244
+ "\n",
245
+ " # Forward pass\n",
246
+ " outputs = model(X_batch)\n",
247
+ " loss = criterion(outputs, y_batch)\n",
248
+ " running_loss += loss.item()\n",
249
+ "\n",
250
+ " # Binary predictions\n",
251
+ " predicted = (outputs > 0.5).float()\n",
252
+ "\n",
253
+ " # Accuracy calculation\n",
254
+ " correct += (predicted == y_batch).sum().item()\n",
255
+ " total += y_batch.size(0)\n",
256
+ "\n",
257
+ " avg_loss = running_loss / len(test_loader)\n",
258
+ " accuracy = correct / total\n",
259
+ "\n",
260
+ " return avg_loss, accuracy\n"
261
+ ],
262
+ "execution_count": null,
263
+ "outputs": []
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "metadata": {},
268
+ "source": [
269
+ "# Task 4: Define device, model, loss, optimizer:\n",
270
+ "# Device configuration\n",
271
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
272
+ "print(f\"Using device: {device}\")\n",
273
+ "\n",
274
+ "num_epochs = 20\n",
275
+ "learning_rate = 0.001\n",
276
+ "\n",
277
+ "# Model, Criterion, Optimizer\n",
278
+ "input_dim = 3*36*36\n",
279
+ "hidden_dim1 = 64\n",
280
+ "hidden_dim2 = 32\n",
281
+ "hidden_dim3 = 32\n",
282
+ "model =NN4Layer(input_dim, hidden_dim1,hidden_dim2,hidden_dim3).to(device)\n",
283
+ "criterion = nn.MSELoss()\n",
284
+ "optimizer = Adam(model.parameters(), lr=learning_rate)\n",
285
+ "\n",
286
+ "\n",
287
+ "# Run Training\n",
288
+ "train_losses = []\n",
289
+ "val_losses = []\n",
290
+ "val_accuracies = []\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
+ "print('Starting Training...')\n",
302
+ "for epoch in range(num_epochs):\n",
303
+ " # Train one epoch\n",
304
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
305
+ "\n",
306
+ " # Validate\n",
307
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
308
+ "\n",
309
+ " train_losses.append(train_loss)\n",
310
+ " val_losses.append(val_loss)\n",
311
+ " val_accuracies.append(val_accuracy)\n",
312
+ "\n",
313
+ " if (epoch + 1) % 5 == 0:\n",
314
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
315
+ "\n",
316
+ "print('Training Complete!')"
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
+ "# Plotting results\n",
327
+ "plt.figure(figsize=(7, 5))\n",
328
+ "\n",
329
+ "plt.plot(train_losses, label='Train Loss')\n",
330
+ "plt.plot(val_losses, label='Validation Loss')\n",
331
+ "plt.title('Loss over Epochs')\n",
332
+ "plt.xlabel('Epoch')\n",
333
+ "plt.ylabel('Loss')\n",
334
+ "plt.legend()\n",
335
+ "\n",
336
+ "plt.tight_layout()\n",
337
+ "plt.show()"
338
+ ],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "metadata": {},
345
+ "source": [
346
+ "# Task 2 (Bonus): Write your code here:"
347
+ ],
348
+ "execution_count": null,
349
+ "outputs": []
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "metadata": {},
354
+ "source": [],
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/140/Q3.ipynb ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "from sklearn.preprocessing import StandardScaler\n",
12
+ "from catboost import CatBoostClassifier\n",
13
+ "from sklearn.ensemble import RandomForestClassifier\n",
14
+ "from sklearn.model_selection import StratifiedKFold\n",
15
+ "from sklearn.metrics import f1_score, accuracy_score"
16
+ ],
17
+ "execution_count": null,
18
+ "outputs": []
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "metadata": {},
23
+ "source": [
24
+ "import kagglehub\n",
25
+ "\n",
26
+ "\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
+ "df = pd.read_csv(path + \"/Q3_data.csv\")"
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
+ "df.describe().loc[[\"mean\",\"std\",\"min\",\"max\"]]"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "df.shape"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# Task 1: Write your code here:\n",
102
+ "ms = df.isna().sum()\n",
103
+ "ms_cols = ms[ms > 0].index\n",
104
+ "ms_cols"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "df[ms_cols].mean()"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "df.fillna(df[ms_cols].mean(),inplace=True)"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "df.isna().sum()"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 2: Write your code here:\n",
141
+ "print(df.duplicated().sum())\n",
142
+ "df.drop_duplicates(inplace=True)"
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
+ "df.select_dtypes(include=[\"object\"]).columns"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 4: Write your code here:\n",
162
+ "sc=StandardScaler()\n",
163
+ "dCols = df.columns.drop(\"Target\") ## desired columns to scale (Not scaleing the Target)\n",
164
+ "df_scaled = df.copy()\n",
165
+ "df_scaled[dCols] = sc.fit_transform(df_scaled[dCols])"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "df_scaled.head()"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "# Task 5: Write your code here:\n",
184
+ "print(df[\"Target\"].value_counts(normalize=True)*100)\n",
185
+ "sns.countplot(x=df[\"Target\"])"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 1: Write your code here:\n",
195
+ "X = df_scaled[dCols].values\n",
196
+ "y = df_scaled[\"Target\"].values"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "X.shape"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "y.shape"
215
+ ],
216
+ "execution_count": null,
217
+ "outputs": []
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "# Task 2,3,4,5: Write your code here:\n",
224
+ "kf = StratifiedKFold(n_splits=5,shuffle=True,random_state=42)\n",
225
+ "model = CatBoostClassifier()\n",
226
+ "accuracy_=[]\n",
227
+ "F1Score=[]"
228
+ ],
229
+ "execution_count": null,
230
+ "outputs": []
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "metadata": {},
235
+ "source": [
236
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
237
+ " # 1. Split data\n",
238
+ " X_train, X_test = X[train_index], X[test_index]\n",
239
+ " y_train, y_test = y[train_index], y[test_index]\n",
240
+ "\n",
241
+ " model.fit(X_train, y_train) # train\n",
242
+ " y_pred = model.predict(X_test) # validate\n",
243
+ "\n",
244
+ " # 3. Save metrics for that model in this fold\n",
245
+ " accuracy = accuracy_score(y_test, y_pred)\n",
246
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
247
+ "\n",
248
+ " accuracy_.append(accuracy)\n",
249
+ " F1Score.append(f1)"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "metadata": {},
257
+ "source": [
258
+ "print(f\"Accracy mean {np.mean(accuracy_)*100}\")\n",
259
+ "print(f\"F1 mean {np.mean(F1Score)*100}\")"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "# Retrieve CatBoost feature importances and sort them\n",
276
+ "catboost_importance = list(zip(df.columns, model.feature_importances_))\n",
277
+ "sorted_catboost_importance = sorted(catboost_importance, key=lambda x: x[1], reverse=True)\n",
278
+ "\n",
279
+ "# Extract features and their importances\n",
280
+ "features, importances = zip(*sorted_catboost_importance)\n",
281
+ "\n",
282
+ "# Plot feature importances\n",
283
+ "plt.figure(figsize=(30, 60))\n",
284
+ "plt.barh(features, importances, color='orange')\n",
285
+ "plt.xlabel('Importance Score')\n",
286
+ "plt.ylabel('Features')\n",
287
+ "plt.title('CatBoost Feature Importance')\n",
288
+ "plt.yticks()\n",
289
+ "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
290
+ "plt.show()\n"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "# Task 2: Write your code here:\n",
300
+ "print(f\"The most important feature is P_2\")"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "# Task Bonus: Write your code here:"
310
+ ],
311
+ "execution_count": null,
312
+ "outputs": []
313
+ }
314
+ ],
315
+ "metadata": {
316
+ "kernelspec": {
317
+ "display_name": "Python 3",
318
+ "name": "python3"
319
+ },
320
+ "language_info": {
321
+ "name": "python"
322
+ }
323
+ },
324
+ "nbformat": 4,
325
+ "nbformat_minor": 0
326
+ }
submissions_extracted/141/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 os\n",
23
+ "import pandas as pd\n",
24
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
25
+ "\n",
26
+ "df = pd.read_csv(csv_path)"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "# Task 2: Write your code here:\n",
36
+ "df.head()"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 3: Write your code here:\n",
46
+ "df.info()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 4: Write your code here:\n",
56
+ "df.describe()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 5: Write your code here:\n",
66
+ "import matplotlib.pyplot as plt\n",
67
+ "def check_target_distribution(df, target_column):\n",
68
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
69
+ "\n",
70
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
71
+ " plt.xlabel(target_column)\n",
72
+ " plt.ylabel(\"Frequency\")\n",
73
+ " plt.grid(False)\n",
74
+ "\n",
75
+ " plt.show()\n",
76
+ "\n",
77
+ "check_target_distribution(df, \"Delivery_Time\")"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 1: Write your code here:\n",
87
+ "df.drop(\"Order_ID\",axis = 1,inplace=True)\n",
88
+ "df.info()"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# Task 2: Write your code here:\n",
98
+ "# target must be rows null erase\n",
99
+ "null_cols = [\"Delivery_Time\", \"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Courier_Experience_yrs\"]\n",
100
+ "df_clean = df.dropna(subset=null_cols).copy()\n",
101
+ "df_clean.info()"
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
+ "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_clean)\n",
122
+ "df_clean.info()"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# Task 4: Write your code here:\n",
132
+ "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
133
+ "categorical_cols = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n",
134
+ "for col in categorical_cols:\n",
135
+ " le = LabelEncoder()\n",
136
+ " df_clean[col] = le.fit_transform(df_clean[col])\n",
137
+ "df_clean.head()"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# Task 5: Write your code here:\n",
147
+ "\n",
148
+ "numerical_cols = df_clean.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
149
+ "\n",
150
+ "scaler = StandardScaler()\n",
151
+ "df_clean[numerical_cols] = scaler.fit_transform(df_clean[numerical_cols])\n",
152
+ "df_clean.head()\n"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 6: Write your code here:\n",
162
+ "#it kinda unbalanced in the end but not that deep\n",
163
+ "check_target_distribution(df_clean, \"Delivery_Time\")"
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
+ "from sklearn.ensemble import RandomForestRegressor\n",
174
+ "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
175
+ "y = df_clean['Delivery_Time'].astype(float)"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 2,3,4,5: Write your code here:\n",
185
+ "from sklearn.model_selection import StratifiedKFold\n",
186
+ "\n",
187
+ "\n",
188
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
189
+ "mse = 0\n",
190
+ "model = RandomForestRegressor(n_estimators=200)\n",
191
+ "n_splits = 5 # K=5 Folds\n",
192
+ "\n",
193
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
194
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
195
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
196
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
197
+ "\n",
198
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
199
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
200
+ " model.fit(X_train, y_train)\n",
201
+ "\n",
202
+ " # Predict\n",
203
+ " y_pred = model.predict(X_test)\n",
204
+ "\n",
205
+ " # Calculate metrics\n",
206
+ " mse_per = sklearn_mse(y_test, y_pred)\n",
207
+ " print(\"MSE : \", mse_per)\n",
208
+ " mse += mse_per\n",
209
+ "\n",
210
+ "print(f\" MSE: {mse / n_splits:.4f}\")"
211
+ ],
212
+ "execution_count": null,
213
+ "outputs": []
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "# Task 1: Write your code here:\n",
220
+ "import numpy as np\n",
221
+ "feature_importance = pd.DataFrame({\n",
222
+ " 'feature': X.columns,\n",
223
+ " 'importance': model.feature_importances_\n",
224
+ "}).sort_values('importance', ascending=False)\n",
225
+ "plt.figure(figsize=(10, 6))\n",
226
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
227
+ "plt.xlabel('Importance')\n",
228
+ "plt.title('Feature Importance')\n",
229
+ "plt.gca().invert_yaxis()\n",
230
+ "plt.show()"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task 2: Write your code here:"
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/141/Q2.ipynb ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import torch.nn as nn\n",
9
+ "import torch.nn.functional as F\n",
10
+ "from torch.optim import AdamW\n",
11
+ "# Download latest version\n",
12
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
13
+ "\n",
14
+ "print(\"Path to dataset files:\", path)"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "import os\n",
24
+ "import pandas as pd\n",
25
+ "import numpy as np\n",
26
+ "from PIL import Image\n",
27
+ "from sklearn.model_selection import train_test_split\n",
28
+ "\n",
29
+ "# Load Labels\n",
30
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
31
+ "img_dir = os.path.join(path, \"images\")\n",
32
+ "images = []\n",
33
+ "ages = []\n",
34
+ "\n",
35
+ "# Load Images and Resize\n",
36
+ "print(\"Loading images...\")\n",
37
+ "for index, row in labels_df.iterrows():\n",
38
+ " img_name = row.iloc[0]\n",
39
+ " age = row.iloc[1]\n",
40
+ " img_path = os.path.join(img_dir, img_name)\n",
41
+ "\n",
42
+ " if os.path.exists(img_path):\n",
43
+ " img = Image.open(img_path).convert('RGB')\n",
44
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
45
+ " images.append(img_array)\n",
46
+ " ages.append(age)\n",
47
+ "\n",
48
+ "X = np.array(images)\n",
49
+ "y = np.array(ages)\n",
50
+ "\n",
51
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
52
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
53
+ "\n",
54
+ "# Split Data\n",
55
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
56
+ "\n",
57
+ "print(f\"X_train shape: {X_train.shape}\")\n",
58
+ "print(f\"X_test shape: {X_test.shape}\")\n",
59
+ "print(f\"y_train shape: {y_train.shape}\")\n",
60
+ "print(f\"y_test shape: {y_test.shape}\")\n",
61
+ "unique_label = len(np.unique(labels_df['age']))\n",
62
+ "print(\"Unique Label\",unique_label)"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
72
+ "import torch\n",
73
+ "from torch.utils.data import TensorDataset\n",
74
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
75
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
76
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
77
+ "y_test = torch.tensor(y_test, dtype=torch.long)"
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
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "from torch.utils.data import DataLoader\n",
99
+ "# 3. Create DataLoaders\n",
100
+ "train_loader = DataLoader(\n",
101
+ " train_dataset,\n",
102
+ " batch_size=32,\n",
103
+ " shuffle=True,\n",
104
+ " num_workers=2\n",
105
+ ")\n",
106
+ "# DataLoader for test/validation data\n",
107
+ "test_loader = DataLoader(\n",
108
+ " test_dataset,\n",
109
+ " batch_size=32,\n",
110
+ " shuffle=False,\n",
111
+ " num_workers=2\n",
112
+ ")\n",
113
+ "\n"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# 4. Print shape of one batch\n",
123
+ "\n",
124
+ "X_batch, y_batch = next(iter(train_loader))\n",
125
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
126
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# 5. Display sample images\n",
136
+ "# Get one batch of images and labels\n",
137
+ "images, labels = next(iter(train_loader))\n",
138
+ "# Display the first 6 images in the batch\n",
139
+ "plt.figure(figsize=(8, 4))\n",
140
+ "\n",
141
+ "for i in range(6):\n",
142
+ " plt.subplot(2, 3, i + 1)\n",
143
+ "\n",
144
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
145
+ " img = images[i].permute(1, 2, 0)\n",
146
+ "\n",
147
+ " plt.imshow(img)\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()"
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
+ "class NN4Layer(nn.Module):\n",
163
+ "\n",
164
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
165
+ " super(NN4Layer, self).__init__()\n",
166
+ "\n",
167
+ "\n",
168
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
169
+ "\n",
170
+ "\n",
171
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
172
+ "\n",
173
+ "\n",
174
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
175
+ "\n",
176
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
177
+ "\n",
178
+ "\n",
179
+ " # activation function for non-linearity\n",
180
+ " self.relu = nn.ReLU()\n",
181
+ "\n",
182
+ " # Defines how input data flows through the network\n",
183
+ " def forward(self, x):\n",
184
+ " z1 = self.layer1(x)\n",
185
+ " a1 = self.relu(z1)\n",
186
+ "\n",
187
+ " z2 = self.layer2(a1)\n",
188
+ " a2 = self.relu(z2)\n",
189
+ "\n",
190
+ " z3 = self.layer3(a2)\n",
191
+ " a3 = self.relu(z3)\n",
192
+ "\n",
193
+ " z4 = self.layer4(a3)\n",
194
+ "\n",
195
+ " return z4"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Task 2: Write your training loop here:\n",
205
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
206
+ " # Set the model to training mode\n",
207
+ " model.train()\n",
208
+ "\n",
209
+ " running_loss = 0.0\n",
210
+ "\n",
211
+ " for X_batch, y_batch in train_loader:\n",
212
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
213
+ " y_batch = y_batch.to(device)\n",
214
+ "\n",
215
+ "\n",
216
+ " outputs = model(X_batch)\n",
217
+ " loss = criterion(outputs, y_batch)\n",
218
+ "\n",
219
+ " # Backward pass & optimization\n",
220
+ " optimizer.zero_grad() # Clear previous gradients\n",
221
+ " loss.backward() # Compute gradients\n",
222
+ " optimizer.step() # Update model parameters\n",
223
+ "\n",
224
+ " running_loss += loss.item()\n",
225
+ "\n",
226
+ " # Average loss over all batches\n",
227
+ " avg_loss = running_loss / len(train_loader)\n",
228
+ "\n",
229
+ " return avg_loss"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Task 3: Write your validation loop here:\n",
239
+ "def validate(model, criterion, test_loader, device):\n",
240
+ " # Set the model to evaluation mode\n",
241
+ " model.eval()\n",
242
+ "\n",
243
+ " running_loss = 0.0\n",
244
+ " correct = 0\n",
245
+ " total = 0\n",
246
+ "\n",
247
+ " with torch.no_grad():\n",
248
+ " for X_batch, y_batch in test_loader:\n",
249
+ " # Move data to device\n",
250
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
251
+ " y_batch = y_batch.to(device)\n",
252
+ "\n",
253
+ " # Forward pass\n",
254
+ "\n",
255
+ " outputs = model(X_batch)\n",
256
+ "\n",
257
+ " loss = criterion(outputs, y_batch)\n",
258
+ " running_loss += loss.item()\n",
259
+ "\n",
260
+ "\n",
261
+ " probabilities = F.softmax(outputs, dim=1)\n",
262
+ "\n",
263
+ "\n",
264
+ " predicted = torch.argmax(probabilities, dim=1)\n",
265
+ "\n",
266
+ " # Accuracy calculation\n",
267
+ " correct += (predicted == y_batch).sum().item()\n",
268
+ " total += y_batch.size(0)\n",
269
+ "\n",
270
+ " avg_loss = running_loss / len(test_loader)\n",
271
+ " accuracy = correct / total\n",
272
+ "\n",
273
+ " return avg_loss, accuracy"
274
+ ],
275
+ "execution_count": null,
276
+ "outputs": []
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "metadata": {},
281
+ "source": [
282
+ "# Task 4: Define device, model, loss, optimizer:\n",
283
+ "# Device setup\n",
284
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
285
+ "learning_rate = 0.001\n",
286
+ "criterion = nn.CrossEntropyLoss()\n",
287
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
288
+ "# Model parameters\n",
289
+ "input_dim = 3 * 36 * 36\n",
290
+ "\n",
291
+ "\n",
292
+ "hidden_dim = 64\n",
293
+ "\n",
294
+ "\n",
295
+ "output_dim = unique_label+13\n",
296
+ "\n",
297
+ "\n",
298
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
299
+ "print(\"Model:\")\n",
300
+ "print(model)"
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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
311
+ " # Set the model to training mode\n",
312
+ " model.train()\n",
313
+ "\n",
314
+ " running_loss = 0.0\n",
315
+ "\n",
316
+ " for X_batch, y_batch in train_loader:\n",
317
+ " # Move batch to the selected device\n",
318
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
319
+ " y_batch = y_batch.to(device)\n",
320
+ " # Forward pass\n",
321
+ " outputs = model(X_batch)\n",
322
+ " loss = criterion(outputs, y_batch)\n",
323
+ "\n",
324
+ " # Backward pass & optimization\n",
325
+ " optimizer.zero_grad() # Clear previous gradients\n",
326
+ " loss.backward() # Compute gradients\n",
327
+ " optimizer.step() # Update model parameters\n",
328
+ "\n",
329
+ " running_loss += loss.item()\n",
330
+ "\n",
331
+ " # Average loss over all batches\n",
332
+ " avg_loss = running_loss / len(train_loader)\n",
333
+ "\n",
334
+ " return avg_loss\n",
335
+ "\n",
336
+ "\n",
337
+ "num_epochs = 20\n",
338
+ "train_losses = []\n",
339
+ "val_losses = []\n",
340
+ "val_accuracies = []\n",
341
+ "\n",
342
+ "print('Starting Training...')\n",
343
+ "for epoch in range(num_epochs):\n",
344
+ " # Train one epoch\n",
345
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
346
+ "\n",
347
+ " # Validate\n",
348
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
349
+ "\n",
350
+ " train_losses.append(train_loss)\n",
351
+ " val_losses.append(val_loss)\n",
352
+ " val_accuracies.append(val_accuracy)\n",
353
+ "\n",
354
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
355
+ "\n",
356
+ "print('Training Complete!')\n",
357
+ "#==============================\n",
358
+ "#I don't how to solve the error I spent 1 hour in this tiny logic error. Please take my apolgizies\n",
359
+ "#=============================="
360
+ ],
361
+ "execution_count": null,
362
+ "outputs": []
363
+ },
364
+ {
365
+ "cell_type": "code",
366
+ "metadata": {},
367
+ "source": [
368
+ "# Task 1: Write your code here:\n",
369
+ "# 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')\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
+ ],
391
+ "execution_count": null,
392
+ "outputs": []
393
+ }
394
+ ],
395
+ "metadata": {
396
+ "kernelspec": {
397
+ "display_name": "Python 3",
398
+ "name": "python3"
399
+ },
400
+ "language_info": {
401
+ "name": "python"
402
+ }
403
+ },
404
+ "nbformat": 4,
405
+ "nbformat_minor": 0
406
+ }
submissions_extracted/141/Q3.ipynb ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
13
+ "import os\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "# Download latest version\n",
18
+ "\n",
19
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
20
+ "\n",
21
+ "\n",
22
+ "\n",
23
+ "print(\"Path to dataset files:\", path)\n"
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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
34
+ "\n",
35
+ "df = pd.read_csv(csv_path)\n"
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 1: Write your code here:\n",
75
+ "\n",
76
+ "def check_missing_values(df):\n",
77
+ " missing_values = df.isnull().sum()\n",
78
+ " print(\"Missing Values per Column:\")\n",
79
+ " print(missing_values[missing_values > 0])\n",
80
+ " if missing_values.any():\n",
81
+ " print(\"\\nHandle Missing Values as needed.\")\n",
82
+ " else:\n",
83
+ " print(\"\\nNo Missing Values Found.\")\n",
84
+ "\n",
85
+ "df = df.fillna(df.mean())\n",
86
+ "check_missing_values(df)"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 2: Write your code here:\n",
96
+ "def check_duplicates(df):\n",
97
+ " duplicates = df.duplicated().sum()\n",
98
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
99
+ " if duplicates > 0:\n",
100
+ " print(\"Dropping Duplicates...\")\n",
101
+ " df.drop_duplicates(inplace=True)\n",
102
+ " print(\"Duplicates Dropped.\")\n",
103
+ " else:\n",
104
+ " print(\"No Duplicate Samples Found.\")\n",
105
+ "\n",
106
+ "check_duplicates(df)"
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.info()\n",
117
+ "#No need to encode since no object"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# Task 4: Write your code here:\n",
127
+ "from sklearn.preprocessing import StandardScaler\n",
128
+ "\n",
129
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
130
+ "\n",
131
+ "scaler = StandardScaler()\n",
132
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
133
+ "df.head()"
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
+ "def check_target_imbalance(df, target_column):\n",
144
+ " print(\"Target Distribution:\")\n",
145
+ " print(df[target_column].value_counts(normalize=True))\n",
146
+ " sns.countplot(x=df[target_column])\n",
147
+ " plt.title(\"Target Distribution\")\n",
148
+ " plt.show()\n",
149
+ "\n",
150
+ "check_target_imbalance(df, \"Target\")"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 1: Write your code here:\n",
160
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
161
+ "y = df['Target'].astype(float)"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 2,3,4,5: Write your code here:\n",
171
+ "from sklearn.model_selection import StratifiedKFold\n",
172
+ "from catboost import CatBoostClassifier\n",
173
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
174
+ "n_splits = 5 # K=5 Folds\n",
175
+ "\n",
176
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
177
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
178
+ "sklearn_models = {\n",
179
+ " \"CatBoost\": CatBoostClassifier(\n",
180
+ " verbose=0,\n",
181
+ " n_estimators=320,\n",
182
+ " max_depth=4\n",
183
+ " )\n",
184
+ "}\n",
185
+ "\n",
186
+ "lr_accuracy = []\n",
187
+ "lr_f1 = []\n",
188
+ "all_results = {}\n",
189
+ "\n",
190
+ "for name in sklearn_models:\n",
191
+ " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
192
+ "\n",
193
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
194
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
195
+ "\n",
196
+ " # 1. Split data\n",
197
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
198
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
199
+ "\n",
200
+ " # 2. Train & Validate sklearn models\n",
201
+ " for model_name, model in sklearn_models.items():\n",
202
+ " print(f\"Training {model_name}...\")\n",
203
+ " model.fit(X_train, y_train) # train\n",
204
+ " y_pred = model.predict(X_test) # validate\n",
205
+ "\n",
206
+ " # 3. Save metrics for that model in this fold\n",
207
+ " accuracy = accuracy_score(y_test, y_pred)\n",
208
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
209
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
210
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
211
+ "\n",
212
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
213
+ " all_results[model_name]['precision'].append(precision)\n",
214
+ " all_results[model_name]['recall'].append(recall)\n",
215
+ " all_results[model_name]['f1'].append(f1)\n",
216
+ ""
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "for model_name in all_results:\n",
226
+ " print(f\"\\n{model_name}:\")\n",
227
+ " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
228
+ " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n",
229
+ " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n",
230
+ " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task 1: Write your code here:\n",
240
+ "#Top 10\n",
241
+ "importances = {}\n",
242
+ "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
243
+ "\n",
244
+ "features = X.columns\n",
245
+ "\n",
246
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
247
+ " # Sort features by importance for a cleaner plot\n",
248
+ " sorted_idx = np.argsort(imp)\n",
249
+ "\n",
250
+ " plt.barh(features[sorted_idx[-10:]], imp[sorted_idx[-10:]])\n",
251
+ "\n",
252
+ "plt.tight_layout()\n",
253
+ "plt.show()"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 2: Write your code here:\n",
263
+ "print(\"The Golden Feature is : \",features[sorted_idx[-1]])"
264
+ ],
265
+ "execution_count": null,
266
+ "outputs": []
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "metadata": {},
271
+ "source": [
272
+ "# Task Bonus: Write your code here:"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ }
277
+ ],
278
+ "metadata": {
279
+ "kernelspec": {
280
+ "display_name": "Python 3",
281
+ "name": "python3"
282
+ },
283
+ "language_info": {
284
+ "name": "python"
285
+ }
286
+ },
287
+ "nbformat": 4,
288
+ "nbformat_minor": 0
289
+ }
submissions_extracted/142/Q1.ipynb ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import numpy as np\n",
22
+ "import pandas as pd\n",
23
+ "import matplotlib.pyplot as plt\n",
24
+ "import os\n",
25
+ "import kagglehub\n",
26
+ "\n",
27
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
28
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n",
29
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
30
+ "import matplotlib.pyplot as plt\n",
31
+ "from sklearn.linear_model import LinearRegression"
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
+ "# Loading the data into the dataframe df_delivery\n",
42
+ "delivery_path = os.path.join(path, 'Q1_data.csv')\n",
43
+ "df_delivery = pd.read_csv(delivery_path)\n",
44
+ "df_delivery"
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_delivery.head() # Showing the first 5 samples"
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_delivery.info()\n",
65
+ "# I noticed there are some null rows in some cols and some categorial cols"
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_delivery.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
+ "plt.figure(figsize=(10, 5))\n",
86
+ "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=70, edgecolor='black')\n",
87
+ "plt.title('delivery time Distribution')\n",
88
+ "plt.xlabel('delivery time')\n",
89
+ "plt.ylabel('Frequency')\n",
90
+ "plt.show()\n",
91
+ "# Notice how the graph is a bit skewed to the right and it has a mean of approx. 56"
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_delivery = df_delivery.drop(columns=['Order_ID'])\n",
102
+ "df_delivery.columns"
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
+ "# let's take a look by using isnull.sum\n",
113
+ "print(df_delivery.isnull().sum())\n",
114
+ "# weather trafficlevel timeofday courier and delivery time has some missing data\n",
115
+ "df_delivery.info()\n",
116
+ "# first let's fix the weather, traffic level and time of day col by filling the null rows with the most frequent in data (mode)\n",
117
+ "\n",
118
+ "df_delivery['Weather'] = df_delivery['Weather'].fillna(df_delivery['Weather'].mode()[0])\n",
119
+ "df_delivery['Traffic_Level'] = df_delivery['Traffic_Level'].fillna(df_delivery['Traffic_Level'].mode()[0])\n",
120
+ "df_delivery['Time_of_Day'] = df_delivery['Time_of_Day'].fillna(df_delivery['Time_of_Day'].mode()[0])\n",
121
+ "\n",
122
+ "# fix the courier exp years by filling the mode also since the data has integer number of years\n",
123
+ "df_delivery['Courier_Experience_yrs'] = df_delivery['Courier_Experience_yrs'].fillna(df_delivery['Courier_Experience_yrs'].mode()[0])\n",
124
+ "\n",
125
+ "# finally with the deliv time we must drop them since we cannot predict without them\n",
126
+ "df_delivery = df_delivery.dropna(subset=['Delivery_Time'])\n",
127
+ "\n",
128
+ "\n",
129
+ "print(df_delivery.isnull().sum())\n"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 3: Write your code here:\n",
139
+ "duplicate_rows = df_delivery.duplicated().sum()\n",
140
+ "if duplicate_rows > 0:\n",
141
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
142
+ " df_delivery.drop_duplicates(inplace=True)\n",
143
+ " print(\"Duplicate rows removed.\")\n",
144
+ "else:\n",
145
+ " print(\"No duplicate rows found.\")"
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
+ "\n",
156
+ "categorical_cols = df_delivery.select_dtypes(include=[\"object\"]).columns # Check and select our categorical cols\n",
157
+ "print(categorical_cols)\n",
158
+ "\n",
159
+ "le = LabelEncoder()\n",
160
+ "print(\"Applying Label encoder Encoding\")\n",
161
+ "for i in categorical_cols:\n",
162
+ " df_delivery[i] = le.fit_transform(df_delivery[i])\n",
163
+ "\n",
164
+ "df_delivery.head()"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 5: Write your code here:\n",
174
+ "# We shouldn't do this now to avoid data leakage but since u asked...\n",
175
+ "all_cols = df_delivery.columns.drop(\"Delivery_Time\")\n",
176
+ "\n",
177
+ "# scale the features\n",
178
+ "scaler = StandardScaler()\n",
179
+ "df_delivery[all_cols] = scaler.fit_transform(df_delivery[all_cols])\n",
180
+ "df_delivery.head()\n"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "# Task 6: Write your code here:\n",
190
+ "# Target imbalance ? this is a linear regression problem and the target doesn't classes here"
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_delivery[all_cols]\n",
201
+ "y = df_delivery['Delivery_Time']\n",
202
+ "X.head()"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "y.head()"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task 2,3,4,5: Write your code here:\n",
221
+ "from sklearn.ensemble import RandomForestRegressor\n",
222
+ "from sklearn.model_selection import KFold\n",
223
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
224
+ "\n",
225
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
226
+ "\n",
227
+ "\n",
228
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
229
+ "\n",
230
+ "mae_scores = []\n",
231
+ "rmse_scores = []\n",
232
+ "ypred = []\n",
233
+ "ytest = []\n",
234
+ "for fold, (train_idx, test_idx) in enumerate(kfold.split(X), start=1):\n",
235
+ " # indexing for each fold\n",
236
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
237
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
238
+ " # print shapes\n",
239
+ " model.fit(X_train, y_train)\n",
240
+ " y_fold_pred = model.predict(X_test)\n",
241
+ " ytest.append(y_test)\n",
242
+ " ypred.append(y_fold_pred)\n",
243
+ " # Calculate metrics\n",
244
+ " mae_scores.append(mean_absolute_error(y_test, y_fold_pred))\n",
245
+ " rmse_scores.append(np.sqrt(mean_squared_error(y_test, y_fold_pred)))\n",
246
+ " print(\"-\" * 30)\n",
247
+ "\n",
248
+ "\n",
249
+ "mae_scores = np.array(mae_scores)\n",
250
+ "rmse_scores = np.array(rmse_scores)\n",
251
+ "\n",
252
+ "print(f\"5-Fold CV Results:\")\n",
253
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
254
+ "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# Task 1: Write your code here:\n",
264
+ "feature_importance = pd.DataFrame({\n",
265
+ " 'feature': X.columns,\n",
266
+ " 'importance': model.feature_importances_\n",
267
+ "}).sort_values('importance', ascending=False)\n",
268
+ "\n",
269
+ "plt.figure(figsize=(10, 6))\n",
270
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
271
+ "plt.xlabel('Importance')\n",
272
+ "plt.title('Feature Importance')\n",
273
+ "plt.gca().invert_yaxis()\n",
274
+ "plt.show()"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 2: Write your code here:\n",
284
+ "plt.figure(figsize=(6, 4))\n",
285
+ "plt.scatter(ytest, ypred, alpha=0.7)\n",
286
+ "plt.plot([min(y_test), max(y_test)], [min(y_test), max(y_test)], 'r--', linewidth=2)\n",
287
+ "plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
288
+ "plt.ylabel(\"Predicted y_pred (Linear Regression)\")\n",
289
+ "plt.title(\"Linear Regression: Predictions vs. Ground Truth\")\n",
290
+ "plt.grid(True)\n",
291
+ "\n",
292
+ "plt.tight_layout()\n",
293
+ "plt.show()"
294
+ ],
295
+ "execution_count": null,
296
+ "outputs": []
297
+ },
298
+ {
299
+ "cell_type": "code",
300
+ "metadata": {},
301
+ "source": [
302
+ "# Task Bonus: Write your code here:"
303
+ ],
304
+ "execution_count": null,
305
+ "outputs": []
306
+ }
307
+ ],
308
+ "metadata": {
309
+ "kernelspec": {
310
+ "display_name": "Python 3",
311
+ "name": "python3"
312
+ },
313
+ "language_info": {
314
+ "name": "python"
315
+ }
316
+ },
317
+ "nbformat": 4,
318
+ "nbformat_minor": 0
319
+ }
submissions_extracted/142/Q2.ipynb ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# 3. Create DataLoaders\n",
99
+ "from torch.utils.data import DataLoader\n",
100
+ "\n",
101
+ "# DataLoader for training data\n",
102
+ "train_loader = DataLoader(\n",
103
+ " train_dataset,\n",
104
+ " batch_size=32,\n",
105
+ " shuffle=True,\n",
106
+ " num_workers=2\n",
107
+ ")\n",
108
+ "# DataLoader for test/validation data\n",
109
+ "test_loader = DataLoader(\n",
110
+ " test_dataset,\n",
111
+ " batch_size=32,\n",
112
+ " shuffle=False,\n",
113
+ " num_workers=2\n",
114
+ ")\n",
115
+ "# Get the first batch from the training DataLoader\n",
116
+ "X_batch, y_batch = next(iter(train_loader))\n",
117
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
118
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
119
+ "\n"
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
+ "first_sample, _ = train_dataset[0]\n",
130
+ "print(f\"Shape of one sample: {first_sample.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
+ "import matplotlib.pyplot as plt\n",
141
+ "images, labels = next(iter(train_loader))\n",
142
+ "\n",
143
+ "# Display the first 6 images in the batch\n",
144
+ "plt.figure(figsize=(8, 4))\n",
145
+ "\n",
146
+ "for i in range(6):\n",
147
+ " plt.subplot(2, 3, i + 1)\n",
148
+ "\n",
149
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
150
+ " img = images[i].permute(1, 2, 0)\n",
151
+ "\n",
152
+ " plt.imshow(img)\n",
153
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
154
+ " plt.axis('off')\n",
155
+ "\n",
156
+ "plt.tight_layout()\n",
157
+ "plt.show()\n"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your model class here:\n",
167
+ "import torch.nn as nn\n",
168
+ "\n",
169
+ "class NN4Layer(nn.Module):\n",
170
+ "\n",
171
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
172
+ " super(NN4Layer, self).__init__()\n",
173
+ "\n",
174
+ " # First linear layer: input features -> hidden layer\n",
175
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
176
+ "\n",
177
+ " # Second linear layer: hidden layer -> hidden layer\n",
178
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
179
+ "\n",
180
+ " # Third linear layer: hidden layer -> hidden layer\n",
181
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
182
+ "\n",
183
+ " # Output layer: hidden layer -> number of classes (logits)\n",
184
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
185
+ "\n",
186
+ " # ReLU activation for non-linearity\n",
187
+ " self.relu = nn.ReLU()\n",
188
+ "\n",
189
+ " # Defines how input data flows through the network\n",
190
+ " def forward(self, x):\n",
191
+ " # First hidden layer\n",
192
+ " a1 = self.relu(self.layer1(x))\n",
193
+ "\n",
194
+ " # Second hidden layer\n",
195
+ " a2 = self.relu(self.layer2(a1))\n",
196
+ "\n",
197
+ " # Third hidden layer\n",
198
+ " a3 = self.relu(self.layer3(a2))\n",
199
+ "\n",
200
+ " # Output layer (raw scores / logits)\n",
201
+ " output = self.layer4(a3)\n",
202
+ "\n",
203
+ " return output\n"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 2: Write your training loop here:\n",
213
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
214
+ " # Set the model to training mode\n",
215
+ " model.train()\n",
216
+ "\n",
217
+ " running_loss = 0.0\n",
218
+ "\n",
219
+ " for X_batch, y_batch in train_loader:\n",
220
+ " # Move batch to the selected device\n",
221
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
222
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
223
+ "\n",
224
+ " # Forward pass\n",
225
+ " outputs = model(X_batch)\n",
226
+ " loss = criterion(outputs, y_batch)\n",
227
+ "\n",
228
+ " # Backward pass & optimization\n",
229
+ " optimizer.zero_grad() # Clear previous gradients\n",
230
+ " loss.backward() # Compute gradients\n",
231
+ " optimizer.step() # Update model parameters\n",
232
+ "\n",
233
+ " running_loss += loss.item()\n",
234
+ "\n",
235
+ " # Average loss over all batches\n",
236
+ " avg_loss = running_loss / len(train_loader)\n",
237
+ "\n",
238
+ " return avg_loss\n"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "# Task 3: Write your validation loop here:\n",
248
+ "def validate(model, criterion, test_loader, device):\n",
249
+ " # Set the model to evaluation mode\n",
250
+ " model.eval()\n",
251
+ "\n",
252
+ " running_loss = 0.0\n",
253
+ " correct = 0\n",
254
+ " total = 0\n",
255
+ "\n",
256
+ " with torch.no_grad(): # Disable gradient computation\n",
257
+ " for X_batch, y_batch in test_loader:\n",
258
+ " # Move batch to the selected device\n",
259
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
260
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
261
+ "\n",
262
+ " # Forward pass\n",
263
+ " outputs = model(X_batch)\n",
264
+ " loss = criterion(outputs, y_batch)\n",
265
+ " running_loss += loss.item()\n",
266
+ "\n",
267
+ " # Binary predictions\n",
268
+ " predicted = (outputs > 0.5).float()\n",
269
+ "\n",
270
+ " # Accuracy calculation\n",
271
+ " correct += (predicted == y_batch).sum().item()\n",
272
+ " total += y_batch.size(0)\n",
273
+ "\n",
274
+ " avg_loss = running_loss / len(test_loader)\n",
275
+ " accuracy = correct / total\n",
276
+ "\n",
277
+ " return avg_loss, accuracy\n"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task 4: Define device, model, loss, optimizer:\n",
287
+ "from torch.optim import AdamW\n",
288
+ "# Device setup\n",
289
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
290
+ "\n",
291
+ "# Model parameters\n",
292
+ "input_dim = 3 * 36 * 36\n",
293
+ "hidden_dim = 20 # Design choice\n",
294
+ "output_dim = 1\n",
295
+ "\n",
296
+ "# Instantiate model\n",
297
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
298
+ "\n",
299
+ "# Print the model architecture\n",
300
+ "print(\"Model Architecture:\\n\")\n",
301
+ "print(model)\n",
302
+ "\n",
303
+ "# Calculate the total number of trainable parameters\n",
304
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
305
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
306
+ "num_epochs = 20\n",
307
+ "learning_rate = 0.001\n",
308
+ "\n",
309
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
310
+ "criterion = nn.CrossEntropyLoss()\n",
311
+ "# Define optimizer\n",
312
+ "optimizer = AdamW(model.parameters(), learning_rate)\n"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "metadata": {},
320
+ "source": [
321
+ "# Task 5: Start training for 20 epochs:\n",
322
+ "train_losses = []\n",
323
+ "val_losses = []\n",
324
+ "val_accuracies = []\n",
325
+ "\n",
326
+ "print('Starting Training...')\n",
327
+ "for epoch in range(num_epochs):\n",
328
+ " # Train one epoch\n",
329
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
330
+ "\n",
331
+ " # Validate\n",
332
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
333
+ "\n",
334
+ " train_losses.append(train_loss)\n",
335
+ " val_losses.append(val_loss)\n",
336
+ " val_accuracies.append(val_accuracy)\n",
337
+ "\n",
338
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
339
+ "\n",
340
+ "print('Training Complete!')"
341
+ ],
342
+ "execution_count": null,
343
+ "outputs": []
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "metadata": {},
348
+ "source": [
349
+ "# Task 1: Write your code here:\n",
350
+ "plt.figure(figsize=(7, 5))\n",
351
+ "\n",
352
+ "plt.plot(train_losses, label='Train Loss')\n",
353
+ "plt.plot(val_losses, label='Validation Loss')\n",
354
+ "plt.title('Loss over Epochs')\n",
355
+ "plt.xlabel('Epoch')\n",
356
+ "plt.ylabel('Loss')\n",
357
+ "plt.legend()\n",
358
+ "\n",
359
+ "plt.tight_layout()\n",
360
+ "plt.show()"
361
+ ],
362
+ "execution_count": null,
363
+ "outputs": []
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "metadata": {},
368
+ "source": [
369
+ "# Task 2 (Bonus): Write your code here:"
370
+ ],
371
+ "execution_count": null,
372
+ "outputs": []
373
+ }
374
+ ],
375
+ "metadata": {
376
+ "kernelspec": {
377
+ "display_name": "Python 3",
378
+ "name": "python3"
379
+ },
380
+ "language_info": {
381
+ "name": "python"
382
+ }
383
+ },
384
+ "nbformat": 4,
385
+ "nbformat_minor": 0
386
+ }
submissions_extracted/142/Q3.ipynb ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "\n",
12
+ "# Download latest version\n",
13
+ "\n",
14
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
15
+ "\n",
16
+ "\n",
17
+ "\n",
18
+ "print(\"Path to dataset files:\", path)"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "# Task 1: Write your code here:\n",
28
+ "import torch\n",
29
+ "import torch.nn as nn\n",
30
+ "from torch.optim import Adam\n",
31
+ "from torch.utils.data import DataLoader\n",
32
+ "from torchvision.datasets import MNIST\n",
33
+ "from torchvision.transforms import ToTensor, Compose, Normalize\n",
34
+ "\n",
35
+ "from sklearn.decomposition import PCA\n",
36
+ "from sklearn.manifold import TSNE\n",
37
+ "from sklearn.cluster import KMeans\n",
38
+ "\n",
39
+ "import matplotlib.pyplot as plt\n",
40
+ "import numpy as np\n",
41
+ "from collections import Counter\n",
42
+ "import os\n",
43
+ "import pandas as pd\n",
44
+ "\n",
45
+ "\n",
46
+ "ano_path = os.path.join(path, 'Q3_data.csv')\n",
47
+ "df = pd.read_csv(ano_path)\n"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 2: Write your code here:\n",
57
+ "df.head()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 3: Write your code here:\n",
67
+ "df.info()"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# Task 4: Write your code here:\n",
77
+ "df.describe()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 1: Write your code here:\n",
87
+ "#drop cols that has more than quarter of entries null\n",
88
+ "print((df.isnull().sum()>(20001/ 4)))\n",
89
+ "max_null = df[df.isnull().sum()>(20001/ 4)]\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
+ "duplicate_rows = df.duplicated().sum()\n",
100
+ "if duplicate_rows > 0:\n",
101
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
102
+ " df.drop_duplicates(inplace=True)\n",
103
+ " print(\"Duplicate rows removed.\")\n",
104
+ "else:\n",
105
+ " print(\"No duplicate rows found.\")"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# Task 3: Write your code here:"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# Task 4: Write your code here:"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 5: Write your code here:"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 1: Write your code here:"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 2,3,4,5: Write your code here:"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 1: Write your code here:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 2: Write your code here:"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task Bonus: Write your code here:"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ }
182
+ ],
183
+ "metadata": {
184
+ "kernelspec": {
185
+ "display_name": "Python 3",
186
+ "name": "python3"
187
+ },
188
+ "language_info": {
189
+ "name": "python"
190
+ }
191
+ },
192
+ "nbformat": 4,
193
+ "nbformat_minor": 0
194
+ }
submissions_extracted/143/Q1.ipynb ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import pandas as pd\n",
8
+ "import numpy as np\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import seaborn as sns\n",
11
+ "import kagglehub\n",
12
+ "import os\n",
13
+ "from tqdm import tqdm\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.preprocessing import LabelEncoder,StandardScaler\n",
16
+ "from sklearn.model_selection import KFold\n",
17
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
18
+ "%matplotlib inline"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "import kagglehub\n",
28
+ "from sklearn.ensemble import RandomForestRegressor\n",
29
+ "# Download latest version\n",
30
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
31
+ "\n",
32
+ "print(\"Path to dataset files:\", path)"
33
+ ],
34
+ "execution_count": null,
35
+ "outputs": []
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "metadata": {},
40
+ "source": [
41
+ "# Task 1: Write your code here:\n",
42
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
43
+ "df = pd.read_csv(csv_path)\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
+ "def check_target_distribution(df, target_column):\n",
84
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
85
+ "\n",
86
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
87
+ " plt.xlabel(target_column)\n",
88
+ " plt.ylabel(\"Frequency\")\n",
89
+ " plt.grid(False)\n",
90
+ "\n",
91
+ " plt.show()\n",
92
+ "check_target_distribution(df, \"Delivery_Time\")"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# Task 1: Write your code here:\n",
102
+ "df = df.drop('Order_ID', axis = 1)\n",
103
+ "df.head(1)"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 2: Write your code here:\n",
113
+ "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
+ "#with weather I will use the mode or most repeated value\n",
124
+ "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
125
+ "#Same logic with Traffic Level, Time of day since they are labels:\n",
126
+ "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
127
+ "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
128
+ "#with delevery time and experience yrs i will take the average since they are numbers:\n",
129
+ "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mean())\n",
130
+ "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
131
+ "check_missing_values(df)\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 3: Write your code here:\n",
141
+ "def check_duplicates(df):\n",
142
+ " duplicates = df.duplicated().sum()\n",
143
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
144
+ " if duplicates > 0:\n",
145
+ " print(\"Dropping Duplicates...\")\n",
146
+ " df.drop_duplicates(inplace=True)\n",
147
+ " print(\"Duplicates Dropped.\")\n",
148
+ " else:\n",
149
+ " print(\"No Duplicate Samples Found.\")\n",
150
+ "\n",
151
+ "check_duplicates(df)"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 4: Write your code here:\n",
161
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
162
+ "le = LabelEncoder()\n",
163
+ "for col in categorical_cols:\n",
164
+ " df[col] = le.fit_transform(df[col])\n",
165
+ "df.head()"
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
+ "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n",
176
+ "\n",
177
+ "scaler = StandardScaler()\n",
178
+ "\n",
179
+ "# scale the `numerical_cols`\n",
180
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
181
+ "\n",
182
+ "df.head()"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "# Task 6: Write your code here:\n",
192
+ "#Answer: this is not needed we are not making classification"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "# Task 1: Write your code here:\n",
202
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
203
+ "y = df['Delivery_Time'].astype(float)"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 2,3,4,5: Write your code here:\n",
213
+ "n_splits = 5 # K=5 Folds\n",
214
+ "model = RandomForestRegressor(n_estimators=200)\n",
215
+ "# 5-Fold Cross-Validation, shuffled\n",
216
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
217
+ "lr_mae = []\n",
218
+ "\n",
219
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)): #the .split() function returns the idex of the test and train\n",
220
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\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
+ " # Train\n",
226
+ " model.fit(X_train, y_train)\n",
227
+ " # Validate\n",
228
+ " y_pred = model.predict(X_test)\n",
229
+ "\n",
230
+ " # Calculate evaluation metrics\n",
231
+ " mae = mean_absolute_error(y_test,y_pred)\n",
232
+ "\n",
233
+ " # Store results\n",
234
+ " lr_mae.append(mae)\n",
235
+ "print(\"The mean MAE across the folds:\",np.mean(lr_mae))"
236
+ ],
237
+ "execution_count": null,
238
+ "outputs": []
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "metadata": {},
243
+ "source": [
244
+ "# Task 1: Write your code here:\n",
245
+ "coeffs = model.coef_\n",
246
+ "print(coeffs)"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "# Task 2: Write your code here:\n",
256
+ "plt.hist(y_pred, bins = 30, color = 'red', edgecolor = 'black')\n",
257
+ "plt.grid(True)\n",
258
+ "plt.xlabel(\"Predicted Delivery Time\")\n",
259
+ "plt.ylabel(\"Frequency of predicted Delievery Time\")\n",
260
+ "plt.title(\"Distribution of Predicted Delivery Time\")\n",
261
+ "plt.show()"
262
+ ],
263
+ "execution_count": null,
264
+ "outputs": []
265
+ },
266
+ {
267
+ "cell_type": "code",
268
+ "metadata": {},
269
+ "source": [
270
+ "# Task Bonus: Write your code here:"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ }
275
+ ],
276
+ "metadata": {
277
+ "kernelspec": {
278
+ "display_name": "Python 3",
279
+ "name": "python3"
280
+ },
281
+ "language_info": {
282
+ "name": "python"
283
+ }
284
+ },
285
+ "nbformat": 4,
286
+ "nbformat_minor": 0
287
+ }
submissions_extracted/143/Q2.ipynb ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 torch\n",
22
+ "from sklearn.datasets import load_breast_cancer\n",
23
+ "from sklearn.model_selection import train_test_split\n",
24
+ "from sklearn.preprocessing import StandardScaler\n",
25
+ "from torch.utils.data import TensorDataset\n",
26
+ "from torch.utils.data import DataLoader"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "import os\n",
36
+ "import pandas as pd\n",
37
+ "import numpy as np\n",
38
+ "from PIL import Image\n",
39
+ "from sklearn.model_selection import train_test_split\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}\")"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
83
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
84
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
85
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
86
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
87
+ "\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
+ "train_dataset = TensorDataset(X_train, y_train)\n",
98
+ "test_dataset = TensorDataset(X_test, y_test)\n"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# 3. Create DataLoaders\n",
108
+ "from torch.utils.data import DataLoader\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, #((Only shuffle the train not the test))\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
+ "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
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# 5. Display sample images\n",
144
+ "import matplotlib.pyplot as plt\n",
145
+ "images, labels = next(iter(train_loader))\n",
146
+ "\n",
147
+ "# Display the first 6 images in the batch\n",
148
+ "plt.figure(figsize=(8, 4))\n",
149
+ "\n",
150
+ "for i in range(6):\n",
151
+ " plt.subplot(2, 3, i + 1)\n",
152
+ " plt.imshow(images[i].squeez())\n",
153
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
154
+ " plt.axis('off')\n",
155
+ "\n",
156
+ "plt.tight_layout()\n",
157
+ "plt.show()\n"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "import torch\n",
167
+ "import torch.nn as nn\n",
168
+ "from torchvision.datasets import MNIST\n",
169
+ "from torch.utils.data import DataLoader\n",
170
+ "from torch.optim import Adam\n",
171
+ "from torchvision.transforms.functional import to_tensor\n",
172
+ "import torch.nn.functional as F"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 1: Write your model class here:\n",
182
+ "input_dim = 3*36*36\n",
183
+ "hidden_dim = 256\n",
184
+ "output_dim = 1\n",
185
+ "class NN4Layer(nn.Module):\n",
186
+ "\n",
187
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
188
+ " super(NN4Layer, self).__init__()\n",
189
+ "\n",
190
+ " # First linear layer: input features -> hidden layer\n",
191
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
192
+ " # Second linear layer: hidden layer -> hidden layer\n",
193
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
194
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
195
+ " # Output layer: hidden layer -> number of classes (logits)\n",
196
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
197
+ "\n",
198
+ " # ReLU activation for non-linearity\n",
199
+ " self.relu = nn.ReLU()\n",
200
+ " self.softmax = nn.Softmax()\n",
201
+ "\n",
202
+ " # Defines how input data flows through the network\n",
203
+ " def forward(self, x):\n",
204
+ " # First hidden layer\n",
205
+ " z1 = self.layer1(x)\n",
206
+ " a1 = self.relu(z1)\n",
207
+ "\n",
208
+ " # Second hidden layer\n",
209
+ " z2 = self.layer2(a1)\n",
210
+ " a2 = self.relu(z2)\n",
211
+ "\n",
212
+ " #Third hidden layer\n",
213
+ " z3 = self.layer3(a2)\n",
214
+ " a3 = self.relu(z3)\n",
215
+ "\n",
216
+ " #Fourth Layer\n",
217
+ " z4 = self.layer4(a3)\n",
218
+ " a4 = self.softmax(z4)\n",
219
+ "\n",
220
+ " # Output layer\n",
221
+ " output = a4\n",
222
+ "\n",
223
+ " return output\n",
224
+ "print(input_dim)"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Task 2: Write your training loop here:\n",
234
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
235
+ " # Set the model to training mode\n",
236
+ " model.train()\n",
237
+ "\n",
238
+ " running_loss = 0.0\n",
239
+ "\n",
240
+ " for X_batch, y_batch in train_loader:\n",
241
+ " # Move batch to the selected device\n",
242
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
243
+ " y_batch = y_batch.to(device)\n",
244
+ "\n",
245
+ " # Forward pass\n",
246
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
247
+ " loss = criterion(outputs, y_batch)\n",
248
+ "\n",
249
+ " # Backward pass & optimization\n",
250
+ " optimizer.zero_grad() # Clear previous gradients\n",
251
+ " loss.backward() # Compute gradients\n",
252
+ " optimizer.step() # Update model parameters\n",
253
+ "\n",
254
+ " running_loss += loss.item()\n",
255
+ "\n",
256
+ " # Average loss over all batches\n",
257
+ " avg_loss = running_loss / len(train_loader)\n",
258
+ "\n",
259
+ " return avg_loss"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task 3: Write your validation loop here:\n",
269
+ "def validate(model, criterion, test_loader, device):\n",
270
+ " # Set the model to evaluation mode\n",
271
+ " model.eval()\n",
272
+ "\n",
273
+ " running_loss = 0.0\n",
274
+ " correct = 0\n",
275
+ " total = 0\n",
276
+ "\n",
277
+ " with torch.no_grad():\n",
278
+ " for X_batch, y_batch in test_loader:\n",
279
+ " # Move data to device\n",
280
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
281
+ " y_batch = y_batch.to(device)\n",
282
+ "\n",
283
+ " # Forward pass\n",
284
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
285
+ " loss = criterion(outputs, y_batch)\n",
286
+ " running_loss += loss.item()\n",
287
+ "\n",
288
+ " # Apply Softmax to get probabilities\n",
289
+ " probabilities = F.softmax(outputs, dim=1)\n",
290
+ "\n",
291
+ " # 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
+ " accuracy = correct / total\n",
300
+ "\n",
301
+ " return avg_loss, accuracy"
302
+ ],
303
+ "execution_count": null,
304
+ "outputs": []
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "metadata": {},
309
+ "source": [
310
+ "from torch.optim import AdamW\n",
311
+ "learning_rate = 0.001\n",
312
+ "num_epochs = 20\n",
313
+ "# Task 4: Define device, model, loss, optimizer:\n",
314
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
315
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
316
+ "criterion = nn.MSELoss()\n",
317
+ "optimizer = AdamW(model.parameters(), learning_rate)"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "# Task 5: Start training for 20 epochs:\n",
327
+ "# Run Training\n",
328
+ "train_losses = []\n",
329
+ "val_losses = []\n",
330
+ "val_accuracies = []\n",
331
+ "\n",
332
+ "print('Starting Training...')\n",
333
+ "for epoch in range(num_epochs):\n",
334
+ " # Train one epoch\n",
335
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
336
+ "\n",
337
+ " # Validate\n",
338
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
339
+ "\n",
340
+ " train_losses.append(train_loss)\n",
341
+ " val_losses.append(val_loss)\n",
342
+ " val_accuracies.append(val_accuracy)\n",
343
+ "\n",
344
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
345
+ "\n",
346
+ "print('Training Complete!')"
347
+ ],
348
+ "execution_count": null,
349
+ "outputs": []
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "metadata": {},
354
+ "source": [
355
+ "# Task 1: Write your code here:\n",
356
+ "plt.figure(figsize=(7, 5))\n",
357
+ "\n",
358
+ "plt.plot(train_losses, label='Train Loss')\n",
359
+ "plt.plot(val_losses, label='Validation Loss')\n",
360
+ "plt.title('Loss over Epochs')\n",
361
+ "plt.xlabel('Epoch')\n",
362
+ "plt.ylabel('Loss')\n",
363
+ "plt.legend()\n",
364
+ "\n",
365
+ "plt.tight_layout()\n",
366
+ "plt.show()"
367
+ ],
368
+ "execution_count": null,
369
+ "outputs": []
370
+ },
371
+ {
372
+ "cell_type": "code",
373
+ "metadata": {},
374
+ "source": [
375
+ "# Task 2 (Bonus): Write your code here:"
376
+ ],
377
+ "execution_count": null,
378
+ "outputs": []
379
+ }
380
+ ],
381
+ "metadata": {
382
+ "kernelspec": {
383
+ "display_name": "Python 3",
384
+ "name": "python3"
385
+ },
386
+ "language_info": {
387
+ "name": "python"
388
+ }
389
+ },
390
+ "nbformat": 4,
391
+ "nbformat_minor": 0
392
+ }
submissions_extracted/143/Q3.ipynb ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "from torchvision.datasets import CIFAR10\n",
8
+ "from torchvision.transforms.functional import to_tensor\n",
9
+ "from torch.utils.data import DataLoader\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import torch.nn as nn\n",
12
+ "import torch.nn.functional as F\n",
13
+ "import torch\n",
14
+ "from torch.optim import AdamW\n",
15
+ "import pandas as pd\n",
16
+ "import numpy as np\n",
17
+ "import matplotlib.pyplot as plt\n",
18
+ "import seaborn as sns\n",
19
+ "import kagglehub\n",
20
+ "import os\n",
21
+ "from tqdm import tqdm\n",
22
+ "from sklearn.preprocessing import LabelEncoder,StandardScaler\n"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "import kagglehub\n",
32
+ "\n",
33
+ "\n",
34
+ "\n",
35
+ "# Download latest version\n",
36
+ "\n",
37
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
38
+ "\n",
39
+ "\n",
40
+ "\n",
41
+ "print(\"Path to dataset files:\", path)"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 1: Write your code here:\n",
51
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
52
+ "df = pd.read_csv(csv_path)\n"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 2: Write your code here:\n",
62
+ "df.head()"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 3: Write your code here:\n",
72
+ "df.info()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 4: Write your code here:\n",
82
+ "df.describe()"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# Task 1: Write your code here:\n",
92
+ "def check_missing_values(df):\n",
93
+ " missing_values = df.isnull().sum()\n",
94
+ " print(\"Missing Values per Column:\")\n",
95
+ " print(missing_values[missing_values > 0])\n",
96
+ " if missing_values.any():\n",
97
+ " print(\"\\nHandle Missing Values as needed.\")\n",
98
+ " else:\n",
99
+ " print(\"\\nNo Missing Values Found.\")\n",
100
+ "\n",
101
+ "check_missing_values(df)\n",
102
+ "print(\"total misisng values\", df.isnull().sum().sum())\n",
103
+ "#fill missing values with the mean\n",
104
+ "for col in df.columns:\n",
105
+ " df[col] = df[col].fillna(df[col].mean())\n",
106
+ "check_missing_values(df)"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 2: Write your code here:\n",
116
+ "def check_duplicates(df):\n",
117
+ " duplicates = df.duplicated().sum()\n",
118
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
119
+ " if duplicates > 0:\n",
120
+ " print(\"Dropping Duplicates...\")\n",
121
+ " df.drop_duplicates(inplace=True)\n",
122
+ " print(\"Duplicates Dropped.\")\n",
123
+ " else:\n",
124
+ " print(\"No Duplicate Samples Found.\")\n",
125
+ "\n",
126
+ "check_duplicates(df)"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# Task 3: Write your code here:\n",
136
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
137
+ "print(categorical_cols)\n",
138
+ "#no need"
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
+ "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
149
+ "\n",
150
+ "scaler = StandardScaler()\n",
151
+ "\n",
152
+ "# scale the `numerical_cols`\n",
153
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
154
+ "\n",
155
+ "df.head()\n"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 5: Write your code here:\n",
165
+ "percent_of_one = len(df[(df['Target'] == 1)])/len(df['Target'])\n",
166
+ "print(f\"percent of Target that equals 1: {percent_of_one*100:.2f}%\")\n",
167
+ "#Target = 1 is the minority class"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "from IPython.display import clear_output\n",
177
+ "\n",
178
+ "%pip install kagglehub catboost xgboost tqdm imbalanced-learn -q\n",
179
+ "\n",
180
+ "clear_output()"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "# Task 1: Write your code here:\n",
190
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
191
+ "y = df['Target'].astype(float)"
192
+ ],
193
+ "execution_count": null,
194
+ "outputs": []
195
+ },
196
+ {
197
+ "cell_type": "code",
198
+ "metadata": {},
199
+ "source": [
200
+ "# Task 2,3,4,5: Write your code here:\n",
201
+ "from sklearn.model_selection import StratifiedKFold\n",
202
+ "from sklearn.metrics import accuracy_score, f1_score\n",
203
+ "from catboost import CatBoostClassifier\n",
204
+ "F1 = []\n",
205
+ "acc = []\n",
206
+ "n_splits = 3 # K=3 Folds\n",
207
+ "model = CatBoostClassifier(\n",
208
+ " verbose=0,\n",
209
+ " n_estimators=200,\n",
210
+ " max_depth=4\n",
211
+ " )\n",
212
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
213
+ "sr_results = {'loss': [], 'acc': [], 'f1': []}\n",
214
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
215
+ "\n",
216
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
217
+ "\n",
218
+ " # Get the train & test split for this fold\n",
219
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
220
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
221
+ "\n",
222
+ " # Train using gradient descent with learning rate = 0.5\n",
223
+ " model.fit(X_train, y_train)\n",
224
+ "\n",
225
+ " # Calculate z & class probabilities for X_test\n",
226
+ " y_pred = model.predict(X_test)\n",
227
+ "\n",
228
+ " # Calculate evaluation metrics\n",
229
+ " accuracy = accuracy_score(y_test, y_pred)\n",
230
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
231
+ "\n",
232
+ " acc.append(accuracy)\n",
233
+ " F1.append(f1)"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "metadata": {},
241
+ "source": [
242
+ "# Task 1: Write your code here:\n",
243
+ "importances = {}\n",
244
+ "\n",
245
+ "importances['CatBoost'] = model.feature_importances_\n",
246
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
247
+ "axes = axes.flatten()\n",
248
+ "features = X.columns\n",
249
+ "\n",
250
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
251
+ " # Sort features by importance for a cleaner plot\n",
252
+ " sorted_idx = np.argsort(imp)\n",
253
+ "\n",
254
+ " ax = axes[i]\n",
255
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
256
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
257
+ " ax.set_xlabel(\"Importance Score\")\n",
258
+ "\n",
259
+ "plt.tight_layout()\n",
260
+ "plt.show()\n",
261
+ "# Create a 1x3 plot\n",
262
+ "sorted_idx = np.argsort(importances['CatBoost'][:5])\n",
263
+ "features = X.columns\n",
264
+ "\n",
265
+ "plt.tight_layout()\n",
266
+ "plt.show()"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "sort_idx = np.argsort(model.feature_importances_)\n",
276
+ "print(features[sort_idx][:5])\n",
277
+ "plt.barh(features[sort_idx][:8],model.feature_importances_[:8])"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task 2: Write your code here:"
287
+ ],
288
+ "execution_count": null,
289
+ "outputs": []
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "metadata": {},
294
+ "source": [
295
+ "# Task Bonus: Write your code here:"
296
+ ],
297
+ "execution_count": null,
298
+ "outputs": []
299
+ }
300
+ ],
301
+ "metadata": {
302
+ "kernelspec": {
303
+ "display_name": "Python 3",
304
+ "name": "python3"
305
+ },
306
+ "language_info": {
307
+ "name": "python"
308
+ }
309
+ },
310
+ "nbformat": 4,
311
+ "nbformat_minor": 0
312
+ }
submissions_extracted/144/Q1.ipynb ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, KFold\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
23
+ "\n",
24
+ "print(\"Path to dataset files:\", path)"
25
+ ],
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "source": [
33
+ "# Load the dataset\n",
34
+ "food_path = os.path.join(path, 'Q1_data.csv')\n",
35
+ "df_food = pd.read_csv(food_path)\n"
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_food.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
+ "# Check data types and structure\n",
56
+ "df_food.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_food.describe()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 5: Write your code here:\n",
76
+ "# delivery_time distribution (target variable)\n",
77
+ "plt.figure(figsize=(10, 5))\n",
78
+ "plt.hist(df_food['Delivery_Time'].dropna(), bins=20, edgecolor='black')\n",
79
+ "plt.title('delivery_time Distribution')\n",
80
+ "plt.xlabel('delivery_time')\n",
81
+ "plt.ylabel('Frequency')\n",
82
+ "plt.show()\n",
83
+ "\n"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 1: Write your code here:\n",
93
+ "df_food.drop(columns=['Order_ID'])"
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
+ "\n",
104
+ "df_clean = df_food.copy()\n",
105
+ "\n",
106
+ "\n",
107
+ "df_clean = df_clean.dropna(subset=['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs', 'Delivery_Time',])\n",
108
+ "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
+ "\n",
119
+ "duplicates = df_clean.duplicated().sum()\n",
120
+ "print(f\"Number of Duplicate Samples: {duplicates}\")\n",
121
+ "if duplicates > 0:\n",
122
+ " print(\"Dropping Duplicates...\")\n",
123
+ " df_clean.drop_duplicates(inplace=True)\n",
124
+ " print(\"Duplicates Dropped.\")\n",
125
+ "else:\n",
126
+ " print(\"No Duplicate Samples Found.\")\n",
127
+ "\n",
128
+ "df_clean.shape\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 4: Write your code here:\n",
138
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
139
+ "for col in categorical_cols:\n",
140
+ " le = LabelEncoder()\n",
141
+ " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
142
+ "\n",
143
+ "df_clean.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:"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 6: Write your code here:"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 1: Write your code here:"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 2,3,4,5: Write your code here:"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 1: Write your code here:"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 2: Write your code here:"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task Bonus: Write your code here:"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ }
211
+ ],
212
+ "metadata": {
213
+ "kernelspec": {
214
+ "display_name": "Python 3",
215
+ "name": "python3"
216
+ },
217
+ "language_info": {
218
+ "name": "python"
219
+ }
220
+ },
221
+ "nbformat": 4,
222
+ "nbformat_minor": 0
223
+ }
submissions_extracted/144/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/144/Q3.ipynb ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "import pandas as pd\n",
10
+ "import numpy as np\n",
11
+ "import matplotlib.pyplot as plt\n",
12
+ "import seaborn as sns\n",
13
+ "import kagglehub\n",
14
+ "import os\n",
15
+ "from tqdm import tqdm\n",
16
+ "%matplotlib inline\n",
17
+ "# Download latest version\n",
18
+ "\n",
19
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
20
+ "\n",
21
+ "\n",
22
+ "\n",
23
+ "print(\"Path to dataset files:\", path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 1: Write your code here:\n",
33
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
34
+ "\n",
35
+ "df = pd.read_csv(csv_path)\n",
36
+ "\n"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 2: Write your code here:\n",
46
+ "df.head()"
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
+ "def check_missing_values(df):\n",
77
+ "\n",
78
+ " # Get missing values using pandas\n",
79
+ " missing_values = df.isnull().sum()\n",
80
+ "\n",
81
+ " print(\"Missing Values per Column:\")\n",
82
+ " print(missing_values[missing_values > 0])\n",
83
+ "\n",
84
+ " if missing_values.any():\n",
85
+ " print(\"\\nHandle Missing Values as needed.\")\n",
86
+ " else:\n",
87
+ " print(\"\\nNo Missing Values Found.\")\n",
88
+ "\n",
89
+ "check_missing_values(df)"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 2: Write your code here:\n",
99
+ "def check_duplicates(df):\n",
100
+ "\n",
101
+ " #TODO: get duplicated data using pandas\n",
102
+ " duplicates = df.duplicated().sum()\n",
103
+ "\n",
104
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
105
+ " if duplicates > 0:\n",
106
+ " print(\"Dropping Duplicates...\")\n",
107
+ " df.drop_duplicates(inplace=True)\n",
108
+ " print(\"Duplicates Dropped.\")\n",
109
+ " else:\n",
110
+ " print(\"No Duplicate Samples Found.\")\n",
111
+ "\n",
112
+ "check_duplicates(df)"
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
+ "from sklearn.preprocessing import LabelEncoder\n",
123
+ "le = LabelEncoder()\n"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 4: Write your code here:"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 5: Write your code here:"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 1: Write your code here:"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 2,3,4,5: Write your code here:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 2: Write your code here:"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task Bonus: Write your code here:"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ }
191
+ ],
192
+ "metadata": {
193
+ "kernelspec": {
194
+ "display_name": "Python 3",
195
+ "name": "python3"
196
+ },
197
+ "language_info": {
198
+ "name": "python"
199
+ }
200
+ },
201
+ "nbformat": 4,
202
+ "nbformat_minor": 0
203
+ }
submissions_extracted/145/Q1.ipynb ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import pandas as pd\n",
8
+ "import os\n",
9
+ "import matplotlib.pyplot as plt"
10
+ ],
11
+ "execution_count": null,
12
+ "outputs": []
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "metadata": {},
17
+ "source": [
18
+ "import kagglehub\n",
19
+ "\n",
20
+ "# Download latest version\n",
21
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
22
+ "\n",
23
+ "print(\"Path to dataset files:\", path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 1: Write your code here:\n",
33
+ "#Read the dataset\n",
34
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
35
+ "df_data = pd.read_csv(data_path)\n"
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
+ "#head()\n",
46
+ "df_data.head()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 3: Write your code here:\n",
56
+ "#Display dataset\n",
57
+ "df_data.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_data.describe()\n"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# Task 5: Write your code here:\n",
77
+ "#Plot the target distribution\n",
78
+ "plt.figure(figsize=(10, 5))\n",
79
+ "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
80
+ "plt.title('Target Distribution')\n",
81
+ "plt.xlabel('Time')\n",
82
+ "plt.ylabel('Frequency')\n",
83
+ "plt.show()"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "print(\"Before dropping:\\n\", df_data)"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# Task 1: Write your code here:\n",
102
+ "#Drop the 'Order_ID'\n",
103
+ "df_clean = df_data.copy()\n",
104
+ "df_clean=df_data.drop(columns=['Order_ID'])\n",
105
+ "print(\"After dropping:\\n\" ,df_clean)"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# Task 2: Write your code here:\n",
115
+ "# missing values\n",
116
+ "missing_values = df_clean.isnull().sum()\n",
117
+ "print(\"Missing values:\\n\" ,missing_values)"
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
+ "#Encode categorical variables\n",
128
+ "duplicates=df_clean.drop_duplicates(inplace=True)\n",
129
+ "duplicates"
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
+ "# scaling\n",
140
+ "from sklearn.preprocessing import LabelEncoder\n",
141
+ "categorical_cols = df_clean.select_dtypes(include=[\"object\"]).columns\n",
142
+ "for col in categorical_cols:\n",
143
+ " print(f\"Encoding column: {col}\")\n",
144
+ " le = LabelEncoder()\n",
145
+ " df_clean[col] = le.fit_transform(df_clean[col])\n",
146
+ "df_clean"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Task 5: Write your code here:\n",
156
+ "from sklearn.preprocessing import StandardScaler\n",
157
+ "data_for_scale=df_clean.copy()\n",
158
+ "print('data before scaling:\\n', data_for_scale) #show before scaling\n",
159
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
160
+ "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n",
161
+ "\n",
162
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
163
+ ],
164
+ "execution_count": null,
165
+ "outputs": []
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "metadata": {},
170
+ "source": [
171
+ "# Task 6: Write your code here:\n",
172
+ "#Check for target imbalance\n",
173
+ "import seaborn as sns\n",
174
+ "def check_target_imbalance(df_data, target_column):\n",
175
+ " print(\"Target Distribution:\")\n",
176
+ " print(df_data[target_column].value_counts(normalize=True))\n",
177
+ " sns.countplot(x=df_data[target_column])\n",
178
+ " plt.title(\"Target Distribution\")\n",
179
+ " plt.show()\n",
180
+ "\n",
181
+ "check_target_imbalance(df_data, \"Delivery_Time\")"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 2,3,4,5: Write your code here:"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 1: Write your code here:"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 2: Write your code here:"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Task Bonus: Write your code here:"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ }
229
+ ],
230
+ "metadata": {
231
+ "kernelspec": {
232
+ "display_name": "Python 3",
233
+ "name": "python3"
234
+ },
235
+ "language_info": {
236
+ "name": "python"
237
+ }
238
+ },
239
+ "nbformat": 4,
240
+ "nbformat_minor": 0
241
+ }
submissions_extracted/145/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/145/Q3.ipynb ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import pandas as pd\n",
8
+ "import os\n",
9
+ "import matplotlib.pyplot as plt"
10
+ ],
11
+ "execution_count": null,
12
+ "outputs": []
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "metadata": {},
17
+ "source": [
18
+ "import kagglehub\n",
19
+ "\n",
20
+ "\n",
21
+ "\n",
22
+ "# Download latest version\n",
23
+ "\n",
24
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
25
+ "\n",
26
+ "\n",
27
+ "\n",
28
+ "print(\"Path to dataset files:\", path)"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "# Task 1: Write your code here:\n",
38
+ "#Read the dataset\n",
39
+ "data_path = os.path.join(path, 'Q3_data.csv')\n",
40
+ "df_data = pd.read_csv(data_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_data.head()"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 3: Write your code here:\n",
60
+ "#Display dataset\n",
61
+ "df_data.info()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 4: Write your code here:\n",
71
+ "df_data.describe()"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 1: Write your code here:\n",
81
+ "#Handle missing values\n",
82
+ "missing_values = df_data.isnull().sum()\n",
83
+ "print(\"Missing values:\\n\" ,missing_values)"
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
+ "#Check and remove duplicates\n",
94
+ "df_data.duplicated()\n",
95
+ "duplicates = df_data.drop_duplicates(inplace=True)\n",
96
+ "print(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
+ "#Encode categorical variables\n",
107
+ "from sklearn.preprocessing import LabelEncoder\n",
108
+ "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n",
109
+ "for col in categorical_cols:\n",
110
+ " print(f\"Encoding column: {col}\")\n",
111
+ " le = LabelEncoder()\n",
112
+ " df_data[col] = le.fit_transform(df_data[col])\n",
113
+ "df_data"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# Task 4: Write your code here:\n",
123
+ "#scaling\n",
124
+ "from sklearn.preprocessing import StandardScaler\n",
125
+ "data_for_scale=df_data.copy()\n",
126
+ "print('data before scaling:\\n', data_for_scale) #show before scaling\n",
127
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
128
+ "data_standard_scaled = standard_scaler.fit_transform(data_for_scale) # Apply fit_transform\n",
129
+ "\n",
130
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 5: Write your code here:\n",
140
+ "#Check for target imbalance\n",
141
+ "import seaborn as sns\n",
142
+ "def check_target_imbalance(df_data, target_column):\n",
143
+ " print(\"Target Distribution:\")\n",
144
+ " print(df_data[target_column].value_counts(normalize=True))\n",
145
+ " sns.countplot(x=df_data[target_column])\n",
146
+ " plt.title(\"Target Distribution\")\n",
147
+ " plt.show()\n",
148
+ "\n",
149
+ "check_target_imbalance(df_data, \"Target\")"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "# Task 1: Write your code here:\n",
159
+ "from sklearn.model_selection import train_test_split\n",
160
+ "X_s = df_data.drop(\"target\", axis=1).astype(float)\n",
161
+ "y_s = df_data[\"target\"].astype(float)"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 2,3,4,5: Write your code here:\n",
171
+ "from sklearn.model_selection import KFold\n",
172
+ "\n",
173
+ "\n",
174
+ "X, y = X_s.copy(), y_s.copy()\n",
175
+ "\n",
176
+ "# K-Fold Cross Validation\n",
177
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
178
+ "\n",
179
+ "# Iterate through folds\n",
180
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
181
+ " # indexing for each fold\n",
182
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
183
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
184
+ " # print shapes\n",
185
+ " print(f\"Fold {fold}\")\n",
186
+ " print(\" X_train shape:\", X_train.shape)\n",
187
+ " print(\" X_test shape :\", X_test.shape)\n",
188
+ " print(\" y_train shape:\", y_train.shape)\n",
189
+ " print(\" y_test shape :\", y_test.shape)\n",
190
+ " print(\"-\" * 30)"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task 1: Write your code here:"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "# Task 2: Write your code here:"
209
+ ],
210
+ "execution_count": null,
211
+ "outputs": []
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "metadata": {},
216
+ "source": [
217
+ "# Task Bonus: Write your code here:"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ }
222
+ ],
223
+ "metadata": {
224
+ "kernelspec": {
225
+ "display_name": "Python 3",
226
+ "name": "python3"
227
+ },
228
+ "language_info": {
229
+ "name": "python"
230
+ }
231
+ },
232
+ "nbformat": 4,
233
+ "nbformat_minor": 0
234
+ }
submissions_extracted/146/Q1.ipynb ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.preprocessing import StandardScaler\n",
14
+ "from sklearn.preprocessing import OneHotEncoder\n",
15
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
17
+ "from sklearn.ensemble import RandomForestClassifier\n",
18
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
19
+ "\n",
20
+ "import warnings\n",
21
+ "warnings.filterwarnings('ignore')"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "import kagglehub\n",
31
+ "\n",
32
+ "# Download latest version\n",
33
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
34
+ "\n",
35
+ "print(\"Path to dataset files:\", path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 1: Write your code here:\n",
45
+ "delivery_path = os.path.join(path, 'Q1_data.csv')\n",
46
+ "df_delivery = pd.read_csv(delivery_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_delivery.shape}\")\n",
57
+ "df_delivery.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_delivery.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_delivery.describe()"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# Task 5: Write your code here:\n",
87
+ "#delivery_time\n",
88
+ "plt.figure(figsize=(10, 5))\n",
89
+ "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
90
+ "plt.title('Delivery time Distribution')\n",
91
+ "plt.xlabel('delivery')\n",
92
+ "plt.ylabel('Frequency')\n",
93
+ "plt.show()"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 1: Write your code here:\n",
103
+ "df_clean = df_delivery.drop(columns=['Order_ID']).copy()\n"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 2: Write your code here:\n",
113
+ "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
+ "check_missing_values(df_delivery)\n"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 3: Write your code here:\n",
131
+ "def check_duplicates(df):\n",
132
+ " duplicates = df.duplicated().sum()\n",
133
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
134
+ " if duplicates > 0:\n",
135
+ " print(\"Dropping Duplicates...\")\n",
136
+ " df.drop_duplicates(inplace=True)\n",
137
+ " print(\"Duplicates Dropped.\")\n",
138
+ " else:\n",
139
+ " print(\"No Duplicate Samples Found.\")\n",
140
+ "check_duplicates(df_delivery)\n"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "#Apply feature scaling for all features (Use StandardScaler)\n",
150
+ "\n",
151
+ "categorical_cols =(df_delivery)\n",
152
+ "for col in categorical_cols:\n",
153
+ " le = LabelEncoder()\n",
154
+ " df_clean[col] = le.fit_transform(df_clean[col].astype(str))\n",
155
+ "\n",
156
+ "df_clean.head()"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 5: Write your code here:\n",
166
+ "# 1. Is the target imbalanced?\n",
167
+ "def check_target_imbalance(df, target_column):\n",
168
+ " print(\"Target Distribution:\")\n",
169
+ " print(df[target_column].value_counts(normalize=True))\n",
170
+ " plt.title(\"Target Distribution\")\n",
171
+ " plt.show()\n",
172
+ "check_target_imbalance(df_delivery, \"delivery_time\")\n"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 6: Write your code here:\n",
182
+ "def check_target_imbalance(df, target_column):\n",
183
+ " print(\"Target Distribution:\")\n",
184
+ " print(df[target_column].value_counts(normalize=True))\n",
185
+ " plt.title(\"Target Distribution\")\n",
186
+ " plt.show()\n",
187
+ "check_target_imbalance(df_delivery, \"delivery_time\")"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Task 1: Write your code here:"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 2,3,4,5: Write your code here:"
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': feature_cols,\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:"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task Bonus: Write your code here:"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ }
248
+ ],
249
+ "metadata": {
250
+ "kernelspec": {
251
+ "display_name": "Python 3",
252
+ "name": "python3"
253
+ },
254
+ "language_info": {
255
+ "name": "python"
256
+ }
257
+ },
258
+ "nbformat": 4,
259
+ "nbformat_minor": 0
260
+ }
submissions_extracted/146/Q2.ipynb ADDED
@@ -0,0 +1,192 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "\n"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# 2. Create TensorDataset objects\n",
80
+ "\n",
81
+ "\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 3. Create DataLoaders\n",
91
+ "\n",
92
+ "\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 4. Print shape of one batch\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 5. Display sample images\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 1: Write your model class here:"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 2: Write your training loop here:"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 3: Write your validation loop here:"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Define device, model, loss, optimizer:"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Start training for 20 epochs:"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 1: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2 (Bonus): Write your code here:"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ }
180
+ ],
181
+ "metadata": {
182
+ "kernelspec": {
183
+ "display_name": "Python 3",
184
+ "name": "python3"
185
+ },
186
+ "language_info": {
187
+ "name": "python"
188
+ }
189
+ },
190
+ "nbformat": 4,
191
+ "nbformat_minor": 0
192
+ }
submissions_extracted/146/Q3.ipynb ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.preprocessing import StandardScaler\n",
14
+ "from sklearn.preprocessing import OneHotEncoder\n",
15
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
17
+ "from sklearn.ensemble import RandomForestClassifier\n",
18
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
19
+ "\n",
20
+ "import warnings\n",
21
+ "warnings.filterwarnings('ignore')"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "import kagglehub\n",
31
+ "\n",
32
+ "\n",
33
+ "\n",
34
+ "# Download latest version\n",
35
+ "\n",
36
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
37
+ "\n",
38
+ "\n",
39
+ "\n",
40
+ "print(\"Path to dataset files:\", path)"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 1: Write your code here:\n",
50
+ "anony_path = os.path.join(path, 'Q3_data.csv')\n",
51
+ "df_anony = pd.read_csv(anony_path)"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 2: Write your code here:\n",
61
+ "df_anony.head()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 3: Write your code here:\n",
71
+ "df_anony.info()"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 4: Write your code here:\n",
81
+ "df_anony.describe()"
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
+ "def check_missing_values(df):\n",
92
+ " missing_values = df.isnull().sum()\n",
93
+ " print(\"Missing Values per Column:\")\n",
94
+ " print(missing_values[missing_values > 0])\n",
95
+ " print(\"\\nNo Missing Values Found.\")\n",
96
+ "check_missing_values(df_anony)"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# Task 2: Write your code here:\n",
106
+ "def check_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
+ "check_duplicates(df_anony)"
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
+ "from sklearn.preprocessing import LabelEncoder\n",
126
+ "le = LabelEncoder()\n",
127
+ "\n",
128
+ "# Encode the target column\n",
129
+ "df['Air Quality'] = le.fit_transform(df['Air Quality'])\n",
130
+ "\n",
131
+ "df"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4: Write your code here:"
141
+ ],
142
+ "execution_count": null,
143
+ "outputs": []
144
+ },
145
+ {
146
+ "cell_type": "code",
147
+ "metadata": {},
148
+ "source": [
149
+ "# Task 5: Write your code here:"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "# Task 1: Write your code here:"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 2,3,4,5: Write your code here:"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "# Task 1: Write your code here:\n",
177
+ "feature_importance = pd.DataFrame({\n",
178
+ " 'feature': feature_cols,\n",
179
+ " 'importance': model.feature_importances_\n",
180
+ "}).sort_values('importance', ascending=False)\n",
181
+ "\n",
182
+ "plt.figure(figsize=(10, 6))\n",
183
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
184
+ "plt.xlabel('Importance')\n",
185
+ "plt.title('Feature Importance')\n",
186
+ "plt.gca().invert_yaxis()\n",
187
+ "plt.show()"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Task 2: Write your code here:\n"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task Bonus: Write your code here:"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ }
210
+ ],
211
+ "metadata": {
212
+ "kernelspec": {
213
+ "display_name": "Python 3",
214
+ "name": "python3"
215
+ },
216
+ "language_info": {
217
+ "name": "python"
218
+ }
219
+ },
220
+ "nbformat": 4,
221
+ "nbformat_minor": 0
222
+ }
submissions_extracted/147/Q1.ipynb ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "from IPython.display import clear_output\n",
8
+ "\n",
9
+ "%pip install kagglehub catboost lightgbm tqdm -q\n",
10
+ "\n",
11
+ "clear_output()"
12
+ ],
13
+ "execution_count": null,
14
+ "outputs": []
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "metadata": {},
19
+ "source": [
20
+ "import pandas as pd\n",
21
+ "import numpy as np\n",
22
+ "import matplotlib.pyplot as plt\n",
23
+ "import seaborn as sns\n",
24
+ "import kagglehub\n",
25
+ "import os\n",
26
+ "from tqdm import tqdm\n",
27
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
28
+ "from sklearn.model_selection import StratifiedKFold\n",
29
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
30
+ "\n",
31
+ "%matplotlib inline\n",
32
+ "\n",
33
+ "# Download latest version\n",
34
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
35
+ "\n",
36
+ "print(\"Path to dataset files:\", path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 1: Write your code here:\n",
46
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
47
+ "\n",
48
+ "df = pd.read_csv(csv_path)\n"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 2: Write your code here:\n",
58
+ "df.head() # Showing the first 5 rows!!"
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() # Showing the characteristics of each feature with also the target y (delivery time)!!"
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() # Statistics information!!"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# Task 5: Write your code here:\n",
88
+ "plt.figure(figsize=(10, 5))\n",
89
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
90
+ "plt.title('Delivery Time Distribution')\n",
91
+ "plt.xlabel('Delivery Time')\n",
92
+ "plt.ylabel('Frequency')\n",
93
+ "plt.show()"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 1: Write your code here:\n",
103
+ "df_N=df.columns.drop(\"Order_ID\")"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 2: Write your code here:\n",
113
+ "def check_missing_values(df_N):\n",
114
+ "\n",
115
+ " # Get missing values using pandas\n",
116
+ " missing_values = df_N.isnull().sum()\n",
117
+ "\n",
118
+ " print(\"Missing Values per Column:\")\n",
119
+ " print(missing_values[missing_values > 0])\n",
120
+ "\n",
121
+ " if missing_values.any():\n",
122
+ " print(\"\\nHandle Missing Values as needed.\")\n",
123
+ " else:\n",
124
+ " print(\"\\nNo Missing Values Found.\")\n",
125
+ "\n",
126
+ "check_missing_values(df_N)\n",
127
+ "# I believe that there are missing values but my code showed inverse!"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# Task 3: Write your code here:\n",
137
+ "def check_duplicates(df_N):\n",
138
+ " duplicates = df_N.duplicated().sum()\n",
139
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
140
+ " if duplicates > 0:\n",
141
+ " print(\"Dropping Duplicates...\")\n",
142
+ " df_N.drop_duplicates(inplace=True)\n",
143
+ " print(\"Duplicates Dropped.\")\n",
144
+ " else:\n",
145
+ " print(\"No Duplicate Samples Found.\")\n",
146
+ "\n",
147
+ "check_duplicates(df_N)"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 4: Write your code here:\n",
157
+ "categorical_cols=df_N.select_dtypes(include=[\"object\"]).columns\n",
158
+ "\n",
159
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
160
+ "## Error is happening I don't know why\n",
161
+ "\n",
162
+ "for col in categorical_cols:\n",
163
+ " le = LabelEncoder()\n",
164
+ " df_N[col] = le.fit_transform(df_N[col].astype(str))\n",
165
+ "\n",
166
+ "df_N.head()"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "\n",
176
+ "# Task 5: Write your code here:\n",
177
+ "features = df_N.columns.drop(\"Delivery_Time\").astype(float) #features\n",
178
+ "scaler = StandardScaler()\n",
179
+ "df[features] = scaler.fit_transform(df[features])\n",
180
+ "df.head()\n"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "# Task 6: Write your code here:\n",
190
+ "target_column=df[\"Delivery_Time\"]\n",
191
+ "def check_target_imbalance(df, target_column):\n",
192
+ " print(\"Target Distribution:\")\n",
193
+ "\n",
194
+ " df[target_column].hist()\n",
195
+ " plt.show()\n",
196
+ "\n",
197
+ "check_target_imbalance(df, \"Delivery_Time\")"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 1: Write your code here:\n",
207
+ "X = df_N.drop(\"Delivery_Time\", axis=1).astype(float)\n",
208
+ "y = df['Delivery_Time'].astype(float)\n",
209
+ "#I will be using stratifiedKFold for ensuring! which is for the imbalanced data"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "# Task 2,3,4,5: Write your code here:\n",
219
+ "n_splits = 5 # K=5 Folds\n",
220
+ "\n",
221
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
222
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
223
+ "\n",
224
+ "lr_losses = []\n",
225
+ "lr_mse = []\n",
226
+ "lr_rmse = []\n",
227
+ "lr_r2 = []\n",
228
+ "\n",
229
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)): # enumerate returns two vals!\n",
230
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
231
+ "\n",
232
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
233
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
234
+ "\n",
235
+ " # Train\n",
236
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
237
+ "\n",
238
+ " # Validate\n",
239
+ " y_pred = np.dot(X_test.values, theta)\n",
240
+ "\n",
241
+ " # Calculate evaluation metrics\n",
242
+ " mae = mean_absolute_error(y_test, y_pred)\n",
243
+ " rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
244
+ " r2 = r2_score(y_test, y_pred)\n",
245
+ "\n",
246
+ " # Store results\n",
247
+ " lr_losses.append(losses)\n",
248
+ " lr_mse.append(mse)\n",
249
+ " lr_rmse.append(rmse)\n",
250
+ " lr_r2.append(r2)\n",
251
+ "\n",
252
+ "print(f\"MAE: ${mae:,.2f}\")\n",
253
+ "print(f\"RMSE: ${rmse:,.2f}\")\n",
254
+ "avg_loss = np.mean(lr_losses, axis=0)\n",
255
+ "print(avg_loss)"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "metadata": {},
263
+ "source": [
264
+ "# Task 1: Write your code here:\n",
265
+ "feature_importance = pd.DataFrame({\n",
266
+ " 'feature': feature_cols,\n",
267
+ " 'importance': model.feature_importances_\n",
268
+ "}).sort_values('importance', ascending=False)\n",
269
+ "\n",
270
+ "plt.figure(figsize=(10, 6))\n",
271
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
272
+ "plt.xlabel('Importance')\n",
273
+ "plt.title('Feature Importance')\n",
274
+ "plt.gca().invert_yaxis()\n",
275
+ "plt.show()"
276
+ ],
277
+ "execution_count": null,
278
+ "outputs": []
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "metadata": {},
283
+ "source": [
284
+ "# Task 2: Write your code here:\n",
285
+ "plt.figure(figsize=(10, 5))\n",
286
+ "plt.hist(y_pred.dropna(), bins=50, edgecolor='black')\n",
287
+ "plt.title('Delivery Time Distribution')\n",
288
+ "plt.xlabel('Delivery Time')\n",
289
+ "plt.ylabel('Frequency')\n",
290
+ "plt.show()"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "# Task Bonus: Write your code here:"
300
+ ],
301
+ "execution_count": null,
302
+ "outputs": []
303
+ }
304
+ ],
305
+ "metadata": {
306
+ "kernelspec": {
307
+ "display_name": "Python 3",
308
+ "name": "python3"
309
+ },
310
+ "language_info": {
311
+ "name": "python"
312
+ }
313
+ },
314
+ "nbformat": 4,
315
+ "nbformat_minor": 0
316
+ }
submissions_extracted/147/Q2.ipynb ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "import torch\n",
27
+ "import torch.nn as nn\n",
28
+ "from torch.optim import AdamW\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "from torch.utils.data import DataLoader, TensorDataset\n",
31
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
32
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
33
+ "\n",
34
+ "# Load Labels\n",
35
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
36
+ "img_dir = os.path.join(path, \"images\")\n",
37
+ "\n",
38
+ "images = []\n",
39
+ "ages = []\n",
40
+ "\n",
41
+ "# Load Images and Resize\n",
42
+ "print(\"Loading images...\")\n",
43
+ "for index, row in labels_df.iterrows():\n",
44
+ " img_name = row.iloc[0]\n",
45
+ " age = row.iloc[1]\n",
46
+ " img_path = os.path.join(img_dir, img_name)\n",
47
+ "\n",
48
+ " if os.path.exists(img_path):\n",
49
+ " img = Image.open(img_path).convert('RGB')\n",
50
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
51
+ " images.append(img_array)\n",
52
+ " ages.append(age)\n",
53
+ "\n",
54
+ "X = np.array(images)\n",
55
+ "y = np.array(ages)\n",
56
+ "\n",
57
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
58
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
59
+ "\n",
60
+ "# Split Data\n",
61
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
62
+ "\n",
63
+ "print(f\"X_train shape: {X_train.shape}\")\n",
64
+ "print(f\"X_test shape: {X_test.shape}\")\n",
65
+ "print(f\"y_train shape: {y_train.shape}\")\n",
66
+ "print(f\"y_test shape: {y_test.shape}\")"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
76
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
77
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
78
+ "y_train = torch.tensor(y_train.values, dtype=torch.float32)\n",
79
+ "y_test = torch.tensor(y_test.values, dtype=torch.float32)"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# 2. Create TensorDataset objects\n",
89
+ "train_dataset = TensorDataset(X_train, y_train)\n",
90
+ "test_dataset = TensorDataset(X_test, y_test)\n",
91
+ "\n",
92
+ "print(\"Train dataset:\", len(train_dataset))\n",
93
+ "print(\"Test dataset:\", len(test_dataset))"
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)"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 4. Print shape of one batch\n",
114
+ "X_batch, y_batch = next(iter(train_loader))\n",
115
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
116
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# 5. Display sample images\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
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
134
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
135
+ " plt.axis('off')\n",
136
+ "\n",
137
+ "plt.tight_layout()\n",
138
+ "plt.show()\n"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 1: Write your model class here:\n",
148
+ "class NN4Layer(nn.Module): #\n",
149
+ " def __init__(self, input_dim, hidden_dim):\n",
150
+ " super(NN4Layer, self).__init__()\n",
151
+ "\n",
152
+ " # First linear layer: input features -> hidden layer\n",
153
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
154
+ "\n",
155
+ " # Second linear layer: hidden layer -> hidden layer\n",
156
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
157
+ "\n",
158
+ " # Third layer: hidden layer -> hidden layer\n",
159
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
160
+ "\n",
161
+ " # Output layer: hidden layer -> single continuous value\n",
162
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
163
+ "\n",
164
+ " # ReLU activation for non-linearity in hidden layers\n",
165
+ " self.relu = nn.ReLU()\n",
166
+ "\n",
167
+ " # Defines how input data flows through the network\n",
168
+ " def forward(self, x):\n",
169
+ " # First hidden layer\n",
170
+ " a1 = self.relu(self.layer1(x))\n",
171
+ "\n",
172
+ " # Second hidden layer\n",
173
+ " a2 = self.relu(self.layer2(a1))\n",
174
+ "\n",
175
+ " # Third hidden layer\n",
176
+ " a3 = self.relu(self.layer3(a2))\n",
177
+ "\n",
178
+ " # Output layer (regression output)\n",
179
+ " output = self.layer4(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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
192
+ " # Set the model to training mode\n",
193
+ " model.train()\n",
194
+ "\n",
195
+ " running_loss = 0.0\n",
196
+ "\n",
197
+ " for X_batch, y_batch in train_loader:\n",
198
+ " # Move batch to the selected device\n",
199
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
200
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
201
+ "\n",
202
+ " # Forward pass (continuous output)\n",
203
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
204
+ " loss = criterion(outputs, y_batch)\n",
205
+ "\n",
206
+ " # Backward pass & optimization\n",
207
+ " optimizer.zero_grad() # Clear previous gradients\n",
208
+ " loss.backward() # Compute gradients\n",
209
+ " optimizer.step() # Update model parameters\n",
210
+ "\n",
211
+ " running_loss += loss.item()\n",
212
+ "\n",
213
+ " # Average loss over all batches\n",
214
+ " avg_loss = running_loss / len(train_loader)\n",
215
+ "\n",
216
+ " return avg_loss"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "# Task 3: Write your validation loop here:\n",
226
+ "def validate(model, criterion, test_loader, device):\n",
227
+ " # Set the model to evaluation mode\n",
228
+ " model.eval()\n",
229
+ "\n",
230
+ " running_loss = 0.0\n",
231
+ "\n",
232
+ " with torch.no_grad():\n",
233
+ " for X_batch, y_batch in test_loader:\n",
234
+ " # Move data to 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
+ " running_loss += loss.item()\n",
243
+ "\n",
244
+ " # Average loss over all batches\n",
245
+ " avg_loss = running_loss / len(test_loader)\n",
246
+ "\n",
247
+ " return avg_loss"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task 4: Define device, model, loss, optimizer:\n",
257
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
258
+ "\n",
259
+ "# Model parameters\n",
260
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
261
+ "hidden_dim = 64 # Design choice\n",
262
+ "\n",
263
+ "# Instantiate regression model\n",
264
+ "model = NN4Layer(input_dim, hidden_dim).to(device)\n",
265
+ "\n",
266
+ "# Print the model architecture\n",
267
+ "print(\"Model Architecture:\\n\")\n",
268
+ "print(model)\n",
269
+ "\n",
270
+ "# Calculate the total number of trainable parameters\n",
271
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
272
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
273
+ "\n",
274
+ "num_epochs = 20\n",
275
+ "learning_rate = 0.001\n",
276
+ "\n",
277
+ "criterion = nn.MSELoss() #Regression Problem!\n",
278
+ "\n",
279
+ "optimizer = AdamW(model.parameters(), learning_rate)"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "metadata": {},
287
+ "source": [
288
+ "# Task 5: Start training for 20 epochs:\n",
289
+ "train_losses = []\n",
290
+ "val_losses = []\n",
291
+ "\n",
292
+ "print('Starting Training...')\n",
293
+ "for epoch in range(num_epochs):\n",
294
+ " # Train one epoch\n",
295
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
296
+ "\n",
297
+ " # Validate\n",
298
+ " val_loss = validate(model, criterion, test_loader, device)\n",
299
+ "\n",
300
+ " train_losses.append(train_loss)\n",
301
+ " val_losses.append(val_loss)\n",
302
+ "\n",
303
+ " if (epoch + 1) % 5 == 0:\n",
304
+ " print(\n",
305
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
306
+ " f'Train Loss: {train_loss:.4f}, '\n",
307
+ " f'Val Loss: {val_loss:.4f}'\n",
308
+ " )\n",
309
+ "\n",
310
+ "print('Training Complete!')"
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
+ "plt.figure(figsize=(7, 5))\n",
321
+ "\n",
322
+ "plt.plot(train_losses, label='Train Loss')\n",
323
+ "plt.plot(val_losses, label='Validation Loss')\n",
324
+ "plt.title('Loss over Epochs')\n",
325
+ "plt.xlabel('Epoch')\n",
326
+ "plt.ylabel('Loss (MSE)')\n",
327
+ "plt.legend()\n",
328
+ "\n",
329
+ "plt.tight_layout()\n",
330
+ "plt.show()"
331
+ ],
332
+ "execution_count": null,
333
+ "outputs": []
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "metadata": {},
338
+ "source": [
339
+ "# Task 2 (Bonus): Write your code here:"
340
+ ],
341
+ "execution_count": null,
342
+ "outputs": []
343
+ }
344
+ ],
345
+ "metadata": {
346
+ "kernelspec": {
347
+ "display_name": "Python 3",
348
+ "name": "python3"
349
+ },
350
+ "language_info": {
351
+ "name": "python"
352
+ }
353
+ },
354
+ "nbformat": 4,
355
+ "nbformat_minor": 0
356
+ }
submissions_extracted/147/Q3.ipynb ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import torch\n",
10
+ "import torch.nn as nn\n",
11
+ "from torch.optim import AdamW\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "import seaborn as sns\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
+ "from sklearn.model_selection import StratifiedKFold\n",
19
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "\n",
23
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
24
+ "\n",
25
+ "\n",
26
+ "\n",
27
+ "print(\"Path to dataset files:\", path)"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 1: Write your code here:\n",
37
+ "df = pd.read_csv(f\"{path}/Q3_data.csv\")"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df.head()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 3: Write your code here:\n",
57
+ "df.info() #This won't show everything as I think the number of features is high, hence just a summary\n",
58
+ "print(\"\\n\\n--------------------------------------\\n\\n\")\n",
59
+ "df.info(all, show_counts= all) #This in compare to regular df.info(), shows the dataset information"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 4: Write your code here:\n",
69
+ "df.describe() # Showing the statistics information"
70
+ ],
71
+ "execution_count": null,
72
+ "outputs": []
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "metadata": {},
77
+ "source": [
78
+ "# Task 1: Write your code here:\n",
79
+ "def check_missing_values(df):\n",
80
+ " missing_values = df.isnull().sum()\n",
81
+ " print(\"Missing Values per Column:\")\n",
82
+ " print(missing_values[missing_values > 0])\n",
83
+ " if missing_values.any():\n",
84
+ " print(\"\\nHandle Missing Values as needed.\")\n",
85
+ " else:\n",
86
+ " print(\"\\nNo Missing Values Found.\")\n",
87
+ "\n",
88
+ "check_missing_values(df)"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# Task 2: Write your code here:\n",
98
+ "def check_duplicates(df):\n",
99
+ " duplicates = df.duplicated().sum()\n",
100
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
101
+ " if duplicates > 0:\n",
102
+ " print(\"Dropping Duplicates...\")\n",
103
+ " df.drop_duplicates(inplace=True)\n",
104
+ " print(\"Duplicates Dropped.\")\n",
105
+ " else:\n",
106
+ " print(\"No Duplicate Samples Found.\")\n",
107
+ "\n",
108
+ "check_duplicates(df)"
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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
119
+ "for col in categorical_cols:\n",
120
+ " print(f\"Encoding column: {col}\")\n",
121
+ " le = LabelEncoder()\n",
122
+ " df[col] = le.fit_transform(df[col])\n",
123
+ "df"
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
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") #Feature Scaling!!\n",
134
+ "scaler = StandardScaler()\n",
135
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
136
+ "df"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 5: Write your code here:\n",
146
+ "def check_target_imbalance(df, target_column):\n",
147
+ " print(\"Target Distribution:\")\n",
148
+ " print(df[target_column].value_counts(normalize=True))\n",
149
+ " sns.countplot(x=df[target_column])\n",
150
+ " plt.title(\"Target Distribution\")\n",
151
+ " plt.show()\n",
152
+ "\n",
153
+ "check_target_imbalance(df, \"Target\")\n",
154
+ "\n",
155
+ "#It is inbalanced!!"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 1: Write your code here:\n",
165
+ "X = df.drop(\"Target\",axis=1)\n",
166
+ "y = df['Target']"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 2,3,4,5: Write your code here:\n",
176
+ "#We will be using StratifiedKFold as our data is imbalanced!\n",
177
+ "\n",
178
+ "n_splits = 5 # K=5 Folds\n",
179
+ "\n",
180
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
181
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
182
+ "\n",
183
+ "#We will list the following metrics eventhough accuarcy and F1 score were asked!\n",
184
+ "lr_losses = []\n",
185
+ "lr_accuracy = []\n",
186
+ "lr_precision = []\n",
187
+ "lr_recall = []\n",
188
+ "lr_f1 = []\n",
189
+ "\n",
190
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
191
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
192
+ "\n",
193
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
194
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
195
+ "\n",
196
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
197
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
198
+ "y_train = torch.tensor(y_train.values, dtype=torch.long)\n",
199
+ "y_test = torch.tensor(y_test.values, dtype=torch.long)\n",
200
+ "\n",
201
+ "train_dataset = TensorDataset(X_train, y_train)\n",
202
+ "test_dataset = TensorDataset(X_test, y_test)\n",
203
+ "\n",
204
+ "# Create Dataloaders to train and test data in batches\n",
205
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
206
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
207
+ "\n",
208
+ "# Print dataset sizes\n",
209
+ "print(\"Train dataset:\", len(train_dataset))\n",
210
+ "print(\"Test dataset:\", len(test_dataset))\n",
211
+ "\n",
212
+ "# Get the first batch from the training DataLoader\n",
213
+ "X_batch, y_batch = next(iter(train_loader))\n",
214
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
215
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
216
+ "\n",
217
+ "\n",
218
+ "\n",
219
+ "class NN4Layer(nn.Module):\n",
220
+ "\n",
221
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
222
+ " super(NN4Layer, self).__init__()\n",
223
+ "\n",
224
+ " # First linear layer: input features -> hidden layer\n",
225
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
226
+ "\n",
227
+ " # Second linear layer: hidden layer -> hidden layer\n",
228
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
229
+ "\n",
230
+ " # Third linear layer: hidden layer -> hidden layer\n",
231
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
232
+ "\n",
233
+ " # Output layer: hidden layer -> number of classes (logits)\n",
234
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
235
+ "\n",
236
+ " # ReLU activation for non-linearity\n",
237
+ " self.relu = nn.ReLU()\n",
238
+ "\n",
239
+ " # Defines how input data flows through the network\n",
240
+ " def forward(self, x):\n",
241
+ " # First hidden layer\n",
242
+ " a1 = self.relu(self.layer1(x))\n",
243
+ "\n",
244
+ " # Second hidden layer\n",
245
+ " a2 = self.relu(self.layer2(a1))\n",
246
+ "\n",
247
+ " # Third hidden layer\n",
248
+ " a3 = self.relu(self.layer3(a2))\n",
249
+ "\n",
250
+ " # Output layer (raw scores / logits)\n",
251
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
252
+ "\n",
253
+ " return output\n",
254
+ "\n",
255
+ "\n",
256
+ "#Training Loop\n",
257
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
258
+ " # Set the model to training mode\n",
259
+ " model.train()\n",
260
+ "\n",
261
+ " running_loss = 0.0\n",
262
+ "\n",
263
+ " for X_batch, y_batch in train_loader:\n",
264
+ " # Move batch to the selected device\n",
265
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
266
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
267
+ "\n",
268
+ " # Forward pass (outputs are logits)\n",
269
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
270
+ " loss = criterion(outputs, y_batch)\n",
271
+ "\n",
272
+ " # Backward pass & optimization\n",
273
+ " optimizer.zero_grad() # Clear previous gradients\n",
274
+ " loss.backward() # Compute gradients\n",
275
+ " optimizer.step() # Update model parameters\n",
276
+ "\n",
277
+ " running_loss += loss.item()\n",
278
+ "\n",
279
+ " accuracy = accuracy_score(y_test, y_batch)\n",
280
+ " precision = precision_score(y_test, y_batch, zero_division=0)\n",
281
+ " recall = recall_score(y_test, y_batch, zero_division=0)\n",
282
+ " f1 = f1_score(y_test, y_batch, zero_division=0)\n",
283
+ "\n",
284
+ "\n",
285
+ " lr_accuracy.append(accuracy)\n",
286
+ " lr_precision.append(precision)\n",
287
+ " lr_recall.append(recall)\n",
288
+ " lr_f1.append(f1)\n",
289
+ "\n",
290
+ " # Average loss over all batches\n",
291
+ " avg_loss = running_loss / len(train_loader)\n",
292
+ "\n",
293
+ " return avg_loss\n",
294
+ "\n",
295
+ "\n",
296
+ "\n",
297
+ "#Validiation Loop\n",
298
+ "def validate(model, criterion, test_loader, device):\n",
299
+ " # Set the model to evaluation mode\n",
300
+ " model.eval()\n",
301
+ "\n",
302
+ " running_loss = 0.0\n",
303
+ " correct = 0\n",
304
+ " total = 0\n",
305
+ "\n",
306
+ " with torch.no_grad():\n",
307
+ " for X_batch, y_batch in test_loader:\n",
308
+ " # Move data to device\n",
309
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
310
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
311
+ "\n",
312
+ " # Forward pass\n",
313
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
314
+ " loss = criterion(outputs, y_batch)\n",
315
+ " running_loss += loss.item()\n",
316
+ "\n",
317
+ " # Apply Softmax to get probabilities\n",
318
+ " probabilities = F.softmax(outputs, dim=1)\n",
319
+ "\n",
320
+ " # Pick the classes with highest probabilities\n",
321
+ " predicted = torch.argmax(probabilities, dim=1)\n",
322
+ "\n",
323
+ " # Accuracy calculation\n",
324
+ " correct += (predicted == y_batch).sum().item()\n",
325
+ " total += y_batch.size(0)\n",
326
+ "\n",
327
+ " avg_loss = running_loss / len(test_loader)\n",
328
+ " accuracy = correct / total\n",
329
+ "\n",
330
+ " return avg_loss, accuracy\n",
331
+ "\n",
332
+ "# Device setup\n",
333
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
334
+ "\n",
335
+ "# Model parameters\n",
336
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
337
+ "hidden_dim = 14 # Design choice\n",
338
+ "output_dim = 189 # P-2:......B:188\n",
339
+ "\n",
340
+ "# Instantiate model\n",
341
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
342
+ "\n",
343
+ "# Print the model architecture\n",
344
+ "print(\"Model Architecture:\\n\")\n",
345
+ "print(model)\n",
346
+ "\n",
347
+ "# Calculate the total number of trainable parameters\n",
348
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
349
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
350
+ "\n",
351
+ "num_epochs = 20\n",
352
+ "learning_rate = 0.001\n",
353
+ "\n",
354
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
355
+ "criterion = nn.CrossEntropyLoss()\n",
356
+ "# Define optimizer\n",
357
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
358
+ "\n",
359
+ "\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!')\n",
379
+ "\n",
380
+ "\n"
381
+ ],
382
+ "execution_count": null,
383
+ "outputs": []
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "metadata": {},
388
+ "source": [
389
+ "# Task 1: Write your code here:\n",
390
+ "feature_importance = pd.DataFrame({\n",
391
+ " 'feature': feature_cols,\n",
392
+ " 'importance': model.feature_importances_\n",
393
+ "}).sort_values('importance', ascending=False)\n",
394
+ "\n",
395
+ "plt.figure(figsize=(10, 6))\n",
396
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
397
+ "plt.xlabel('Importance')\n",
398
+ "plt.title('Feature Importance')\n",
399
+ "plt.gca().invert_yaxis()\n",
400
+ "plt.show()"
401
+ ],
402
+ "execution_count": null,
403
+ "outputs": []
404
+ },
405
+ {
406
+ "cell_type": "code",
407
+ "metadata": {},
408
+ "source": [
409
+ "# Task 2: Write your code here:\n",
410
+ "#Couldn't figure it out as my code is not working :(\n",
411
+ "#If the code was working properly then the golden feaure will be shown clearly!"
412
+ ],
413
+ "execution_count": null,
414
+ "outputs": []
415
+ },
416
+ {
417
+ "cell_type": "code",
418
+ "metadata": {},
419
+ "source": [
420
+ "# Task Bonus: Write your code here:"
421
+ ],
422
+ "execution_count": null,
423
+ "outputs": []
424
+ }
425
+ ],
426
+ "metadata": {
427
+ "kernelspec": {
428
+ "display_name": "Python 3",
429
+ "name": "python3"
430
+ },
431
+ "language_info": {
432
+ "name": "python"
433
+ }
434
+ },
435
+ "nbformat": 4,
436
+ "nbformat_minor": 0
437
+ }
submissions_extracted/148/Q1.ipynb ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import matplotlib.pyplot as plt\n",
12
+ "import seaborn as sns\n",
13
+ "from tqdm import tqdm\n",
14
+ "from PIL import Image\n",
15
+ "from sklearn.model_selection import train_test_split\n",
16
+ "\n",
17
+ "# Download latest version\n",
18
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "# Task 1: Write your code here:\n",
30
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
31
+ "\n",
32
+ "df = pd.read_csv(csv_path)"
33
+ ],
34
+ "execution_count": null,
35
+ "outputs": []
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "metadata": {},
40
+ "source": [
41
+ "# Task 2: Write your code here:\n",
42
+ "df.head()"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 3: Write your code here:\n",
52
+ "df.info()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 4: Write your code here:\n",
62
+ "df.describe()"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 5: Write your code here:\n",
72
+ "def check_target_distribution(df, target_column):\n",
73
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
74
+ "\n",
75
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
76
+ " plt.xlabel(target_column)\n",
77
+ " #plt.ylabel(\"Frequency\")\n",
78
+ " plt.ylabel(\"\")\n",
79
+ " plt.grid(False)\n",
80
+ "\n",
81
+ " plt.show()\n",
82
+ "\n",
83
+ "check_target_distribution(df, \"delivery_time\")"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 1: Write your code here:\n",
93
+ "df.drop(columns=['Order_ID'])"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 2: Write your code here:\n",
103
+ "def check_missing_values(df):\n",
104
+ " missing_values = df.isnull().sum()\n",
105
+ " print(\"Missing Values per Column:\")\n",
106
+ " print(missing_values[missing_values > 0])\n",
107
+ " if missing_values.any():\n",
108
+ " print(\"\\nHandle Missing Values as needed.\")\n",
109
+ " else:\n",
110
+ " print(\"\\nNo Missing Values Found.\")\n",
111
+ "\n",
112
+ "check_missing_values(df)"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 3: Write your code here:\n",
122
+ "def check_duplicates(df):\n",
123
+ " duplicates = df.duplicated().sum()\n",
124
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
125
+ " if duplicates > 0:\n",
126
+ " print(\"Dropping Duplicates...\")\n",
127
+ " df.drop_duplicates(inplace=True)\n",
128
+ " print(\"Duplicates Dropped.\")\n",
129
+ " else:\n",
130
+ " print(\"No Duplicate Samples Found.\")\n",
131
+ "\n",
132
+ "check_duplicates(df)"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 4: Write your code here:\n",
142
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
143
+ "\n",
144
+ "\n",
145
+ "print('data before encoding:\\n', df) #show before encoding\n",
146
+ "\n",
147
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
148
+ "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n",
149
+ "\n",
150
+ "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding\n",
151
+ "\n",
152
+ "\n",
153
+ "#categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
154
+ "\n",
155
+ "#print(\"Categorical Columns:\", list(categorical_cols))"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 5: Write your code here:\n",
165
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
166
+ "\n",
167
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
168
+ "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
169
+ "\n",
170
+ "#print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 6: Write your code here:\n",
180
+ "def check_target_imbalance(df, target_column):\n",
181
+ " print(\"Target Distribution:\")\n",
182
+ "\n",
183
+ " df[target_column].hist()\n",
184
+ " plt.show()\n",
185
+ "\n",
186
+ "check_target_imbalance(df, \"delivery_time\")"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "# Task 1: Write your code here:\n",
196
+ "\n",
197
+ "X = df_clean[feature_cols]\n",
198
+ "y = df_clean['delivery_time']\n",
199
+ "\n",
200
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
201
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
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.ensemble import RandomForestRegressor\n",
212
+ "#2\n",
213
+ "from sklearn.model_selection import KFold\n",
214
+ "\n",
215
+ "# Use previously generated random data (example: regression data)\n",
216
+ "X, y = X_reg.copy(), y_reg.copy()\n",
217
+ "\n",
218
+ "# Define K-Fold Cross Validation\n",
219
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
220
+ "\n",
221
+ "lr_losses = []\n",
222
+ "lr_mse = []\n",
223
+ "lr_rmse = []\n",
224
+ "lr_r2 = []\n",
225
+ "\n",
226
+ "# Iterate through folds\n",
227
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
228
+ " # indexing for each fold\n",
229
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
230
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
231
+ " # print shapes\n",
232
+ " print(f\"Fold {fold}\")\n",
233
+ " print(\" X_train shape:\", X_train.shape)\n",
234
+ " print(\" X_test shape :\", X_test.shape)\n",
235
+ " print(\" y_train shape:\", y_train.shape)\n",
236
+ " print(\" y_test shape :\", y_test.shape)\n",
237
+ " print(\"-\" * 30)\n",
238
+ "#3\n",
239
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
240
+ "model.fit(X_train_scaled, y_train)\n",
241
+ "print(\"Model trained!\")\n",
242
+ "\n",
243
+ "#4: evaluate\n",
244
+ "y_pred = model.predict(X_test_scaled) #data_standard_scaled\n",
245
+ "mae = mean_absolute_error(y_test, y_pred)\n",
246
+ "print(f\"MAE: ${mae:,.2f}\")\n",
247
+ "\n",
248
+ "#5\n",
249
+ "\n",
250
+ "model = {\n",
251
+ "\n",
252
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200)\n",
253
+ "}\n",
254
+ "\n",
255
+ "all_results = {}\n",
256
+ "\n",
257
+ "for name in models:\n",
258
+ " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
259
+ "\n",
260
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
261
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
262
+ "\n",
263
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
264
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
265
+ "\n",
266
+ "for model_name, model in model.items():\n",
267
+ " print(f\"Training {model_name}...\")\n",
268
+ "\n",
269
+ " # Train\n",
270
+ " model.fit(X_train, y_train)\n",
271
+ "\n",
272
+ " # Predict\n",
273
+ " y_pred = model.predict(X_test)\n",
274
+ "\n",
275
+ " # Calculate metrics\n",
276
+ " mse = sklearn_mse(y_test, y_pred)\n",
277
+ " rmse = np.sqrt(mse)\n",
278
+ " r2 = r2_score(y_test, y_pred)\n",
279
+ "\n",
280
+ " # Store results\n",
281
+ " all_results[model_name][\"mse\"].append(mse)\n",
282
+ " all_results[model_name][\"rmse\"].append(rmse)\n",
283
+ " all_results[model_name][\"r2\"].append(r2)\n",
284
+ "\n",
285
+ "for model_name in all_results:\n",
286
+ " print(f\"\\n{model_name}:\")\n",
287
+ " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
288
+ " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
289
+ " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ },
294
+ {
295
+ "cell_type": "code",
296
+ "metadata": {},
297
+ "source": [
298
+ "# Task 1: Write your code here:\n",
299
+ "coeffs = {}\n",
300
+ "\n",
301
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
302
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
303
+ "\n",
304
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
305
+ "axes = axes.flatten()\n",
306
+ "features = X.columns\n",
307
+ "\n",
308
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
309
+ " # Sort features by absolute coefficient value\n",
310
+ " absolute_coef = np.abs(coef)\n",
311
+ " sorted_idx = np.argsort(absolute_coef)\n",
312
+ "\n",
313
+ " ax = axes[i]\n",
314
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
315
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
316
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
317
+ "\n",
318
+ "plt.tight_layout()\n",
319
+ "plt.show()"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {},
327
+ "source": [
328
+ "# Task 2: Write your code here:\n",
329
+ "plt.figure(figsize=(6, 4))\n",
330
+ "plt.scatter(y_test, y_pred, alpha=0.7)\n",
331
+ "plt.plot([min(y_test), max(y_test)],\n",
332
+ " [min(y_test), max(y_test)],\n",
333
+ " 'r--', linewidth=2)\n",
334
+ "\n",
335
+ "plt.xlabel(\"Actual Delivery time\")\n",
336
+ "plt.ylabel(\"Predicted delivery time\")\n",
337
+ "plt.title(\"Predicted delivery time\")\n",
338
+ "plt.grid(True)\n",
339
+ "\n",
340
+ "plt.tight_layout()\n",
341
+ "plt.show()"
342
+ ],
343
+ "execution_count": null,
344
+ "outputs": []
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "metadata": {},
349
+ "source": [
350
+ "# Task Bonus: Write your code here:\n",
351
+ "from sklearn.ensemble import RandomForestRegressor\n",
352
+ "from catboost import CatBoostRegressor\n",
353
+ "\n",
354
+ "models = {\n",
355
+ " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n",
356
+ " \"CatBoost\": CatBoostRegressor(verbose=0)\n",
357
+ "}\n",
358
+ "\n",
359
+ "# Storage for results\n",
360
+ "all_results = {}\n",
361
+ "\n",
362
+ "for name in models:\n",
363
+ " all_results[name] = {'mse': [], 'rmse': [], 'r2': []}\n",
364
+ "\n",
365
+ "\n",
366
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
367
+ "\n",
368
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
369
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
370
+ "\n",
371
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
372
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
373
+ "\n",
374
+ " for model_name, model in models.items():\n",
375
+ " print(f\"Training {model_name}...\")\n",
376
+ "\n",
377
+ " # Train\n",
378
+ " model.fit(X_train, y_train)\n",
379
+ "\n",
380
+ " # Predict\n",
381
+ " y_pred = model.predict(X_test)\n",
382
+ "\n",
383
+ " # Calculate metrics\n",
384
+ " mse = sklearn_mse(y_test, y_pred)\n",
385
+ " rmse = np.sqrt(mse)\n",
386
+ " r2 = r2_score(y_test, y_pred)\n",
387
+ "\n",
388
+ " # Store results\n",
389
+ " all_results[model_name][\"mse\"].append(mse)\n",
390
+ " all_results[model_name][\"rmse\"].append(rmse)\n",
391
+ " all_results[model_name][\"r2\"].append(r2)\n",
392
+ "\n",
393
+ " for model_name in all_results:\n",
394
+ " print(f\"\\n{model_name}:\")\n",
395
+ " print(f\" MSE: {np.mean(all_results[model_name]['mse']):.4f}\")\n",
396
+ " print(f\" RMSE: {np.mean(all_results[model_name]['rmse']):.4f}\")\n",
397
+ " print(f\" R2: {np.mean(all_results[model_name]['r2']):.4f}\")"
398
+ ],
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/148/Q2.ipynb ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import matplotlib.pyplot as plt\n",
12
+ "import seaborn as sns\n",
13
+ "from tqdm import tqdm\n",
14
+ "from PIL import Image\n",
15
+ "from sklearn.model_selection import train_test_split\n",
16
+ "\n",
17
+ "# Download latest version\n",
18
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
19
+ "\n",
20
+ "print(\"Path to dataset files:\", path)"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "\n",
30
+ "# Load Labels\n",
31
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
32
+ "img_dir = os.path.join(path, \"images\")\n",
33
+ "\n",
34
+ "images = []\n",
35
+ "ages = []\n",
36
+ "\n",
37
+ "# Load Images and Resize\n",
38
+ "print(\"Loading images...\")\n",
39
+ "for index, row in labels_df.iterrows():\n",
40
+ " img_name = row.iloc[0]\n",
41
+ " age = row.iloc[1]\n",
42
+ " img_path = os.path.join(img_dir, img_name)\n",
43
+ "\n",
44
+ " if os.path.exists(img_path):\n",
45
+ " img = Image.open(img_path).convert('RGB')\n",
46
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
47
+ " images.append(img_array)\n",
48
+ " ages.append(age)\n",
49
+ "\n",
50
+ "X = np.array(images)\n",
51
+ "y = np.array(ages)\n",
52
+ "\n",
53
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
54
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
55
+ "\n",
56
+ "# Split Data\n",
57
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
58
+ "\n",
59
+ "print(f\"X_train shape: {X_train.shape}\")\n",
60
+ "print(f\"X_test shape: {X_test.shape}\")\n",
61
+ "print(f\"y_train shape: {y_train.shape}\")\n",
62
+ "print(f\"y_test shape: {y_test.shape}\")"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
72
+ "# transform to tensors\n",
73
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
74
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
75
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
76
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# 2. Create TensorDataset objects\n",
86
+ "\n",
87
+ "train_dataset = TensorDataset(X_train, y_train)\n",
88
+ "test_dataset = TensorDataset(X_test, y_test)"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# 3. Create DataLoaders\n",
98
+ "from torch.utils.data import DataLoader\n",
99
+ "\n",
100
+ "# DataLoader for training data\n",
101
+ "train_loader = DataLoader(\n",
102
+ " train_dataset,\n",
103
+ " batch_size=32,\n",
104
+ " shuffle=True,\n",
105
+ " num_workers=2\n",
106
+ ")\n",
107
+ "# DataLoader for test/validation data\n",
108
+ "test_loader = DataLoader(\n",
109
+ " test_dataset,\n",
110
+ " batch_size=32,\n",
111
+ " shuffle=False,\n",
112
+ " num_workers=2\n",
113
+ ")"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# 4. Print shape of one batch\n",
123
+ "\n",
124
+ "# Get the first batch from the training DataLoader\n",
125
+ "X_batch, y_batch = next(iter(train_loader))\n",
126
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
127
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
128
+ ],
129
+ "execution_count": null,
130
+ "outputs": []
131
+ },
132
+ {
133
+ "cell_type": "code",
134
+ "metadata": {},
135
+ "source": [
136
+ "# 5. Display sample images\n",
137
+ "\n",
138
+ "sample_image, sample_label = train_dataset[0]\n",
139
+ "\n",
140
+ "print(f\"\\n Image shape: {sample_image.shape}\") # (1, 28, 28)\n",
141
+ "print(f\"Label: {sample_label}\")"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 1: Write your model class here:\n",
151
+ "\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 linear layer: hidden layer -> hidden layer\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, output_dim)\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
+ " a1 = self.relu(self.layer1(x))\n",
176
+ "\n",
177
+ " # Second hidden layer\n",
178
+ " a2 = self.relu(self.layer2(a1))\n",
179
+ "\n",
180
+ " # Third hidden layer\n",
181
+ " a3 = self.relu(self.layer3(a2))\n",
182
+ "\n",
183
+ " # Output layer (raw scores / logits)\n",
184
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
185
+ "\n",
186
+ " return output"
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:\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.to(device) # shape: (batch_size, num_features)\n",
205
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
206
+ "\n",
207
+ " # Forward pass (outputs are logits)\n",
208
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\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
+ "def validate(model, criterion, test_loader, device):\n",
232
+ " # Set the model to evaluation mode\n",
233
+ " model.eval()\n",
234
+ "\n",
235
+ " running_loss = 0.0\n",
236
+ " correct = 0\n",
237
+ " total = 0\n",
238
+ "\n",
239
+ " with torch.no_grad():\n",
240
+ " for X_batch, y_batch in test_loader:\n",
241
+ " # Move data to device\n",
242
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
243
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
244
+ "\n",
245
+ " # Forward pass\n",
246
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
247
+ " loss = criterion(outputs, y_batch)\n",
248
+ " running_loss += loss.item()\n",
249
+ "\n",
250
+ " # Apply Softmax to get probabilities\n",
251
+ " probabilities = F.softmax(outputs, dim=1)\n",
252
+ "\n",
253
+ " # Pick the classes with highest probabilities\n",
254
+ " predicted = torch.argmax(probabilities, dim=1)\n",
255
+ "\n",
256
+ " # Accuracy calculation\n",
257
+ " correct += (predicted == y_batch).sum().item()\n",
258
+ " total += y_batch.size(0)\n",
259
+ "\n",
260
+ " avg_loss = running_loss / len(test_loader)\n",
261
+ " accuracy = correct / total\n",
262
+ "\n",
263
+ " return avg_loss, accuracy"
264
+ ],
265
+ "execution_count": null,
266
+ "outputs": []
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "metadata": {},
271
+ "source": [
272
+ "# Task 4: Define device, model, loss, optimizer:\n",
273
+ "# Device setup\n",
274
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
275
+ "\n",
276
+ "# Model parameters\n",
277
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
278
+ "hidden_dim = 14 # Design choice\n",
279
+ "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
280
+ "\n",
281
+ "# Instantiate model\n",
282
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
283
+ "# Print the model architecture\n",
284
+ "print(\"Model Architecture:\\n\")\n",
285
+ "print(model)\n",
286
+ "\n",
287
+ "# Calculate the total number of trainable parameters\n",
288
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
289
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
290
+ "\n",
291
+ "num_epochs = 20\n",
292
+ "learning_rate = 0.001\n",
293
+ "\n",
294
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
295
+ "criterion = nn.CrossEntropyLoss()\n",
296
+ "# Define optimizer\n",
297
+ "optimizer = AdamW(model.parameters(), learning_rate)"
298
+ ],
299
+ "execution_count": null,
300
+ "outputs": []
301
+ },
302
+ {
303
+ "cell_type": "code",
304
+ "metadata": {},
305
+ "source": [
306
+ "# Task 5: Start training for 20 epochs:\n",
307
+ "# Run Training\n",
308
+ "train_losses = []\n",
309
+ "val_losses = []\n",
310
+ "val_accuracies = []\n",
311
+ "\n",
312
+ "print('Starting Training...')\n",
313
+ "for epoch in range(num_epochs):\n",
314
+ " # Train one epoch\n",
315
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
316
+ "\n",
317
+ " # Validate\n",
318
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
319
+ "\n",
320
+ " train_losses.append(train_loss)\n",
321
+ " val_losses.append(val_loss)\n",
322
+ " val_accuracies.append(val_accuracy)\n",
323
+ "\n",
324
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
325
+ "\n",
326
+ "print('Training Complete!')"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "# Task 1: Write your code here:\n",
336
+ "# Plotting results\n",
337
+ "plt.figure(figsize=(7, 5))\n",
338
+ "\n",
339
+ "plt.plot(train_losses, label='Train Loss')\n",
340
+ "plt.plot(val_losses, label='Validation Loss')\n",
341
+ "plt.title('Loss over Epochs')\n",
342
+ "plt.xlabel('Epoch')\n",
343
+ "plt.ylabel('Loss')\n",
344
+ "plt.legend()\n",
345
+ "\n",
346
+ "plt.tight_layout()\n",
347
+ "plt.show()"
348
+ ],
349
+ "execution_count": null,
350
+ "outputs": []
351
+ },
352
+ {
353
+ "cell_type": "code",
354
+ "metadata": {},
355
+ "source": [
356
+ "# Task 2 (Bonus): Write your code here:\n",
357
+ "plt.figure(figsize=(6, 4))\n",
358
+ "plt.scatter(y_test, y_pred, alpha=0.6)\n",
359
+ "plt.plot(\n",
360
+ " [y_test.min(), y_test.max()],\n",
361
+ " [y_test.min(), y_test.max()],\n",
362
+ " \"r--\",\n",
363
+ " linewidth=2\n",
364
+ ")\n",
365
+ "plt.xlabel(\"Actual image\")\n",
366
+ "plt.ylabel(\"Predicted image\")\n",
367
+ "plt.title(\"Linear Regression: Predictions vs Actual\")\n",
368
+ "plt.grid(True)\n",
369
+ "\n",
370
+ "plt.tight_layout()\n",
371
+ "plt.show()"
372
+ ],
373
+ "execution_count": null,
374
+ "outputs": []
375
+ }
376
+ ],
377
+ "metadata": {
378
+ "kernelspec": {
379
+ "display_name": "Python 3",
380
+ "name": "python3"
381
+ },
382
+ "language_info": {
383
+ "name": "python"
384
+ }
385
+ },
386
+ "nbformat": 4,
387
+ "nbformat_minor": 0
388
+ }
submissions_extracted/148/Q3.ipynb ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import matplotlib.pyplot as plt\n",
12
+ "import seaborn as sns\n",
13
+ "from tqdm import tqdm\n",
14
+ "\n",
15
+ "\n",
16
+ "# Download latest version\n",
17
+ "\n",
18
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
19
+ "\n",
20
+ "\n",
21
+ "\n",
22
+ "print(\"Path to dataset files:\", path)"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "# Task 1: Write your code here:\n",
32
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
33
+ "\n",
34
+ "df = pd.read_csv(csv_path)"
35
+ ],
36
+ "execution_count": null,
37
+ "outputs": []
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "metadata": {},
42
+ "source": [
43
+ "# Task 2: Write your code here:\n",
44
+ "df.head()"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# Task 3: Write your code here:\n",
54
+ "df.info()"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "# Task 4: Write your code here:\n",
64
+ "df.describe()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 1: Write your code here:\n",
74
+ "def check_missing_values(df):\n",
75
+ " missing_values = df.isnull().sum()\n",
76
+ " print(\"Missing Values per Column:\")\n",
77
+ " print(missing_values[missing_values > 0])\n",
78
+ " if missing_values.any():\n",
79
+ " print(\"\\nHandle Missing Values as needed.\")\n",
80
+ " else:\n",
81
+ " print(\"\\nNo Missing Values Found.\")\n",
82
+ "\n",
83
+ "check_missing_values(df)"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 2: Write your code here:\n",
93
+ "def check_duplicates(df):\n",
94
+ "\n",
95
+ " #TODO: get duplicated data using pandas\n",
96
+ " duplicates = df.duplicated().sum()\n",
97
+ "\n",
98
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
99
+ " if duplicates > 0:\n",
100
+ " print(\"Dropping Duplicates...\")\n",
101
+ " df.drop_duplicates(inplace=True)\n",
102
+ " print(\"Duplicates Dropped.\")\n",
103
+ " else:\n",
104
+ " print(\"No Duplicate Samples Found.\")\n",
105
+ "\n",
106
+ "check_duplicates(df)"
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
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
117
+ "\n",
118
+ "\n",
119
+ "print('data before encoding:\\n', df) #show before encoding\n",
120
+ "\n",
121
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
122
+ "data_onehot_encoded = onehot_encoder.fit_transform(df) # Apply fit_transform to the copied\n",
123
+ "\n",
124
+ "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 4: Write your code here:\n",
134
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
135
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
136
+ "data_standard_scaled = standard_scaler.fit_transform(df)"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 5: Write your code here:\n",
146
+ "def check_target_imbalance(df, target_column):\n",
147
+ " print(\"Target Distribution:\")\n",
148
+ "\n",
149
+ " df[target_column].hist()\n",
150
+ " plt.show()\n",
151
+ "\n",
152
+ "check_target_imbalance(df, \"Target\")"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 1: Write your code here:\n",
162
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
163
+ "y = df['Target'].astype(float)"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 2,3,4,5: Write your code here:\n",
173
+ "#2,3\n",
174
+ "from sklearn.neighbors import KNeighborsClassifier\n",
175
+ "from sklearn.svm import SVC\n",
176
+ "from sklearn.tree import DecisionTreeClassifier\n",
177
+ "from sklearn.ensemble import RandomForestClassifier\n",
178
+ "from xgboost import XGBClassifier\n",
179
+ "from catboost import CatBoostClassifier\n",
180
+ "\n",
181
+ "skmodel = {\n",
182
+ " \"CatBoost\": CatBoostClassifier(\n",
183
+ " verbose=0,\n",
184
+ " n_estimators=320,\n",
185
+ " max_depth=4)\n",
186
+ "}\n",
187
+ "\n",
188
+ "all_results = {}\n",
189
+ "\n",
190
+ "for name in skmodel:\n",
191
+ " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
192
+ "\n",
193
+ "n_splits = 5 # K\n",
194
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
195
+ "\n",
196
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
197
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
198
+ "\n",
199
+ " # 1. Split data\n",
200
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
201
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
202
+ "\n",
203
+ " # 2. Train & Validate sklearn models\n",
204
+ " for model_name, model in skmodel.items():\n",
205
+ " print(f\"Training {model_name}...\")\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
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
212
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
213
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
214
+ "\n",
215
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
216
+ " all_results[model_name]['precision'].append(precision)\n",
217
+ " all_results[model_name]['recall'].append(recall)\n",
218
+ " all_results[model_name]['f1'].append(f1)\n",
219
+ "\n",
220
+ "#4\n",
221
+ "for model_name in all_results:\n",
222
+ " print(f\"\\n{model_name}:\")\n",
223
+ " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
224
+ " print(f\" Precision: {np.mean(all_results[model_name]['precision']):.4f}\")\n",
225
+ " print(f\" Recall: {np.mean(all_results[model_name]['recall']):.4f}\")\n",
226
+ " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
227
+ ],
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "metadata": {},
234
+ "source": [
235
+ "# Task 1: Write your code here:\n",
236
+ "importances = {}\n",
237
+ "importances['CatBoost'] = model['CatBoost'].feature_importances_\n",
238
+ "\n",
239
+ "\n",
240
+ "# Create a 1x3 plot\n",
241
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
242
+ "axes = axes.flatten()\n",
243
+ "features = X.columns\n",
244
+ "\n",
245
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
246
+ " # Sort features by importance for a cleaner plot\n",
247
+ " sorted_idx = np.argsort(imp)\n",
248
+ "\n",
249
+ " ax = axes[i]\n",
250
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
251
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
252
+ " ax.set_xlabel(\"Importance Score\")\n",
253
+ "\n",
254
+ "plt.tight_layout()\n",
255
+ "plt.show()"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "metadata": {},
263
+ "source": [
264
+ "# Task 2: Write your code here:\n",
265
+ "print(f\"the Golden Feature:\" features[sorted_idx[0]])"
266
+ ],
267
+ "execution_count": null,
268
+ "outputs": []
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "metadata": {},
273
+ "source": [
274
+ "# Task Bonus: Write your code here:"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ }
279
+ ],
280
+ "metadata": {
281
+ "kernelspec": {
282
+ "display_name": "Python 3",
283
+ "name": "python3"
284
+ },
285
+ "language_info": {
286
+ "name": "python"
287
+ }
288
+ },
289
+ "nbformat": 4,
290
+ "nbformat_minor": 0
291
+ }
submissions_extracted/149/Q1.ipynb ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os\n",
22
+ "import pandas as pd\n",
23
+ "\n",
24
+ "import numpy as np\n",
25
+ "\n",
26
+ "\n",
27
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
28
+ "# print(data_path) # just to make sure if the path is correct\n",
29
+ "data = pd.read_csv(data_path)"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "data.head()"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "data.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "data.describe()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "import matplotlib.pyplot as plt\n",
66
+ "\n",
67
+ "# Price distribution (target variable)\n",
68
+ "plt.figure(figsize=(10, 5))\n",
69
+ "plt.hist(data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
70
+ "plt.title('Delivery Time Distribution')\n",
71
+ "\n",
72
+ "plt.show()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "clean_data = data.drop(columns=['Order_ID'])\n",
82
+ "clean_data.head()"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# 2. Do we have missing values?\n",
92
+ "def check_missing_values(df):\n",
93
+ "\n",
94
+ " # Get missing values using pandas\n",
95
+ " missing_values = df.isnull().sum()\n",
96
+ "\n",
97
+ " print(\"Missing Values per Column:\")\n",
98
+ " print(missing_values[missing_values > 0])\n",
99
+ "\n",
100
+ " if missing_values.any():\n",
101
+ " df['Weather'].fillna(df['Weather'].mode()[0])\n",
102
+ " df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
103
+ " df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n",
104
+ " df['Delivery_Time'].fillna(df['Delivery_Time'].mean())\n",
105
+ " print(\"handled\")\n",
106
+ "\n",
107
+ " else:\n",
108
+ " print(\"\\nNo Missing Values Found.\")\n",
109
+ "\n",
110
+ "check_missing_values(clean_data)\n",
111
+ "\n"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "def check_duplicates(df):\n",
121
+ " duplicates = df.duplicated().sum()\n",
122
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
123
+ " if duplicates > 0:\n",
124
+ " print(\"Dropping Duplicates...\")\n",
125
+ " df.drop_duplicates(inplace=True)\n",
126
+ " print(\"Duplicates Dropped.\")\n",
127
+ " else:\n",
128
+ " print(\"No Duplicate Samples Found.\")\n",
129
+ "\n",
130
+ "check_duplicates(clean_data)\n",
131
+ "clean_data.info()"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "\n",
141
+ "from sklearn.preprocessing import LabelEncoder\n",
142
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
143
+ "\n",
144
+ "for col in categorical_cols:\n",
145
+ " le = LabelEncoder()\n",
146
+ " clean_data[col] = le.fit_transform(clean_data[col].astype(str))\n"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
156
+ "\n",
157
+ "print('data before scaling:\\n', clean_data) #show before scaling\n",
158
+ "StandardScaler = StandardScaler() # Instantiate StandardScaler\n",
159
+ "data_standard_scaled = StandardScaler.fit_transform(clean_data) # Apply fit_transform\n",
160
+ "\n",
161
+ "print('\\nData after scaling:\\n', clean_data) #show after scaling"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "clean_data.info()\n",
171
+ "\n",
172
+ "\n",
173
+ "def check_target_imbalance(df, target_column):\n",
174
+ " print(\"Target Distribution:\")\n",
175
+ "\n",
176
+ " df[target_column].hist() # Yeah you can just do this :)\n",
177
+ " plt.show()\n",
178
+ "\n",
179
+ "check_target_imbalance(clean_data, \"Delivery_Time\")\n"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Define features (X) and target (y)\n",
189
+ "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
190
+ " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
191
+ "X = clean_data[feature_cols]\n",
192
+ "y = clean_data['Delivery_Time']"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "from sklearn.model_selection import KFold\n",
202
+ "\n",
203
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
204
+ "\n",
205
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
206
+ " # indexing for each fold\n",
207
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
208
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
209
+ " # print shapes\n",
210
+ " print(f\"Fold {fold}\")\n",
211
+ " print(\" X_train shape:\", X_train.shape)\n",
212
+ " print(\" X_test shape :\", X_test.shape)\n",
213
+ " print(\" y_train shape:\", y_train.shape)\n",
214
+ " print(\" y_test shape :\", y_test.shape)\n",
215
+ " print(\"-\" * 30)"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "# Feature importance\n",
225
+ "feature_importance = pd.DataFrame({\n",
226
+ " 'feature': feature_cols,\n",
227
+ " 'importance': model.feature_importances_\n",
228
+ "}).sort_values('importance', ascending=False)\n",
229
+ "\n",
230
+ "plt.figure(figsize=(10, 6))\n",
231
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
232
+ "plt.xlabel('Importance')\n",
233
+ "plt.title('Feature Importance')\n",
234
+ "plt.gca().invert_yaxis()\n",
235
+ "plt.show()"
236
+ ],
237
+ "execution_count": null,
238
+ "outputs": []
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "metadata": {},
243
+ "source": [
244
+ "# Task 2: Write your code here:"
245
+ ],
246
+ "execution_count": null,
247
+ "outputs": []
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "metadata": {},
252
+ "source": [
253
+ "# Task Bonus: Write your code here:"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ }
258
+ ],
259
+ "metadata": {
260
+ "kernelspec": {
261
+ "display_name": "Python 3",
262
+ "name": "python3"
263
+ },
264
+ "language_info": {
265
+ "name": "python"
266
+ }
267
+ },
268
+ "nbformat": 4,
269
+ "nbformat_minor": 0
270
+ }
submissions_extracted/149/Q2.ipynb ADDED
@@ -0,0 +1,340 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "import torch\n",
69
+ "from torch.utils.data import TensorDataset\n",
70
+ "\n",
71
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
72
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
73
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
74
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "train_dataset = TensorDataset(X_train, y_train)\n",
84
+ "test_dataset = TensorDataset(X_test, y_test)\n"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "from torch.utils.data import DataLoader\n",
94
+ "\n",
95
+ "# dataLoader for training data\n",
96
+ "train_loader = DataLoader(\n",
97
+ " train_dataset,\n",
98
+ " batch_size=32,\n",
99
+ " shuffle=True,\n",
100
+ " num_workers=2\n",
101
+ ")\n",
102
+ "# dataLoader for test data\n",
103
+ "test_loader = DataLoader(\n",
104
+ " test_dataset,\n",
105
+ " batch_size=32,\n",
106
+ " shuffle=False,\n",
107
+ " num_workers=2\n",
108
+ ")\n"
109
+ ],
110
+ "execution_count": null,
111
+ "outputs": []
112
+ },
113
+ {
114
+ "cell_type": "code",
115
+ "metadata": {},
116
+ "source": [
117
+ "X_batch, y_batch = next(iter(train_loader))\n",
118
+ "print(f\"Training batch input shape: {X_batch.shape}\")"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# 5. Display sample images\n",
128
+ "\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "import torch\n",
138
+ "import torch.nn as nn\n",
139
+ "\n",
140
+ "class NN4Layer(nn.Module):\n",
141
+ "\n",
142
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
143
+ " super(NN4Layer, self).__init__()\n",
144
+ "\n",
145
+ " # First linear layer: input features -> hidden layer\n",
146
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
147
+ "\n",
148
+ " # Second linear layer: hidden layer -> hidden layer\n",
149
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
150
+ "\n",
151
+ " # Third linear layer: hidden layer -> hidden layer\n",
152
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
153
+ "\n",
154
+ " # Output layer: hidden layer -> number of classes (logits)\n",
155
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
156
+ "\n",
157
+ " # ReLU activation for non-linearity\n",
158
+ " self.relu = nn.ReLU()\n",
159
+ "\n",
160
+ " # Defines how input data flows through the network\n",
161
+ " def forward(self, x):\n",
162
+ " # First hidden layer\n",
163
+ " a1 = self.relu(self.layer1(x))\n",
164
+ "\n",
165
+ " # Second hidden layer\n",
166
+ " a2 = self.relu(self.layer2(a1))\n",
167
+ "\n",
168
+ " # Third hidden layer\n",
169
+ " a3 = self.relu(self.layer3(a2))\n",
170
+ "\n",
171
+ " # Output layer (raw scores / logits)\n",
172
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
173
+ "\n",
174
+ " return output\n",
175
+ "\n"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
185
+ " # Set the model to training mode\n",
186
+ " model.train()\n",
187
+ "\n",
188
+ " running_loss = 0.0\n",
189
+ "\n",
190
+ " for X_batch, y_batch in train_loader:\n",
191
+ " # Move batch to the selected device\n",
192
+ " X_batch = X_batch.to(device)\n",
193
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
194
+ "\n",
195
+ " # Forward pass\n",
196
+ " outputs = model(X_batch)\n",
197
+ " loss = criterion(outputs, y_batch)\n",
198
+ "\n",
199
+ " # Backward pass & optimization\n",
200
+ " optimizer.zero_grad() # Clear previous gradients\n",
201
+ " loss.backward() # Compute gradients\n",
202
+ " optimizer.step() # Update model parameters\n",
203
+ "\n",
204
+ " running_loss += loss.item()\n",
205
+ "\n",
206
+ " # Average loss over all batches\n",
207
+ " avg_loss = running_loss / len(train_loader)\n",
208
+ "\n",
209
+ " return avg_loss"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "def validate(model, criterion, test_loader, device):\n",
219
+ " # Set the model to evaluation mode\n",
220
+ " model.eval()\n",
221
+ "\n",
222
+ " running_loss = 0.0\n",
223
+ " correct = 0\n",
224
+ " total = 0\n",
225
+ "\n",
226
+ " with torch.no_grad():\n",
227
+ " for X_batch, y_batch in test_loader:\n",
228
+ " # Move data to device\n",
229
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
230
+ " y_batch = y_batch.to(device)\n",
231
+ "\n",
232
+ " # Forward pass\n",
233
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
234
+ " loss = criterion(outputs, y_batch)\n",
235
+ " running_loss += loss.item()\n",
236
+ "\n",
237
+ " # Apply Softmax to get probabilities\n",
238
+ " probabilities = F.softmax(outputs, dim=1)\n",
239
+ "\n",
240
+ " # Multiclass predictions\n",
241
+ " predicted = torch.argmax(probabilities, dim=1)\n",
242
+ "\n",
243
+ " # Accuracy calculation\n",
244
+ " correct += (predicted == y_batch).sum().item()\n",
245
+ " total += y_batch.size(0)\n",
246
+ "\n",
247
+ " avg_loss = running_loss / len(test_loader)\n",
248
+ " accuracy = correct / total\n",
249
+ "\n",
250
+ " return avg_loss, accuracy\n"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "metadata": {},
258
+ "source": [
259
+ "from torch.optim import Adam\n",
260
+ "\n",
261
+ "# Device setup\n",
262
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
263
+ "\n",
264
+ "# Model parameters\n",
265
+ "input_dim = 36 * 36 # images shape\n",
266
+ "hidden_dim = 14 # design choice\n",
267
+ "output_dim = 10 # Digits 0–9\n",
268
+ "\n",
269
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
270
+ "\n",
271
+ "learning_rate = 0.001\n",
272
+ "\n",
273
+ "criterion = nn.CrossEntropyLoss()\n",
274
+ "# Define optimizer\n",
275
+ "optimizer = Adam(model.parameters(), learning_rate)\n"
276
+ ],
277
+ "execution_count": null,
278
+ "outputs": []
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "metadata": {},
283
+ "source": [
284
+ "num_epochs = 20\n",
285
+ "\n",
286
+ "# Run Training\n",
287
+ "train_losses = []\n",
288
+ "val_losses = []\n",
289
+ "val_accuracies = []\n",
290
+ "\n",
291
+ "print('Starting Training...')\n",
292
+ "for epoch in range(num_epochs):\n",
293
+ " # Train one epoch\n",
294
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
295
+ "\n",
296
+ " # Validate\n",
297
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
298
+ "\n",
299
+ " train_losses.append(train_loss)\n",
300
+ " val_losses.append(val_loss)\n",
301
+ " val_accuracies.append(val_accuracy)\n",
302
+ "\n",
303
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\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
+ "# i don't know how to use plot LOL ¯\\(ツ)/¯"
315
+ ],
316
+ "execution_count": null,
317
+ "outputs": []
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "metadata": {},
322
+ "source": [
323
+ "# Task 2 (Bonus): Write your code here:"
324
+ ],
325
+ "execution_count": null,
326
+ "outputs": []
327
+ }
328
+ ],
329
+ "metadata": {
330
+ "kernelspec": {
331
+ "display_name": "Python 3",
332
+ "name": "python3"
333
+ },
334
+ "language_info": {
335
+ "name": "python"
336
+ }
337
+ },
338
+ "nbformat": 4,
339
+ "nbformat_minor": 0
340
+ }
submissions_extracted/149/Q3.ipynb ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "import pandas as pd\n",
27
+ "\n",
28
+ "df = pd.read_csv(path + \"/Q3_data.csv\")\n"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "df.head()"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "df.info()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "df.describe()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# # 2. Do we have missing values?\n",
65
+ "def check_missing_values(df):\n",
66
+ "\n",
67
+ " # Get missing values using pandas\n",
68
+ " missing_values = df.isnull().sum()\n",
69
+ "\n",
70
+ " print(\"Missing Values per Column:\")\n",
71
+ " print(missing_values[missing_values > 0])\n",
72
+ "\n",
73
+ " if missing_values.any():\n",
74
+ " df.drop(columns=['D_87'])\n",
75
+ " df.drop(columns=['D_88'])\n",
76
+ " df.drop(columns=['B_39'])\n",
77
+ " df.drop(columns=['D_110'])\n",
78
+ " df.drop(columns=['D_111'])\n",
79
+ " df.drop(columns=['D_108'])\n",
80
+ " df.drop(columns=['B_42'])\n",
81
+ " df.drop(columns=['D_73'])\n",
82
+ " df.drop(columns=['D_136'])\n",
83
+ " df.drop(columns=['D_138'])\n",
84
+ " df.drop(columns=['D_134'])\n",
85
+ " df.drop(columns=['D_137'])\n",
86
+ " df.drop(columns=['R_9'])\n",
87
+ " df.drop(columns=['B_29'])\n",
88
+ " df.drop(columns=['D_106'])\n",
89
+ " df.drop(columns=['D_132'])\n",
90
+ " df.drop(columns=['D_49'])\n",
91
+ " df.drop(columns=['D_66'])\n",
92
+ " df.drop(columns=['R_26'])\n",
93
+ " df.drop(columns=['D_76'])\n",
94
+ " df.drop(columns=['D_142'])\n",
95
+ " df.drop(columns=['D_53'])\n",
96
+ "\n",
97
+ "\n",
98
+ " print(\"handled\")\n",
99
+ "\n",
100
+ " else:\n",
101
+ " print(\"\\nNo Missing Values Found.\")\n",
102
+ "\n",
103
+ "check_missing_values(df)"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# 4. Do we have duplicate samples?\n",
113
+ "def check_duplicates(df):\n",
114
+ " duplicates = df.duplicated().sum()\n",
115
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
116
+ " if duplicates > 0:\n",
117
+ " print(\"Dropping Duplicates...\")\n",
118
+ " df.drop_duplicates(inplace=True)\n",
119
+ " print(\"Duplicates Dropped.\")\n",
120
+ " else:\n",
121
+ " print(\"No Duplicate Samples Found.\")\n",
122
+ "\n",
123
+ "check_duplicates(df)"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "from sklearn.preprocessing import LabelEncoder\n",
133
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
134
+ "for col in categorical_cols:\n",
135
+ " print(f\"Encoding column: {col}\")\n",
136
+ " le = LabelEncoder()\n",
137
+ " df[col] = le.fit_transform(df[col])"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "from sklearn.preprocessing import StandardScaler\n",
147
+ "\n",
148
+ "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
149
+ "\n",
150
+ "scaler = StandardScaler()\n",
151
+ "\n",
152
+ "# TODO: Apply fit_transform to scale the numerical columns\n",
153
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
154
+ "\n",
155
+ "df.head()"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "import matplotlib.pyplot as plt\n",
165
+ "\n",
166
+ "df.info()\n",
167
+ "\n",
168
+ "\n",
169
+ "def check_target_imbalance(df, target_column):\n",
170
+ " print(\"Target Distribution:\")\n",
171
+ "\n",
172
+ " df[target_column].hist() # Yeah you can just do this :)\n",
173
+ " plt.show()\n",
174
+ "\n",
175
+ "check_target_imbalance(df, \"Target\")\n",
176
+ "\n",
177
+ "# wow a big one LOL"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Define features (X) and target (y)\n",
187
+ "feature_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
188
+ "X = df[feature_cols]\n",
189
+ "y = df['Target']"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "from sklearn.model_selection import KFold\n",
199
+ "\n",
200
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
201
+ "\n",
202
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
203
+ " # indexing for each fold\n",
204
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
205
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
206
+ " # print shapes\n",
207
+ " print(f\"Fold {fold}\")\n",
208
+ " print(\" X_train shape:\", X_train.shape)\n",
209
+ " print(\" X_test shape :\", X_test.shape)\n",
210
+ " print(\" y_train shape:\", y_train.shape)\n",
211
+ " print(\" y_test shape :\", y_test.shape)\n",
212
+ " print(\"-\" * 30)"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# Feature importance\n",
222
+ "feature_importance = pd.DataFrame({\n",
223
+ " 'feature': feature_cols,\n",
224
+ " 'importance': model.feature_importances_\n",
225
+ "}).sort_values('importance', ascending=False)\n",
226
+ "\n",
227
+ "plt.figure(figsize=(10, 6))\n",
228
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
229
+ "plt.xlabel('Importance')\n",
230
+ "plt.title('Feature Importance')\n",
231
+ "plt.gca().invert_yaxis()\n",
232
+ "plt.show()"
233
+ ],
234
+ "execution_count": null,
235
+ "outputs": []
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "metadata": {},
240
+ "source": [
241
+ "# Task 2: Write your code here:"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# Task Bonus: Write your code here:"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ }
255
+ ],
256
+ "metadata": {
257
+ "kernelspec": {
258
+ "display_name": "Python 3",
259
+ "name": "python3"
260
+ },
261
+ "language_info": {
262
+ "name": "python"
263
+ }
264
+ },
265
+ "nbformat": 4,
266
+ "nbformat_minor": 0
267
+ }
submissions_extracted/15/Q1.ipynb ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, KFold\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n",
20
+ "\n"
21
+ ],
22
+ "execution_count": null,
23
+ "outputs": []
24
+ },
25
+ {
26
+ "cell_type": "code",
27
+ "metadata": {},
28
+ "source": [
29
+ "\n",
30
+ "\n",
31
+ "# Download latest version\n",
32
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
33
+ "\n",
34
+ "print(\"Path to dataset files:\", path)"
35
+ ],
36
+ "execution_count": null,
37
+ "outputs": []
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "metadata": {},
42
+ "source": [
43
+ "# Task 1: Write your code here:\n",
44
+ "# Load the dataset\n",
45
+ "delivery_path = os.path.join(path, 'Q1_data.csv')\n",
46
+ "df_delivery= pd.read_csv(delivery_path)\n",
47
+ "\n",
48
+ "print(f\"Dataset shape: {df_delivery.shape}\")\n",
49
+ "#df_delivery.head()"
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
+ "# here the head() task\n",
60
+ "\n",
61
+ "df_delivery.head()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 3: Write your code here:\n",
71
+ "df_delivery.info()"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 4: Write your code here:\n",
81
+ "df_delivery.describe()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 5: Write your code here:\n",
91
+ "# delivery_time distribution (target variable)\n",
92
+ "plt.figure(figsize=(10, 5))\n",
93
+ "plt.hist(df_delivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
94
+ "plt.title('Delivery_Time Distribution')\n",
95
+ "plt.xlabel('Delivery_Time')\n",
96
+ "plt.ylabel('Frequency')\n",
97
+ "plt.show()"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Define stat columns\n",
107
+ "stat_cols = [ 'Order_ID' ]\n",
108
+ "\n",
109
+ "# Drop rows with missing stat values\n",
110
+ "df_clean = df_delivery.dropna(subset=stat_cols).copy()\n",
111
+ "print(f\"Shape after cleaning: {df_clean.shape}\")"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# Task 2: Write your code here:\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 3: Write your code here:\n",
130
+ "# 4. Do we have duplicate samples?\n",
131
+ "def check_duplicates(df_delivery):\n",
132
+ " duplicates = df_delivery.duplicated().sum()\n",
133
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
134
+ " if duplicates > 0:\n",
135
+ " print(\"Dropping Duplicates...\")\n",
136
+ " df_delivery.drop_duplicates(inplace=True)\n",
137
+ " print(\"Duplicates Dropped.\")\n",
138
+ " else:\n",
139
+ " print(\"No Duplicate Samples Found.\")\n",
140
+ "\n",
141
+ "check_duplicates(df_delivery)"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 4: Write your code here:\n",
151
+ "\n",
152
+ "# Random data generation for encoding\n",
153
+ "import pandas as pd\n",
154
+ "\n",
155
+ "categories = pd.DataFrame({\"Traffic_Level\":['Low','Medium''Low','Medium','Low']}) # DataFrame of one column\n",
156
+ "\n",
157
+ "categories_wether = pd.DataFrame({\"Weather\":['Windy\t','Clear''Foggy','Rainy','Clear']})\n",
158
+ "\n",
159
+ "print(\"Before encoding:\")\n",
160
+ "categories\n",
161
+ "\n",
162
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
163
+ "\n",
164
+ "print('data before encoding:\\n', categories,categories_wether) #show before encoding\n",
165
+ "\n",
166
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
167
+ "data_onehot_encoded = onehot_encoder.fit_transform(categories,categories_wether) # Apply fit_transform to the copied\n",
168
+ "\n",
169
+ "print('\\nData after encoding:\\n', data_onehot_encoded) #show after encoding"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 5: Write your code here:\n",
179
+ "# Scale features - fit on train, transform both\n",
180
+ "from sklearn.preprocessing import LabelEncoder\n",
181
+ "\n",
182
+ "for col in X_train.select_dtypes(include='object'):\n",
183
+ " le = LabelEncoder()\n",
184
+ " X_train[col] = le.fit_transform(X_train[col])\n",
185
+ " X_test[col] = le.transform(X_test[col])\n",
186
+ "\n",
187
+ "scaler = StandardScaler()\n",
188
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
189
+ "X_test_scaled = scaler.transform(X_test)\n",
190
+ "\n",
191
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
192
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n",
193
+ "\n"
194
+ ],
195
+ "execution_count": null,
196
+ "outputs": []
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "metadata": {},
201
+ "source": [
202
+ "# Task 6: Write your code here:"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 1: Write your code here:\n",
212
+ "# Define features (X) and target (y)\n",
213
+ "feature_cols = ['Order_ID','Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
214
+ "X = df_clean[feature_cols]\n",
215
+ "y = df_clean['Delivery_Time']\n",
216
+ "\n",
217
+ "# Train-test split (80% train, 20% test)\n",
218
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
219
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
220
+ ],
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "metadata": {},
227
+ "source": [
228
+ "# Task 2,3,4,5: Write your code here:\n",
229
+ "# Train Random Forest Regressor\n",
230
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
231
+ "model.fit(X_train_scaled, y_train)\n",
232
+ "print(\"Model trained!\")\n",
233
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
234
+ "\n",
235
+ "mae_scores = []\n",
236
+ "rmse_scores = []\n",
237
+ "\n",
238
+ "for train_idx, val_idx in kfold.split(X_train_scaled):\n",
239
+ " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
240
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
241
+ "\n",
242
+ " # Train and predict\n",
243
+ " model.fit(X_fold_train, y_fold_train)\n",
244
+ " y_fold_pred = model.predict(X_fold_val)\n",
245
+ "\n",
246
+ " # Calculate metrics\n",
247
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
248
+ " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
249
+ "\n",
250
+ "mae_scores = np.array(mae_scores)\n",
251
+ "rmse_scores = np.array(rmse_scores)\n",
252
+ "\n",
253
+ "print(f\"5-Fold CV Results:\")\n",
254
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
255
+ "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "metadata": {},
263
+ "source": [
264
+ "# Task 1: Write your code here:"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ },
269
+ {
270
+ "cell_type": "code",
271
+ "metadata": {},
272
+ "source": [
273
+ "# Task 2: Write your code here:"
274
+ ],
275
+ "execution_count": null,
276
+ "outputs": []
277
+ },
278
+ {
279
+ "cell_type": "code",
280
+ "metadata": {},
281
+ "source": [
282
+ "# Task Bonus: Write your code here:"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ }
287
+ ],
288
+ "metadata": {
289
+ "kernelspec": {
290
+ "display_name": "Python 3",
291
+ "name": "python3"
292
+ },
293
+ "language_info": {
294
+ "name": "python"
295
+ }
296
+ },
297
+ "nbformat": 4,
298
+ "nbformat_minor": 0
299
+ }
submissions_extracted/15/Q2.ipynb ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "from torch.utils.data import DataLoader, TensorDataset\n",
8
+ "import kagglehub\n",
9
+ "import os\n",
10
+ "import pandas as pd\n",
11
+ "import numpy as np\n",
12
+ "from PIL import Image\n",
13
+ "from sklearn.model_selection import train_test_split\n",
14
+ "import torch\n",
15
+ "import torch.nn as nn\n",
16
+ "from torchvision.datasets import MNIST\n",
17
+ "from torch.utils.data import DataLoader\n",
18
+ "from torch.optim import Adam\n",
19
+ "from torchvision.transforms.functional import to_tensor\n",
20
+ "import torch.nn.functional as F\n",
21
+ "import matplotlib.pyplot as plt\n",
22
+ "import torch"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "\n",
32
+ "\n",
33
+ "# Download latest version\n",
34
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
35
+ "\n",
36
+ "print(\"Path to dataset files:\", path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "\n",
46
+ "\n",
47
+ "# Load Labels\n",
48
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
49
+ "img_dir = os.path.join(path, \"images\")\n",
50
+ "\n",
51
+ "images = []\n",
52
+ "ages = []\n",
53
+ "\n",
54
+ "# Load Images and Resize\n",
55
+ "print(\"Loading images...\")\n",
56
+ "for index, row in labels_df.iterrows():\n",
57
+ " img_name = row.iloc[0]\n",
58
+ " age = row.iloc[1]\n",
59
+ " img_path = os.path.join(img_dir, img_name)\n",
60
+ "\n",
61
+ " if os.path.exists(img_path):\n",
62
+ " img = Image.open(img_path).convert('RGB')\n",
63
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
64
+ " images.append(img_array)\n",
65
+ " ages.append(age)\n",
66
+ "\n",
67
+ "X = np.array(images)\n",
68
+ "y = np.array(ages)\n",
69
+ "\n",
70
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
71
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
72
+ "\n",
73
+ "# Split Data\n",
74
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
75
+ "\n",
76
+ "print(f\"X_train shape: {X_train.shape}\")\n",
77
+ "print(f\"X_test shape: {X_test.shape}\")\n",
78
+ "print(f\"y_train shape: {y_train.shape}\")\n",
79
+ "print(f\"y_test shape: {y_test.shape}\")"
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
+ "X_train_tensor=torch.tensor(X_train, dtype=torch.float32)\n",
90
+ "X_test_tensor=torch.tensor(X_test, dtype=torch.float32)\n",
91
+ "\n",
92
+ "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
93
+ "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n",
94
+ "\n",
95
+ "\n",
96
+ "print(\"X_train_tensor:\", X_train_tensor.shape, X_train_tensor.dtype)\n",
97
+ "print(\"X_test_tensor :\", X_test_tensor.shape, X_test_tensor.dtype)\n",
98
+ "print(\"y_train_tensor:\", y_train_tensor.shape, y_train_tensor.dtype)\n",
99
+ "print(\"y_test_tensor :\", y_test_tensor.shape, y_test_tensor.dtype)\n"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# 2. Create TensorDataset objects\n",
109
+ "\n",
110
+ "\n",
111
+ "# Create TensorDatasets for training and testing\n",
112
+ "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
113
+ "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)\n",
114
+ "\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
+ "\n",
119
+ "# Print dataset sizes\n",
120
+ "print(\"Train dataset:\", len(train_dataset))\n",
121
+ "print(\"Test dataset:\", len(test_dataset))\n"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# 3. Create DataLoaders\n",
131
+ "\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}\")\n",
137
+ "\n"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# 4. Print shape of one batch\n",
147
+ "\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(1):\n",
155
+ " plt.subplot(2, 3, i + 1)\n",
156
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
157
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
158
+ " plt.axis('off')\n",
159
+ "\n",
160
+ "plt.tight_layout()\n",
161
+ "plt.show()"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# 5. Display sample images\n",
171
+ "\n"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "# Task 1: Write your model class here:\n",
181
+ "class NN4Layer(nn.Module):\n",
182
+ "\n",
183
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
184
+ " super(NN4Layer, self).__init__()\n",
185
+ "\n",
186
+ " # First linear layer: input features -> hidden layer\n",
187
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
188
+ "\n",
189
+ " # Second linear layer: hidden layer -> hidden layer\n",
190
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
191
+ "\n",
192
+ "\n",
193
+ " # third linear layer: hidden layer -> hidden layer\n",
194
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
195
+ "\n",
196
+ " # Output layer: hidden layer -> number of classes (logits)\n",
197
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
198
+ "\n",
199
+ " # ReLU activation for non-linearity\n",
200
+ " self.relu = nn.ReLU()\n",
201
+ "\n",
202
+ " # Defines how input data flows through the network\n",
203
+ " def forward(self, x):\n",
204
+ " # First hidden layer\n",
205
+ " z1 = self.layer1(x)\n",
206
+ " a1 = self.relu(z1)\n",
207
+ "\n",
208
+ " # Second hidden layer\n",
209
+ " z2 = self.layer2(a1)\n",
210
+ " a2 = self.relu(z2)\n",
211
+ "\n",
212
+ " #third hidden layer\n",
213
+ " z3 = self.layer3(a2)\n",
214
+ " a3 = self.relu(z3)\n",
215
+ "\n",
216
+ " # Output layer (raw scores / logits)\n",
217
+ " output = self.layer4(a3) # there is something missing here, remember? :)\n",
218
+ "\n",
219
+ " return output\n"
220
+ ],
221
+ "execution_count": null,
222
+ "outputs": []
223
+ },
224
+ {
225
+ "cell_type": "code",
226
+ "metadata": {},
227
+ "source": [
228
+ "# Task 2: Write your training loop here:\n",
229
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
230
+ " # Set the model to training mode\n",
231
+ " model.train()\n",
232
+ "\n",
233
+ " running_loss = 0.0\n",
234
+ "\n",
235
+ " for X_batch, y_batch in train_loader:\n",
236
+ " # Move batch to the selected device\n",
237
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
238
+ " y_batch = y_batch.to(device)\n",
239
+ "\n",
240
+ " # Forward pass\n",
241
+ " outputs = model(X_batch) # shape: (batch_size, 10)\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
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
280
+ " loss = criterion(outputs, y_batch)\n",
281
+ " running_loss += loss.item()\n",
282
+ "\n",
283
+ " # Apply Softmax to get probabilities\n",
284
+ " probabilities = F.softmax(outputs, dim=1)\n",
285
+ "\n",
286
+ " # 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
+ " accuracy = correct / total\n",
295
+ "\n",
296
+ " return avg_loss, accuracy\n"
297
+ ],
298
+ "execution_count": null,
299
+ "outputs": []
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "metadata": {},
304
+ "source": [
305
+ "# Task 4: Define device, model, loss, optimizer:\n",
306
+ "\n",
307
+ "# Device setup\n",
308
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
309
+ "\n",
310
+ "# Model parameters\n",
311
+ "input_dim = # MNIST images flattened\n",
312
+ "hidden_dim = 14 # Design choice\n",
313
+ "output_dim = 10 # Digits 0–9\n",
314
+ "\n",
315
+ "# Instantiate model\n",
316
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
317
+ "\n",
318
+ "# Print the model architecture\n",
319
+ "print(\"Model Architecture:\\n\")\n",
320
+ "print(model)\n",
321
+ "\n",
322
+ "# Calculate the total number of trainable parameters\n",
323
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
324
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
325
+ ],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "# Task 5: Start training for 20 epochs:\n",
334
+ "num_epochs = 20\n",
335
+ "learning_rate = 0.001\n",
336
+ "\n",
337
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
338
+ "criterion = nn.CrossEntropyLoss()\n",
339
+ "# Define optimizer\n",
340
+ "optimizer = Adam(model.parameters(), learning_rate)\n",
341
+ "# Run Training\n",
342
+ "train_losses = []\n",
343
+ "val_losses = []\n",
344
+ "val_accuracies = []\n",
345
+ "\n",
346
+ "print('Starting Training...')\n",
347
+ "for epoch in range(num_epochs):\n",
348
+ " # Train one epoch\n",
349
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
350
+ "\n",
351
+ " # Validate\n",
352
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
353
+ "\n",
354
+ " train_losses.append(train_loss)\n",
355
+ " val_losses.append(val_loss)\n",
356
+ " val_accuracies.append(val_accuracy)\n",
357
+ "\n",
358
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
359
+ "\n",
360
+ "print('Training Complete!')"
361
+ ],
362
+ "execution_count": null,
363
+ "outputs": []
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "metadata": {},
368
+ "source": [
369
+ "# Task 1: Write your code here:"
370
+ ],
371
+ "execution_count": null,
372
+ "outputs": []
373
+ },
374
+ {
375
+ "cell_type": "code",
376
+ "metadata": {},
377
+ "source": [
378
+ "# Task 2 (Bonus): Write your code here:"
379
+ ],
380
+ "execution_count": null,
381
+ "outputs": []
382
+ }
383
+ ],
384
+ "metadata": {
385
+ "kernelspec": {
386
+ "display_name": "Python 3",
387
+ "name": "python3"
388
+ },
389
+ "language_info": {
390
+ "name": "python"
391
+ }
392
+ },
393
+ "nbformat": 4,
394
+ "nbformat_minor": 0
395
+ }
submissions_extracted/15/Q3.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
+ "import pandas as pd\n",
10
+ "import numpy as np\n",
11
+ "import matplotlib.pyplot as plt\n",
12
+ "import seaborn as sns\n",
13
+ "import kagglehub\n",
14
+ "import os\n",
15
+ "from tqdm import tqdm\n",
16
+ "\n",
17
+ "# Download latest version\n",
18
+ "\n",
19
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
20
+ "\n",
21
+ "\n",
22
+ "\n",
23
+ "print(\"Path to dataset files:\", path)"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "# Task 1: Write your code here:\n",
33
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
34
+ "\n",
35
+ "df = pd.read_csv(csv_path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 2: Write your code here:\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 3: Write your code here:\n",
55
+ "df.info()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 4: Write your code here:\n",
65
+ "df.describe()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 1: Write your code here:\n",
75
+ "def check_missing_values(df):\n",
76
+ "\n",
77
+ " # Get missing values using pandas\n",
78
+ " missing_values = df.isnull().sum()\n",
79
+ "\n",
80
+ " print(\"Missing Values per Column:\")\n",
81
+ " print(missing_values[missing_values > 0])\n",
82
+ "\n",
83
+ " if missing_values.any():\n",
84
+ " print(\"\\nHandle Missing Values as needed.\")\n",
85
+ " else:\n",
86
+ " print(\"\\nNo Missing Values Found.\")\n",
87
+ "\n",
88
+ "check_missing_values(df)\n",
89
+ "\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
+ "# 4. Check for duplicates\n",
100
+ "def check_duplicates(df):\n",
101
+ "\n",
102
+ " #TODO: get duplicated data using pandas\n",
103
+ " duplicates = df.duplicated().sum()\n",
104
+ "\n",
105
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
106
+ " if duplicates > 0:\n",
107
+ " print(\"Dropping Duplicates...\")\n",
108
+ " df.drop_duplicates(inplace=True)\n",
109
+ " print(\"Duplicates Dropped.\")\n",
110
+ " else:\n",
111
+ " print(\"No Duplicate Samples Found.\")\n",
112
+ "\n",
113
+ "check_duplicates(df)"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# Task 3: Write your code here:"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# Task 4: Write your code here:\n",
132
+ "from sklearn.preprocessing import StandardScaler\n",
133
+ "\n",
134
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"D_145\",\"D_144\") # DON'T SCALE THE TARGET\n",
135
+ "\n",
136
+ "scaler = StandardScaler()\n",
137
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
138
+ "df.head()\n"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 5: Write your code here:"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 1: Write your code here:"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 2,3,4,5: Write your code here:"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 1: Write your code here:"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "# Task 2: Write your code here:"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "# Task 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/150/Q1.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/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "# Task 1: Write your code here:\n",
22
+ "\n",
23
+ "import pandas as pd\n",
24
+ "import matplotlib.pyplot as plt\n",
25
+ "import os\n",
26
+ "\n",
27
+ "q1 = os.path.join(path, 'Q1_data.csv')\n",
28
+ "df = pd.read_csv(q1)\n",
29
+ "\n"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 2: Write your code here:\n",
39
+ "df.head()"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# Task 3: Write your code here:\n",
49
+ "df.info()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 4: Write your code here:\n",
59
+ "df.describe()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 5: Write your code here:\n",
69
+ "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
+ "\n",
85
+ "df = df.drop(['Order_ID'], axis=1)\n",
86
+ "df.head()"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 2: Write your code here:\n",
96
+ "def check_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
+ "\n",
108
+ "\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
+ "print(\"Checking for duplicate rows...\")\n",
119
+ "duplicate_rows = df.duplicated().sum()\n",
120
+ "if duplicate_rows > 0:\n",
121
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
122
+ " df.drop_duplicates(inplace=True)\n",
123
+ " print(\"Duplicate rows removed.\")\n",
124
+ "else:\n",
125
+ " print(\"No duplicate rows found.\")"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 4: Write your code here:\n",
135
+ "# 3. Do we have categorical columns?\n",
136
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
137
+ "\n",
138
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
139
+ "\n",
140
+ "\n",
141
+ "# the output tells us there is categorical columns so we should use encoding\n",
142
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
143
+ "\n",
144
+ "print('data before encoding:\\n', categorical_cols) #show before encoding\n",
145
+ "\n",
146
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate OneHotEncoder\n",
147
+ "data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols) # Apply fit_transform to the copied\n",
148
+ "\n",
149
+ "print('\\nData after encoding:\\n', data_onehot_encoded)"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "# Task 5: Write your code here:\n",
159
+ "from sklearn.preprocessing import StandardScaler\n",
160
+ "\n",
161
+ "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
162
+ "\n",
163
+ "scaler = StandardScaler()\n",
164
+ "df[features] = scaler.fit_transform(df[features])\n",
165
+ "df.head()"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 6: Write your code here:\n",
175
+ "import seaborn as sns\n",
176
+ "def check_target_imbalance(df, target_column):\n",
177
+ " print(\"Target Distribution:\")\n",
178
+ " print(df[target_column].value_counts(normalize=True))\n",
179
+ " sns.countplot(x=df[target_column])\n",
180
+ " plt.title(\"Target Distribution\")\n",
181
+ " plt.show()\n",
182
+ "\n",
183
+ "check_target_imbalance(df, \"Delivery_Time\")\n",
184
+ "\n",
185
+ "\n",
186
+ "#targer lef skewed (imblabnced)"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "# Task 1: Write your code here:\n",
196
+ "# Define features (X) and target (y)\n",
197
+ "\n",
198
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
199
+ "y = df['Delivery_Time'].astype(float)"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "# Task 2,3,4,5: Write your code here:\n",
209
+ "import numpy as np\n",
210
+ "from sklearn.ensemble import RandomForestRegressor\n",
211
+ "from sklearn.model_selection import StratifiedKFold\n",
212
+ "\n",
213
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
214
+ "n_splits = 5 # K=5 Folds\n",
215
+ "\n",
216
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
217
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
218
+ "from sklearn.model_selection import StratifiedKFold\n",
219
+ "\n",
220
+ "# Use previously generated random classification data\n",
221
+ "X, y = X.copy(), y.copy()\n",
222
+ "\n",
223
+ "# Show full dataset class distribution\n",
224
+ "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
225
+ "print(\"Full Dataset Class Distribution\")\n",
226
+ "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
227
+ "print(\"-\" * 40)\n",
228
+ "\n",
229
+ "# Define Stratified K-Fold\n",
230
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
231
+ "\n",
232
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
233
+ "\n",
234
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
235
+ " # indexing for each fold\n",
236
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
237
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
238
+ "\n",
239
+ " print(f\"Fold {fold}\")\n",
240
+ " print(\" X_train shape:\", X_train.shape)\n",
241
+ " print(\" X_test shape :\", X_test.shape)\n",
242
+ " print(\" y_train shape:\", y_train.shape)\n",
243
+ " print(\" y_test shape :\", y_test.shape)\n",
244
+ "\n",
245
+ " # showing class distribution\n",
246
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
247
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
248
+ "\n",
249
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
250
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
251
+ "\n",
252
+ " print(\"-\" * 40)\n",
253
+ "\n",
254
+ "model = RandomForestRegressor(n_estimators=200) # instantiate\n",
255
+ "model.fit(X_train, y_train) # fit\n",
256
+ "y_pred = model.predict(X_test) # predict\n",
257
+ "\n",
258
+ "# Calculate metric\n",
259
+ "\n",
260
+ "mae = mean_absolute_error(y_test, y_pred)\n",
261
+ "\n",
262
+ "\n",
263
+ "print(\"MAE :\", mae)\n",
264
+ "\n",
265
+ "avg=np.mean(mae)\n",
266
+ "print(avg)\n",
267
+ "\n",
268
+ "\n",
269
+ "\n",
270
+ "\n"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "metadata": {},
278
+ "source": [
279
+ "# Task 1: Write your code here:\n",
280
+ "# Feature importance\n",
281
+ "importance = pd.DataFrame({\n",
282
+ " 'feature': x ,\n",
283
+ " 'importance': model.feature_importances_\n",
284
+ "}).sort_values('importance', ascending=False)\n",
285
+ "\n",
286
+ "plt.figure(figsize=(10, 6))\n",
287
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
288
+ "plt.xlabel('Importance')\n",
289
+ "plt.title('Feature Importance')\n",
290
+ "plt.gca().invert_yaxis()\n",
291
+ "plt.show()"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "metadata": {},
299
+ "source": [
300
+ "# Task 2: Write your code here:\n",
301
+ "plt.figure(figsize=(10, 6))\n",
302
+ "plt.plot(y_pred)\n",
303
+ "plt.xlabel('y')\n",
304
+ "plt.title('predicted delivery time')\n",
305
+ "plt.gca().invert_yaxis()\n",
306
+ "plt.show()\n"
307
+ ],
308
+ "execution_count": null,
309
+ "outputs": []
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "metadata": {},
314
+ "source": [
315
+ "# Task 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/150/Q2.ipynb ADDED
@@ -0,0 +1,391 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "# transform to tensors\n",
71
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
72
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
73
+ "y_train = torch.tensor(y_train.values, dtype=torch.long)\n",
74
+ "y_test = torch.tensor(y_test.values, dtype=torch.long)\n",
75
+ "\n",
76
+ "\n",
77
+ "\n",
78
+ "\n"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# 2. Create TensorDataset objects\n",
88
+ "train_dataset = TensorDataset(X_train, y_train)\n",
89
+ "test_dataset = TensorDataset(X_test, y_test)\n",
90
+ "\n",
91
+ "\n"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# 3. Create DataLoaders\n",
101
+ "\n",
102
+ "Create Dataloaders to train and test data in batches\n",
103
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
104
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
105
+ "\n",
106
+ "\n",
107
+ "\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
+ "print(\"Train dataset:\", len(train_dataset))\n",
119
+ "print(\"Test dataset:\", len(test_dataset))\n",
120
+ "\n",
121
+ "# Get the first batch from the training DataLoader\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
+ "\n",
126
+ "\n",
127
+ "# now Access a single sample from the dataset\n",
128
+ "\n",
129
+ "first_sample, _ = train_dataset[0]\n",
130
+ "print(f\"Shape of one sample: {first_sample.shape}\")\n",
131
+ "\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# 5. Display sample images\n",
141
+ "\n",
142
+ " #Get one batch of images and labels\n",
143
+ "images, labels = next(iter(train_loader))\n",
144
+ "\n",
145
+ "# Display the first 6 images in the batch\n",
146
+ "plt.figure(figsize=(8, 4))\n",
147
+ "\n",
148
+ "for i in range(6):\n",
149
+ " plt.subplot(2, 3, i + 1)\n",
150
+ " plt.imshow(images[i].squeeze(), cmap='gray')\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()\n"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 1: Write your model class here:\n",
165
+ "class NN3Layer(nn.Module):\n",
166
+ "\n",
167
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
168
+ " super(NN3Layer, self).__init__()\n",
169
+ "\n",
170
+ " # First linear layer: input features -> hidden layer\n",
171
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
172
+ "\n",
173
+ " # Second linear layer: hidden layer -> hidden layer\n",
174
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
175
+ "\n",
176
+ " # Output layer: hidden layer -> number of classes (logits)\n",
177
+ " self.layer3 = nn.Linear(hidden_dim, output_dim)\n",
178
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
179
+ "\n",
180
+ " # ReLU activation for non-linearity\n",
181
+ " self.relu = nn.ReLU()\n",
182
+ "\n",
183
+ " # Defines how input data flows through the network\n",
184
+ " def forward(self, x):\n",
185
+ " # First hidden layer\n",
186
+ " z1 = self.layer1(x)\n",
187
+ " a1 = self.relu(z1)\n",
188
+ "\n",
189
+ " # Second hidden layer\n",
190
+ " z2 = self.layer2(a1)\n",
191
+ " a2 = self.relu(z2)\n",
192
+ " #thrid hidden layer\n",
193
+ " z3=self.layer3(a2)\n",
194
+ " a3=self.relu(z3)\n",
195
+ "\n",
196
+ "\n",
197
+ "\n",
198
+ " # Output layer (raw scores / logits)\n",
199
+ " output = self.layer4(a3)\n",
200
+ " return output"
201
+ ],
202
+ "execution_count": null,
203
+ "outputs": []
204
+ },
205
+ {
206
+ "cell_type": "code",
207
+ "metadata": {},
208
+ "source": [
209
+ "# Task 2: Write your training loop here:\n",
210
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
211
+ " # Set the model to training mode\n",
212
+ " model.train()\n",
213
+ "\n",
214
+ " running_loss = 0.0\n",
215
+ "\n",
216
+ " for X_batch, y_batch in train_loader:\n",
217
+ " # Move batch to the selected device\n",
218
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
219
+ " y_batch = y_batch.to(device)\n",
220
+ "\n",
221
+ " # Forward pass\n",
222
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
223
+ " loss = criterion(outputs, y_batch)\n",
224
+ "\n",
225
+ " # Backward pass & optimization\n",
226
+ " optimizer.zero_grad() # Clear previous gradients\n",
227
+ " loss.backward() # Compute gradients\n",
228
+ " optimizer.step() # Update model parameters\n",
229
+ "\n",
230
+ " running_loss += loss.item()\n",
231
+ "\n",
232
+ " # Average loss over all batches\n",
233
+ " avg_loss = running_loss / len(train_loader)\n",
234
+ "\n",
235
+ " return avg_loss"
236
+ ],
237
+ "execution_count": null,
238
+ "outputs": []
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "metadata": {},
243
+ "source": [
244
+ "# Task 3: Write your validation loop here:\n",
245
+ "\n",
246
+ "\n",
247
+ "def validate(model, criterion, test_loader, device):\n",
248
+ " # Set the model to evaluation mode\n",
249
+ " model.eval()\n",
250
+ "\n",
251
+ " running_loss = 0.0\n",
252
+ " correct = 0\n",
253
+ " total = 0\n",
254
+ "\n",
255
+ " with torch.no_grad():\n",
256
+ " for X_batch, y_batch in test_loader:\n",
257
+ " # Move data to device\n",
258
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
259
+ " y_batch = y_batch.to(device)\n",
260
+ "\n",
261
+ " # Forward pass\n",
262
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
263
+ " loss = criterion(outputs, y_batch)\n",
264
+ " running_loss += loss.item()\n",
265
+ "\n",
266
+ " # Apply Softmax to get probabilities\n",
267
+ " probabilities = F.softmax(outputs, dim=1)\n",
268
+ "\n",
269
+ " # Multiclass predictions\n",
270
+ " predicted = torch.argmax(probabilities, dim=1)\n",
271
+ "\n",
272
+ " # Accuracy calculation\n",
273
+ " correct += (predicted == y_batch).sum().item()\n",
274
+ " total += y_batch.size(0)\n",
275
+ "\n",
276
+ " avg_loss = running_loss / len(test_loader)\n",
277
+ " accuracy = correct / total\n",
278
+ "\n",
279
+ " return avg_loss, accuracy\n"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "metadata": {},
287
+ "source": [
288
+ "# Task 4: Define device, model, loss, optimizer:\n",
289
+ "# Device setup\n",
290
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
291
+ "\n",
292
+ "# Model parameters\n",
293
+ "input_dim = 28 * 28 # MNIST images flattened\n",
294
+ "hidden_dim = 14 # Design choice\n",
295
+ "output_dim = 10 # Digits 0–9\n",
296
+ "\n",
297
+ "# Instantiate model\n",
298
+ "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
299
+ "\n",
300
+ "# Print the model architecture\n",
301
+ "print(\"Model Architecture:\\n\")\n",
302
+ "print(model)\n",
303
+ "\n",
304
+ "# Calculate the total number of trainable parameters\n",
305
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
306
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
307
+ "\n",
308
+ "\n",
309
+ "num_epochs = 20\n",
310
+ "learning_rate = 0.001\n",
311
+ "\n",
312
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
313
+ "criterion = nn.CrossEntropyLoss()\n",
314
+ "# Define optimizer\n",
315
+ "optimizer = Adam(model.parameters(), learning_rate)\n"
316
+ ],
317
+ "execution_count": null,
318
+ "outputs": []
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "metadata": {},
323
+ "source": [
324
+ "# Task 5: Start training for 20 epochs:\n",
325
+ "# Run Training\n",
326
+ "train_losses = []\n",
327
+ "val_losses = []\n",
328
+ "val_accuracies = []\n",
329
+ "\n",
330
+ "print('Starting Training...')\n",
331
+ "for epoch in range(num_epochs):\n",
332
+ " # Train one epoch\n",
333
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
334
+ "\n",
335
+ " # Validate\n",
336
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
337
+ "\n",
338
+ " train_losses.append(train_loss)\n",
339
+ " val_losses.append(val_loss)\n",
340
+ " val_accuracies.append(val_accuracy)\n",
341
+ "\n",
342
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
343
+ "\n",
344
+ "print('Training Complete!')"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ },
349
+ {
350
+ "cell_type": "code",
351
+ "metadata": {},
352
+ "source": [
353
+ "# Task 1: Write your code here:\n",
354
+ "# Plotting results\n",
355
+ "plt.figure(figsize=(7, 5))\n",
356
+ "\n",
357
+ "plt.plot(train_losses, label='Train Loss')\n",
358
+ "plt.plot(val_losses, label='Validation Loss')\n",
359
+ "plt.title('Loss over Epochs')\n",
360
+ "plt.xlabel('Epoch')\n",
361
+ "plt.ylabel('Loss')\n",
362
+ "plt.legend()\n",
363
+ "\n",
364
+ "plt.tight_layout()\n",
365
+ "plt.show()"
366
+ ],
367
+ "execution_count": null,
368
+ "outputs": []
369
+ },
370
+ {
371
+ "cell_type": "code",
372
+ "metadata": {},
373
+ "source": [
374
+ "# Task 2 (Bonus): Write your code here:"
375
+ ],
376
+ "execution_count": null,
377
+ "outputs": []
378
+ }
379
+ ],
380
+ "metadata": {
381
+ "kernelspec": {
382
+ "display_name": "Python 3",
383
+ "name": "python3"
384
+ },
385
+ "language_info": {
386
+ "name": "python"
387
+ }
388
+ },
389
+ "nbformat": 4,
390
+ "nbformat_minor": 0
391
+ }
submissions_extracted/150/Q3.ipynb ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)\n",
18
+ "\n"
19
+ ],
20
+ "execution_count": null,
21
+ "outputs": []
22
+ },
23
+ {
24
+ "cell_type": "code",
25
+ "metadata": {},
26
+ "source": [
27
+ "from IPython.display import clear_output\n",
28
+ "\n",
29
+ "%pip install catboost -q\n",
30
+ "\n",
31
+ "clear_output()"
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
+ "import pandas as pd\n",
42
+ "import matplotlib.pyplot as plt\n",
43
+ "import os\n",
44
+ "\n",
45
+ "q3 = os.path.join(path, 'Q3_data.csv')\n",
46
+ "df = pd.read_csv(q3)"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 2: Write your code here:\n",
56
+ "df.head()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 3: Write your code here:\n",
66
+ "df.info()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 4: Write your code here:\n",
76
+ "df.describe()"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 1: Write your code here:\n",
86
+ "def check_missing_values(df):\n",
87
+ " missing_values = df.isnull().sum()\n",
88
+ " print(\"Missing Values per Column:\")\n",
89
+ " print(missing_values[missing_values > 0])\n",
90
+ " if missing_values.any():\n",
91
+ " print(\"\\nHandle Missing Values as needed.\")\n",
92
+ "\n",
93
+ " else:\n",
94
+ " print(\"\\nNo Missing Values Found.\")\n",
95
+ "\n",
96
+ "check_missing_values(df)"
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
+ "print(\"Checking for duplicate rows...\")\n",
107
+ "duplicate_rows = df.duplicated().sum()\n",
108
+ "if duplicate_rows > 0:\n",
109
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
110
+ " df.drop_duplicates(inplace=True)\n",
111
+ " print(\"Duplicate rows removed.\")\n",
112
+ "else:\n",
113
+ " print(\"No duplicate rows found.\")"
114
+ ],
115
+ "execution_count": null,
116
+ "outputs": []
117
+ },
118
+ {
119
+ "cell_type": "code",
120
+ "metadata": {},
121
+ "source": [
122
+ "# Task 3: Write your code here:\n",
123
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
124
+ "\n",
125
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
126
+ "\n"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# Task 4: Write your code here:\n",
136
+ "from sklearn.preprocessing import StandardScaler\n",
137
+ "\n",
138
+ "features = df.columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
139
+ "\n",
140
+ "scaler = StandardScaler()\n",
141
+ "df[features] = scaler.fit_transform(df[features])\n",
142
+ "df.head()"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 5: Write your code here:\n",
152
+ "import seaborn as sns\n",
153
+ "def check_target_imbalance(df, target_column):\n",
154
+ " print(\"Target Distribution:\")\n",
155
+ " print(df[target_column].value_counts(normalize=True))\n",
156
+ " sns.countplot(x=df[target_column])\n",
157
+ " plt.title(\"Target Distribution\")\n",
158
+ " plt.show()\n",
159
+ "\n",
160
+ "check_target_imbalance(df, \"Target\")"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task 1: Write your code here:\n",
170
+ "# Define features (X) and target (y)\n",
171
+ "\n",
172
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
173
+ "y = df['Target'].astype(float)"
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
+ "import numpy as np\n",
184
+ "from catboost import CatBoostClassifier\n",
185
+ "from sklearn.model_selection import StratifiedKFold\n",
186
+ "from sklearn.metrics import accuracy_score, f1_score\n",
187
+ "\n",
188
+ "\n",
189
+ "n_splits = 5 # K=5 Folds\n",
190
+ "\n",
191
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
192
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
193
+ "from sklearn.model_selection import StratifiedKFold\n",
194
+ "\n",
195
+ "# Use previously generated random classification data\n",
196
+ "X, y = X.copy(), y.copy()\n",
197
+ "\n",
198
+ "# Show full dataset class distribution\n",
199
+ "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
200
+ "print(\"Full Dataset Class Distribution\")\n",
201
+ "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
202
+ "print(\"-\" * 40)\n",
203
+ "\n",
204
+ "# Define Stratified K-Fold\n",
205
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
206
+ "\n",
207
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
208
+ "\n",
209
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
210
+ " # indexing for each fold\n",
211
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
212
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
213
+ "\n",
214
+ " print(f\"Fold {fold}\")\n",
215
+ " print(\" X_train shape:\", X_train.shape)\n",
216
+ " print(\" X_test shape :\", X_test.shape)\n",
217
+ " print(\" y_train shape:\", y_train.shape)\n",
218
+ " print(\" y_test shape :\", y_test.shape)\n",
219
+ "\n",
220
+ " # showing class distribution\n",
221
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
222
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
223
+ "\n",
224
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
225
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
226
+ "\n",
227
+ " print(\"-\" * 40)\n",
228
+ "\n",
229
+ "model = CatBoostClassifier(verbose=0,\n",
230
+ " n_estimators=200,\n",
231
+ " max_depth=4) # instantiate\n",
232
+ "model.fit(X_train, y_train) # fit\n",
233
+ "y_pred = model.predict(X_test) # predict\n",
234
+ "\n",
235
+ "# Calculate metric\n",
236
+ "\n",
237
+ "accuracy = accuracy_score(y_test, y_pred)\n",
238
+ "f1 = f1_score(y_test, y_pred, average='macro')\n",
239
+ "\n",
240
+ "print(accuracy)\n",
241
+ "\n",
242
+ "print(f1)\n",
243
+ "\n",
244
+ "print(f\" Accuracy: {np.mean(accuracy):.4f}\")\n",
245
+ "print(f\" F1-Score: {np.mean(f1):.4f}\")\n",
246
+ "\n",
247
+ "\n",
248
+ "\n",
249
+ "\n"
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
+ "# Feature importance\n",
260
+ "importance = pd.DataFrame({\n",
261
+ " 'feature': X_train ,\n",
262
+ " 'importance': model.feature_importances_\n",
263
+ "}).sort_values('importance', ascending=False)\n",
264
+ "\n",
265
+ "plt.figure(figsize=(10, 6))\n",
266
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
267
+ "plt.xlabel('Importance')\n",
268
+ "plt.title('Feature Importance')\n",
269
+ "plt.gca().invert_yaxis()\n",
270
+ "plt.show()"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "metadata": {},
278
+ "source": [
279
+ "# Task 2: Write your code here:\n"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "metadata": {},
287
+ "source": [
288
+ "# Task Bonus: Write your code here:"
289
+ ],
290
+ "execution_count": null,
291
+ "outputs": []
292
+ }
293
+ ],
294
+ "metadata": {
295
+ "kernelspec": {
296
+ "display_name": "Python 3",
297
+ "name": "python3"
298
+ },
299
+ "language_info": {
300
+ "name": "python"
301
+ }
302
+ },
303
+ "nbformat": 4,
304
+ "nbformat_minor": 0
305
+ }
submissions_extracted/151/Q1.ipynb ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestClassifier\n",
16
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
23
+ "\n",
24
+ "print(\"Path to dataset files:\", path)"
25
+ ],
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "source": [
33
+ "# Task 1: Write your code here:\n",
34
+ "\n",
35
+ "Q1_path = os.path.join(path, 'Q1_data.csv')\n",
36
+ "df_Q1 = pd.read_csv(Q1_path)\n",
37
+ "\n"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "print(f\"Shape: {df_Q1.shape}\")\n",
48
+ "df_Q1.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_Q1.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_Q1.describe()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 5: Write your code here:\n",
78
+ "plt.figure(figsize=(10, 5))\n",
79
+ "plt.hist(df_Q1['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
80
+ "plt.title('Delivery Time Distribution')\n",
81
+ "plt.xlabel('Distance')\n",
82
+ "plt.ylabel('Prep time')\n",
83
+ "plt.show()"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 1: Write your code here:\n",
93
+ "df_Q1.drop(\"Order_ID\", axis=1)"
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
+ "print(\"Missing values:\")\n",
104
+ "print(df_Q1.isnull().sum())\n",
105
+ "\n",
106
+ "df_Q1['Order_ID'] = df_Q1['Order_ID'].fillna('none')\n",
107
+ "df_Q1['Distance_km'] = df_Q1['Distance_km'].fillna('none')\n",
108
+ "df_Q1['Vehicle_Type'] = df_Q1['Vehicle_Type'].fillna('none')\n",
109
+ "df_Q1['Preparation_Time_min'] = df_Q1['Preparation_Time_min'].fillna('none')"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 3: Write your code here:\n",
119
+ "print(\"Checking for duplicates...\")\n",
120
+ "dups = df_Q1.duplicated().sum()\n",
121
+ "if dups > 0:\n",
122
+ " print(f\"Found {dups} duplicates. Removing them...\")\n",
123
+ " df_Q1.drop_duplicates(inplace=True)\n",
124
+ " print(\"Duplicates removed.\")\n",
125
+ "else:\n",
126
+ " print(\"No duplicates found.\")"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# Task 4: Write your code here:\n",
136
+ "categorical_cols = ['Weather', 'Time_of_Day', 'Vehicle_Type', 'Traffic_Level']\n",
137
+ "for col in categorical_cols:\n",
138
+ " le = LabelEncoder()\n",
139
+ " df_Q1[col] = le.fit_transform(df_Q1[col].astype(str))"
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
+ "scaler = StandardScaler()\n",
150
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
151
+ "X_test_scaled = scaler.transform(X_test)\n",
152
+ "\n",
153
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
154
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)\n"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 6: Write your code here:"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 1: Write your code here:"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 2,3,4,5: Write your code here:"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 1: Write your code here:"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task 2: Write your code here:"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "# Task Bonus: Write your code here:"
209
+ ],
210
+ "execution_count": null,
211
+ "outputs": []
212
+ }
213
+ ],
214
+ "metadata": {
215
+ "kernelspec": {
216
+ "display_name": "Python 3",
217
+ "name": "python3"
218
+ },
219
+ "language_info": {
220
+ "name": "python"
221
+ }
222
+ },
223
+ "nbformat": 4,
224
+ "nbformat_minor": 0
225
+ }
submissions_extracted/151/Q2.ipynb ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "from PIL import Image\n",
24
+ "from sklearn.model_selection import train_test_split\n",
25
+ "\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
+ "# 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
+ "\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
+ "\n",
95
+ "train_dataset = TensorDataset(X_train, y_train)\n",
96
+ "test_dataset = TensorDataset(X_test, y_test)\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# 3. Create DataLoaders\n",
106
+ "\n",
107
+ "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
+ "sample_image, sample_label = train_dataset[0]\n",
119
+ "print(f\"Image shape: {sample_image.shape}\")\n",
120
+ "print(f\"Label: {sample_label}\")\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# 5. Display sample images\n",
130
+ "images, labels = next(iter(train_loader))\n",
131
+ "\n",
132
+ "plt.figure(figsize=(8, 4))\n",
133
+ "\n",
134
+ "for i in range(6):\n",
135
+ " plt.subplot(2, 3, i + 1)\n",
136
+ "\n",
137
+ " img = images[i].permute(1, 2, 0)\n",
138
+ "\n",
139
+ " plt.imshow(img)\n",
140
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
141
+ " plt.axis('off')\n",
142
+ "\n",
143
+ "plt.tight_layout()\n",
144
+ "plt.show()\n"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 1: Write your model class here:\n",
154
+ "\n",
155
+ "class NN4Layer(nn.Module):\n",
156
+ "\n",
157
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
158
+ " super(NN4Layer, self).__init__()\n",
159
+ "\n",
160
+ "\n",
161
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
162
+ "\n",
163
+ "\n",
164
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
165
+ "\n",
166
+ "\n",
167
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
168
+ "\n",
169
+ "\n",
170
+ " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
171
+ "\n",
172
+ "\n",
173
+ "\n",
174
+ " self.relu = nn.ReLU()\n",
175
+ "\n",
176
+ "\n",
177
+ " def forward(self, x):\n",
178
+ "\n",
179
+ " z1 = self.layer1(x)\n",
180
+ " a1 = self.relu(z1)\n",
181
+ "\n",
182
+ "\n",
183
+ " z2 = self.layer2(a1)\n",
184
+ " a2 = self.relu(z2)\n",
185
+ "\n",
186
+ "\n",
187
+ " z3 = self.layer3(a2)\n",
188
+ " a3 = self.relu(z3)\n",
189
+ "\n",
190
+ "\n",
191
+ " z4 = self.layer4(a3)\n",
192
+ "\n",
193
+ "\n",
194
+ " return z4"
195
+ ],
196
+ "execution_count": null,
197
+ "outputs": []
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "metadata": {},
202
+ "source": [
203
+ "# Task 2: Write your training loop here:\n",
204
+ "\n",
205
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
206
+ "\n",
207
+ " model.train()\n",
208
+ "\n",
209
+ " running_loss = 0.0\n",
210
+ "\n",
211
+ " for X_batch, y_batch in train_loader:\n",
212
+ "\n",
213
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
214
+ " y_batch = y_batch.to(device)\n",
215
+ "\n",
216
+ "\n",
217
+ " outputs = model(X_batch)\n",
218
+ "\n",
219
+ " loss = criterion(outputs, y_batch)\n",
220
+ "\n",
221
+ "\n",
222
+ " optimizer.zero_grad()\n",
223
+ " loss.backward()\n",
224
+ " optimizer.step()\n",
225
+ "\n",
226
+ " running_loss += loss.item()\n",
227
+ "\n",
228
+ " avg_loss = running_loss / len(train_loader)\n",
229
+ "\n",
230
+ " return avg_loss"
231
+ ],
232
+ "execution_count": null,
233
+ "outputs": []
234
+ },
235
+ {
236
+ "cell_type": "code",
237
+ "metadata": {},
238
+ "source": [
239
+ "# Task 3: Write your validation loop here:\n",
240
+ "def validate(model, criterion, test_loader, device):\n",
241
+ "\n",
242
+ " model.eval()\n",
243
+ "\n",
244
+ " running_loss = 0.0\n",
245
+ " correct = 0\n",
246
+ " total = 0\n",
247
+ "\n",
248
+ " with torch.no_grad():\n",
249
+ " for X_batch, y_batch in test_loader:\n",
250
+ "\n",
251
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
252
+ " y_batch = y_batch.to(device)\n",
253
+ "\n",
254
+ "\n",
255
+ " outputs = model(X_batch)\n",
256
+ "\n",
257
+ " loss = criterion(outputs, y_batch)\n",
258
+ " running_loss += loss.item()\n",
259
+ "\n",
260
+ "\n",
261
+ " probabilities = F.softmax(outputs, dim=1)\n",
262
+ "\n",
263
+ "\n",
264
+ " predicted = torch.argmax(probabilities, dim=1)\n",
265
+ "\n",
266
+ "\n",
267
+ " correct += (predicted == y_batch).sum().item()\n",
268
+ " total += y_batch.size(0)\n",
269
+ "\n",
270
+ " avg_loss = running_loss / len(test_loader)\n",
271
+ "\n",
272
+ " accuracy = correct / total\n",
273
+ "\n",
274
+ " return avg_loss, accuracy"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 4: Define device, model, loss, optimizer:\n",
284
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
285
+ "\n",
286
+ "input_dim = 3 * 36 * 36 #3 * 32 * 32\n",
287
+ "\n",
288
+ "\n",
289
+ "hidden_dim = 64\n",
290
+ "\n",
291
+ "\n",
292
+ "output_dim = 10\n",
293
+ "\n",
294
+ "\n",
295
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
296
+ "\n",
297
+ "\n",
298
+ "print(\"Model Architecture:\\n\")\n",
299
+ "print(model)\n",
300
+ "\n",
301
+ "\n",
302
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
303
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
304
+ "\n",
305
+ "\n",
306
+ "learning_rate = 0.001\n",
307
+ "\n",
308
+ "\n",
309
+ "criterion = nn.CrossEntropyLoss()\n",
310
+ "\n",
311
+ "optimizer = AdamW(model.parameters(), learning_rate)"
312
+ ],
313
+ "execution_count": null,
314
+ "outputs": []
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "metadata": {},
319
+ "source": [
320
+ "# Task 5: Start training for 20 epochs:\n",
321
+ "\n",
322
+ "num_epochs = 20\n",
323
+ "\n",
324
+ "train_losses = []\n",
325
+ "val_losses = []\n",
326
+ "val_accuracies = []\n",
327
+ "\n",
328
+ "print('Starting Training...')\n",
329
+ "for epoch in range(num_epochs):\n",
330
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
331
+ "\n",
332
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
333
+ "\n",
334
+ " train_losses.append(train_loss)\n",
335
+ " val_losses.append(val_loss)\n",
336
+ " val_accuracies.append(val_accuracy)\n",
337
+ "\n",
338
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
339
+ "\n",
340
+ "print('Training Complete!')\n"
341
+ ],
342
+ "execution_count": null,
343
+ "outputs": []
344
+ },
345
+ {
346
+ "cell_type": "code",
347
+ "metadata": {},
348
+ "source": [
349
+ "# Task 1: Write your code here:\n",
350
+ "plt.figure(figsize=(7, 5))\n",
351
+ "\n",
352
+ "plt.plot(train_losses, label='Train Loss')\n",
353
+ "plt.plot(val_losses, label='Validation Loss')\n",
354
+ "plt.title('Loss over Epochs')\n",
355
+ "plt.xlabel('Epoch')\n",
356
+ "plt.ylabel('Loss')\n",
357
+ "plt.legend()\n",
358
+ "\n",
359
+ "plt.tight_layout()\n",
360
+ "plt.show()"
361
+ ],
362
+ "execution_count": null,
363
+ "outputs": []
364
+ },
365
+ {
366
+ "cell_type": "code",
367
+ "metadata": {},
368
+ "source": [
369
+ "# Task 2 (Bonus): Write your code here:"
370
+ ],
371
+ "execution_count": null,
372
+ "outputs": []
373
+ }
374
+ ],
375
+ "metadata": {
376
+ "kernelspec": {
377
+ "display_name": "Python 3",
378
+ "name": "python3"
379
+ },
380
+ "language_info": {
381
+ "name": "python"
382
+ }
383
+ },
384
+ "nbformat": 4,
385
+ "nbformat_minor": 0
386
+ }
submissions_extracted/151/Q3.ipynb ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "import numpy as np\n",
11
+ "import pandas as pd\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "import os\n",
14
+ "import kagglehub\n",
15
+ "\n",
16
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
17
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
18
+ "from sklearn.ensemble import RandomForestClassifier\n",
19
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
20
+ "\n",
21
+ "import warnings\n",
22
+ "warnings.filterwarnings('ignore')\n",
23
+ "\n",
24
+ "\n",
25
+ "# Download latest version\n",
26
+ "\n",
27
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
28
+ "\n",
29
+ "\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
+ "Q3_path = os.path.join(path, 'Q3_data.csv')\n",
42
+ "df_Q3 = pd.read_csv(Q3_path)"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "print(f\"Shape: {df_Q3.shape}\")\n",
53
+ "df_Q3.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_Q3.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_Q3.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
+ "print(\"Missing values:\")\n",
84
+ "print(df_Q3.isnull().sum())\n",
85
+ "\n",
86
+ "df_Q3['D_39'] = df_Q3['D_39'].fillna('none')\n",
87
+ "df_Q3['B_1'] = df_Q3['B_1'].fillna('none')\n",
88
+ "df_Q3['R_1'] = df_Q3['R_1'].fillna('none')\n",
89
+ "df_Q3['Target'] = df_Q3['Target'].fillna('none')"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# Task 2: Write your code here:\n",
99
+ "print(\"Checking for duplicates...\")\n",
100
+ "dups = df_Q3.duplicated().sum()\n",
101
+ "if dups > 0:\n",
102
+ " print(f\"Found {dups} duplicates. Removing them...\")\n",
103
+ " df_Q3.drop_duplicates(inplace=True)\n",
104
+ " print(\"Duplicates removed.\")\n",
105
+ "else:\n",
106
+ " print(\"No duplicates found.\")"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# Task 3: Write your code here:\n",
116
+ "categorical_cols = ['', '', '', '']\n",
117
+ "for col in categorical_cols:\n",
118
+ " le = LabelEncoder()\n",
119
+ " df_Q3[col] = le.fit_transform(df_Q3[col].astype(str))"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 4: Write your code here:"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 5: Write your code here:"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# Task 1: Write your code here:"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Task 2,3,4,5: Write your code here:"
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: Write your code here:"
174
+ ],
175
+ "execution_count": null,
176
+ "outputs": []
177
+ },
178
+ {
179
+ "cell_type": "code",
180
+ "metadata": {},
181
+ "source": [
182
+ "# Task Bonus: Write your code here:"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ }
187
+ ],
188
+ "metadata": {
189
+ "kernelspec": {
190
+ "display_name": "Python 3",
191
+ "name": "python3"
192
+ },
193
+ "language_info": {
194
+ "name": "python"
195
+ }
196
+ },
197
+ "nbformat": 4,
198
+ "nbformat_minor": 0
199
+ }
submissions_extracted/152/Q1.ipynb ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, KFold\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "import kagglehub\n",
29
+ "\n",
30
+ "# Download latest version\n",
31
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
32
+ "\n",
33
+ "print(\"Path to dataset files:\", path)"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 1: Write your code here:\n",
43
+ "#Read the dataset Q1_data.csv using read_csv()\n",
44
+ "\n",
45
+ "lap_path = os.path.join(path, 'Q1_data.csv')\n",
46
+ "df_food = pd.read_csv(lap_path)\n",
47
+ "\n",
48
+ "print(f\"Dataset shape: {df_food.shape}\")\n"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 2: Write your code here:\n",
58
+ "#Inspect the first few rows using head()\n",
59
+ "df_food.head()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 3: Write your code here:\n",
69
+ "#Display dataset information using info()\n",
70
+ "df_food.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
+ "#Show statistical description using describe()\n",
81
+ "df_food.describe()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 5: Write your code here:\n",
91
+ "#Plot the target distribution (delivery_time)\n",
92
+ "plt.figure(figsize=(10, 5))\n",
93
+ "plt.hist(df_food['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
94
+ "plt.title('target delivery_time Distribution')\n",
95
+ "plt.xlabel('delivery time')\n",
96
+ "plt.ylabel('Frequency')\n",
97
+ "plt.show()"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 1: Write your code here:\n",
107
+ "#Drop the 'Order_ID' column from the data\n",
108
+ "df_food.drop(columns=['Order_ID'])\n",
109
+ "df_food.columns"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 2: Write your code here:\n",
119
+ "#Handle missing values appropriately\n",
120
+ "# Fill categorical columns with 'unknown' - missing likely means \"not specified\"\n",
121
+ "for col in ['Weather', 'Traffic_Level', 'Time_of_Day']:\n",
122
+ " df_food[col] = df_food[col].fillna('unknown')\n",
123
+ "\n",
124
+ "# Fill cylinders with mode - discrete feature, mode is most representative\n",
125
+ "df_food['Courier_Experience_yrs'] = df_food['Courier_Experience_yrs'].fillna(df_food['Courier_Experience_yrs'].mode()[0])\n",
126
+ "#handle whith missing in label\n",
127
+ "df_food['Delivery_Time']=df_food['Delivery_Time'].fillna(df_food['Delivery_Time'].mode()[0])\n",
128
+ "print(\"Missing values remaining:\", df_food.isnull().sum().sum())"
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
+ "#Check and remove duplicates\n",
139
+ "# . Do we have duplicate samples?\n",
140
+ "def check_duplicates(df_food):\n",
141
+ " duplicates = df_food().duplicated().sum()\n",
142
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
143
+ " if duplicates > 0:\n",
144
+ " print(\"Dropping Duplicates...\")\n",
145
+ " df_food.drop_duplicates(inplace=True)\n",
146
+ " print(\"Duplicates Dropped.\")\n",
147
+ " else:\n",
148
+ " print(\"No Duplicate Samples Found.\")\n",
149
+ "\n",
150
+ "check_duplicates(df_food)"
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
+ "#Encode categorical variables\n",
161
+ "categorical_cols = df_food.select_dtypes(include=[\"object\"]).columns\n",
162
+ "\n",
163
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
164
+ "\n",
165
+ "label_encoders = {}\n",
166
+ "for col in categorical_cols:\n",
167
+ " le = LabelEncoder()\n",
168
+ " df_food[col] = le.fit_transform(df_food[col])\n",
169
+ " label_encoders[col] = le\n",
170
+ "df_food"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 5: Write your code here:\n",
180
+ "#Apply feature scaling for all features\n",
181
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
182
+ "num_cols = df_food.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\")# DON'T SCALE THE TARGET\n",
183
+ "\n",
184
+ "scaler = StandardScaler()\n",
185
+ "num_cols_scaled = scaler.fit_transform(df_food[num_cols])\n"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 6: Write your code here:\n",
195
+ "#Check for target imbalance and state if it is imbalanced or not\n",
196
+ "# Is the target imbalanced?\n",
197
+ "#it is regression so not eather balance or not\n"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 1: Write your code here:\n",
207
+ "# Train-test split (80% train, 20% test)\n",
208
+ "X = df_food.drop(\"Delivery_Time\", axis=1)\n",
209
+ "y = df_food['Delivery_Time']\n",
210
+ "\n",
211
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
212
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
213
+ "df_food.head()\n"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 2,3,4,5: Write your code here:\n",
223
+ "\n",
224
+ "from sklearn.model_selection import train_test_split, KFold\n",
225
+ "from sklearn.ensemble import RandomForestRegressor\n",
226
+ "#random forest model\n",
227
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
228
+ "model.fit(X_train, y_train)\n",
229
+ "print(\"Model trained!\")\n",
230
+ "# Predictions\n",
231
+ "y_pred = model.predict(X_test)\n",
232
+ "\n",
233
+ "#k-fold\n",
234
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
235
+ "\n",
236
+ "mae_scores = []\n",
237
+ "\n",
238
+ "for train_idx, val_idx in kfold.split(X_train):\n",
239
+ " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n",
240
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
241
+ "\n",
242
+ " # Train and predict\n",
243
+ " model.fit(X_fold_train, y_fold_train)\n",
244
+ " y_fold_pred = model.predict(X_fold_val)\n",
245
+ "\n",
246
+ "\n",
247
+ " # Calculate metrics\n",
248
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
249
+ "\n",
250
+ "mae_scores = np.array(mae_scores)\n",
251
+ "\n",
252
+ "print(f\"5-Fold CV Results:\")\n",
253
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
254
+ "\n",
255
+ "\n",
256
+ "mae = mean_absolute_error(y_test, y_pred)\n",
257
+ "\n",
258
+ "print(f\"MAE: ${mae:,.2f}\")\n"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 1: Write your code here:\n",
268
+ "# Feature importance\n",
269
+ "feature_cols=df_food[ 'Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
270
+ " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']\n",
271
+ "importance = pd.DataFrame({\n",
272
+ " 'feature': feature_cols,\n",
273
+ " 'importance': model.feature_importances_\n",
274
+ "}).sort_values('importance', ascending=False)\n",
275
+ "\n",
276
+ "plt.figure(figsize=(10, 6))\n",
277
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
278
+ "plt.xlabel('Importance')\n",
279
+ "plt.title('Feature Importance')\n",
280
+ "plt.gca().invert_yaxis()\n",
281
+ "plt.show()"
282
+ ],
283
+ "execution_count": null,
284
+ "outputs": []
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "metadata": {},
289
+ "source": [
290
+ "# Task 2: Write your code here:"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ },
295
+ {
296
+ "cell_type": "code",
297
+ "metadata": {},
298
+ "source": [
299
+ "# Task Bonus: Write your code here:"
300
+ ],
301
+ "execution_count": null,
302
+ "outputs": []
303
+ }
304
+ ],
305
+ "metadata": {
306
+ "kernelspec": {
307
+ "display_name": "Python 3",
308
+ "name": "python3"
309
+ },
310
+ "language_info": {
311
+ "name": "python"
312
+ }
313
+ },
314
+ "nbformat": 4,
315
+ "nbformat_minor": 0
316
+ }
submissions_extracted/152/Q2.ipynb ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import torch\n",
10
+ "import torch.nn as nn\n",
11
+ "from torch.optim import AdamW\n",
12
+ "import matplotlib.pyplot as plt\n",
13
+ "import torch.nn.functional as F\n",
14
+ "from torch.utils.data import DataLoader, TensorDataset\n",
15
+ "from sklearn.model_selection import train_test_split\n",
16
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder"
17
+ ],
18
+ "execution_count": null,
19
+ "outputs": []
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "metadata": {},
24
+ "source": [
25
+ "import kagglehub\n",
26
+ "\n",
27
+ "# Download latest version\n",
28
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
29
+ "\n",
30
+ "print(\"Path to dataset files:\", path)"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "import os\n",
40
+ "import pandas as pd\n",
41
+ "import numpy as np\n",
42
+ "from PIL import Image\n",
43
+ "from sklearn.model_selection import train_test_split\n",
44
+ "\n",
45
+ "# Load Labels\n",
46
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
47
+ "img_dir = os.path.join(path, \"images\")\n",
48
+ "\n",
49
+ "images = []\n",
50
+ "ages = []\n",
51
+ "\n",
52
+ "# Load Images and Resize\n",
53
+ "print(\"Loading images...\")\n",
54
+ "for index, row in labels_df.iterrows():\n",
55
+ " img_name = row.iloc[0]\n",
56
+ " age = row.iloc[1]\n",
57
+ " img_path = os.path.join(img_dir, img_name)\n",
58
+ "\n",
59
+ " if os.path.exists(img_path):\n",
60
+ " img = Image.open(img_path).convert('RGB')\n",
61
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
62
+ " images.append(img_array)\n",
63
+ " ages.append(age)\n",
64
+ "\n",
65
+ "X = np.array(images)\n",
66
+ "y = np.array(ages)\n",
67
+ "\n",
68
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
69
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
70
+ "\n",
71
+ "# Split Data\n",
72
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
73
+ "\n",
74
+ "print(f\"X_train shape: {X_train.shape}\")\n",
75
+ "print(f\"X_test shape: {X_test.shape}\")\n",
76
+ "print(f\"y_train shape: {y_train.shape}\")\n",
77
+ "print(f\"y_test shape: {y_test.shape}\")"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
87
+ "import torch\n",
88
+ "# transform to tensors\n",
89
+ "X_train = torch.tensor(X_train)\n",
90
+ "X_test = torch.tensor(X_test)\n",
91
+ "y_train = torch.tensor(y_train)\n",
92
+ "y_test = torch.tensor(y_test)\n"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 2. Create TensorDataset objects\n",
102
+ "\n",
103
+ "train_dataset = TensorDataset(X_train, y_train)\n",
104
+ "test_dataset = TensorDataset(X_test, y_test)\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 3. Create DataLoaders\n",
114
+ "# Create Dataloaders to train and test data in batches\n",
115
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
116
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
117
+ "\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
+ "print(\"Train dataset:\", len(train_dataset))\n",
129
+ "print(\"Test dataset:\", len(test_dataset))\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
+ "images, labels = next(iter(train_loader))\n",
143
+ "\n",
144
+ "# Display the first 6 images in the batch\n",
145
+ "plt.figure(figsize=(8, 4))\n",
146
+ "\n",
147
+ "for i in range(6):\n",
148
+ " plt.subplot(2, 3, i + 1)\n",
149
+ " # plt.imshow(images[i].squeeze(), cmap='gray')\n",
150
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
151
+ " plt.axis('off')\n",
152
+ "\n",
153
+ "plt.tight_layout()\n",
154
+ "plt.show()"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 1: Write your model class here:\n",
164
+ "class NN4Layer(nn.Module):\n",
165
+ "\n",
166
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
167
+ " super(NN4Layer, self).__init__()\n",
168
+ "\n",
169
+ " # First linear layer: input features -> hidden layer\n",
170
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
171
+ "\n",
172
+ " # Second linear layer: hidden layer -> hidden layer\n",
173
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
174
+ "\n",
175
+ " # Third linear layer: hidden layer -> hidden layer\n",
176
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
177
+ "\n",
178
+ " # Output layer: hidden layer -> number of classes (logits)\n",
179
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
180
+ "\n",
181
+ " # ReLU activation for non-linearity\n",
182
+ " self.relu = nn.ReLU()\n",
183
+ "\n",
184
+ " # Defines how input data flows through the network\n",
185
+ " def forward(self, x):\n",
186
+ " # First hidden layer\n",
187
+ " a1 = self.relu(self.layer1(x))\n",
188
+ "\n",
189
+ " # Second hidden layer\n",
190
+ " a2 = self.relu(self.layer2(a1))\n",
191
+ "\n",
192
+ " # Third hidden layer\n",
193
+ " a3 = self.relu(self.layer3(a2))\n",
194
+ "\n",
195
+ " # Output layer (raw scores / logits)\n",
196
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
197
+ "\n",
198
+ " return output\n"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 2: Write your training loop here:\n",
208
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
209
+ " # Set the model to training mode\n",
210
+ " model.train()\n",
211
+ "\n",
212
+ " running_loss = 0.0\n",
213
+ "\n",
214
+ " for X_batch, y_batch in train_loader:\n",
215
+ " # Move batch to the selected device\n",
216
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
217
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
218
+ "\n",
219
+ " # Forward pass (outputs are logits)\n",
220
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
221
+ " loss = criterion(outputs, y_batch)\n",
222
+ "\n",
223
+ " # Backward pass & optimization\n",
224
+ " optimizer.zero_grad() # Clear previous gradients\n",
225
+ " loss.backward() # Compute gradients\n",
226
+ " optimizer.step() # Update model parameters\n",
227
+ "\n",
228
+ " running_loss += loss.item()\n",
229
+ "\n",
230
+ " # Average loss over all batches\n",
231
+ " avg_loss = running_loss / len(train_loader)\n",
232
+ "\n",
233
+ " return avg_loss\n"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "metadata": {},
241
+ "source": [
242
+ "# Task 3: Write your validation loop here:\n",
243
+ "def validate(model, criterion, test_loader, device):\n",
244
+ " # Set the model to evaluation mode\n",
245
+ " model.eval()\n",
246
+ "\n",
247
+ " running_loss = 0.0\n",
248
+ " correct = 0\n",
249
+ " total = 0\n",
250
+ "\n",
251
+ " with torch.no_grad():\n",
252
+ " for X_batch, y_batch in test_loader:\n",
253
+ " # Move data to device\n",
254
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
255
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
256
+ "\n",
257
+ " # Forward pass\n",
258
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
259
+ " loss = criterion(outputs, y_batch)\n",
260
+ " running_loss += loss.item()\n",
261
+ "\n",
262
+ " # Apply Softmax to get probabilities\n",
263
+ " probabilities = F.softmax(outputs, dim=1)\n",
264
+ "\n",
265
+ " # Pick the classes with highest probabilities\n",
266
+ " predicted = torch.argmax(probabilities, dim=1)\n",
267
+ "\n",
268
+ " # Accuracy calculation\n",
269
+ " correct += (predicted == y_batch).sum().item()\n",
270
+ " total += y_batch.size(0)\n",
271
+ "\n",
272
+ " avg_loss = running_loss / len(test_loader)\n",
273
+ " accuracy = correct / total\n",
274
+ "\n",
275
+ " return avg_loss, accuracy"
276
+ ],
277
+ "execution_count": null,
278
+ "outputs": []
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "metadata": {},
283
+ "source": [
284
+ "# Task 4: Define device, model, loss, optimizer:\n",
285
+ "# Device setup\n",
286
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
287
+ "\n",
288
+ "# Model parameters\n",
289
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
290
+ "hidden_dim = 14 # Design choice\n",
291
+ "output_dim = 1 # only age\n",
292
+ "\n",
293
+ "# Instantiate model\n",
294
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
295
+ "\n",
296
+ "# Print the model architecture\n",
297
+ "print(\"Model Architecture:\\n\")\n",
298
+ "print(model)\n",
299
+ "\n",
300
+ "# Calculate the total number of trainable parameters\n",
301
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
302
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
303
+ ],
304
+ "execution_count": null,
305
+ "outputs": []
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "metadata": {},
310
+ "source": [
311
+ "# Task 5: Start training for 20 epochs:\n",
312
+ "from torch.optim import Adam\n",
313
+ "num_epochs = 20\n",
314
+ "learning_rate = 0.001\n",
315
+ "\n",
316
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
317
+ "criterion = nn.MSELoss()\n",
318
+ "# Define optimizer\n",
319
+ "optimizer = AdamW(model.parameters(), learning_rate)"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ },
324
+ {
325
+ "cell_type": "code",
326
+ "metadata": {},
327
+ "source": [
328
+ "# Task 1: Write your code here:\n",
329
+ "# Run Training\n",
330
+ "train_losses = []\n",
331
+ "val_losses = []\n",
332
+ "\n",
333
+ "print('Starting Training...')\n",
334
+ "for epoch in range(num_epochs):\n",
335
+ " # Train one epoch\n",
336
+ " train_losses = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
337
+ "\n",
338
+ " # Validate\n",
339
+ " val_loss = validate(model, criterion, test_loader, device)\n",
340
+ "\n",
341
+ " train_losses.append(train_losses)\n",
342
+ " val_losses.append(val_loss)\n",
343
+ "\n",
344
+ " if (epoch + 1) % 5 == 0:\n",
345
+ " print(\n",
346
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
347
+ " f'Train Loss: {train_losses:.4f}, '\n",
348
+ " f'Val Loss: {val_loss:.4f}'\n",
349
+ " )\n",
350
+ "\n",
351
+ "print('Training Complete!')\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:"
364
+ ],
365
+ "execution_count": null,
366
+ "outputs": []
367
+ }
368
+ ],
369
+ "metadata": {
370
+ "kernelspec": {
371
+ "display_name": "Python 3",
372
+ "name": "python3"
373
+ },
374
+ "language_info": {
375
+ "name": "python"
376
+ }
377
+ },
378
+ "nbformat": 4,
379
+ "nbformat_minor": 0
380
+ }
submissions_extracted/152/Q3.ipynb ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, KFold\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "import kagglehub\n",
29
+ "\n",
30
+ "\n",
31
+ "\n",
32
+ "# Download latest version\n",
33
+ "\n",
34
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
35
+ "\n",
36
+ "\n",
37
+ "\n",
38
+ "print(\"Path to dataset files:\", path)"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 1: Write your code here:\n",
48
+ "lap_path = os.path.join(path, 'Q3_data.csv')\n",
49
+ "df = pd.read_csv(lap_path)\n",
50
+ "\n",
51
+ "print(f\"Dataset shape: {df.shape}\")"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 2: Write your code here:\n",
61
+ "df.head()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 3: Write your code here:\n",
71
+ "df.info()"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 4: Write your code here:\n",
81
+ "df.describe()"
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
+ "def check_missing_values(df):\n",
92
+ " missing_values = df.isnull().sum()\n",
93
+ " print(\"Missing Values per Column:\")\n",
94
+ " print(missing_values[missing_values > 0])\n",
95
+ " if missing_values.any():\n",
96
+ " print(\"\\nHandle Missing Values as needed.\")\n",
97
+ " else:\n",
98
+ " print(\"\\nNo Missing Values Found.\")\n",
99
+ "\n",
100
+ "check_missing_values(df)\n",
101
+ "\n",
102
+ "df[col] = df[col].fillna(df[col].mode()[0])"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# Task 2: Write your code here:\n",
112
+ "def check_duplicates(df):\n",
113
+ " duplicates = df.duplicated().sum()\n",
114
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
115
+ " if duplicates > 0:\n",
116
+ " print(\"Dropping Duplicates...\")\n",
117
+ " df.drop_duplicates(inplace=True)\n",
118
+ " print(\"Duplicates Dropped.\")\n",
119
+ " else:\n",
120
+ " print(\"No Duplicate Samples Found.\")\n",
121
+ "\n",
122
+ "check_duplicates(df)"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# Task 3: Write your code here:\n",
132
+ "# 2. Do we have missing values?no\n",
133
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
134
+ "\n",
135
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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
+ "#Apply feature scaling for all features\n",
146
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
147
+ "num_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")# DON'T SCALE THE TARGET\n",
148
+ "\n",
149
+ "scaler = StandardScaler()\n",
150
+ "num_cols_scaled = scaler.fit_transform(df[num_cols])"
151
+ ],
152
+ "execution_count": null,
153
+ "outputs": []
154
+ },
155
+ {
156
+ "cell_type": "code",
157
+ "metadata": {},
158
+ "source": [
159
+ "# Task 5: Write your code here:"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 1: Write your code here:\n",
169
+ "X = df.drop(\"Target\", axis=1)\n",
170
+ "y = df['Target']\n",
171
+ "\n",
172
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
173
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")"
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
+ "from catboost import CatBoostClassifier\n",
184
+ "model= CatBoostClassifier(\n",
185
+ " verbose=0,\n",
186
+ " n_estimators=320,\n",
187
+ " max_depth=4)\n",
188
+ "n_splits = 5 # K\n",
189
+ "r_results = {'loss': [], 'acc': [], 'f1': []}\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
+ " # Train using gradient descent with learning rate = 0.5\n",
200
+ " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n",
201
+ "\n",
202
+ " # Calculate z & class probabilities for X_test\n",
203
+ " z = np.dot(X_test, theta)\n",
204
+ " y_pred_proba = softmax(z)\n",
205
+ "\n",
206
+ " # Pick the predicted classes with the highest probability\n",
207
+ " y_pred = np.argmax(y_pred_proba, axis=1)\n",
208
+ "\n",
209
+ " # Calculate evaluation metrics\n",
210
+ " accuracy = accuracy_score(y_test, y_pred)\n",
211
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
212
+ "\n",
213
+ " # Store results\n",
214
+ " sr_results['loss'].append(losses)\n",
215
+ " sr_results['acc'].append(accuracy)\n",
216
+ " sr_results['f1'].append(f1)"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "# Task 1: Write your code here:"
226
+ ],
227
+ "execution_count": null,
228
+ "outputs": []
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "# Task 2: Write your code here:"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task Bonus: Write your code here:"
244
+ ],
245
+ "execution_count": null,
246
+ "outputs": []
247
+ }
248
+ ],
249
+ "metadata": {
250
+ "kernelspec": {
251
+ "display_name": "Python 3",
252
+ "name": "python3"
253
+ },
254
+ "language_info": {
255
+ "name": "python"
256
+ }
257
+ },
258
+ "nbformat": 4,
259
+ "nbformat_minor": 0
260
+ }
submissions_extracted/153/Q1.ipynb ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 seaborn as sns\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestClassifier\n",
16
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n"
20
+ ],
21
+ "execution_count": null,
22
+ "outputs": []
23
+ },
24
+ {
25
+ "cell_type": "code",
26
+ "metadata": {},
27
+ "source": [
28
+ "import kagglehub\n",
29
+ "\n",
30
+ "# Download latest version\n",
31
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
32
+ "\n",
33
+ "print(\"Path to dataset files:\", path)"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 1: Write your code here:\n",
43
+ "Q1_data = pd.read_csv(path + \"/Q1_data.csv\")"
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
+ "Q1_data.head(20)"
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
+ "Q1_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
+ "Q1_data.describe()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 5: Write your code here:\n",
83
+ "plt.figure(figsize=(10, 5))\n",
84
+ "plt.hist(Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
85
+ "plt.title('Delivery Time Distribution')\n",
86
+ "plt.xlabel('Delivery Time')\n",
87
+ "plt.ylabel('Frequency')\n",
88
+ "plt.show()"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# Task 1: Write your code here:\n",
98
+ "Q1_data = Q1_data.drop('Order_ID', axis=1)"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# Task 2: Write your code here:\n",
108
+ "print(\"Missing values:\")\n",
109
+ "print(Q1_data.isnull().sum())\n",
110
+ "\n",
111
+ "missing_percentage = (Q1_data.isnull().sum() / len(Q1_data)) * 100\n",
112
+ "missing_data = pd.DataFrame({\n",
113
+ " 'Column': missing_percentage.index,\n",
114
+ " 'Missing_Percentage': missing_percentage.values\n",
115
+ "})\n",
116
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
117
+ "\n",
118
+ "print(\"Missing Data Analysis:\")\n",
119
+ "missing_data.head(10)"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "\n",
129
+ "Q1_data = Q1_data.fillna({'Weather': 'Unknown', 'Traffic_Level': 'Unknown', 'Time_of_Day': 'Unknown'})\n",
130
+ "print(\"\\n2. Fill with constant:\")\n",
131
+ "print(Q1_data)\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "Q1_data = Q1_data.dropna()\n",
141
+ "print(\"\\n1. After dropna():\", len(Q1_data), \"rows\")\n"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "print(\"Missing values:\")\n",
151
+ "print(Q1_data.isnull().sum())"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "Q1_data.info()\n",
161
+ "#success :)"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 3: Write your code here:\n",
171
+ "print(\"Checking for duplicate rows...\")\n",
172
+ "duplicate_rows = Q1_data.duplicated().sum()\n",
173
+ "if duplicate_rows > 0:\n",
174
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
175
+ " Q1_data.drop_duplicates(inplace=True)\n",
176
+ " print(\"Duplicate rows removed.\")\n",
177
+ "else:\n",
178
+ " print(\"No duplicate rows found.\")"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 4: Write your code here:\n",
188
+ "from sklearn.preprocessing import LabelEncoder\n",
189
+ "categorical_cols = ['Weather', 'Traffic_Level','Time_of_Day', 'Vehicle_Type']\n",
190
+ "for col in categorical_cols:\n",
191
+ " le = LabelEncoder()\n",
192
+ " Q1_data[col] = le.fit_transform(Q1_data[col].astype(str))\n",
193
+ "\n",
194
+ "Q1_data.head()\n"
195
+ ],
196
+ "execution_count": null,
197
+ "outputs": []
198
+ },
199
+ {
200
+ "cell_type": "code",
201
+ "metadata": {},
202
+ "source": [
203
+ "# Task 5: Write your code here:\n",
204
+ "\n",
205
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
206
+ "\n",
207
+ "print('data before scaling:\\n', Q1_data) #show before scaling\n",
208
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
209
+ "data_standard_scaled = standard_scaler.fit_transform(Q1_data) # Apply fit_transform\n",
210
+ "\n",
211
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task 6: Write your code here:"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "metadata": {},
228
+ "source": [
229
+ "# Task 1: Write your code here:\n",
230
+ "target_column = \"Delivery_Time\"\n",
231
+ "X = Q1_data.drop(target_column, axis=1)\n",
232
+ "y = Q1_data[target_column]\n",
233
+ "\n",
234
+ "print(\"\\nDataset Shapes\")\n",
235
+ "print(\"X:\", X.shape)\n",
236
+ "print(\"y:\", y.shape)"
237
+ ],
238
+ "execution_count": null,
239
+ "outputs": []
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "metadata": {},
244
+ "source": [
245
+ "# Task 2,3,4,5: Write your code here:\n",
246
+ "from sklearn.ensemble import RandomForestRegressor\n",
247
+ "from sklearn.metrics import mean_absolute_error, r2_score\n",
248
+ "X_scaled = standard_scaler.fit_transform(X)\n",
249
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
250
+ "\n",
251
+ "mse_scores = []\n",
252
+ "mae_scores = []\n",
253
+ "\n",
254
+ "for train_idx, test_idx in kf.split(X_scaled):\n",
255
+ " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n",
256
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
257
+ "\n",
258
+ "model = RandomForestRegressor(n_estimators=100,\n",
259
+ "random_state=42)\n",
260
+ "model.fit(X_train, y_train)\n",
261
+ "y_pred = model.predict(X_test)\n",
262
+ "mae = mean_absolute_error(y_test, y_pred)\n",
263
+ "r2 = r2_score(y_test, y_pred)"
264
+ ],
265
+ "execution_count": null,
266
+ "outputs": []
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "metadata": {},
271
+ "source": [
272
+ "# Print Evaluation Metrics\n",
273
+ "print(\"\\nModel Evaluation Metrics (K-Fold)\\n\" + \"-\"*5)\n",
274
+ "print(f\"MAE : {np.mean(mae):.2f}\")\n"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "# Task 1: Write your code here:\n",
284
+ "feature_importance = pd.DataFrame({\n",
285
+ "'feature': X_train.columns,\n",
286
+ "'importance': model.feature_importances_\n",
287
+ "}).sort_values('importance', ascending=False)\n",
288
+ "plt.figure(figsize=(12, 8))\n",
289
+ "plt.barh(feature_importance['feature'][:15],\n",
290
+ "feature_importance['importance'][:15])\n",
291
+ "plt.gca().invert_yaxis()\n",
292
+ "plt.title('Top 15 Feature Importances')\n",
293
+ "plt.xlabel('Importance Score')\n",
294
+ "plt.tight_layout()\n",
295
+ "plt.show()"
296
+ ],
297
+ "execution_count": null,
298
+ "outputs": []
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "metadata": {},
303
+ "source": [
304
+ "# Task 2: Write your code here:\n",
305
+ "plt.figure(figsize=(12, 5))\n",
306
+ "# Subplot 1: Actual vs Predicted scatter\n",
307
+ "plt.subplot(1, 2, 1)\n",
308
+ "plt.scatter(y_valid, y_pred, alpha=0.5, s=10)\n",
309
+ "plt.plot([y_valid.min(), y_valid.max()], [y_valid.min(),\n",
310
+ "y_valid.max()], 'r--', lw=2)\n",
311
+ "plt.xlabel('Actual Emissions')\n",
312
+ "plt.ylabel('Predicted Emissions')\n",
313
+ "plt.title('Actual vs Predicted Emissions')\n",
314
+ "plt.grid(True, alpha=0.3)\n",
315
+ "# Subplot 2: Histogram of predictions\n",
316
+ "plt.subplot(1, 2, 2)\n",
317
+ "plt.hist(y_pred, bins=50, alpha=0.7, label='Predicted',\n",
318
+ "color='orange', edgecolor='black')\n",
319
+ "plt.hist(y_valid, bins=50, alpha=0.5, label='Actual',\n",
320
+ "color='blue', edgecolor='black')\n",
321
+ "plt.xlabel('Emission Value')\n",
322
+ "plt.ylabel('Frequency')\n",
323
+ "plt.title('Distribution: Actual vs Predicted')\n",
324
+ "plt.legend()\n",
325
+ "plt.grid(True, alpha=0.3)\n",
326
+ "plt.tight_layout()\n",
327
+ "plt.show()"
328
+ ],
329
+ "execution_count": null,
330
+ "outputs": []
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "metadata": {},
335
+ "source": [
336
+ "# Task Bonus: Write your code here:"
337
+ ],
338
+ "execution_count": null,
339
+ "outputs": []
340
+ }
341
+ ],
342
+ "metadata": {
343
+ "kernelspec": {
344
+ "display_name": "Python 3",
345
+ "name": "python3"
346
+ },
347
+ "language_info": {
348
+ "name": "python"
349
+ }
350
+ },
351
+ "nbformat": 4,
352
+ "nbformat_minor": 0
353
+ }
submissions_extracted/153/Q2.ipynb ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import torch\n",
8
+ "import torch.nn as nn\n",
9
+ "from torch.optim import Adam"
10
+ ],
11
+ "execution_count": null,
12
+ "outputs": []
13
+ },
14
+ {
15
+ "cell_type": "code",
16
+ "metadata": {},
17
+ "source": [
18
+ "import matplotlib.pyplot as plt\n",
19
+ "from torch.utils.data import DataLoader, TensorDataset\n",
20
+ "from sklearn.model_selection import train_test_split\n",
21
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
22
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "import kagglehub\n",
32
+ "\n",
33
+ "# Download latest version\n",
34
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
35
+ "\n",
36
+ "print(\"Path to dataset files:\", path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "import os\n",
46
+ "import pandas as pd\n",
47
+ "import numpy as np\n",
48
+ "from PIL import Image\n",
49
+ "from sklearn.model_selection import train_test_split\n",
50
+ "\n",
51
+ "# Load Labels\n",
52
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
53
+ "img_dir = os.path.join(path, \"images\")\n",
54
+ "\n",
55
+ "images = []\n",
56
+ "ages = []\n",
57
+ "\n",
58
+ "# Load Images and Resize\n",
59
+ "print(\"Loading images...\")\n",
60
+ "for index, row in labels_df.iterrows():\n",
61
+ " img_name = row.iloc[0]\n",
62
+ " age = row.iloc[1]\n",
63
+ " img_path = os.path.join(img_dir, img_name)\n",
64
+ "\n",
65
+ " if os.path.exists(img_path):\n",
66
+ " img = Image.open(img_path).convert('RGB')\n",
67
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
68
+ " images.append(img_array)\n",
69
+ " ages.append(age)\n",
70
+ "\n",
71
+ "X = np.array(images)\n",
72
+ "y = np.array(ages)\n",
73
+ "\n",
74
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
75
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
76
+ "\n",
77
+ "# Split Data\n",
78
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
79
+ "\n",
80
+ "print(f\"X_train shape: {X_train.shape}\")\n",
81
+ "print(f\"X_test shape: {X_test.shape}\")\n",
82
+ "print(f\"y_train shape: {y_train.shape}\")\n",
83
+ "print(f\"y_test shape: {y_test.shape}\")"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
93
+ "train_dataset = TensorDataset(X_train, y_train)\n",
94
+ "test_dataset = TensorDataset(X_test, y_test)\n"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# 2. Create TensorDataset objects\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
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
116
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# 4. Print shape of one batch\n",
126
+ "X_batch, y_batch = next(iter(train_loader))\n",
127
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
128
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# 5. Display sample images\n",
138
+ "\n"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 1: Write your model class here:\n",
148
+ "class NN3Layer(nn.Module):\n",
149
+ "\n",
150
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
151
+ " super(NN3Layer, self).__init__()\n",
152
+ "\n",
153
+ " # First linear layer: input features -> hidden layer\n",
154
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
155
+ "\n",
156
+ " # Second linear layer: hidden layer -> hidden layer\n",
157
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
158
+ "\n",
159
+ " # Third linear layer: hidden layer -> hidden layer\n",
160
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
161
+ "\n",
162
+ " # Output layer: hidden layer -> number of classes (logits)\n",
163
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
164
+ "\n",
165
+ " # ReLU activation for non-linearity\n",
166
+ " self.relu = nn.ReLU()\n",
167
+ "\n",
168
+ " # Defines how input data flows through the network\n",
169
+ " def forward(self, x):\n",
170
+ " # First hidden layer\n",
171
+ " z1 = self.layer1(x)\n",
172
+ " a1 = self.relu(z1)\n",
173
+ "\n",
174
+ " # Second hidden layer\n",
175
+ " z2 = self.layer2(a1)\n",
176
+ " a2 = self.relu(z2)\n",
177
+ "\n",
178
+ " # Output layer (raw scores / logits)\n",
179
+ " output = self.layer3(a2) # there is something missing here, remember? :)\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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
192
+ " # Set the model to training mode\n",
193
+ " model.train()\n",
194
+ "\n",
195
+ " running_loss = 0.0\n",
196
+ "\n",
197
+ " for X_batch, y_batch in train_loader:\n",
198
+ " # Move batch to the selected device\n",
199
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
200
+ " y_batch = y_batch.to(device)\n",
201
+ "\n",
202
+ " # Forward pass\n",
203
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
204
+ " loss = criterion(outputs, y_batch)\n",
205
+ "\n",
206
+ " # Backward pass & optimization\n",
207
+ " optimizer.zero_grad() # Clear previous gradients\n",
208
+ " loss.backward() # Compute gradients\n",
209
+ " optimizer.step() # Update model parameters\n",
210
+ "\n",
211
+ " running_loss += loss.item()\n",
212
+ "\n",
213
+ " # Average loss over all batches\n",
214
+ " avg_loss = running_loss / len(train_loader)\n",
215
+ "\n",
216
+ " return avg_loss"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "# Task 3: Write your validation loop here:\n",
226
+ "def validate(model, criterion, test_loader, device):\n",
227
+ " # Set the model to evaluation mode\n",
228
+ " model.eval()\n",
229
+ "\n",
230
+ " running_loss = 0.0\n",
231
+ " correct = 0\n",
232
+ " total = 0\n",
233
+ "\n",
234
+ " with torch.no_grad():\n",
235
+ " for X_batch, y_batch in test_loader:\n",
236
+ " # Move data to device\n",
237
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
238
+ " y_batch = y_batch.to(device)\n",
239
+ "\n",
240
+ " # Forward pass\n",
241
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
242
+ " loss = criterion(outputs, y_batch)\n",
243
+ " running_loss += loss.item()\n",
244
+ "\n",
245
+ " # Apply Softmax to get probabilities\n",
246
+ " probabilities = F.softmax(outputs, dim=1)\n",
247
+ "\n",
248
+ " # Multiclass predictions\n",
249
+ " predicted = torch.argmax(probabilities, dim=1)\n",
250
+ "\n",
251
+ " # Accuracy calculation\n",
252
+ " correct += (predicted == y_batch).sum().item()\n",
253
+ " total += y_batch.size(0)\n",
254
+ "\n",
255
+ " avg_loss = running_loss / len(test_loader)\n",
256
+ " accuracy = correct / total\n",
257
+ "\n",
258
+ " return avg_loss, accuracy"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 4: Define device, model, loss, optimizer:\n",
268
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
269
+ "\n",
270
+ "input_dim = 28 * 28 # MNIST images flattened\n",
271
+ "hidden_dim = 14 # Design choice\n",
272
+ "output_dim = 10 # Digits 0–9\n",
273
+ "\n",
274
+ "# Instantiate model\n",
275
+ "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
276
+ "\n",
277
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
278
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
279
+ "\n",
280
+ "num_epochs = 20\n",
281
+ "learning_rate = 0.001\n",
282
+ "\n",
283
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
284
+ "criterion = nn.CrossEntropyLoss()\n",
285
+ "# Define optimizer\n",
286
+ "optimizer = Adam(model.parameters(), learning_rate)"
287
+ ],
288
+ "execution_count": null,
289
+ "outputs": []
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "metadata": {},
294
+ "source": [
295
+ "# Task 5: Start training for 20 epochs:\n",
296
+ "train_losses = []\n",
297
+ "val_losses = []\n",
298
+ "val_accuracies = []\n",
299
+ "\n",
300
+ "print('Starting Training...')\n",
301
+ "for epoch in range(num_epochs):\n",
302
+ " # Train one epoch\n",
303
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
304
+ "\n",
305
+ " # Validate\n",
306
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
307
+ "\n",
308
+ " train_losses.append(train_loss)\n",
309
+ " val_losses.append(val_loss)\n",
310
+ " val_accuracies.append(val_accuracy)\n",
311
+ "\n",
312
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
313
+ "\n",
314
+ "print('Training Complete!')"
315
+ ],
316
+ "execution_count": null,
317
+ "outputs": []
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "metadata": {},
322
+ "source": [
323
+ "# Task 1: Write your code here:\n",
324
+ "plt.figure(figsize=(7, 5))\n",
325
+ "\n",
326
+ "plt.plot(train_losses, label='Train Loss')\n",
327
+ "plt.plot(val_losses, label='Validation Loss')\n",
328
+ "plt.title('Loss over Epochs')\n",
329
+ "plt.xlabel('Epoch')\n",
330
+ "plt.ylabel('Loss')\n",
331
+ "plt.legend()\n",
332
+ "\n",
333
+ "plt.tight_layout()\n",
334
+ "plt.show()"
335
+ ],
336
+ "execution_count": null,
337
+ "outputs": []
338
+ },
339
+ {
340
+ "cell_type": "code",
341
+ "metadata": {},
342
+ "source": [
343
+ "# Task 2 (Bonus): Write your code here:"
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/153/Q3.ipynb ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import seaborn as sns\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestClassifier\n",
16
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n"
17
+ ],
18
+ "execution_count": null,
19
+ "outputs": []
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "metadata": {},
24
+ "source": [
25
+ "import kagglehub\n",
26
+ "\n",
27
+ "\n",
28
+ "\n",
29
+ "# Download latest version\n",
30
+ "\n",
31
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
32
+ "\n",
33
+ "\n",
34
+ "\n",
35
+ "print(\"Path to dataset files:\", path)"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 1: Write your code here:\n",
45
+ "Q3_data = pd.read_csv(path + \"/Q3_data.csv\")"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 2: Write your code here:\n",
55
+ "Q3_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
+ "Q3_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
+ "Q3_data.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
+ "print(\"\\nMissing values before handling:\")\n",
86
+ "print(Q3_data.isnull().sum())\n",
87
+ "\n",
88
+ "missing_percentage = (Q3_data.isnull().sum() / len(Q3_data)) * 100\n",
89
+ "missing_data = pd.DataFrame({\n",
90
+ " 'Column': missing_percentage.index,\n",
91
+ " 'Missing_Percentage': missing_percentage.values\n",
92
+ "})\n",
93
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
94
+ "\n",
95
+ "print(\"Missing Data Analysis:\")\n",
96
+ "missing_data.head(10)\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "\n",
106
+ "# Strategy 2: Fill with constant\n",
107
+ "Q3_data = Q3_data.fillna('0')\n",
108
+ "print(\"\\n2. Fill:\")\n",
109
+ "print(Q3_data)\n",
110
+ "\n",
111
+ "# When to use each:\n",
112
+ "# dropna(): <5% missing, random pattern\n",
113
+ "# fillna('Unknown'): Categorical, 'missing' has meaning\n",
114
+ "# fillna(mean/median): Numerical, <20% missing\n",
115
+ "# fillna(mode): Categorical, <30% missing\n",
116
+ "# Imputation (advanced): >30% missing, pattern exists"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 2: Write your code here:\n",
126
+ "print(\"Checking for duplicate rows...\")\n",
127
+ "duplicate_rows = Q3_data.duplicated().sum()\n",
128
+ "if duplicate_rows > 0:\n",
129
+ " print(f\"Found {duplicate_rows} duplicate rows. Removing them...\")\n",
130
+ " Q3_data.drop_duplicates(inplace=True)\n",
131
+ " print(\"Duplicate rows removed.\")\n",
132
+ "else:\n",
133
+ " print(\"No duplicate rows found.\")"
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
+ "#no need"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 4: Write your code here:\n",
153
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
154
+ "\n",
155
+ "print('data before scaling:\\n', Q3_data) #show before scaling\n",
156
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
157
+ "data_standard_scaled = standard_scaler.fit_transform(Q3_data) # Apply fit_transform\n",
158
+ "\n",
159
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 5: Write your code here:"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 1: Write your code here:"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 2,3,4,5: Write your code here:\n",
187
+ "from sklearn.model_selection import KFold\n",
188
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
189
+ "df['category_target_encoded'] = 0\n",
190
+ "\n",
191
+ "for train_idx, val_idx in kf.split(df):\n",
192
+ " train_df = df.iloc[train_idx]\n",
193
+ " val_df = df.iloc[val_idx]"
194
+ ],
195
+ "execution_count": null,
196
+ "outputs": []
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "metadata": {},
201
+ "source": [
202
+ "# Task 1: Write your code here:"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 2: Write your code here:"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task Bonus: Write your code here:"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ }
225
+ ],
226
+ "metadata": {
227
+ "kernelspec": {
228
+ "display_name": "Python 3",
229
+ "name": "python3"
230
+ },
231
+ "language_info": {
232
+ "name": "python"
233
+ }
234
+ },
235
+ "nbformat": 4,
236
+ "nbformat_minor": 0
237
+ }
submissions_extracted/154/Q1.ipynb ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# @title\n",
8
+ "#Implementing all the necessary libraries\n",
9
+ "import numpy as np\n",
10
+ "import pandas as pd\n",
11
+ "import matplotlib.pyplot as plt\n",
12
+ "import kagglehub\n",
13
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
14
+ "from sklearn.model_selection import KFold\n",
15
+ "from sklearn.linear_model import LinearRegression\n",
16
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
17
+ "\n"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# @title\n",
27
+ "import kagglehub\n",
28
+ "\n",
29
+ "# Download latest version\n",
30
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
31
+ "\n",
32
+ "print(\"Path to dataset files:\", path)\n",
33
+ "\n"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# @title\n",
43
+ "# Task 1:\n",
44
+ "df = pd.read_csv(f\"{path}/Q1_data.csv\")"
45
+ ],
46
+ "execution_count": null,
47
+ "outputs": []
48
+ },
49
+ {
50
+ "cell_type": "code",
51
+ "metadata": {},
52
+ "source": [
53
+ "# @title\n",
54
+ "# Task 2:\n",
55
+ "df.head()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 3:\n",
65
+ "df.info()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 4:\n",
75
+ "df.describe()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 5:\n",
85
+ "plt.figure(figsize=(10, 5))\n",
86
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
87
+ "plt.title('Delivery Time')\n",
88
+ "plt.xlabel('Time')\n",
89
+ "plt.ylabel('Frequency')\n",
90
+ "plt.show()\n"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# Task 1:\n",
100
+ "df.drop(columns=['Order_ID'], inplace=True)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 2:\n",
110
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
111
+ "missing_data = pd.DataFrame({\n",
112
+ " 'Column': missing_percentage.index,\n",
113
+ " 'Missing_Percentage': missing_percentage.values\n",
114
+ "})\n",
115
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
116
+ "\n",
117
+ "print(\"Missing Data Analysis:\")\n",
118
+ "print(missing_data)\n",
119
+ "\n",
120
+ "# Dropping rows with missing values if they are few\n",
121
+ "df.dropna(inplace=True)"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 3:\n",
131
+ "df.drop_duplicates(inplace=True)"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4:\n",
141
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
142
+ "# Identify categorical columns\n",
143
+ "categorical_cols = df.select_dtypes(include=['object']).columns.tolist()\n",
144
+ "for col in categorical_cols:\n",
145
+ " le = LabelEncoder()\n",
146
+ " df[col] = le.fit_transform(df[col].astype(str))\n",
147
+ "\n",
148
+ "df"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5:\n",
158
+ "scaler = StandardScaler()\n",
159
+ "df[df.columns] = scaler.fit_transform(df)"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 6: Write your code here:\n",
169
+ "import seaborn as sns\n",
170
+ "# Checking for target imbalance\n",
171
+ "delivery_time_counts = df['Delivery_Time'].value_counts()\n",
172
+ "plt.figure(figsize=(10, 5))\n",
173
+ "sns.histplot(delivery_time_counts, bins=30)\n",
174
+ "plt.title('Target Variable Distribution')\n",
175
+ "plt.xlabel('Delivery Time (minutes)')\n",
176
+ "plt.ylabel('Frequency')\n",
177
+ "plt.show()"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 1:\n",
187
+ "X = df.drop(columns=['Delivery_Time'])\n",
188
+ "y = df['Delivery_Time']"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "# Task 2,3,4,5:\n",
198
+ "from sklearn.model_selection import KFold\n",
199
+ "from sklearn.ensemble import RandomForestRegressor\n",
200
+ "from sklearn.metrics import mean_absolute_error\n",
201
+ "\n",
202
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
203
+ "mae_scores = []\n",
204
+ "\n",
205
+ "for train_index, test_index in kf.split(X):\n",
206
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
207
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
208
+ "\n",
209
+ " model = RandomForestRegressor(random_state=42)\n",
210
+ " model.fit(X_train, y_train)\n",
211
+ " predictions = model.predict(X_test)\n",
212
+ "\n",
213
+ " mae = mean_absolute_error(y_test, predictions)\n",
214
+ " mae_scores.append(mae)\n",
215
+ "\n",
216
+ "average_mae = np.mean(mae_scores)\n",
217
+ "print(f'Average MAE across folds: {average_mae}')\n"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 1:\n",
227
+ "#Average feature importance across folds\n",
228
+ "importances = model.feature_importances_\n",
229
+ "features = X.columns\n",
230
+ "indices = np.argsort(importances)[::-1]\n",
231
+ "\n",
232
+ "plt.figure(figsize=(12, 6))\n",
233
+ "plt.title('Feature Importances')\n",
234
+ "plt.bar(range(X.shape[1]), importances[indices], align='center')\n",
235
+ "plt.xticks(range(X.shape[1]), features[indices], rotation=90)\n",
236
+ "plt.xlim([-1, X.shape[1]])\n",
237
+ "plt.show()"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task 2:\n",
247
+ "predictions = model.predict(X)\n",
248
+ "plt.figure(figsize=(10, 5))\n",
249
+ "plt.hist(predictions, bins=50, edgecolor='black')\n",
250
+ "plt.title('Predicted Delivery Time Distribution')\n",
251
+ "plt.xlabel('Predicted Time (minutes)')\n",
252
+ "plt.ylabel('Frequency')\n",
253
+ "plt.show()"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "%pip install catboost"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {},
270
+ "source": [
271
+ "# Task Bonus: Write your code here:\n",
272
+ "from catboost import CatBoostRegressor\n",
273
+ "\n",
274
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
275
+ "mae_scores = []\n",
276
+ "\n",
277
+ "for train_index, test_index in kf.split(X):\n",
278
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
279
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
280
+ "\n",
281
+ " rf_model = RandomForestRegressor(random_state=42)\n",
282
+ " cb_model = CatBoostRegressor(verbose=0)\n",
283
+ "\n",
284
+ " rf_model.fit(X_train, y_train) #Training RandomForest Model\n",
285
+ " cb_model.fit(X_train, y_train) #Training CatBoost Model\n",
286
+ "\n",
287
+ " rf_predictions = rf_model.predict(X_test)\n",
288
+ " cb_predictions = cb_model.predict(X_test)\n",
289
+ "\n",
290
+ " # Average predictions\n",
291
+ " avg_predictions = (rf_predictions + cb_predictions) / 2\n",
292
+ "\n",
293
+ " mae = mean_absolute_error(y_test, avg_predictions)\n",
294
+ " mae_scores.append(mae)\n",
295
+ "\n",
296
+ "average_mae = np.mean(mae_scores)\n",
297
+ "print(f'Average MAE across folds with ensemble: {average_mae}')\n"
298
+ ],
299
+ "execution_count": null,
300
+ "outputs": []
301
+ }
302
+ ],
303
+ "metadata": {
304
+ "kernelspec": {
305
+ "display_name": "Python 3",
306
+ "name": "python3"
307
+ },
308
+ "language_info": {
309
+ "name": "python"
310
+ }
311
+ },
312
+ "nbformat": 4,
313
+ "nbformat_minor": 0
314
+ }
submissions_extracted/154/Q2.ipynb ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "from torch.utils.data import TensorDataset, DataLoader\n",
71
+ "\n",
72
+ "# Convert Numpy arrays to PyTorch Tensors\n",
73
+ "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
74
+ "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
75
+ "y_train_tensor = torch.tensor(y_train, dtype=torch.float32).view(-1, 1)\n",
76
+ "y_test_tensor = torch.tensor(y_test, dtype=torch.float32).view(-1, 1)"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# 2. Create TensorDataset objects\n",
86
+ "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
87
+ "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# 3. Create DataLoaders\n",
97
+ "batch_size =32\n",
98
+ "train_loader = DataLoader(train_dataset, batch_size=batch_size , shuffle=True)\n",
99
+ "test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# 4. Print shape of one batch\n",
109
+ "X_batch, y_batch = next(iter(train_loader))\n",
110
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
111
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# 5. Display sample images\n",
121
+ "import matplotlib.pyplot as plt\n",
122
+ "\n",
123
+ "# Function to display a few images\n",
124
+ "def show_sample_images(images):\n",
125
+ " fig, axes = plt.subplots(1, 5, figsize=(15, 5))\n",
126
+ " for i in range(5):\n",
127
+ " axes[i].imshow(images[i].permute(1, 2, 0).numpy())\n",
128
+ " axes[i].axis('off')\n",
129
+ " plt.show()\n",
130
+ "\n",
131
+ "# Display sample images\n",
132
+ "show_sample_images(X_train_tensor[:5])\n",
133
+ "\n"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# Task 1: Write your model class here:\n",
143
+ "import torch.nn as nn\n",
144
+ "\n",
145
+ "class AgePredictionModel(nn.Module):\n",
146
+ " def __init__(self):\n",
147
+ " super(AgePredictionModel, self).__init__()\n",
148
+ " self.flatten = nn.Flatten()\n",
149
+ " self.fc1 = nn.Linear(3888, 512) # no first dim seems to work but 3888 , to be able to mat multiply even though it gives ridiculous outputs\n",
150
+ " self.fc2 = nn.Linear(512, 256)\n",
151
+ " self.fc3 = nn.Linear(256, 128)\n",
152
+ " self.fc4 = nn.Linear(128, 1)\n",
153
+ "\n",
154
+ " def forward(self, x):\n",
155
+ " x = self.flatten(x)\n",
156
+ " x = nn.ReLU()(self.fc1(x))\n",
157
+ " x = nn.ReLU()(self.fc2(x))\n",
158
+ " x = nn.ReLU()(self.fc3(x))\n",
159
+ " x = self.fc4(x)\n",
160
+ " return x"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task 2: Write your training loop here:\n",
170
+ "def train_model(model, train_loader, optimizer, criterion, epochs):\n",
171
+ " model.train()\n",
172
+ " for epoch in range(epochs):\n",
173
+ " for imgs, ages in train_loader:\n",
174
+ " optimizer.zero_grad()\n",
175
+ " outputs = model(imgs)\n",
176
+ " loss = criterion(outputs.squeeze(), ages)\n",
177
+ " loss.backward()\n",
178
+ " optimizer.step()\n",
179
+ " print(f'Epoch [{epoch+1}/{epochs}], Loss: {loss.item():.4f}')\n"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 3: Write your validation loop here:\n",
189
+ "def validate_model(model, test_loader, criterion):\n",
190
+ " model.eval()\n",
191
+ " val_loss = 0\n",
192
+ " with torch.no_grad():\n",
193
+ " for imgs, ages in test_loader:\n",
194
+ " outputs = model(imgs)\n",
195
+ " loss = criterion(outputs.squeeze(), ages)\n",
196
+ " val_loss += loss.item()\n",
197
+ " return val_loss / len(test_loader)\n"
198
+ ],
199
+ "execution_count": null,
200
+ "outputs": []
201
+ },
202
+ {
203
+ "cell_type": "code",
204
+ "metadata": {},
205
+ "source": [
206
+ "# Task 4: Define device, model, loss, optimizer:\n",
207
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
208
+ "model = AgePredictionModel().to(device)\n",
209
+ "criterion = nn.MSELoss()\n",
210
+ "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n"
211
+ ],
212
+ "execution_count": null,
213
+ "outputs": []
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "# Task 5: Start training for 20 epochs:\n",
220
+ "epochs = 20\n",
221
+ "for epoch in range(epochs):\n",
222
+ " train_model(model, train_loader, optimizer, criterion, epochs=1)\n",
223
+ " val_loss = validate_model(model, test_loader, criterion)\n",
224
+ " print(f'Validation Loss after Epoch {epoch + 1}: {val_loss:.4f}')\n"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Task 1: Write your code here:\n",
234
+ "# Create lists to store losses\n",
235
+ "train_losses = []\n",
236
+ "val_losses = []\n",
237
+ "\n",
238
+ "# Modify training loop to store losses\n",
239
+ "for epoch in range(epochs):\n",
240
+ " train_model(model, train_loader, optimizer, criterion, epochs=1)\n",
241
+ " val_loss = validate_model(model, test_loader, criterion)\n",
242
+ " val_losses.append(val_loss)\n",
243
+ " print(f'Validation Loss after Epoch {epoch + 1}: {val_loss:.4f}')\n",
244
+ "\n",
245
+ "# Plotting training and validation loss\n",
246
+ "plt.plot(range(1, epochs + 1), val_losses, label='Validation Loss')\n",
247
+ "plt.xlabel('Epochs')\n",
248
+ "plt.ylabel('Loss')\n",
249
+ "plt.title('Training and Validation Loss')\n",
250
+ "plt.legend()\n",
251
+ "plt.show()"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task 2 (Bonus): Write your code here:\n",
261
+ "def plot_predictions(model, test_loader, num_images=5):\n",
262
+ " model.eval()\n",
263
+ " with torch.no_grad():\n",
264
+ " imgs, ages = next(iter(test_loader))\n",
265
+ " outputs = model(imgs)\n",
266
+ "\n",
267
+ " fig, axes = plt.subplots(1, num_images, figsize=(15, 5))\n",
268
+ " for i in range(num_images):\n",
269
+ " axes[i].imshow(imgs[i].permute(1, 2, 0).numpy())\n",
270
+ " axes[i].set_title(f'Predicted Age: {outputs[i].item():.2f}\\nActual Age: {ages[i].item()}')\n",
271
+ " axes[i].axis('off')\n",
272
+ " plt.show()\n",
273
+ "\n",
274
+ "# Plot predictions\n",
275
+ "plot_predictions(model, test_loader)\n",
276
+ "\n",
277
+ "# I really tried :'("
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
+ "metadata": {
291
+ "kernelspec": {
292
+ "display_name": "Python 3",
293
+ "name": "python3"
294
+ },
295
+ "language_info": {
296
+ "name": "python"
297
+ }
298
+ },
299
+ "nbformat": 4,
300
+ "nbformat_minor": 0
301
+ }
submissions_extracted/154/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
+ "# Download latest version\n",
10
+ "\n",
11
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
12
+ "\n",
13
+ "print(\"Path to dataset files:\", path)"
14
+ ],
15
+ "execution_count": null,
16
+ "outputs": []
17
+ },
18
+ {
19
+ "cell_type": "code",
20
+ "metadata": {},
21
+ "source": [
22
+ "# Task 1: Write your code here:\n",
23
+ "import pandas as pd\n",
24
+ "\n",
25
+ "data = pd.read_csv(f\"{path}/Q3_data.csv\")"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "# Task 2: Write your code here:\n",
35
+ "data.head()"
36
+ ],
37
+ "execution_count": null,
38
+ "outputs": []
39
+ },
40
+ {
41
+ "cell_type": "code",
42
+ "metadata": {},
43
+ "source": [
44
+ "# Task 3: Write your code here:\n",
45
+ "data.info()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 4: Write your code here:\n",
55
+ "data.describe()"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 1: Write your code here:\n",
65
+ "print(data.isnull().sum())\n",
66
+ "data.fillna(data.median(), inplace=True) # filled null data with median"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 2: Write your code here:\n",
76
+ "duplicates = data.duplicated().sum()\n",
77
+ "print(f'Duplicates: {duplicates}')\n",
78
+ "data.drop_duplicates(inplace=True)"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# Task 3: Write your code here:\n",
88
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
89
+ "# Identify categorical columns\n",
90
+ "categorical_cols = data.select_dtypes(include=['object']).columns.tolist()\n",
91
+ "for col in categorical_cols:\n",
92
+ " le = LabelEncoder()\n",
93
+ " data[col] = le.fit_transform(data[col].astype(str))\n",
94
+ "\n",
95
+ "data"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "# Task 4: Write your code here:\n",
105
+ "scaler = StandardScaler()\n",
106
+ "numerical_cols = data.select_dtypes(include=['int64', 'float64']).columns.drop(\"Target\").tolist()\n",
107
+ "data[numerical_cols] = scaler.fit_transform(data[numerical_cols])"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# Task 5: Write your code here:\n",
117
+ "target_counts = data['Target'].value_counts()\n",
118
+ "print(target_counts)\n",
119
+ "print('Is the target imbalanced?', target_counts.min() / target_counts.max() < 0.1)\n"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "%pip install catboost"
129
+ ],
130
+ "execution_count": null,
131
+ "outputs": []
132
+ },
133
+ {
134
+ "cell_type": "code",
135
+ "metadata": {},
136
+ "source": [
137
+ "# Task 1: Write your code here:\n",
138
+ "from sklearn.model_selection import StratifiedKFold\n",
139
+ "from catboost import CatBoostClassifier\n",
140
+ "from sklearn.metrics import f1_score\n",
141
+ "\n",
142
+ "X = data.drop('Target', axis=1)\n",
143
+ "y = data['Target']\n"
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "# Task 2,3,4,5: Write your code here:\n",
153
+ "kfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
154
+ "f1_scores = []\n",
155
+ "\n",
156
+ "# Task 3 and 4: Train CatBoostClassifier and evaluate\n",
157
+ "for train_index, test_index in kfold.split(X, y):\n",
158
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
159
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
160
+ "\n",
161
+ " model = CatBoostClassifier(iterations=100, learning_rate=0.1, depth=6, silent=True)\n",
162
+ " model.fit(X_train, y_train)\n",
163
+ "\n",
164
+ " y_pred = model.predict(X_test)\n",
165
+ "\n",
166
+ " # Task 4: Evaluate using F1 Score\n",
167
+ " f1_scores.append(f1_score(y_test, y_pred))\n",
168
+ "\n",
169
+ "# Task 5: Print the averaged F1 score across all folds\n",
170
+ "print('Average F1 Score:', sum(f1_scores) / len(f1_scores))\n"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Task 1: Write your code here:\n",
180
+ "import matplotlib.pyplot as plt\n",
181
+ "\n",
182
+ "# Task 1: Plot feature importance from your trained model\n",
183
+ "feature_importances = model.get_feature_importance()\n",
184
+ "features = X.columns\n",
185
+ "\n",
186
+ "# Create a DataFrame for visualization\n",
187
+ "importance_df = pd.DataFrame({'Feature': features, 'Importance': feature_importances})\n",
188
+ "importance_df = importance_df.sort_values(by='Importance', ascending=False)\n",
189
+ "\n",
190
+ "# Plot\n",
191
+ "plt.figure(figsize=(12, 6))\n",
192
+ "plt.barh(importance_df['Feature'], importance_df['Importance'])\n",
193
+ "plt.xlabel('Importance')\n",
194
+ "plt.title('Feature Importance')\n",
195
+ "plt.show()"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Task 2: Write your code here:\n",
205
+ "golden_feature = importance_df.iloc[0]['Feature']\n",
206
+ "print('Golden Feature:', golden_feature)"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "#Task Bonus: Write your code here:\n",
216
+ "X_golden = X[[golden_feature]]\n",
217
+ "\n",
218
+ "#Run the same KFold loop with this single feature\n",
219
+ "f1_scores_golden = []\n",
220
+ "\n",
221
+ "for train_index, test_index in kfold.split(X_golden, y):\n",
222
+ " X_train, X_test = X_golden.iloc[train_index], X_golden.iloc[test_index]\n",
223
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
224
+ "\n",
225
+ " model_golden = CatBoostClassifier(iterations=100, learning_rate=0.1, depth=6, silent=True)\n",
226
+ " model_golden.fit(X_train, y_train)\n",
227
+ "\n",
228
+ " y_pred = model_golden.predict(X_test)\n",
229
+ " f1_scores_golden.append(f1_score(y_test, y_pred))\n",
230
+ "\n",
231
+ "#Print and compare the accuracy with the full model\n",
232
+ "print('Average F1 Score with Golden Feature:', sum(f1_scores_golden) / len(f1_scores_golden))\n"
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/155/Q1.ipynb ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "# Task 2: Write your code here:"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# Task 3: Write your code here:"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# Task 4: Write your code here:"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 5: Write your code here:"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 1: Write your code here:"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 2: Write your code here:"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 3: Write your code here:"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Task 4: Write your code here:"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Task 5: Write your code here:"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# Task 6: Write your code here:"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# Task 1: Write your code here:"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 2,3,4,5: Write your code here:"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 1: Write your code here:"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 2: Write your code here:"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task Bonus: Write your code here:"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ }
161
+ ],
162
+ "metadata": {
163
+ "kernelspec": {
164
+ "display_name": "Python 3",
165
+ "name": "python3"
166
+ },
167
+ "language_info": {
168
+ "name": "python"
169
+ }
170
+ },
171
+ "nbformat": 4,
172
+ "nbformat_minor": 0
173
+ }
submissions_extracted/155/Q2.ipynb ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "\n",
71
+ "# Create tensors\n",
72
+ "x = torch.tensor([1.0, 2.0, 3.0])\n",
73
+ "y = torch.randn(3)\n",
74
+ "print(\"x:\", x)\n",
75
+ "print(\"y:\", y)\n",
76
+ "\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
+ "a = torch.tensor([1.0, 2.0, 3.0])\n",
88
+ "b = torch.tensor([4.0, 5.0, 6.0])\n",
89
+ "\n",
90
+ "# Element-wise operations\n",
91
+ "print(\"Addition:\", a + b)\n",
92
+ "print(\"Multiplication:\", a * b)\n",
93
+ "\n",
94
+ "# Matrix multiplication\n",
95
+ "A = torch.randn(2, 3)\n",
96
+ "B = torch.randn(3, 2)\n",
97
+ "C = A @ B\n",
98
+ "\n",
99
+ "print(\"ANON_OWNER/q2-exam-data:\", C.shape)\n",
100
+ "\n",
101
+ "\n",
102
+ "\n"
103
+ ],
104
+ "execution_count": null,
105
+ "outputs": []
106
+ },
107
+ {
108
+ "cell_type": "code",
109
+ "metadata": {},
110
+ "source": [
111
+ "# 3. Create DataLoaders\n",
112
+ "from torch.utils.data import DataLoader\n",
113
+ "\n",
114
+ "train_loader = DataLoader(\n",
115
+ " train_dataset,\n",
116
+ " batch_size=32,\n",
117
+ " shuffle=True,\n",
118
+ " num_workers=2\n",
119
+ ")\n",
120
+ "test_loader = DataLoader(\n",
121
+ " test_dataset,\n",
122
+ " batch_size=32,\n",
123
+ " shuffle=False,\n",
124
+ " num_workers=2\n",
125
+ ")\n",
126
+ "\n",
127
+ "X_batch, y_batch = next(iter(train_loader))\n",
128
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
129
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n",
130
+ "\n",
131
+ "\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# 4. Print shape of one batch\n",
141
+ "print(\"Shape of x:\", x.shape)\n"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# 5. Display sample images\n",
151
+ "\n"
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
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
162
+ " # Set the model to training mode\n",
163
+ " model.train()\n",
164
+ "\n",
165
+ " running_loss = 0.0\n",
166
+ "\n",
167
+ " for X_batch, y_batch in train_loader:\n",
168
+ " # Move batch to the selected device\n",
169
+ " X_batch = X_batch.to(device)\n",
170
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
171
+ "\n",
172
+ " # Forward pass\n",
173
+ " outputs = model(X_batch)\n",
174
+ " loss = criterion(outputs, y_batch)\n",
175
+ "\n",
176
+ " # Backward pass & optimization\n",
177
+ " optimizer.zero_grad() # Clear previous gradients\n",
178
+ " loss.backward() # Compute gradients\n",
179
+ " optimizer.step() # Update model parameters\n",
180
+ "\n",
181
+ " running_loss += loss.item()\n",
182
+ "\n",
183
+ " # Average loss over all batches\n",
184
+ " avg_loss = running_loss / len(train_loader)\n",
185
+ "\n",
186
+ " return avg_loss"
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:\n",
196
+ "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)\n",
197
+ "criterion = nn.CrossEntropyLoss()\n",
198
+ "\n",
199
+ "# Loop\n",
200
+ "for epoch in range(10):\n",
201
+ " train_loss = train_step(model, train_loader, criterion, optimizer)\n",
202
+ " val_loss = validate_step(model, test_loader, criterion)\n",
203
+ " print(f\"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}\")"
204
+ ],
205
+ "execution_count": null,
206
+ "outputs": []
207
+ },
208
+ {
209
+ "cell_type": "code",
210
+ "metadata": {},
211
+ "source": [
212
+ "# Task 3: Write your validation loop here:\n",
213
+ "# Loop\n",
214
+ "for epoch in range(10):\n",
215
+ " train_loss = train_step(model, train_loader, criterion, optimizer)\n",
216
+ " val_loss = validate_step(model, test_loader, criterion)\n",
217
+ " print(f\"Epoch {epoch+1}: Train Loss={train_loss:.4f}, Val Loss={val_loss:.4f}\")"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 4: Define device, model, loss, optimizer:\n",
227
+ "class SimpleNN(nn.Module):\n",
228
+ " def __init__(self, input_dim, output_dim):\n",
229
+ " super(SimpleNN, self).__init__()\n",
230
+ " self.layer1 = nn.Linear(input_dim, 64)\n",
231
+ " self.output = nn.Linear(64, output_dim)\n",
232
+ " self.relu = nn.ReLU()\n",
233
+ "\n",
234
+ " def forward(self, x):\n",
235
+ " x = self.relu(self.layer1(x))\n",
236
+ " x = self.output(x)\n",
237
+ " return x"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task 5: Start training for 20 epochs:"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "# Task 1: Write your code here:\n",
256
+ "plt.figure(figsize=(7, 5))\n",
257
+ "\n",
258
+ "plt.plot(train_losses, label='Train Loss')\n",
259
+ "plt.plot(val_losses, label='Validation Loss')\n",
260
+ "plt.title('Loss over Epochs')\n",
261
+ "plt.xlabel('Epoch')\n",
262
+ "plt.ylabel('Loss')\n",
263
+ "plt.legend()\n",
264
+ "\n",
265
+ "plt.tight_layout()\n",
266
+ "plt.show()"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "# Task 2 (Bonus): Write your code here:\n",
276
+ "def validate(model, criterion, test_loader, device):\n",
277
+ "\n",
278
+ " model.eval()\n",
279
+ "\n",
280
+ " running_loss = 0.0\n",
281
+ " correct = 0\n",
282
+ " total = 0\n",
283
+ "\n",
284
+ " with torch.no_grad():\n",
285
+ " for X_batch, y_batch in test_loader:\n",
286
+ " X_batch = X_batch.to(device)\n",
287
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
288
+ "\n",
289
+ "\n",
290
+ " outputs = model(X_batch)\n",
291
+ " loss = criterion(outputs, y_batch)\n",
292
+ " running_loss += loss.item()\n",
293
+ "\n",
294
+ " predicted = (outputs > 0.5).float()\n",
295
+ "\n",
296
+ "\n",
297
+ " correct += (predicted == y_batch).sum().item()\n",
298
+ " total += y_batch.size(0)\n",
299
+ "\n",
300
+ " avg_loss = running_loss / len(test_loader)\n",
301
+ " accuracy = correct / total\n",
302
+ "\n",
303
+ " return avg_loss, accuracy\n"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ }
308
+ ],
309
+ "metadata": {
310
+ "kernelspec": {
311
+ "display_name": "Python 3",
312
+ "name": "python3"
313
+ },
314
+ "language_info": {
315
+ "name": "python"
316
+ }
317
+ },
318
+ "nbformat": 4,
319
+ "nbformat_minor": 0
320
+ }