ALLIA12 commited on
Commit
9a610eb
·
verified ·
1 Parent(s): 27acb67

Drop stray Jupyter checkpoint copies

Browse files
.ipynb_checkpoints/README-checkpoint.md DELETED
@@ -1,159 +0,0 @@
1
- # Introduction to AI — Practical Exam Grading Dataset (Stage 2)
2
-
3
- 1,038 anonymized student submissions to a university-level practical AI exam,
4
- each independently graded by **two** teaching assistants, plus the rubric and
5
- the instructor reference solutions.
6
-
7
- The 18 LLM grading runs measured on this data, the graders that produced them,
8
- and the analysis code all live in the project repository alongside the
9
- equivalent Computer Vision dataset; this folder is the data itself.
10
-
11
- The dataset was built to test how sensitive LLM graders are to the *prompt* they
12
- are given — specifically, what happens when an instructor adds a plausible
13
- "be strict" instruction to an otherwise well-behaved grading prompt.
14
-
15
- ## What is here
16
-
17
- | path | contents |
18
- |---|---|
19
- | `Practical_AI_exam_grades.csv` | ground truth: two TA grades per student, per question and total |
20
- | `submissions_extracted/<n>/Q{1,2,3}.ipynb` | the anonymized student notebooks |
21
- | `Solutions/` | instructor reference solution per question |
22
- | `stage_2_rubrics_ta.md` | the marking scheme the TAs graded against |
23
-
24
- Students are identified only by a number (1–1038) that is stable across every
25
- file. Notebook `submissions_extracted/7/Q2.ipynb` belongs to the student in row
26
- `Number == 7` of the grades CSV.
27
-
28
- ## The exam and its scale
29
-
30
- Three questions: **Q1** tabular regression (predict food delivery time),
31
- **Q2** PyTorch (predict age from face images), **Q3** classification (find the
32
- most predictive feature in an anonymized dataset).
33
-
34
- Marks come from the rubric's task tables, not its header totals — the two
35
- disagree in the distributed PDF, which is preserved here as `stage_2_rubrics_ta.md`:
36
-
37
- | question | base | bonus |
38
- |---|---|---|
39
- | Q1 Regression | 23 | 3 |
40
- | Q2 PyTorch | 14 | 3 |
41
- | Q3 Classification | 19 | 3 |
42
-
43
- Two instructor corrections were issued by email *during* grading, both affecting
44
- Q3 only (Part 1 dropped a task and became 2 marks; Part 4 dropped a task and
45
- became 5). Both are folded into the rubric file and marked ⚠.
46
-
47
- ## Ground truth quality
48
-
49
- Every student is graded by two TAs, so the dataset carries its own noise floor:
50
-
51
- | statistic | value |
52
- |---|---|
53
- | TA-vs-TA mean absolute difference (totals) | 5.13 |
54
- | **floor: \|TA − TA mean\|**, the quantity an AI grader is scored against | **2.57** (95% CI 2.41–2.74) |
55
- | inter-TA correlation (totals) | 0.871 |
56
-
57
- The floor is ~4% of the ~65-point scale. Any AI grader should be read against
58
- 2.57, not against zero.
59
-
60
- ## Anonymization
61
-
62
- Student names, ID numbers, emails, and submission links are absent. Notebooks
63
- were rebuilt from scratch keeping only code cells: markdown cells, outputs,
64
- execution counts, and all per-cell metadata were dropped, so Colab
65
- `executionInfo` blocks (which embed a Google account name and user id) do not
66
- survive. Remaining identifiers inside code — names in variable names or
67
- comments, emails, ID numbers, phone numbers, filesystem usernames — were
68
- replaced with `ANON` (identifier-safe) or `[REDACTED]`.
69
-
70
- Scrubbing was verified two ways: an exhaustive scan against the full roster
71
- (every student and TA name, email and ID, plus generic email/ID/phone patterns
72
- and notebook-format regressions), and an LLM review of all ~25k comment and
73
- string literals looking for identifiers the roster could not know about. The
74
- second pass is what caught a reference to an instructor by first name and one
75
- student who had loaded the exam data from a personal account.
76
-
77
- TAs appear only as pseudonyms (`TA_1`, `TA_2`, …). One slot carries the
78
- composite id `TA_49+TA_50`: those 18 students had Q1 and Q2 graded by one TA and
79
- Q3 by another. The pseudonym-to-person mapping is **not** published, so grading
80
- behaviour cannot be attributed to any individual.
81
-
82
- One deliberate difference between the released grader and the script that
83
- produced `results/`: the prompt's opening sentence named the institution and
84
- programme running the course, and reads *"an introductory AI practical exam"*
85
- here instead. That phrase is the only difference, and it changes no grading
86
- rule — but a run reproduced from this bundle sends a prompt one phrase
87
- different from the published one.
88
-
89
- ## Known gaps, stated plainly
90
-
91
- - 24 students from the original cohort are absent: they uploaded nothing, an
92
- unreadable archive, or files that were not the exam. The remaining 1,038 are
93
- numbered contiguously.
94
- - Roughly 96 students are missing a notebook for at least one question — they
95
- did not submit that question. An absent `Q<n>.ipynb` means exactly that, and
96
- the grading code scores it 0.
97
- - The rubric's header totals contradict its own task tables in all three
98
- questions. This is preserved rather than corrected; it is part of what a real
99
- grading prompt has to cope with.
100
- - A handful of TA grades exceed the rubric maximum for a question.
101
- - Two TA grades awarded credit for a question the student never submitted
102
- (8.0 and 10.0, each contradicted by the paired TA's 0). Both were set to 0
103
- and the totals recomputed: ground truth that credits work no grader can see
104
- would penalise every grader, human or machine.
105
-
106
- ## The LLM runs in `results/`
107
-
108
- Nine open-weights models, each run twice over the full cohort with an identical
109
- prompt except for one leading persona sentence:
110
-
111
- - **neutral** — "You are a strict but fair teaching assistant."
112
- - **strict** — "You are a HARSH teaching assistant. Award the MINIMUM defensible
113
- score for any task that is incomplete, buggy, or deviates from the rubric.
114
- Never give partial credit if the task does not run correctly."
115
-
116
- Everything else is held fixed: reference solution included, per-task breakdown
117
- requested, no chain-of-thought, temperature 0, one sample per question. Each
118
- workbook holds the AI score, bonus, and reasoning per question alongside the TA
119
- columns. `runs_summary.csv` carries MAE against the TA average with a
120
- 2,000-resample bootstrap CI.
121
-
122
- `behaviour` classes: `refusal` (≥90% of students zeroed, awarded-total std
123
- < 0.5), `near-refusal` (≥90% zeroed but still varying), `collapse` (MAE ≥ 8,
124
- i.e. ≥3× the human floor, while still discriminating between students),
125
- `graded` otherwise.
126
-
127
- ## Reproducing
128
-
129
- The grading and analysis code lives in the project repository, which expects
130
- this folder at `introduction_to_ai_dataset/`:
131
-
132
- ```bash
133
- # serve a model with vLLM, then:
134
- python introduction_to_ai_grade_with_local.py --all \
135
- --model <hf-model-id> --api-base http://localhost:8000/v1 \
136
- --with-solution --no-reasoning --with-breakdown \
137
- --strictness strict --temperature 0.0 --runs 1 \
138
- --tag IA02_m-<model_tag>_sol1_gd0_rs0_bd1_str-strict_t00_n1
139
-
140
- python introduction_to_ai_analyze_run.py <model_tag> # MAE, CI, behaviour class
141
- ```
142
-
143
- `introduction_to_ai_submit_persona_sweep.sbatch` is the SLURM launcher: an
144
- array job, one task per persona (`--array=0,1` gives the published
145
- neutral+strict pair). `STUDENTS=1-5` turns it into a smoke run that writes
146
- outside the results tree. It also supports splitting one persona across
147
- `SHARDS=K` concurrent jobs, reassembled with
148
- `introduction_to_ai_merge_shards.py`.
149
- Shards must never share an output workbook — the grader holds the whole workbook
150
- in memory and rewrites it after every question, so two writers silently destroy
151
- each other's grades.
152
-
153
- The published runs used vLLM 0.19.1. Grading is not bitwise reproducible:
154
- generation is unconstrained, and JSON is parsed leniently.
155
-
156
- ## Licence and intended use
157
-
158
- The student work belongs to its authors and is released for research on
159
- automated grading. Do not attempt to re-identify students or TAs.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Solutions/.ipynb_checkpoints/Q1_Regression_Solution-checkpoint.ipynb DELETED
@@ -1,331 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "## Question 1 SOLUTION: Predict Food Delivery Time\n",
8
- "\n",
9
- "You are provided with a food delivery dataset that includes features such as delivery distance, restaurant preparation time, traffic conditions, and order details. Your objective is to develop a regression model that accurately predicts the delivery time in minutes.\n",
10
- "\n",
11
- "Your target is the column: \"delivery_time\".\n",
12
- "\n",
13
- "You are provided with the code to download and load the csv file.\n",
14
- "\n",
15
- "Your work will be evaluated based on the completion of the following tasks:\n"
16
- ]
17
- },
18
- {
19
- "cell_type": "markdown",
20
- "metadata": {},
21
- "source": [
22
- "# Part 1: Read Data\n",
23
- "\n",
24
- "**Tasks:**\n",
25
- "\n",
26
- "1. Read the dataset using `read_csv()`\n",
27
- "2. Inspect the first few rows using `head()`\n",
28
- "3. Display dataset information using `info()`\n",
29
- "4. Show statistical description using `describe()`\n",
30
- "5. Plot the target distribution (delivery_time)"
31
- ]
32
- },
33
- {
34
- "cell_type": "code",
35
- "metadata": {},
36
- "source": [
37
- "import kagglehub\n",
38
- "\n",
39
- "# Download latest version\n",
40
- "path = kagglehub.dataset_download(\"mohammad2012191/q1-ka-ai-2026\")\n",
41
- "\n",
42
- "print(\"Path to dataset files:\", path)"
43
- ],
44
- "execution_count": null,
45
- "outputs": []
46
- },
47
- {
48
- "cell_type": "code",
49
- "metadata": {},
50
- "source": [
51
- "import pandas as pd\n",
52
- "import os\n",
53
- "df = pd.read_csv(os.path.join(path, 'Q1_data.csv'))\n",
54
- "df.head()"
55
- ],
56
- "execution_count": null,
57
- "outputs": []
58
- },
59
- {
60
- "cell_type": "code",
61
- "metadata": {},
62
- "source": [
63
- "df.head()"
64
- ],
65
- "execution_count": null,
66
- "outputs": []
67
- },
68
- {
69
- "cell_type": "code",
70
- "metadata": {},
71
- "source": [
72
- "df.info()"
73
- ],
74
- "execution_count": null,
75
- "outputs": []
76
- },
77
- {
78
- "cell_type": "code",
79
- "metadata": {},
80
- "source": [
81
- "df.describe()"
82
- ],
83
- "execution_count": null,
84
- "outputs": []
85
- },
86
- {
87
- "cell_type": "code",
88
- "metadata": {},
89
- "source": [
90
- "df['Delivery_Time'].hist(bins=30)"
91
- ],
92
- "execution_count": null,
93
- "outputs": []
94
- },
95
- {
96
- "cell_type": "markdown",
97
- "metadata": {},
98
- "source": [
99
- "# Part 2: Data Cleaning\n",
100
- "\n",
101
- "**Tasks:**\n",
102
- "\n",
103
- "Inspect and fix the following when needed:\n",
104
- "\n",
105
- "1. **Drop the 'Order_ID' column from the data** \n",
106
- "2. **Handle missing values appropriately** (Hint: I guess you want to have a closer look at the columns with missing values :) )\n",
107
- "3. **Check and remove duplicates** if any exist\n",
108
- "4. **Encode categorical variables** if needed\n",
109
- "5. **Apply feature scaling** to numerical features (Use StandardScaler)\n",
110
- "6. **Check for target imbalance and state if it is imbalanced or not** (keep this cell empty if not needed)"
111
- ]
112
- },
113
- {
114
- "cell_type": "code",
115
- "metadata": {},
116
- "source": [
117
- "# Task 1\n",
118
- "df = df.drop('Order_ID', axis=1)"
119
- ],
120
- "execution_count": null,
121
- "outputs": []
122
- },
123
- {
124
- "cell_type": "code",
125
- "metadata": {},
126
- "source": [
127
- "# Task 2\n",
128
- "# Drop rows with missing target\n",
129
- "df = df.dropna(subset=['Delivery_Time'])\n",
130
- "# Fill missing values\n",
131
- "df = df.fillna(df.median(numeric_only=True))\n",
132
- "df = df.fillna(df.mode().iloc[0])"
133
- ],
134
- "execution_count": null,
135
- "outputs": []
136
- },
137
- {
138
- "cell_type": "code",
139
- "metadata": {},
140
- "source": [
141
- "# Task 3\n",
142
- "df = df.drop_duplicates()"
143
- ],
144
- "execution_count": null,
145
- "outputs": []
146
- },
147
- {
148
- "cell_type": "code",
149
- "metadata": {},
150
- "source": [
151
- "# Task 4\n",
152
- "from sklearn.preprocessing import LabelEncoder\n",
153
- "categorical_cols = df.select_dtypes(\"object\").columns\n",
154
- "for col in categorical_cols:\n",
155
- " le = LabelEncoder()\n",
156
- " df[col] = le.fit_transform(df[col])"
157
- ],
158
- "execution_count": null,
159
- "outputs": []
160
- },
161
- {
162
- "cell_type": "code",
163
- "metadata": {},
164
- "source": [
165
- "# Task 5\n",
166
- "from sklearn.preprocessing import StandardScaler\n",
167
- "scaler = StandardScaler()\n",
168
- "X_cols = [col for col in df.columns if col != 'Delivery_Time']\n",
169
- "df[X_cols] = scaler.fit_transform(df[X_cols])"
170
- ],
171
- "execution_count": null,
172
- "outputs": []
173
- },
174
- {
175
- "cell_type": "code",
176
- "metadata": {},
177
- "source": [
178
- "# Task 6\n",
179
- "# Not applicable for regression"
180
- ],
181
- "execution_count": null,
182
- "outputs": []
183
- },
184
- {
185
- "cell_type": "markdown",
186
- "metadata": {},
187
- "source": [
188
- "# Part 3: Modeling\n",
189
- "\n",
190
- "**Tasks:**\n",
191
- "\n",
192
- "1. Split the dataset into features (X) and target (y)\n",
193
- "2. Use the correct split: **KFold** OR **StratifiedKFold**\n",
194
- "3. Train a **RandomForest** model\n",
195
- "4. Evaluate using **MAE (Mean Absolute Error) ONLY**\n",
196
- "5. Print the averaged score across all folds"
197
- ]
198
- },
199
- {
200
- "cell_type": "code",
201
- "metadata": {},
202
- "source": [
203
- "X = df.drop('Delivery_Time', axis=1)\n",
204
- "y = df['Delivery_Time']"
205
- ],
206
- "execution_count": null,
207
- "outputs": []
208
- },
209
- {
210
- "cell_type": "code",
211
- "metadata": {},
212
- "source": [
213
- "from sklearn.model_selection import KFold\n",
214
- "from sklearn.ensemble import RandomForestRegressor\n",
215
- "from sklearn.metrics import mean_absolute_error\n",
216
- "import numpy as np\n",
217
- "\n",
218
- "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
219
- "model = RandomForestRegressor(random_state=42)\n",
220
- "scores = []\n",
221
- "\n",
222
- "for train_idx, val_idx in kf.split(X):\n",
223
- " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
224
- " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
225
- " model.fit(X_train, y_train)\n",
226
- " y_pred = model.predict(X_val)\n",
227
- " scores.append(mean_absolute_error(y_val, y_pred))\n",
228
- "\n",
229
- "print(f'Average MAE: {np.mean(scores):.2f}')"
230
- ],
231
- "execution_count": null,
232
- "outputs": []
233
- },
234
- {
235
- "cell_type": "markdown",
236
- "metadata": {},
237
- "source": [
238
- "# Part 4: Plots\n",
239
- "\n",
240
- "**Tasks:**\n",
241
- "\n",
242
- "1. Plot feature importance from your trained model\n",
243
- "2. Plot predicted delivery time histogram"
244
- ]
245
- },
246
- {
247
- "cell_type": "code",
248
- "metadata": {},
249
- "source": [
250
- "import matplotlib.pyplot as plt\n",
251
- "plt.barh(X.columns, model.feature_importances_)\n",
252
- "plt.xlabel('Importance')\n",
253
- "plt.tight_layout()\n",
254
- "plt.show()"
255
- ],
256
- "execution_count": null,
257
- "outputs": []
258
- },
259
- {
260
- "cell_type": "code",
261
- "metadata": {},
262
- "source": [
263
- "y_pred = model.predict(X)\n",
264
- "plt.hist(y_pred, bins=30)\n",
265
- "plt.xlabel('Predicted Delivery Time')\n",
266
- "plt.show()"
267
- ],
268
- "execution_count": null,
269
- "outputs": []
270
- },
271
- {
272
- "cell_type": "markdown",
273
- "metadata": {},
274
- "source": [
275
- "# Part 5: Bonus - Ensemble\n",
276
- "\n",
277
- "**Task:**\n",
278
- "\n",
279
- "Why use one model? Let's use 2 then merge!\n",
280
- "\n",
281
- "Rewrite the KFold loop such that you:\n",
282
- "1. Train **2 different models** inside the loop at the same time in each iteration\n",
283
- "2. Average their predictions\n",
284
- "3. Calculate the MAE metric on the averaged predictions\n",
285
- "\n",
286
- "Use RandomForestRegressor and CatBoostRegressor."
287
- ]
288
- },
289
- {
290
- "cell_type": "code",
291
- "metadata": {},
292
- "source": [
293
- "from sklearn.ensemble import RandomForestRegressor\n",
294
- "from catboost import CatBoostRegressor\n",
295
- "\n",
296
- "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
297
- "model1 = RandomForestRegressor(random_state=42)\n",
298
- "model2 = CatBoostRegressor(verbose=0, random_state=42)\n",
299
- "scores = []\n",
300
- "\n",
301
- "for train_idx, val_idx in kf.split(X):\n",
302
- " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
303
- " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
304
- " \n",
305
- " model1.fit(X_train, y_train)\n",
306
- " model2.fit(X_train, y_train)\n",
307
- " \n",
308
- " y_pred1 = model1.predict(X_val)\n",
309
- " y_pred2 = model2.predict(X_val)\n",
310
- " y_pred_avg = (y_pred1 + y_pred2) / 2\n",
311
- " \n",
312
- " scores.append(mean_absolute_error(y_val, y_pred_avg))\n",
313
- "\n",
314
- "print(f'Average MAE (Ensemble): {np.mean(scores):.2f}')"
315
- ],
316
- "execution_count": null,
317
- "outputs": []
318
- }
319
- ],
320
- "metadata": {
321
- "kernelspec": {
322
- "display_name": "Python 3",
323
- "name": "python3"
324
- },
325
- "language_info": {
326
- "name": "python"
327
- }
328
- },
329
- "nbformat": 4,
330
- "nbformat_minor": 0
331
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Solutions/.ipynb_checkpoints/Q2_Pytorch_Solution-checkpoint.ipynb DELETED
@@ -1,396 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "## Question 2: Predict Age from Face Images\n",
8
- "\n",
9
- "You are provided with a face image dataset containing 2000 images of human faces. Your objective is to develop a regression model using PyTorch that accurately predicts the age of a person based on their face image.\n",
10
- "\n",
11
- "You are provided with the code to download and load the dataset.\n",
12
- "\n",
13
- "Your work will be evaluated based on the completion of the following tasks:\n"
14
- ]
15
- },
16
- {
17
- "cell_type": "markdown",
18
- "metadata": {},
19
- "source": [
20
- "# 1. Load and Process Data (Provided)"
21
- ]
22
- },
23
- {
24
- "cell_type": "markdown",
25
- "metadata": {},
26
- "source": [
27
- "### **1. Load and Process Data (Provided)**\n",
28
- "\n",
29
- "The code below is provided for you. It:\n",
30
- "1. Loads images from the `images` folder.\n",
31
- "2. Loads labels from `labels.csv`.\n",
32
- "3. Splits the data into training and testing sets (`X_train`, `X_test`, `y_train`, `y_test`).\n",
33
- "\n",
34
- "**Just run these cell to load the data.**"
35
- ]
36
- },
37
- {
38
- "cell_type": "code",
39
- "metadata": {},
40
- "source": [
41
- "import kagglehub\n",
42
- "\n",
43
- "# Download latest version\n",
44
- "path = kagglehub.dataset_download(\"mohammad2012191/q2-ka-ai-2026\")\n",
45
- "\n",
46
- "print(\"Path to dataset files:\", path)"
47
- ],
48
- "execution_count": null,
49
- "outputs": []
50
- },
51
- {
52
- "cell_type": "code",
53
- "metadata": {},
54
- "source": [
55
- "import os\n",
56
- "import pandas as pd\n",
57
- "import numpy as np\n",
58
- "from PIL import Image\n",
59
- "from sklearn.model_selection import train_test_split\n",
60
- "\n",
61
- "# Load Labels\n",
62
- "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
63
- "img_dir = os.path.join(path, \"images\")\n",
64
- "\n",
65
- "images = []\n",
66
- "ages = []\n",
67
- "\n",
68
- "# Load Images and Resize\n",
69
- "print(\"Loading images...\")\n",
70
- "for index, row in labels_df.iterrows():\n",
71
- " img_name = row.iloc[0]\n",
72
- " age = row.iloc[1]\n",
73
- " img_path = os.path.join(img_dir, img_name)\n",
74
- " \n",
75
- " if os.path.exists(img_path):\n",
76
- " img = Image.open(img_path).convert('RGB')\n",
77
- " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
78
- " images.append(img_array)\n",
79
- " ages.append(age)\n",
80
- "\n",
81
- "X = np.array(images)\n",
82
- "y = np.array(ages)\n",
83
- "\n",
84
- "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
85
- "X = np.transpose(X, (0, 3, 1, 2))\n",
86
- "\n",
87
- "# Split Data\n",
88
- "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
89
- "\n",
90
- "print(f\"X_train shape: {X_train.shape}\")\n",
91
- "print(f\"X_test shape: {X_test.shape}\")\n",
92
- "print(f\"y_train shape: {y_train.shape}\")\n",
93
- "print(f\"y_test shape: {y_test.shape}\")"
94
- ],
95
- "execution_count": null,
96
- "outputs": []
97
- },
98
- {
99
- "cell_type": "markdown",
100
- "metadata": {},
101
- "source": [
102
- "## **Part 1: Prepare Data for PyTorch**\n",
103
- "\n",
104
- "**Tasks:**\n",
105
- "1. **Convert to Tensors:** Convert the numpy arrays (`X_train`, `X_test`, `y_train`, `y_test`) into PyTorch tensors.\n",
106
- "2. **Create Datasets:** Use `TensorDataset` to create `train_dataset` and `test_dataset` from the tensors.\n",
107
- "3. **Create DataLoaders:** Create `train_loader` and `test_loader` with a batch size of 32. \n",
108
- "4. **Inspect Data:** Print the shape of one batch from the train loader and \n",
109
- "5. **Display a few images:** Use matplotlib to display a few images."
110
- ]
111
- },
112
- {
113
- "cell_type": "code",
114
- "metadata": {},
115
- "source": [
116
- "import torch\n",
117
- "\n",
118
- "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
119
- "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
120
- "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
121
- "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)"
122
- ],
123
- "execution_count": null,
124
- "outputs": []
125
- },
126
- {
127
- "cell_type": "code",
128
- "metadata": {},
129
- "source": [
130
- "from torch.utils.data import TensorDataset\n",
131
- "\n",
132
- "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
133
- "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
134
- ],
135
- "execution_count": null,
136
- "outputs": []
137
- },
138
- {
139
- "cell_type": "code",
140
- "metadata": {},
141
- "source": [
142
- "from torch.utils.data import DataLoader\n",
143
- "\n",
144
- "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
145
- "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
146
- ],
147
- "execution_count": null,
148
- "outputs": []
149
- },
150
- {
151
- "cell_type": "code",
152
- "metadata": {},
153
- "source": [
154
- "images, labels = next(iter(train_loader))\n",
155
- "print(f\"Batch images shape: {images.shape}\")\n",
156
- "print(f\"Batch labels shape: {labels.shape}\")"
157
- ],
158
- "execution_count": null,
159
- "outputs": []
160
- },
161
- {
162
- "cell_type": "code",
163
- "metadata": {},
164
- "source": [
165
- "import matplotlib.pyplot as plt\n",
166
- "\n",
167
- "plt.figure(figsize=(10, 5))\n",
168
- "for i in range(4):\n",
169
- " plt.subplot(1, 4, i+1)\n",
170
- " img = images[i].permute(1, 2, 0).numpy()\n",
171
- " plt.imshow(img)\n",
172
- " plt.title(f\"Age: {labels[i].item():.0f}\")\n",
173
- " plt.axis(\"off\")\n",
174
- "plt.show()"
175
- ],
176
- "execution_count": null,
177
- "outputs": []
178
- },
179
- {
180
- "cell_type": "markdown",
181
- "metadata": {},
182
- "source": [
183
- "# Part 2: Model\n",
184
- "\n",
185
- "**Tasks:**\n",
186
- "\n",
187
- "1. Create a model class with **4 linear layers**\n",
188
- "2. Create a training loop function\n",
189
- "3. Create a validation loop function\n",
190
- "4. Define the device, model, loss function, and optimizer\n",
191
- "5. Start training for **20 epochs** and track training and validation losses"
192
- ]
193
- },
194
- {
195
- "cell_type": "code",
196
- "metadata": {},
197
- "source": [
198
- "import torch.nn as nn\n",
199
- "\n",
200
- "class AgeModel(nn.Module):\n",
201
- " def __init__(self, input_dim, hidden_dim, output_dim):\n",
202
- " super(AgeModel, self).__init__()\n",
203
- " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
204
- " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
205
- " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
206
- " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
207
- " self.relu = nn.ReLU()\n",
208
- "\n",
209
- " def forward(self, x):\n",
210
- " x = self.relu(self.layer1(x))\n",
211
- " x = self.relu(self.layer2(x))\n",
212
- " x = self.relu(self.layer3(x))\n",
213
- " x = self.layer4(x)\n",
214
- " return x.squeeze()"
215
- ],
216
- "execution_count": null,
217
- "outputs": []
218
- },
219
- {
220
- "cell_type": "code",
221
- "metadata": {},
222
- "source": [
223
- "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
224
- " # Set the model to training mode\n",
225
- " model.train()\n",
226
- "\n",
227
- " running_loss = 0.0\n",
228
- "\n",
229
- " for X_batch, y_batch in train_loader:\n",
230
- " # Move batch to the selected device\n",
231
- " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
232
- " y_batch = y_batch.to(device)\n",
233
- "\n",
234
- " # Forward pass\n",
235
- " outputs = model(X_batch)\n",
236
- " loss = criterion(outputs, y_batch)\n",
237
- "\n",
238
- " # Backward pass & optimization\n",
239
- " optimizer.zero_grad() # Clear previous gradients\n",
240
- " loss.backward() # Compute gradients\n",
241
- " optimizer.step() # Update model parameters\n",
242
- "\n",
243
- " running_loss += loss.item()\n",
244
- "\n",
245
- " # Average loss over all batches\n",
246
- " avg_loss = running_loss / len(train_loader)\n",
247
- "\n",
248
- " return avg_loss"
249
- ],
250
- "execution_count": null,
251
- "outputs": []
252
- },
253
- {
254
- "cell_type": "code",
255
- "metadata": {},
256
- "source": [
257
- "def validate(model, criterion, test_loader, device):\n",
258
- " # Set the model to evaluation mode\n",
259
- " model.eval()\n",
260
- "\n",
261
- " running_loss = 0.0\n",
262
- "\n",
263
- " with torch.no_grad():\n",
264
- " for X_batch, y_batch in test_loader:\n",
265
- " # Move data to device\n",
266
- " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
267
- " y_batch = y_batch.to(device)\n",
268
- "\n",
269
- " # Forward pass\n",
270
- " outputs = model(X_batch)\n",
271
- " loss = criterion(outputs, y_batch)\n",
272
- " running_loss += loss.item()\n",
273
- "\n",
274
- " avg_loss = running_loss / len(test_loader)\n",
275
- "\n",
276
- " return avg_loss"
277
- ],
278
- "execution_count": null,
279
- "outputs": []
280
- },
281
- {
282
- "cell_type": "code",
283
- "metadata": {},
284
- "source": [
285
- "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
286
- "\n",
287
- "input_dim = 36 * 36 * 3\n",
288
- "hidden_dim = 128\n",
289
- "output_dim = 1\n",
290
- "\n",
291
- "model = AgeModel(input_dim, hidden_dim, output_dim).to(device)\n",
292
- "\n",
293
- "num_epochs = 20\n",
294
- "learning_rate = 0.001\n",
295
- "\n",
296
- "criterion = nn.MSELoss()\n",
297
- "optimizer = torch.optim.AdamW(model.parameters(), learning_rate)"
298
- ],
299
- "execution_count": null,
300
- "outputs": []
301
- },
302
- {
303
- "cell_type": "code",
304
- "metadata": {},
305
- "source": [
306
- "# Run Training\n",
307
- "train_losses = []\n",
308
- "val_losses = []\n",
309
- "\n",
310
- "print('Starting Training...')\n",
311
- "for epoch in range(num_epochs):\n",
312
- " # Train one epoch\n",
313
- " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
314
- "\n",
315
- " # Validate\n",
316
- " val_loss = validate(model, criterion, test_loader, device)\n",
317
- "\n",
318
- " train_losses.append(train_loss)\n",
319
- " val_losses.append(val_loss)\n",
320
- "\n",
321
- " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}')\n",
322
- "\n",
323
- "print('Training Complete!')"
324
- ],
325
- "execution_count": null,
326
- "outputs": []
327
- },
328
- {
329
- "cell_type": "markdown",
330
- "metadata": {},
331
- "source": [
332
- "# Part 3: Plots\n",
333
- "\n",
334
- "**Tasks:**\n",
335
- "\n",
336
- "1. Plot the training and validation loss over epochs\n",
337
- "2. **Bonus:** Plot some predictions with their actual images (show predicted age vs actual age)"
338
- ]
339
- },
340
- {
341
- "cell_type": "code",
342
- "metadata": {},
343
- "source": [
344
- "plt.plot(train_losses, label='Train Loss')\n",
345
- "plt.plot(val_losses, label='Validation Loss')\n",
346
- "plt.title('Loss over Epochs')\n",
347
- "plt.xlabel('Epoch')\n",
348
- "plt.ylabel('Loss')\n",
349
- "plt.legend()\n",
350
- "plt.show()"
351
- ],
352
- "execution_count": null,
353
- "outputs": []
354
- },
355
- {
356
- "cell_type": "code",
357
- "metadata": {},
358
- "source": [
359
- "model.eval()\n",
360
- "images, labels = next(iter(test_loader))\n",
361
- "images = images.to(device)\n",
362
- "with torch.no_grad():\n",
363
- " preds = model(images.view(images.size(0), -1))\n",
364
- "\n",
365
- "plt.figure(figsize=(10, 5))\n",
366
- "for i in range(4):\n",
367
- " plt.subplot(1, 4, i+1)\n",
368
- " img = images[i].cpu().permute(1, 2, 0).numpy()\n",
369
- " plt.imshow(img)\n",
370
- " plt.title(f\"Real: {labels[i].item():.0f}\\nPred: {preds[i].item():.0f}\")\n",
371
- " plt.axis(\"off\")\n",
372
- "plt.show()"
373
- ],
374
- "execution_count": null,
375
- "outputs": []
376
- },
377
- {
378
- "cell_type": "code",
379
- "metadata": {},
380
- "source": [],
381
- "execution_count": null,
382
- "outputs": []
383
- }
384
- ],
385
- "metadata": {
386
- "kernelspec": {
387
- "display_name": "Python 3",
388
- "name": "python3"
389
- },
390
- "language_info": {
391
- "name": "python"
392
- }
393
- },
394
- "nbformat": 4,
395
- "nbformat_minor": 0
396
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
Solutions/.ipynb_checkpoints/Q3_Classification_Solution-checkpoint.ipynb DELETED
@@ -1,397 +0,0 @@
1
- {
2
- "cells": [
3
- {
4
- "cell_type": "markdown",
5
- "metadata": {},
6
- "source": [
7
- "## Question 3: Exploring Anonymized Data - Can You Find the Golden Feature?\n",
8
- "\n",
9
- "\n",
10
- "\n",
11
- "**What is Anonymized Data?**\n",
12
- "\n",
13
- "\n",
14
- "\n",
15
- "Anonymized data is information that has been processed to remove or obscure personally identifiable details, making it impossible to trace back to specific individuals. In credit risk modeling, features are often anonymized (e.g., `P_2`, `D_39`, `B_1`) to protect customer privacy while still enabling powerful predictive analytics.\n",
16
- "\n",
17
- "\n",
18
- "\n",
19
- "**The Challenge:**\n",
20
- "\n",
21
- "\n",
22
- "\n",
23
- "Credit default prediction is central to managing risk in consumer lending. American Express, the world's largest payment card issuer, uses machine learning to predict whether cardholders will default on their payments. This helps optimize lending decisions and creates a better customer experience.\n",
24
- "\n",
25
- "\n",
26
- "\n",
27
- "You are provided with an anonymized dataset containing behavioral and profile features. Your objective is to build a classification model that predicts credit default (0 = No Default, 1 = Default).\n",
28
- "\n",
29
- "\n",
30
- "\n",
31
- "**Your Mission:** Can you discover the 'golden feature' - the most powerful predictor hidden in this anonymized data?\n",
32
- "\n",
33
- "\n",
34
- "\n",
35
- "Your work will be evaluated based on the completion of the following tasks:\n"
36
- ]
37
- },
38
- {
39
- "cell_type": "markdown",
40
- "metadata": {},
41
- "source": [
42
- "# Part 1: Read Data\n",
43
- "\n",
44
- "\n",
45
- "\n",
46
- "**Tasks:**\n",
47
- "\n",
48
- "\n",
49
- "\n",
50
- "1. Read the dataset `Q3_data.csv` using `read_csv()`\n",
51
- "\n",
52
- "2. Inspect the first few rows using `head()`\n",
53
- "\n",
54
- "3. Display dataset information using `info()`\n",
55
- "\n",
56
- "4. Show statistical description using `describe()`\n",
57
- "\n",
58
- "5. Plot the target distribution (target column)\"\n"
59
- ]
60
- },
61
- {
62
- "cell_type": "code",
63
- "metadata": {},
64
- "source": [
65
- "import kagglehub\n",
66
- "\n",
67
- "\n",
68
- "\n",
69
- "# Download latest version\n",
70
- "\n",
71
- "path = kagglehub.dataset_download(\"mohammad2012191/q3-ka-ai-2026\")\n",
72
- "\n",
73
- "\n",
74
- "\n",
75
- "print(\"Path to dataset files:\", path)"
76
- ],
77
- "execution_count": null,
78
- "outputs": []
79
- },
80
- {
81
- "cell_type": "code",
82
- "metadata": {},
83
- "source": [
84
- "import pandas as pd\n",
85
- "import numpy as np\n",
86
- "import matplotlib.pyplot as plt\n",
87
- "\n",
88
- "# The 'path' variable is defined in the download cell\n",
89
- "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))\n"
90
- ],
91
- "execution_count": null,
92
- "outputs": []
93
- },
94
- {
95
- "cell_type": "code",
96
- "metadata": {},
97
- "source": [
98
- "df.head()\n"
99
- ],
100
- "execution_count": null,
101
- "outputs": []
102
- },
103
- {
104
- "cell_type": "code",
105
- "metadata": {},
106
- "source": [
107
- "df.info()\n"
108
- ],
109
- "execution_count": null,
110
- "outputs": []
111
- },
112
- {
113
- "cell_type": "code",
114
- "metadata": {},
115
- "source": [
116
- "df.describe()\n"
117
- ],
118
- "execution_count": null,
119
- "outputs": []
120
- },
121
- {
122
- "cell_type": "code",
123
- "metadata": {},
124
- "source": [
125
- "df['Target'].value_counts().plot(kind='bar')\n",
126
- "plt.title('Target Distribution (0: No Default, 1: Default)')\n",
127
- "plt.xlabel('Target')\n",
128
- "plt.ylabel('Count')\n",
129
- "plt.show()\n"
130
- ],
131
- "execution_count": null,
132
- "outputs": []
133
- },
134
- {
135
- "cell_type": "markdown",
136
- "metadata": {},
137
- "source": [
138
- "# Part 2: Data Cleaning\n",
139
- "\n",
140
- "\n",
141
- "\n",
142
- "**Tasks:**\n",
143
- "\n",
144
- "\n",
145
- "\n",
146
- "Inspect and fix the following when needed:\n",
147
- "\n",
148
- "\n",
149
- "\n",
150
- "1. **Handle missing values appropriately**\n",
151
- "\n",
152
- "2. **Check and remove duplicates** if any exist\n",
153
- "\n",
154
- "3. **Encode categorical variables** if needed\n",
155
- "\n",
156
- "4. **Apply feature scaling** to numerical features (Use StandardScaler)\n",
157
- "\n",
158
- "5. **Check for target imbalance and state if it is imbalanced or not**"
159
- ]
160
- },
161
- {
162
- "cell_type": "code",
163
- "metadata": {},
164
- "source": [
165
- "print(df.isnull().sum())\n",
166
- "df = df.fillna(df.median())\n"
167
- ],
168
- "execution_count": null,
169
- "outputs": []
170
- },
171
- {
172
- "cell_type": "code",
173
- "metadata": {},
174
- "source": [
175
- "print(f'Duplicates: {df.duplicated().sum()}')\n",
176
- "df = df.drop_duplicates()\n"
177
- ],
178
- "execution_count": null,
179
- "outputs": []
180
- },
181
- {
182
- "cell_type": "code",
183
- "metadata": {},
184
- "source": [
185
- "from sklearn.preprocessing import LabelEncoder\n",
186
- "\n",
187
- "categorical_cols = df.select_dtypes(include=['object']).columns\n",
188
- "if len(categorical_cols) > 0:\n",
189
- " le = LabelEncoder()\n",
190
- " for col in categorical_cols:\n",
191
- " df[col] = le.fit_transform(df[col].astype(str))\n",
192
- " print(f'Encoded columns: {list(categorical_cols)}')\n"
193
- ],
194
- "execution_count": null,
195
- "outputs": []
196
- },
197
- {
198
- "cell_type": "code",
199
- "metadata": {},
200
- "source": [
201
- "from sklearn.preprocessing import StandardScaler\n",
202
- "\n",
203
- "scaler = StandardScaler()\n",
204
- "X_cols = df.drop(columns=['Target']).columns\n",
205
- "df[X_cols] = scaler.fit_transform(df[X_cols])\n"
206
- ],
207
- "execution_count": null,
208
- "outputs": []
209
- },
210
- {
211
- "cell_type": "code",
212
- "metadata": {},
213
- "source": [
214
- "df['Target'].value_counts()\n",
215
- "# there is imbalance"
216
- ],
217
- "execution_count": null,
218
- "outputs": []
219
- },
220
- {
221
- "cell_type": "markdown",
222
- "metadata": {},
223
- "source": [
224
- "# Part 3: Modeling\n",
225
- "\n",
226
- "\n",
227
- "\n",
228
- "**Tasks:**\n",
229
- "\n",
230
- "\n",
231
- "\n",
232
- "1. Split the dataset into features (X) and target (y)\n",
233
- "\n",
234
- "2. Use the correct split: **KFold** OR **StratifiedKFold**\n",
235
- "\n",
236
- "3. Train a **CatBoostClassifier** model\n",
237
- "\n",
238
- "4. Evaluate using the appropriate metric only (Accuracy vs. F1 Score).\n",
239
- "\n",
240
- "5. Print the averaged score across all folds"
241
- ]
242
- },
243
- {
244
- "cell_type": "code",
245
- "metadata": {},
246
- "source": [
247
- "X = df.drop(columns=['Target'])\n",
248
- "y = df['Target']\n"
249
- ],
250
- "execution_count": null,
251
- "outputs": []
252
- },
253
- {
254
- "cell_type": "code",
255
- "metadata": {},
256
- "source": [
257
- "from sklearn.model_selection import StratifiedKFold\n",
258
- "from sklearn.ensemble import RandomForestClassifier\n",
259
- "from catboost import CatBoostClassifier\n",
260
- "from sklearn.metrics import f1_score\n",
261
- "\n",
262
- "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
263
- "model = CatBoostClassifier(n_estimators=100, random_state=42)\n",
264
- "\n",
265
- "f1 = []\n",
266
- "\n",
267
- "for train_idx, val_idx in skf.split(X, y):\n",
268
- " X_train, X_val = X.iloc[train_idx], X.iloc[val_idx]\n",
269
- " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
270
- " \n",
271
- " model.fit(X_train, y_train)\n",
272
- " preds = model.predict(X_val)\n",
273
- " f1.append(f1_score(y_val, preds))\n",
274
- "\n",
275
- "print(f'F1: {np.mean(f1):.4f}')\n"
276
- ],
277
- "execution_count": null,
278
- "outputs": []
279
- },
280
- {
281
- "cell_type": "markdown",
282
- "metadata": {},
283
- "source": [
284
- "# Part 4: Find the Golden Feature!\n",
285
- "\n",
286
- "\n",
287
- "\n",
288
- "**Tasks:**\n",
289
- "\n",
290
- "\n",
291
- "\n",
292
- "1. Plot feature importance from your trained model\n",
293
- "\n",
294
- "2. Identify and print the name of the most important feature (the 'golden feature')\n",
295
- "\n",
296
- "3. Plot the distribution of predictions"
297
- ]
298
- },
299
- {
300
- "cell_type": "code",
301
- "metadata": {},
302
- "source": [
303
- "importances = model.feature_importances_\n",
304
- "feat_importances = pd.Series(importances, index=X.columns).sort_values(ascending=False)\n",
305
- "\n",
306
- "plt.figure(figsize=(10, 6))\n",
307
- "feat_importances[:10].plot(kind='barh')\n",
308
- "plt.gca().invert_yaxis()\n",
309
- "plt.title('Top 10 Feature Importances')\n",
310
- "plt.xlabel('Importance')\n",
311
- "plt.show()\n"
312
- ],
313
- "execution_count": null,
314
- "outputs": []
315
- },
316
- {
317
- "cell_type": "code",
318
- "metadata": {},
319
- "source": [
320
- "golden_feature = feat_importances.index[0]\n",
321
- "print(f'The Golden Feature is: {golden_feature}')\n",
322
- "print(f'Importance: {feat_importances.iloc[0]:.4f}')\n"
323
- ],
324
- "execution_count": null,
325
- "outputs": []
326
- },
327
- {
328
- "cell_type": "markdown",
329
- "metadata": {},
330
- "source": [
331
- "# Part 5: Bonus - Retrain with Golden Feature Only\n",
332
- "\n",
333
- "\n",
334
- "\n",
335
- "**Task:**\n",
336
- "\n",
337
- "\n",
338
- "\n",
339
- "Now that you've found the golden feature, let's see how powerful it really is!\n",
340
- "\n",
341
- "\n",
342
- "\n",
343
- "Retrain your CatBoostClassifier using **ONLY the golden feature** and compare its performance to the full model:\n",
344
- "\n",
345
- "\n",
346
- "\n",
347
- "1. Create new X with only the golden feature\n",
348
- "\n",
349
- "2. Run the same KFold loop with this single feature\n",
350
- "\n",
351
- "3. Print and compare the accuracy with the full model"
352
- ]
353
- },
354
- {
355
- "cell_type": "code",
356
- "metadata": {},
357
- "source": [
358
- "from sklearn.model_selection import StratifiedKFold\n",
359
- "from sklearn.ensemble import RandomForestClassifier\n",
360
- "from catboost import CatBoostClassifier\n",
361
- "from sklearn.metrics import f1_score\n",
362
- "\n",
363
- "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
364
- "model = CatBoostClassifier(n_estimators=100, random_state=42)\n",
365
- "\n",
366
- "# Retrain with only the golden feature\n",
367
- "X_golden = X[[golden_feature]]\n",
368
- "\n",
369
- "golden_accuracies = []\n",
370
- "for train_idx, val_idx in skf.split(X_golden, y):\n",
371
- " X_train, X_val = X_golden.iloc[train_idx], X_golden.iloc[val_idx]\n",
372
- " y_train, y_val = y.iloc[train_idx], y.iloc[val_idx]\n",
373
- " \n",
374
- " model.fit(X_train, y_train)\n",
375
- " preds = model.predict(X_val)\n",
376
- " golden_accuracies.append(f1_score(y_val, preds))\n",
377
- "\n",
378
- "print(f'Accuracy with ONLY {golden_feature}: {np.mean(golden_accuracies):.4f}')\n",
379
- "print(f'Full Model Accuracy: {np.mean(f1):.4f}')\n",
380
- "print(f'Difference: {np.mean(f1) - np.mean(golden_accuracies):.4f}')\n"
381
- ],
382
- "execution_count": null,
383
- "outputs": []
384
- }
385
- ],
386
- "metadata": {
387
- "kernelspec": {
388
- "display_name": "Python 3",
389
- "name": "python3"
390
- },
391
- "language_info": {
392
- "name": "python"
393
- }
394
- },
395
- "nbformat": 4,
396
- "nbformat_minor": 0
397
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
submissions_extracted/1001/.ipynb_checkpoints/Q1-checkpoint.ipynb DELETED
@@ -1,229 +0,0 @@
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
- "\n",
15
- "from sklearn.preprocessing import OneHotEncoder\n",
16
- "from sklearn.model_selection import train_test_split\n",
17
- "\n",
18
- "%matplotlib inline"
19
- ],
20
- "execution_count": null,
21
- "outputs": []
22
- },
23
- {
24
- "cell_type": "code",
25
- "metadata": {},
26
- "source": [
27
- "# Download latest version\n",
28
- "path = kagglehub.dataset_download(\"mohammad2012191/q1-ka-ai-2026\")\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
- "# Task 1: Write your code here:\n",
40
- "csv_path = os.path.join(path, 'Q1_data.csv')\n",
41
- "df = pd.read_csv(csv_path)"
42
- ],
43
- "execution_count": null,
44
- "outputs": []
45
- },
46
- {
47
- "cell_type": "code",
48
- "metadata": {},
49
- "source": [
50
- "# Task 2: Write your code here:\n",
51
- "df.head()"
52
- ],
53
- "execution_count": null,
54
- "outputs": []
55
- },
56
- {
57
- "cell_type": "code",
58
- "metadata": {},
59
- "source": [
60
- "# Task 3: Write your code here:\n",
61
- "df.info()"
62
- ],
63
- "execution_count": null,
64
- "outputs": []
65
- },
66
- {
67
- "cell_type": "code",
68
- "metadata": {},
69
- "source": [
70
- "# Task 4: Write your code here:\n",
71
- "df.describe()"
72
- ],
73
- "execution_count": null,
74
- "outputs": []
75
- },
76
- {
77
- "cell_type": "code",
78
- "metadata": {},
79
- "source": [
80
- "# Task 5: Write your code here:\n",
81
- "def check_target_distribution(df, target_column):\n",
82
- " df[target_column].hist(bins=30, edgecolor='black')\n",
83
- "\n",
84
- " plt.title(f\"Target Distribution ({target_column})\")\n",
85
- " plt.xlabel(target_column)\n",
86
- " plt.ylabel(\"Delivery_Time\")\n",
87
- " plt.grid(False)\n",
88
- "\n",
89
- " plt.show()\n",
90
- "\n",
91
- "check_target_distribution(df, \"Delivery_Time\")"
92
- ],
93
- "execution_count": null,
94
- "outputs": []
95
- },
96
- {
97
- "cell_type": "code",
98
- "metadata": {},
99
- "source": [
100
- "# Task 1: Write your code here:\n",
101
- "df.drop(columns=['Order_ID'])"
102
- ],
103
- "execution_count": null,
104
- "outputs": []
105
- },
106
- {
107
- "cell_type": "code",
108
- "metadata": {},
109
- "source": [
110
- "# Task 2: Write your code here:\n",
111
- "# Missing values\n",
112
- "print(\"Missing values:\")\n",
113
- "print(df.isnull().sum())"
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
- "# Duplicates\n",
124
- "print(\"Duplicates:\")\n",
125
- "print(df.duplicated().sum())"
126
- ],
127
- "execution_count": null,
128
- "outputs": []
129
- },
130
- {
131
- "cell_type": "code",
132
- "metadata": {},
133
- "source": [
134
- "#Remove duplicates\n",
135
- "df.drop_duplicates(inplace=True)"
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
- "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
146
- "\n",
147
- "print(\"Categorical Columns:\", list(categorical_cols))"
148
- ],
149
- "execution_count": null,
150
- "outputs": []
151
- },
152
- {
153
- "cell_type": "code",
154
- "metadata": {},
155
- "source": [
156
- "# Task 5: Write your code here:"
157
- ],
158
- "execution_count": null,
159
- "outputs": []
160
- },
161
- {
162
- "cell_type": "code",
163
- "metadata": {},
164
- "source": [
165
- "# Task 6: 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:\n",
175
- "X = df\n",
176
- "y = df"
177
- ],
178
- "execution_count": null,
179
- "outputs": []
180
- },
181
- {
182
- "cell_type": "code",
183
- "metadata": {},
184
- "source": [
185
- "# Task 2,3,4,5: Write your code here:"
186
- ],
187
- "execution_count": null,
188
- "outputs": []
189
- },
190
- {
191
- "cell_type": "code",
192
- "metadata": {},
193
- "source": [
194
- "# Task 1: Write your code here:"
195
- ],
196
- "execution_count": null,
197
- "outputs": []
198
- },
199
- {
200
- "cell_type": "code",
201
- "metadata": {},
202
- "source": [
203
- "# Task 2: Write your code here:"
204
- ],
205
- "execution_count": null,
206
- "outputs": []
207
- },
208
- {
209
- "cell_type": "code",
210
- "metadata": {},
211
- "source": [
212
- "# Task Bonus: Write your code here:"
213
- ],
214
- "execution_count": null,
215
- "outputs": []
216
- }
217
- ],
218
- "metadata": {
219
- "kernelspec": {
220
- "display_name": "Python 3",
221
- "name": "python3"
222
- },
223
- "language_info": {
224
- "name": "python"
225
- }
226
- },
227
- "nbformat": 4,
228
- "nbformat_minor": 0
229
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
submissions_extracted/1001/.ipynb_checkpoints/Q2-checkpoint.ipynb DELETED
@@ -1,198 +0,0 @@
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(\"mohammad2012191/q2-ka-ai-2026\")\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_train = torch.tensor([1.0, 2.0, 3.0])\n",
73
- "y_train = torch.randn(3)\n",
74
- "print(\"x:\", x)\n",
75
- "print(\"y:\", y)\n",
76
- "\n"
77
- ],
78
- "execution_count": null,
79
- "outputs": []
80
- },
81
- {
82
- "cell_type": "code",
83
- "metadata": {},
84
- "source": [
85
- "# 2. Create TensorDataset objects\n",
86
- "\n",
87
- "\n"
88
- ],
89
- "execution_count": null,
90
- "outputs": []
91
- },
92
- {
93
- "cell_type": "code",
94
- "metadata": {},
95
- "source": [
96
- "# 3. Create DataLoaders\n",
97
- "\n",
98
- "\n"
99
- ],
100
- "execution_count": null,
101
- "outputs": []
102
- },
103
- {
104
- "cell_type": "code",
105
- "metadata": {},
106
- "source": [
107
- "# 4. Print shape of one batch\n",
108
- "\n"
109
- ],
110
- "execution_count": null,
111
- "outputs": []
112
- },
113
- {
114
- "cell_type": "code",
115
- "metadata": {},
116
- "source": [
117
- "# 5. Display sample images\n",
118
- "\n"
119
- ],
120
- "execution_count": null,
121
- "outputs": []
122
- },
123
- {
124
- "cell_type": "code",
125
- "metadata": {},
126
- "source": [
127
- "# Task 1: Write your model class here:"
128
- ],
129
- "execution_count": null,
130
- "outputs": []
131
- },
132
- {
133
- "cell_type": "code",
134
- "metadata": {},
135
- "source": [
136
- "# Task 2: Write your training loop here:"
137
- ],
138
- "execution_count": null,
139
- "outputs": []
140
- },
141
- {
142
- "cell_type": "code",
143
- "metadata": {},
144
- "source": [
145
- "# Task 3: Write your validation loop here:"
146
- ],
147
- "execution_count": null,
148
- "outputs": []
149
- },
150
- {
151
- "cell_type": "code",
152
- "metadata": {},
153
- "source": [
154
- "# Task 4: Define device, model, loss, optimizer:"
155
- ],
156
- "execution_count": null,
157
- "outputs": []
158
- },
159
- {
160
- "cell_type": "code",
161
- "metadata": {},
162
- "source": [
163
- "# Task 5: Start training for 20 epochs:"
164
- ],
165
- "execution_count": null,
166
- "outputs": []
167
- },
168
- {
169
- "cell_type": "code",
170
- "metadata": {},
171
- "source": [
172
- "# Task 1: Write your code here:"
173
- ],
174
- "execution_count": null,
175
- "outputs": []
176
- },
177
- {
178
- "cell_type": "code",
179
- "metadata": {},
180
- "source": [
181
- "# Task 2 (Bonus): Write your code here:"
182
- ],
183
- "execution_count": null,
184
- "outputs": []
185
- }
186
- ],
187
- "metadata": {
188
- "kernelspec": {
189
- "display_name": "Python 3",
190
- "name": "python3"
191
- },
192
- "language_info": {
193
- "name": "python"
194
- }
195
- },
196
- "nbformat": 4,
197
- "nbformat_minor": 0
198
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
submissions_extracted/1001/.ipynb_checkpoints/Q3-checkpoint.ipynb DELETED
@@ -1,160 +0,0 @@
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(\"mohammad2012191/q3-ka-ai-2026\")\n",
14
- "\n",
15
- "\n",
16
- "\n",
17
- "print(\"Path to dataset files:\", path)"
18
- ],
19
- "execution_count": null,
20
- "outputs": []
21
- },
22
- {
23
- "cell_type": "code",
24
- "metadata": {},
25
- "source": [
26
- "# Task 1: Write your code here:"
27
- ],
28
- "execution_count": null,
29
- "outputs": []
30
- },
31
- {
32
- "cell_type": "code",
33
- "metadata": {},
34
- "source": [
35
- "# Task 2: Write your code here:"
36
- ],
37
- "execution_count": null,
38
- "outputs": []
39
- },
40
- {
41
- "cell_type": "code",
42
- "metadata": {},
43
- "source": [
44
- "# Task 3: Write your code here:"
45
- ],
46
- "execution_count": null,
47
- "outputs": []
48
- },
49
- {
50
- "cell_type": "code",
51
- "metadata": {},
52
- "source": [
53
- "# Task 4: Write your code here:"
54
- ],
55
- "execution_count": null,
56
- "outputs": []
57
- },
58
- {
59
- "cell_type": "code",
60
- "metadata": {},
61
- "source": [
62
- "# Task 1: Write your code here:"
63
- ],
64
- "execution_count": null,
65
- "outputs": []
66
- },
67
- {
68
- "cell_type": "code",
69
- "metadata": {},
70
- "source": [
71
- "# Task 2: Write your code here:"
72
- ],
73
- "execution_count": null,
74
- "outputs": []
75
- },
76
- {
77
- "cell_type": "code",
78
- "metadata": {},
79
- "source": [
80
- "# Task 3: Write your code here:"
81
- ],
82
- "execution_count": null,
83
- "outputs": []
84
- },
85
- {
86
- "cell_type": "code",
87
- "metadata": {},
88
- "source": [
89
- "# Task 4: Write your code here:"
90
- ],
91
- "execution_count": null,
92
- "outputs": []
93
- },
94
- {
95
- "cell_type": "code",
96
- "metadata": {},
97
- "source": [
98
- "# Task 5: Write your code here:"
99
- ],
100
- "execution_count": null,
101
- "outputs": []
102
- },
103
- {
104
- "cell_type": "code",
105
- "metadata": {},
106
- "source": [
107
- "# Task 1: Write your code here:"
108
- ],
109
- "execution_count": null,
110
- "outputs": []
111
- },
112
- {
113
- "cell_type": "code",
114
- "metadata": {},
115
- "source": [
116
- "# Task 2,3,4,5: Write your code here:"
117
- ],
118
- "execution_count": null,
119
- "outputs": []
120
- },
121
- {
122
- "cell_type": "code",
123
- "metadata": {},
124
- "source": [
125
- "# Task 1: Write your code here:"
126
- ],
127
- "execution_count": null,
128
- "outputs": []
129
- },
130
- {
131
- "cell_type": "code",
132
- "metadata": {},
133
- "source": [
134
- "# Task 2: Write your code here:"
135
- ],
136
- "execution_count": null,
137
- "outputs": []
138
- },
139
- {
140
- "cell_type": "code",
141
- "metadata": {},
142
- "source": [
143
- "# Task Bonus: Write your code here:"
144
- ],
145
- "execution_count": null,
146
- "outputs": []
147
- }
148
- ],
149
- "metadata": {
150
- "kernelspec": {
151
- "display_name": "Python 3",
152
- "name": "python3"
153
- },
154
- "language_info": {
155
- "name": "python"
156
- }
157
- },
158
- "nbformat": 4,
159
- "nbformat_minor": 0
160
- }