ALLIA12 commited on
Commit
1736cdc
·
verified ·
1 Parent(s): 6740237

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

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/218/Q1.ipynb +299 -0
  2. submissions_extracted/218/Q2.ipynb +297 -0
  3. submissions_extracted/218/Q3.ipynb +216 -0
  4. submissions_extracted/219/Q1.ipynb +281 -0
  5. submissions_extracted/219/Q2.ipynb +269 -0
  6. submissions_extracted/219/Q3.ipynb +223 -0
  7. submissions_extracted/22/Q2.ipynb +353 -0
  8. submissions_extracted/220/Q1.ipynb +341 -0
  9. submissions_extracted/220/Q2.ipynb +392 -0
  10. submissions_extracted/220/Q3.ipynb +354 -0
  11. submissions_extracted/221/Q1.ipynb +382 -0
  12. submissions_extracted/221/Q2.ipynb +361 -0
  13. submissions_extracted/221/Q3.ipynb +284 -0
  14. submissions_extracted/222/Q1.ipynb +310 -0
  15. submissions_extracted/222/Q2.ipynb +367 -0
  16. submissions_extracted/222/Q3.ipynb +296 -0
  17. submissions_extracted/223/Q1.ipynb +382 -0
  18. submissions_extracted/223/Q2.ipynb +431 -0
  19. submissions_extracted/223/Q3.ipynb +322 -0
  20. submissions_extracted/224/Q1.ipynb +375 -0
  21. submissions_extracted/224/Q3.ipynb +286 -0
  22. submissions_extracted/225/Q1.ipynb +348 -0
  23. submissions_extracted/225/Q2.ipynb +359 -0
  24. submissions_extracted/225/Q3.ipynb +476 -0
  25. submissions_extracted/226/Q1.ipynb +314 -0
  26. submissions_extracted/226/Q2.ipynb +384 -0
  27. submissions_extracted/226/Q3.ipynb +257 -0
  28. submissions_extracted/227/Q1.ipynb +448 -0
  29. submissions_extracted/227/Q2.ipynb +374 -0
  30. submissions_extracted/228/Q1.ipynb +313 -0
  31. submissions_extracted/228/Q2.ipynb +336 -0
  32. submissions_extracted/228/Q3.ipynb +267 -0
  33. submissions_extracted/229/Q1.ipynb +307 -0
  34. submissions_extracted/229/Q2.ipynb +362 -0
  35. submissions_extracted/229/Q3.ipynb +306 -0
  36. submissions_extracted/23/Q1.ipynb +241 -0
  37. submissions_extracted/23/Q2.ipynb +216 -0
  38. submissions_extracted/23/Q3.ipynb +160 -0
  39. submissions_extracted/230/Q1.ipynb +343 -0
  40. submissions_extracted/230/Q2.ipynb +316 -0
  41. submissions_extracted/230/Q3.ipynb +307 -0
  42. submissions_extracted/231/Q1.ipynb +303 -0
  43. submissions_extracted/231/Q2.ipynb +387 -0
  44. submissions_extracted/231/Q3.ipynb +354 -0
  45. submissions_extracted/232/Q1.ipynb +343 -0
  46. submissions_extracted/232/Q2.ipynb +346 -0
  47. submissions_extracted/232/Q3.ipynb +293 -0
  48. submissions_extracted/233/Q1.ipynb +338 -0
  49. submissions_extracted/233/Q2.ipynb +200 -0
  50. submissions_extracted/233/Q3.ipynb +286 -0
submissions_extracted/218/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, 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
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\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
+ "Q1_data_path=os.path.join(path,'Q1_data.csv')\n",
35
+ "df_Q1_data=pd.read_csv(Q1_data_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
+ "print(f\"Shape:{df_Q1_data.shape}\")\n",
46
+ "df_Q1_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
+ "df_Q1_data.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_Q1_data.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
+ "plt.figure(figsize=(10, 5))\n",
77
+ "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
78
+ "plt.title('Delivery Time')\n",
79
+ "plt.xlabel('Time')\n",
80
+ "plt.ylabel('Frequency')\n",
81
+ "plt.show()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 1: Write your code here:\n",
91
+ "df_clean= df_Q1_data.dropna(subset=['Order_ID']).copy()"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 2: Write your code here:\n",
101
+ "def check_missing_values(df):\n",
102
+ " missing_values = df.isnull().sum()\n",
103
+ " print(\"Missing Values per Column:\")\n",
104
+ " print(missing_values[missing_values > 0])\n",
105
+ " if missing_values.any():\n",
106
+ " print(\"\\nHandle Missing Values as needed.\")\n",
107
+ " else:\n",
108
+ " print(\"\\nNo Missing Values Found.\")\n",
109
+ "\n",
110
+ "check_missing_values(df_Q1_data)"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "# Task 3: Write your code here:\n",
120
+ "# 4. Do we have duplicate samples?\n",
121
+ "def check_duplicates(df_Q1_data):\n",
122
+ " duplicates = df_Q1_data.duplicated().sum()\n",
123
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
124
+ " if duplicates > 0:\n",
125
+ " print(\"Dropping Duplicates...\")\n",
126
+ " df_Q1_data.drop_duplicates(inplace=True)\n",
127
+ " print(\"Duplicates Dropped.\")\n",
128
+ " else:\n",
129
+ " print(\"No Duplicate Samples Found.\")\n",
130
+ "\n",
131
+ "check_duplicates(df_Q1_data)"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4: Write your code here:\n",
141
+ "# Do we have categorical columns?\n",
142
+ "import torch\n",
143
+ "categorical_cols = df_Q1_data.select_dtypes(include=[\"object\"]).columns\n",
144
+ "\n",
145
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
146
+ "\n",
147
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
148
+ "\n",
149
+ "print('data before encoding:\\n', categorical_cols) #show before encoding\n",
150
+ "\n",
151
+ "onehot_encoder = OneHotEncoder(sparse_output=False)\n",
152
+ "\n",
153
+ "categorical_cols.reshape(-1, 1)\n",
154
+ "data_onehot_encoded = onehot_encoder.fit_transform(categorical_cols)\n",
155
+ "\n",
156
+ "print('\\nData after encoding:\\n', data_onehot_encoded)"
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
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
167
+ "standard_scaler = StandardScaler()\n",
168
+ "data_standard_scaled = standard_scaler.fit_transform(df_Q1_data) # Apply fit_transform\n",
169
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling\n"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 6: Write your code here:\n",
179
+ "plt.figure(figsize=(10, 5))\n",
180
+ "plt.hist(df_Q1_data['Delivery_Time'],bins=30, edgecolor='black')\n",
181
+ "plt.title('Data distribution')\n",
182
+ "plt.xlabel('Data')\n",
183
+ "plt.ylabel('Frequency')\n",
184
+ "plt.show()\n",
185
+ "\n",
186
+ "print(\"data right skewed\")"
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
+ "feature_cols = ['Order_ID','Distance_km','Preparation_Time_min','Courier_Experience_yrs']\n",
198
+ "X = df_clean[feature_cols]\n",
199
+ "y = df_clean['Delivery_Time']\n"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "# Task 2,3,4,5: Write your code here:\n",
209
+ "from sklearn.model_selection import KFold\n",
210
+ "\n",
211
+ "# Define K-Fold Cross Validation\n",
212
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
213
+ "\n",
214
+ "# Iterate through folds\n",
215
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
216
+ " # indexing for each fold\n",
217
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
218
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
219
+ " # print shapes\n",
220
+ " print(f\"Fold {fold}\")\n",
221
+ " print(\" X_train shape:\", X_train.shape)\n",
222
+ " print(\" X_test shape :\", X_test.shape)\n",
223
+ " print(\" y_train shape:\", y_train.shape)\n",
224
+ " print(\" y_test shape :\", y_test.shape)\n",
225
+ " print(\"-\" * 30)\n",
226
+ "\n",
227
+ " # Train Random Forest Regressor\n",
228
+ "from sklearn.ensemble import RandomForestRegressor\n",
229
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
230
+ "model.fit(X_train, y_train)\n",
231
+ "print(\"Model trained!\")\n",
232
+ "\n",
233
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
234
+ "mae_scores = []\n",
235
+ "mae_scores.append(mean_absolute_error(y_train, y_test))\n",
236
+ "mae_scores = np.array(mae_scores)\n",
237
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")"
238
+ ],
239
+ "execution_count": null,
240
+ "outputs": []
241
+ },
242
+ {
243
+ "cell_type": "code",
244
+ "metadata": {},
245
+ "source": [
246
+ "# Task 1: Write your code here:\n",
247
+ "# Feature importance\n",
248
+ "importance = pd.DataFrame({\n",
249
+ " 'feature': feature_cols,\n",
250
+ " 'importance': model.feature_importances_\n",
251
+ "}).sort_values('importance', ascending=False)\n",
252
+ "\n",
253
+ "plt.figure(figsize=(10, 6))\n",
254
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
255
+ "plt.xlabel('Importance')\n",
256
+ "plt.title('Feature Importance')\n",
257
+ "plt.gca().invert_yaxis()\n",
258
+ "plt.show()"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 2: Write your code here:\n",
268
+ "plt.figure(figsize=(10, 5))\n",
269
+ "plt.hist(df_Q1_data['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
270
+ "plt.title('Delivery time')\n",
271
+ "plt.xlabel('time')\n",
272
+ "plt.ylabel('Frequency')\n",
273
+ "plt.show()"
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/218/Q2.ipynb ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "import torch\n",
71
+ "# Split the dataset into training and testing sets\n",
72
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
73
+ "\n",
74
+ "# transform to tensors\n",
75
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
76
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
77
+ "y_train = torch.tensor(y_train.values, dtype=torch.long)\n",
78
+ "y_test = torch.tensor(y_test.values, dtype=torch.long)\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
+ "from torch.utils.data import DataLoader, TensorDataset\n",
89
+ "# Create TensorDatasets for training and testing\n",
90
+ "train_dataset = TensorDataset(X_train, y_train)\n",
91
+ "test_dataset = TensorDataset(X_test, y_test)\n",
92
+ "\n",
93
+ "# Create Dataloaders to train and test data in batches\n",
94
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
95
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
96
+ "\n",
97
+ "# Print dataset sizes\n",
98
+ "print(\"Train dataset:\", len(train_dataset))\n",
99
+ "print(\"Test dataset:\", len(test_dataset))\n",
100
+ "\n",
101
+ "# Get the first batch from the training DataLoader\n",
102
+ "X_batch, y_batch = next(iter(train_loader))\n",
103
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
104
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 3. Create DataLoaders\n",
114
+ "\n",
115
+ "\n"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# 4. Print shape of one batch\n",
125
+ "\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# 5. Display sample images\n",
135
+ "\n"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Task 1: Write your model class here:\n",
145
+ "class NN4Layer(nn.Module):\n",
146
+ " def __init__(self, input_dim, hidden_dim):\n",
147
+ " super(NN3Layer, self).__init__()\n",
148
+ "\n",
149
+ " # First linear layer: input features -> hidden layer\n",
150
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
151
+ "\n",
152
+ " # Second linear layer: hidden layer -> hidden layer\n",
153
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
154
+ "\n",
155
+ " # third layer: hidden layer -> hidden layer\n",
156
+ " self.layer3 = nn.Linear(hidden_dim,hidden_dim )\n",
157
+ "\n",
158
+ " # Output layer: hidden layer -> single continuous value\n",
159
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
160
+ "\n",
161
+ " # ReLU activation for non-linearity in hidden layers\n",
162
+ " self.relu = nn.ReLU()\n",
163
+ "\n",
164
+ " # Defines how input data flows through the network\n",
165
+ " def forward(self, x):\n",
166
+ " # First hidden layer\n",
167
+ " a1 = self.relu(self.layer1(x))\n",
168
+ "\n",
169
+ " # Second hidden layer\n",
170
+ " a2 = self.relu(self.layer2(a1))\n",
171
+ "\n",
172
+ " # third hidden layer\n",
173
+ " a3 = self.relu(self.layer3(a2))\n",
174
+ "\n",
175
+ " # Output layer (regression output)\n",
176
+ " output = self.layer4(a3)\n",
177
+ "\n",
178
+ " return output"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 2: Write your training loop here:\n",
188
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
189
+ " # Set the model to training mode\n",
190
+ " model.train()\n",
191
+ "\n",
192
+ " running_loss = 0.0\n",
193
+ "\n",
194
+ " for X_batch, y_batch in train_loader:\n",
195
+ " # Move batch to the selected device\n",
196
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
197
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
198
+ "\n",
199
+ " # Forward pass (continuous output)\n",
200
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
201
+ " loss = criterion(outputs, y_batch)\n",
202
+ "\n",
203
+ " # Backward pass & optimization\n",
204
+ " optimizer.zero_grad() # Clear previous gradients\n",
205
+ " loss.backward() # Compute gradients\n",
206
+ " optimizer.step() # Update model parameters\n",
207
+ "\n",
208
+ " running_loss += loss.item()\n",
209
+ "\n",
210
+ " # Average loss over all batches\n",
211
+ " avg_loss = running_loss / len(train_loader)\n",
212
+ "\n",
213
+ " return avg_loss"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 3: Write your validation loop here:\n",
223
+ "def validate(model, criterion, test_loader, device):\n",
224
+ " # Set the model to evaluation mode\n",
225
+ " model.eval()\n",
226
+ "\n",
227
+ " running_loss = 0.0\n",
228
+ "\n",
229
+ " with torch.no_grad():\n",
230
+ " for X_batch, y_batch in test_loader:\n",
231
+ " # Move data to device\n",
232
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
233
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
234
+ "\n",
235
+ " # Forward pass (continuous output)\n",
236
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
237
+ " loss = criterion(outputs, y_batch)\n",
238
+ "\n",
239
+ " running_loss += loss.item()\n",
240
+ "\n",
241
+ " # Average loss over all batches\n",
242
+ " avg_loss = running_loss / len(test_loader)\n",
243
+ "\n",
244
+ " return avg_loss"
245
+ ],
246
+ "execution_count": null,
247
+ "outputs": []
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "metadata": {},
252
+ "source": [
253
+ "# Task 4: Define device, model, loss, optimizer:"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 5: Start training for 20 epochs:"
263
+ ],
264
+ "execution_count": null,
265
+ "outputs": []
266
+ },
267
+ {
268
+ "cell_type": "code",
269
+ "metadata": {},
270
+ "source": [
271
+ "# Task 1: Write your code here:"
272
+ ],
273
+ "execution_count": null,
274
+ "outputs": []
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "metadata": {},
279
+ "source": [
280
+ "# Task 2 (Bonus): Write your code here:"
281
+ ],
282
+ "execution_count": null,
283
+ "outputs": []
284
+ }
285
+ ],
286
+ "metadata": {
287
+ "kernelspec": {
288
+ "display_name": "Python 3",
289
+ "name": "python3"
290
+ },
291
+ "language_info": {
292
+ "name": "python"
293
+ }
294
+ },
295
+ "nbformat": 4,
296
+ "nbformat_minor": 0
297
+ }
submissions_extracted/218/Q3.ipynb ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "\n",
13
+ "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
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "\n",
23
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
24
+ "\n",
25
+ "\n",
26
+ "\n",
27
+ "print(\"Path to dataset files:\", path)"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 1: Write your code here:\n",
37
+ "Q3_data_path=os.path.join(path,'Q3_data.csv')\n",
38
+ "df_Q3_data=pd.read_csv(Q3_data_path)"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 2: Write your code here:\n",
48
+ "print(f\"Shape:{df_Q3_data.shape}\")\n",
49
+ "df_Q3_data.head()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 3: Write your code here:\n",
59
+ "df_Q3_data.info()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# Task 4: Write your code here:\n",
69
+ "df_Q3_data.describe()"
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_Q3_data)"
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_Q3_data):\n",
99
+ " duplicates = df_Q3_data.duplicated().sum()\n",
100
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
101
+ " if duplicates > 0:\n",
102
+ " print(\"Dropping Duplicates...\")\n",
103
+ " df_Q3_data.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_Q3_data)"
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
+ "#no categroical vars"
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# Task 4: Write your code here:\n",
128
+ "# Define features and target\n",
129
+ "# Scale features\n",
130
+ "scaler = StandardScaler()\n",
131
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
132
+ "X_test_scaled = scaler.transform(X_test)"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 5: Write your code here:\n",
142
+ "plt.figure(figsize=(10, 5))\n",
143
+ "plt.hist(df_Q3_data['Target'],bins=30, edgecolor='black')\n",
144
+ "plt.title('Target')\n",
145
+ "plt.xlabel('Data')\n",
146
+ "plt.ylabel('Frequency')\n",
147
+ "plt.show()\n",
148
+ "\n",
149
+ "print(\"imbalanced\")"
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
+ "\n",
160
+ "# Define features (X) and target (y)\n",
161
+ "feature_cols = ['P_2',\t'D_39',\t'B_1',\t'B_2',\t'R_1',\t'S_3',\t'D_41',\t'B_3',\t'D_42',\t'D_43',\t...,\t'D_137'\t,'D_138',\t'D_139'\t,'D_140'\t,'D_141'\t,'D_142',\t'D_143','D_144','D_145']\n",
162
+ "X = Q3_data_clean[feature_cols]\n",
163
+ "y = Q3_data_clean['Target']"
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:"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 1: Write your code here:"
182
+ ],
183
+ "execution_count": null,
184
+ "outputs": []
185
+ },
186
+ {
187
+ "cell_type": "code",
188
+ "metadata": {},
189
+ "source": [
190
+ "# Task 2: Write your code here:"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task Bonus: Write your code here:"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ }
204
+ ],
205
+ "metadata": {
206
+ "kernelspec": {
207
+ "display_name": "Python 3",
208
+ "name": "python3"
209
+ },
210
+ "language_info": {
211
+ "name": "python"
212
+ }
213
+ },
214
+ "nbformat": 4,
215
+ "nbformat_minor": 0
216
+ }
submissions_extracted/219/Q1.ipynb ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import pandas as pd\n",
22
+ "import numpy as np\n",
23
+ "import os\n",
24
+ "\n",
25
+ "dt = pd.read_csv(os.path.join(path,'Q1_data.csv'))"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "dt.head()"
35
+ ],
36
+ "execution_count": null,
37
+ "outputs": []
38
+ },
39
+ {
40
+ "cell_type": "code",
41
+ "metadata": {},
42
+ "source": [
43
+ "dt.info()"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "dt.describe()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "from matplotlib import pyplot as plt\n",
62
+ "\n",
63
+ "# Year distribution\n",
64
+ "plt.figure(figsize=(10, 5))\n",
65
+ "plt.hist(dt['Delivery_Time'].dropna(), bins=30, edgecolor='black', color='orange')\n",
66
+ "plt.title('Delivery_Time Distribution')\n",
67
+ "plt.xlabel('Delivery_Time')\n",
68
+ "plt.ylabel('Frequency')\n",
69
+ "plt.show()"
70
+ ],
71
+ "execution_count": null,
72
+ "outputs": []
73
+ },
74
+ {
75
+ "cell_type": "code",
76
+ "metadata": {},
77
+ "source": [
78
+ "dt = dt.drop('Order_ID',axis=1)"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "dt = dt.dropna(subset=['Delivery_Time','Traffic_Level','Time_of_Day','Weather'])\n",
88
+ "dt['Courier_Experience_yrs'] = dt['Courier_Experience_yrs'].fillna( int(dt['Courier_Experience_yrs'].mean()) )\n",
89
+ "dt.isna().sum()\n"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "dt = dt.drop_duplicates()\n",
99
+ "print(dt.duplicated().sum())\n",
100
+ "\n",
101
+ "dt"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "from sklearn.preprocessing import LabelEncoder\n",
111
+ "\n",
112
+ "lb = LabelEncoder()\n",
113
+ "\n",
114
+ "dt['Weather'] = lb.fit_transform( dt['Weather'] )\n",
115
+ "dt['Traffic_Level'] = lb.fit_transform( dt['Traffic_Level'] )\n",
116
+ "dt['Time_of_Day'] = lb.fit_transform( dt['Time_of_Day'] )\n",
117
+ "dt['Vehicle_Type'] = lb.fit_transform( dt['Vehicle_Type'] )\n",
118
+ "\n",
119
+ "dt"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "from sklearn.preprocessing import StandardScaler\n",
129
+ "\n",
130
+ "X,y = dt.drop('Delivery_Time',axis=1), dt['Delivery_Time']\n",
131
+ "\n",
132
+ "std = StandardScaler()\n",
133
+ "X = std.fit_transform(X)\n"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# There are no imbalance in the data\n",
143
+ "# The data is well distributed and a linear model was trained on it (not categorical)."
144
+ ],
145
+ "execution_count": null,
146
+ "outputs": []
147
+ },
148
+ {
149
+ "cell_type": "code",
150
+ "metadata": {},
151
+ "source": [
152
+ "from sklearn.model_selection import train_test_split\n",
153
+ "\n",
154
+ "X_train,X_test,y_train,y_test = train_test_split(X,y)"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
164
+ "from sklearn.model_selection import KFold\n",
165
+ "from sklearn.ensemble import RandomForestRegressor\n",
166
+ "\n",
167
+ "model = RandomForestRegressor()\n",
168
+ "\n",
169
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
170
+ "\n",
171
+ "mae_scores = []\n",
172
+ "\n",
173
+ "for train_idx, val_idx in kfold.split(X_train):\n",
174
+ " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n",
175
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
176
+ "\n",
177
+ " # Train and predict\n",
178
+ " model.fit(X_fold_train, y_fold_train)\n",
179
+ " y_fold_pred = model.predict(X_fold_val)\n",
180
+ "\n",
181
+ " # Calculate metrics\n",
182
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
183
+ "\n",
184
+ "mae_scores = np.array(mae_scores)\n",
185
+ "\n",
186
+ "print(f\"5-Fold CV Results:\")\n",
187
+ "print(f\"MAE: {mae_scores.mean():,.2f} Minutes\")"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Feature importance\n",
197
+ "feature_importance = pd.DataFrame({\n",
198
+ " 'feature': ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
199
+ " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs'],\n",
200
+ " 'importance': model.feature_importances_\n",
201
+ "}).sort_values('importance', ascending=False)\n",
202
+ "\n",
203
+ "plt.figure(figsize=(10, 6))\n",
204
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
205
+ "plt.xlabel('Importance')\n",
206
+ "plt.title('Feature Importance')\n",
207
+ "plt.gca().invert_yaxis()\n",
208
+ "plt.show()"
209
+ ],
210
+ "execution_count": null,
211
+ "outputs": []
212
+ },
213
+ {
214
+ "cell_type": "code",
215
+ "metadata": {},
216
+ "source": [
217
+ "plt.scatter(model.predict(X_test),y_test, color='red')\n",
218
+ "plt.plot([10,120],[10,120],color='green')\n",
219
+ "plt.xlabel('Acual Y')\n",
220
+ "plt.ylabel('Predicted Y')\n",
221
+ "plt.show()"
222
+ ],
223
+ "execution_count": null,
224
+ "outputs": []
225
+ },
226
+ {
227
+ "cell_type": "code",
228
+ "metadata": {},
229
+ "source": [
230
+ "from IPython.display import clear_output\n",
231
+ "%pip install catboost -q\n",
232
+ "clear_output()\n",
233
+ "\n",
234
+ "from sklearn.metrics import mean_absolute_error\n",
235
+ "from sklearn.model_selection import KFold\n",
236
+ "from sklearn.ensemble import RandomForestRegressor\n",
237
+ "from catboost import CatBoostRegressor\n",
238
+ "\n",
239
+ "import numpy as np\n",
240
+ "\n",
241
+ "rf_model = RandomForestRegressor(random_state=42)\n",
242
+ "\n",
243
+ "cb_model = CatBoostRegressor(random_state=42, verbose=0)\n",
244
+ "\n",
245
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
246
+ "\n",
247
+ "mae_scores_averaged = []\n",
248
+ "\n",
249
+ "for train_idx, val_idx in kfold.split(X_train):\n",
250
+ " X_fold_train, X_fold_val = X_train[train_idx], X_train[val_idx]\n",
251
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
252
+ "\n",
253
+ " rf_model.fit(X_fold_train, y_fold_train)\n",
254
+ " cb_model.fit(X_fold_train, y_fold_train)\n",
255
+ "\n",
256
+ " rf_preds = rf_model.predict(X_fold_val)\n",
257
+ " cb_preds = cb_model.predict(X_fold_val)\n",
258
+ "\n",
259
+ " averaged_predictions = (rf_preds + cb_preds) / 2\n",
260
+ "\n",
261
+ " fold_mae = mean_absolute_error(y_fold_val, averaged_predictions)\n",
262
+ " mae_scores_averaged.append(fold_mae)\n",
263
+ "\n",
264
+ "print(f\"[+] Averaged Models MAE: {np.mean(mae_scores_averaged)}\")"
265
+ ],
266
+ "execution_count": null,
267
+ "outputs": []
268
+ }
269
+ ],
270
+ "metadata": {
271
+ "kernelspec": {
272
+ "display_name": "Python 3",
273
+ "name": "python3"
274
+ },
275
+ "language_info": {
276
+ "name": "python"
277
+ }
278
+ },
279
+ "nbformat": 4,
280
+ "nbformat_minor": 0
281
+ }
submissions_extracted/219/Q2.ipynb ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
70
+ "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
71
+ "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
72
+ "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
73
+ "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "from torch.utils.data import TensorDataset\n",
83
+ "\n",
84
+ "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
85
+ "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "from torch.utils.data import DataLoader\n",
95
+ "\n",
96
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
97
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "for images, labels in train_loader:\n",
107
+ " print(images.shape)\n",
108
+ " print(labels.shape)\n",
109
+ " break"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "import matplotlib.pyplot as plt\n",
119
+ "\n",
120
+ "fig, axs = plt.subplots(1, 5, figsize=(15, 3))\n",
121
+ "for i in range(5):\n",
122
+ " img = images[i].permute(1, 2, 0).numpy()\n",
123
+ " axs[i].imshow(img)\n",
124
+ "plt.show()"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "import torch.nn as nn\n",
134
+ "\n",
135
+ "class AgePredictor(nn.Module):\n",
136
+ " def __init__(self):\n",
137
+ " super(AgePredictor, self).__init__()\n",
138
+ " self.fc1 = nn.Linear(3*36*36, 512)\n",
139
+ " self.fc2 = nn.Linear(512, 256)\n",
140
+ " self.fc3 = nn.Linear(256, 128)\n",
141
+ " self.fc4 = nn.Linear(128, 1)\n",
142
+ "\n",
143
+ " def forward(self, x):\n",
144
+ " x = x.view(-1,3*36*36)\n",
145
+ " x = torch.relu(self.fc1(x))\n",
146
+ " x = torch.relu(self.fc2(x))\n",
147
+ " x = torch.relu(self.fc3(x))\n",
148
+ " x = self.fc4(x)\n",
149
+ " return x"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "def train(model, loader, optimizer, criterion, device):\n",
159
+ " model.train()\n",
160
+ " total_loss = 0\n",
161
+ " for images, labels in loader:\n",
162
+ " images, labels = images.to(device), labels.to(device)\n",
163
+ " optimizer.zero_grad()\n",
164
+ " outputs = model(images)\n",
165
+ " loss = criterion(outputs.squeeze(), labels)\n",
166
+ " loss.backward()\n",
167
+ " optimizer.step()\n",
168
+ " total_loss += loss.item()\n",
169
+ " return total_loss / len(loader)"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "def validate(model, loader, criterion, device):\n",
179
+ " model.eval()\n",
180
+ " total_loss = 0\n",
181
+ " with torch.no_grad():\n",
182
+ " for images, labels in loader:\n",
183
+ " images, labels = images.to(device), labels.to(device)\n",
184
+ " outputs = model(images)\n",
185
+ " loss = criterion(outputs.squeeze(), labels)\n",
186
+ " total_loss += loss.item()\n",
187
+ " return total_loss / len(loader)"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n",
197
+ "model = AgePredictor().to(device)\n",
198
+ "criterion = nn.MSELoss()\n",
199
+ "optimizer = torch.optim.Adam(model.parameters(), lr=0.001)"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ },
204
+ {
205
+ "cell_type": "code",
206
+ "metadata": {},
207
+ "source": [
208
+ "train_losses = []\n",
209
+ "val_losses = []\n",
210
+ "for epoch in range(20):\n",
211
+ " train_loss = train(model, train_loader, optimizer, criterion, device)\n",
212
+ " val_loss = validate(model, test_loader, criterion, device)\n",
213
+ " train_losses.append(train_loss)\n",
214
+ " val_losses.append(val_loss)\n",
215
+ " print(f\"Epoch {epoch+1}: Train Loss {train_loss:.4f}, Val Loss {val_loss:.4f}\")"
216
+ ],
217
+ "execution_count": null,
218
+ "outputs": []
219
+ },
220
+ {
221
+ "cell_type": "code",
222
+ "metadata": {},
223
+ "source": [
224
+ "plt.plot(train_losses, label='Train Loss')\n",
225
+ "plt.plot(val_losses, label='Val Loss')\n",
226
+ "plt.xlabel('Epoch')\n",
227
+ "plt.ylabel('Loss')\n",
228
+ "plt.legend()\n",
229
+ "plt.show()"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "model.eval()\n",
239
+ "with torch.no_grad():\n",
240
+ " for images, labels in test_loader:\n",
241
+ " images = images.to(device)\n",
242
+ " preds = model(images).squeeze().cpu().numpy()\n",
243
+ " labels = labels.numpy()\n",
244
+ " break\n",
245
+ "\n",
246
+ "fig, axs = plt.subplots(1, 5, figsize=(15, 3))\n",
247
+ "for i in range(5):\n",
248
+ " img = images[i].permute(1, 2, 0).cpu().numpy()\n",
249
+ " axs[i].imshow(img)\n",
250
+ " axs[i].set_title(f\"Pred: {preds[i]:.1f}, Actual: {labels[i]}\")\n",
251
+ " axs[i].axis('off')\n",
252
+ "plt.show()"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ }
257
+ ],
258
+ "metadata": {
259
+ "kernelspec": {
260
+ "display_name": "Python 3",
261
+ "name": "python3"
262
+ },
263
+ "language_info": {
264
+ "name": "python"
265
+ }
266
+ },
267
+ "nbformat": 4,
268
+ "nbformat_minor": 0
269
+ }
submissions_extracted/219/Q3.ipynb ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "import os\n",
28
+ "\n",
29
+ "df = pd.read_csv(os.path.join(path, 'Q3_data.csv'))"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "df.head()"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "df.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "df.describe()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "for col in df.columns:\n",
66
+ " df[col] = df[col].fillna( df[col].mean() )\n",
67
+ "\n",
68
+ "df"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "print(df.duplicated().sum())\n",
78
+ "df = df.drop_duplicates()"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "df.select_dtypes(include=['object']).columns\n",
88
+ "\n",
89
+ "# There isn't any"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "from sklearn.preprocessing import StandardScaler\n",
99
+ "\n",
100
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\")\n",
101
+ "\n",
102
+ "scaler = StandardScaler()\n",
103
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
104
+ "df.head()\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "from sklearn.model_selection import train_test_split\n",
114
+ "\n",
115
+ "X,y = df.drop('Target',axis=1), df['Target']\n",
116
+ "\n",
117
+ "# split ratio (80% train, 20% test)\n",
118
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
119
+ " X,\n",
120
+ " y,\n",
121
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
122
+ " random_state=42, # reproducible output\n",
123
+ " shuffle=True, # representative splits\n",
124
+ ")\n"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "from IPython.display import clear_output\n",
134
+ "%pip install catboost -q\n",
135
+ "clear_output()\n",
136
+ "\n",
137
+ "from sklearn.metrics import f1_score,accuracy_score\n",
138
+ "from sklearn.model_selection import KFold\n",
139
+ "from sklearn.ensemble import RandomForestRegressor\n",
140
+ "from catboost import CatBoostClassifier\n",
141
+ "\n",
142
+ "import numpy as np\n",
143
+ "\n",
144
+ "\n",
145
+ "cb_model = CatBoostClassifier(random_state=42, verbose=0)\n",
146
+ "\n",
147
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
148
+ "\n",
149
+ "f1_scores_averaged = []\n",
150
+ "acc_scores_averaged = []\n",
151
+ "\n",
152
+ "for train_idx, val_idx in kfold.split(X_train):\n",
153
+ " X_fold_train, X_fold_val = X_train.iloc[train_idx], X_train.iloc[val_idx]\n",
154
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
155
+ "\n",
156
+ " cb_model.fit(X_fold_train, y_fold_train)\n",
157
+ "\n",
158
+ " cb_preds = cb_model.predict(X_fold_val)\n",
159
+ "\n",
160
+ " f1_scores_averaged.append(f1_score(y_fold_val, cb_preds))\n",
161
+ " acc_scores_averaged.append(accuracy_score(y_fold_val, cb_preds))\n",
162
+ "\n",
163
+ "print(f\"[+] CatBoost \\nAvg F1: {np.mean(f1_scores_averaged)}\\nAvg Accuracy: {np.mean(acc_scores_averaged)}\")"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "import matplotlib.pyplot as plt\n",
173
+ "\n",
174
+ "# Feature importance\n",
175
+ "feature_importance = pd.DataFrame({\n",
176
+ " 'feature': df.drop('Target',axis=1).columns,\n",
177
+ " 'importance': cb_model.feature_importances_\n",
178
+ "}).sort_values('importance', ascending=False)\n",
179
+ "\n",
180
+ "plt.figure(figsize=(10, 6))\n",
181
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
182
+ "plt.xlabel('Importance')\n",
183
+ "plt.title('Feature Importance')\n",
184
+ "plt.gca().invert_yaxis()\n",
185
+ "plt.show()\n",
186
+ "\n",
187
+ "# Something Strange Xd :)"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "golden_strange_weird_feature_idx = list(cb_model.feature_importances_).index(max(cb_model.feature_importances_))\n",
197
+ "print('The weird feature is :',df.drop('Target',axis=1).columns[0])"
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/22/Q2.ipynb ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "import kagglehub\n",
71
+ "import pandas as pd\n",
72
+ "import numpy as np\n",
73
+ "import matplotlib.pyplot as plt\n",
74
+ "import seaborn as sns\n",
75
+ "from sklearn.model_selection import train_test_split, KFold, cross_val_score\n",
76
+ "from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler\n",
77
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
78
+ "from sklearn.linear_model import LogisticRegression\n",
79
+ "from sklearn.tree import DecisionTreeClassifier\n",
80
+ "from sklearn.ensemble import RandomForestClassifier\n",
81
+ "from sklearn.svm import SVC\n"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# 2. Create TensorDataset objects\n",
91
+ "\n",
92
+ "# Training dataset\n",
93
+ "train_dataset = CIFAR10(root='./datasets', train=True, transform=to_tensor, download=True)\n",
94
+ "# Testing dataset\n",
95
+ "test_dataset = CIFAR10(root='./datasets', train=False, transform=to_tensor, download=True)\n",
96
+ "\n",
97
+ "# Print one sample from the dataset\n",
98
+ "sample_image, sample_label = train_dataset[0]\n",
99
+ "print(f\"Image shape: {sample_image.shape}\") # (3, 32, 32)\n",
100
+ "print(f\"Label: {sample_label}\")\n"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 3. Create DataLoaders\n",
110
+ "\n",
111
+ "# DataLoader for training\n",
112
+ " datatrain_loader = DataLoader( train_dataset, batch_size=32, shuffle=True, num_workers=2)\n",
113
+ " # DataLoader for test\n",
114
+ " datatest_loader = DataLoader( test_dataset, batch_size=32, shuffle=False, num_workers=2)\n",
115
+ " # Get the first batch from the training\n",
116
+ " DataLoaderX_batch, y_batch = next(iter(train_loader))print(f\"Training batch input shape: {X_batch.shape}\")print(f\"Training batch labels shape: {y_batch.shape}\")\n",
117
+ "\n",
118
+ "\n",
119
+ "keyboard_arrow_down\n",
120
+ "\n",
121
+ "more_horiz\n",
122
+ " Training batch input shape: torch.Size([32, 3, 32, 32])\n",
123
+ "Training batch labels shape: torch.Size([32])\n",
124
+ "\n"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# 4. Print shape of one batch\n",
134
+ "X_batch, y_batch = next(iter(train_loader))print(f\"Training batch input shape: {X_batch.shape}\")print(f\"Training batch labels shape: {y_batch.shape}\")\n",
135
+ "\n",
136
+ "\n",
137
+ "keyboard_arrow_down\n",
138
+ "\n",
139
+ "more_horiz\n",
140
+ " Training batch input shape: torch.Size([32, 3, 32, 32])\n",
141
+ "Training batch labels shape: torch.Size([32])\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
+ "# Get one batch of images and labels\n",
152
+ "images, labels = next(iter(train_loader))\n",
153
+ "\n",
154
+ "# Display the first 6 images in the batch\n",
155
+ "plt.figure(figsize=(8, 4))\n",
156
+ "\n",
157
+ "for i in range(6):\n",
158
+ " plt.subplot(2, 3, i + 1)\n",
159
+ "\n",
160
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
161
+ " img = images[i].permute(1, 2, 0)\n",
162
+ "\n",
163
+ " plt.imshow(img)\n",
164
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
165
+ " plt.axis('off')\n",
166
+ "\n",
167
+ "plt.tight_layout()\n",
168
+ "plt.show()\n"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 1: Write your model class here:\n",
178
+ "class NN4Layer(nn.Module):\n",
179
+ "\n",
180
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
181
+ " super(NN4Layer, self).__init__()\n",
182
+ "\n",
183
+ " # TODO: What are the dimensions of the first layer? (hint: features? hidden neurons?)\n",
184
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
185
+ "\n",
186
+ " # TODO: What are the dimensions from previous and next layer?\n",
187
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
188
+ "\n",
189
+ " # TODO: What are the dimensions from previous and next layer?\n",
190
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
191
+ "\n",
192
+ " # TODO: What are the dimensions from previous and next layer?\n",
193
+ " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
194
+ "\n",
195
+ " # activation function for non-linearity\n",
196
+ " self.relu = nn.ReLU()\n"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 2: Write your training loop here:\n",
206
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
207
+ " # Set the model to training mode\n",
208
+ " model.train()\n",
209
+ "\n",
210
+ " running_loss = 0.0\n",
211
+ "\n",
212
+ " for X_batch, y_batch in train_loader:\n",
213
+ " # Move batch to the selected device\n",
214
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
215
+ " y_batch = y_batch.to(device)\n",
216
+ "\n",
217
+ " # Forward pass\n",
218
+ " # TODO: make predictions\n",
219
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
220
+ " # TODO: compute loss\n",
221
+ " loss = criterion(outputs, y_batch)\n",
222
+ "\n",
223
+ " # Backward pass & optimization\n",
224
+ " optimizer.zero_grad() # Clear previous gradients\n",
225
+ " loss.backward() # Compute gradients\n",
226
+ " optimizer.step() # Update model parameters\n",
227
+ "\n",
228
+ " running_loss += loss.item()\n",
229
+ "\n",
230
+ " # Average loss over all batches\n",
231
+ " avg_loss = running_loss / len(train_loader)\n",
232
+ "\n",
233
+ " return avg_loss"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "metadata": {},
241
+ "source": [
242
+ "# Task 3: Write your validation loop here:\n",
243
+ "def validate(model, criterion, test_loader, device):\n",
244
+ " # Set the model to evaluation mode\n",
245
+ " model.eval()\n",
246
+ "\n",
247
+ " running_loss = 0.0\n",
248
+ " 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.view(X_batch.size(0), -1).to(device)\n",
255
+ " y_batch = y_batch.to(device)\n",
256
+ "\n",
257
+ " # Forward pass\n",
258
+ " # TODO: make predictions\n",
259
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
260
+ " # TODO: compute loss\n",
261
+ " loss = criterion(outputs, y_batch)\n",
262
+ " running_loss += loss.item()\n",
263
+ "\n",
264
+ " # TODO: Apply Softmax to get probabilities\n",
265
+ " probabilities = F.softmax(outputs, dim=1)\n",
266
+ "\n",
267
+ " # TODO: Multiclass predictions\n",
268
+ " predicted = torch.argmax(probabilities, dim=1)\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
+ " # TODO: how do we calculate accuracy?\n",
276
+ " accuracy = correct / total\n",
277
+ "\n",
278
+ " return avg_loss, accuracy"
279
+ ],
280
+ "execution_count": null,
281
+ "outputs": []
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "metadata": {},
286
+ "source": [
287
+ "# Task 4: Define device, model, loss, optimizer:\n",
288
+ "# Scatter plot: Predicted vs Actual\n",
289
+ "plt.figure(figsize=(8, 6))\n",
290
+ "\n",
291
+ "# Plot: Predicted vs Actual scatter\n",
292
+ "plt.scatter(y_test.numpy(), predictions.flatten(), alpha=0.5, s=10, c='steelblue')\n",
293
+ "\n",
294
+ "# Add perfect prediction line\n",
295
+ "min_val = min(y_test.min(), predictions.min())\n",
296
+ "max_val = max(y_test.max(), predictions.max())\n",
297
+ "plt.plot([min_val, max_val], [min_val, max_val], 'r--', lw=2, label='Perfect Prediction')\n",
298
+ "\n",
299
+ "plt.xlabel('Actual Price ($)', fontsize=12)\n",
300
+ "plt.ylabel('Predicted Price ($)', fontsize=12)\n",
301
+ "plt.title('Predicted vs Actual Diamond Prices', fontsize=14)\n",
302
+ "plt.legend()\n",
303
+ "plt.grid(True, alpha=0.3)\n",
304
+ "\n",
305
+ "plt.tight_layout()\n",
306
+ "plt.show()"
307
+ ],
308
+ "execution_count": null,
309
+ "outputs": []
310
+ },
311
+ {
312
+ "cell_type": "code",
313
+ "metadata": {},
314
+ "source": [
315
+ "# Task 1: Write your code here:\n",
316
+ "\n",
317
+ "Plotting resultsplt.figure(figsize=(7, 5))plt.plot(train_losses, label='Train Loss')plt.plot(val_losses, label='Validation Loss')plt.title('Loss over Epochs')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.tight_layout()plt.show()"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "# Task 2 (Bonus): Write your code here:"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "# Task 5: Start training for 20 epochs:\n",
336
+ "print (ANON)\n"
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/220/Q1.ipynb ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "!pip install catboost"
22
+ ],
23
+ "execution_count": null,
24
+ "outputs": []
25
+ },
26
+ {
27
+ "cell_type": "code",
28
+ "metadata": {},
29
+ "source": [
30
+ "# Task 1: Write your code here:\n",
31
+ "import os\n",
32
+ "import pandas as pd\n",
33
+ "import numpy as np\n",
34
+ "from sklearn.model_selection import KFold\n",
35
+ "from sklearn.preprocessing import StandardScaler, MinMaxScaler, LabelEncoder, OneHotEncoder\n",
36
+ "\n",
37
+ "from sklearn.ensemble import RandomForestRegressor\n",
38
+ "from sklearn.metrics import mean_absolute_error\n",
39
+ "from catboost import CatBoostClassifier\n",
40
+ "\n",
41
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
42
+ "df = pd.read_csv(csv_path)"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "df.head()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 3: Write your code here:\n",
62
+ "df.info()"
63
+ ],
64
+ "execution_count": null,
65
+ "outputs": []
66
+ },
67
+ {
68
+ "cell_type": "code",
69
+ "metadata": {},
70
+ "source": [
71
+ "# Task 4: Write your code here:\n",
72
+ "df.describe()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "# Task 5: Write your code here:\n",
82
+ "plt.figure(figsize=(10, 5))\n",
83
+ "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n",
84
+ "plt.title('Target Distribution')\n",
85
+ "plt.xlabel('Target')\n",
86
+ "plt.ylabel('Frequency')\n",
87
+ "plt.show()"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# Task 1: Write your code here:\n",
97
+ "df = df.drop(columns=\"Order_ID\", axis=1)\n",
98
+ "df.head()"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# Task 2: Write your code here:\n",
108
+ "# Checking the missing values\n",
109
+ "# print(\"Missing values per column:\")\n",
110
+ "# print(df.isnull().sum())\n",
111
+ "# print(f\"\\nTotal missing: {df.isnull().sum().sum()}\")\n",
112
+ "\n",
113
+ "\n",
114
+ "# We need to copy the data before cleaning\n",
115
+ "df_clean = df.copy()\n",
116
+ "\n",
117
+ "# I will drop the missing values in Weather, Traffic Level, Time_of_Day, and Courier_experience_yrs\n",
118
+ "cols_to_drop = ['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs']\n",
119
+ "df_clean = df_clean.dropna(subset=cols_to_drop)\n",
120
+ "\n",
121
+ "\n",
122
+ "# I will fill the missing target values with the mean:\n",
123
+ "df_clean['Delivery_Time'] = df_clean['Delivery_Time'].fillna(df_clean['Delivery_Time'].mean())\n"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Task 3: Write your code here:\n",
133
+ "\n",
134
+ "print(f\"Duplicates: {df_clean.duplicated().sum()}\")\n",
135
+ "\n",
136
+ "# We have 489 duplicates\n",
137
+ "df_clean.drop_duplicates(inplace=True)"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "# Task 4: Write your code here:\n",
147
+ "categorical_cols = df_clean.select_dtypes(include=['object']).columns\n",
148
+ "categorical_cols = categorical_cols.drop('Traffic_Level')\n",
149
+ "\n",
150
+ "# Traffic Level is ordinal and so label encoder is needed\n",
151
+ "le = LabelEncoder()\n",
152
+ "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n",
153
+ "\n",
154
+ "# One hot encoding for nominal columns\n",
155
+ "df_clean = pd.get_dummies(df_clean, columns=categorical_cols, drop_first=True, dtype=int)"
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
+ "X = df_clean.drop('Delivery_Time', axis=1).astype(float)\n",
166
+ "y = df_clean['Delivery_Time']\n",
167
+ "\n",
168
+ "scaler = StandardScaler()\n",
169
+ "X_scaled = scaler.fit_transform(X)"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 6: Write your code here:\n",
179
+ "# Prediction task doesn't have classes or imbalance"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 1: Write your code here:\n",
189
+ "X = df_clean.drop('Delivery_Time', axis=1).astype(float)\n",
190
+ "y = df_clean['Delivery_Time']"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task 2,3,4,5: Write your code here:\n",
200
+ "\n",
201
+ "scores = []\n",
202
+ "\n",
203
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
204
+ "\n",
205
+ "for fold, (train_idx, val_idx) in enumerate(kf.split(X)):\n",
206
+ " X_train, X_test = X.iloc[train_idx], X.iloc[val_idx]\n",
207
+ " y_train, y_test = y.iloc[train_idx], y.iloc[val_idx]\n",
208
+ " print(f\"Fold {fold+1}: Train={len(train_idx)}, Val={len(val_idx)}\")\n",
209
+ "\n",
210
+ " model = RandomForestRegressor(n_estimators=100, max_depth=10, random_state=42)\n",
211
+ " model.fit(X_train, y_train)\n",
212
+ "\n",
213
+ " y_pred = model.predict(X_test)\n",
214
+ "\n",
215
+ " mae = mean_absolute_error(y_test, y_pred)\n",
216
+ " scores.append(mae)\n",
217
+ "\n",
218
+ "\n",
219
+ "score = sum(scores)/len(scores)\n",
220
+ "\n",
221
+ "print(f\"The average score of all folds is: {score}\")\n",
222
+ ""
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "# Task 1: Write your code here:\n",
232
+ "feature_importance = pd.DataFrame({\n",
233
+ " 'feature': X.columns,\n",
234
+ " 'importance': model.feature_importances_\n",
235
+ "}).sort_values('importance', ascending=True)\n",
236
+ "\n",
237
+ "plt.figure(figsize=(10, 8))\n",
238
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
239
+ "plt.xlabel('Importance')\n",
240
+ "plt.title('Feature Importance')\n",
241
+ "plt.show()"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# Task 2: Write your code here:\n",
251
+ "plt.hist(y_pred)"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task Bonus: Write your code here:\n",
261
+ "\n",
262
+ "# Defining the models\n",
263
+ "sklearn_models = {\n",
264
+ " \"RandomForest\": RandomForestRegressor(\n",
265
+ " n_estimators=100,\n",
266
+ " max_depth=10,\n",
267
+ " random_state=42)\n",
268
+ " ,\n",
269
+ " \"CatBoost\": CatBoostClassifier(\n",
270
+ " verbose=0,\n",
271
+ " n_estimators=320,\n",
272
+ " max_depth=4\n",
273
+ " )\n",
274
+ "}"
275
+ ],
276
+ "execution_count": null,
277
+ "outputs": []
278
+ },
279
+ {
280
+ "cell_type": "code",
281
+ "metadata": {},
282
+ "source": [
283
+ "n_splits = 5\n",
284
+ "\n",
285
+ "scores = []\n",
286
+ "\n",
287
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
288
+ "\n",
289
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
290
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
291
+ "\n",
292
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
293
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
294
+ "\n",
295
+ " random_f = sklearn_models[\"RandomForest\"]\n",
296
+ " catboost = sklearn_models[\"CatBoost\"]\n",
297
+ "\n",
298
+ " random_f.fit(X_train, y_train)\n",
299
+ " catboost.fit(X_train, y_train)\n",
300
+ "\n",
301
+ " y_pred_random = model.predict(X_test)\n",
302
+ " y_pred_catboost = model.predict(X_test)\n",
303
+ "\n",
304
+ " y_pred_avg = (y_pred_random + y_pred_catboost) / 2\n",
305
+ "\n",
306
+ " mae = mean_absolute_error(y_test, y_pred_avg)\n",
307
+ "\n",
308
+ " scores.append(mae)\n"
309
+ ],
310
+ "execution_count": null,
311
+ "outputs": []
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "metadata": {},
316
+ "source": [
317
+ "print(sum(scores) / len(scores))"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ }
329
+ ],
330
+ "metadata": {
331
+ "kernelspec": {
332
+ "display_name": "Python 3",
333
+ "name": "python3"
334
+ },
335
+ "language_info": {
336
+ "name": "python"
337
+ }
338
+ },
339
+ "nbformat": 4,
340
+ "nbformat_minor": 0
341
+ }
submissions_extracted/220/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 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
+ "# Imports\n",
69
+ "import torch\n",
70
+ "import torch.nn as nn\n",
71
+ "from torch.optim import Adam, SGD, AdamW\n",
72
+ "from torch.utils.data import DataLoader, TensorDataset\n",
73
+ "\n",
74
+ "import matplotlib.pyplot as plt"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
84
+ "\n",
85
+ "X_train_tensor = torch.tensor(X_train, dtype=torch.float32)\n",
86
+ "X_test_tensor = torch.tensor(X_test, dtype=torch.float32)\n",
87
+ "y_train_tensor = torch.tensor(y_train, dtype=torch.float32)\n",
88
+ "y_test_tensor = torch.tensor(y_test, dtype=torch.float32)\n"
89
+ ],
90
+ "execution_count": null,
91
+ "outputs": []
92
+ },
93
+ {
94
+ "cell_type": "code",
95
+ "metadata": {},
96
+ "source": [
97
+ "# 2. Create TensorDataset objects\n",
98
+ "\n",
99
+ "train_dataset = TensorDataset(X_train_tensor, y_train_tensor)\n",
100
+ "test_dataset = TensorDataset(X_test_tensor, y_test_tensor)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 3. Create DataLoaders\n",
110
+ "\n",
111
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
112
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# 4. Print shape of one batch\n",
122
+ "\n",
123
+ "X_batch, y_batch = next(iter(train_loader))\n",
124
+ "print(f\"Batch shape: {X_batch.shape}\")"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# 5. Display sample images\n",
134
+ "\n",
135
+ "# Get one batch of images and labels\n",
136
+ "images, labels = next(iter(train_loader))\n",
137
+ "\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
+ " plt.imshow(images[i][0], cmap='BrBG')\n",
144
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
145
+ " plt.axis('off')\n",
146
+ "\n",
147
+ "plt.tight_layout()\n",
148
+ "plt.show()"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 1: Write your model class here:\n",
158
+ "class NN4Layer(nn.Module):\n",
159
+ "\n",
160
+ " def __init__(self, input_dim, hidden_dim):\n",
161
+ " super(NN4Layer, self).__init__()\n",
162
+ "\n",
163
+ " # First linear layer: input features -> hidden layer\n",
164
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
165
+ "\n",
166
+ " # Second linear layer: hidden layer -> hidden layer\n",
167
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
168
+ "\n",
169
+ " # Second linear layer: hidden layer -> hidden layer\n",
170
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
171
+ "\n",
172
+ " # Output layer: layer: hidden -> output\n",
173
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
174
+ "\n",
175
+ " # ReLU activation for non-linearity\n",
176
+ " self.relu = nn.ReLU()\n",
177
+ "\n",
178
+ " # Defines how input data flows through the network\n",
179
+ " def forward(self, x):\n",
180
+ " # First hidden layer\n",
181
+ " z1 = self.layer1(x)\n",
182
+ " a1 = self.relu(z1)\n",
183
+ "\n",
184
+ " # Second hidden layer\n",
185
+ " z2 = self.layer2(a1)\n",
186
+ " a2 = self.relu(z2)\n",
187
+ "\n",
188
+ "\n",
189
+ " # Second hidden layer\n",
190
+ " z3 = self.layer3(a2)\n",
191
+ " a3 = self.relu(z3)\n",
192
+ "\n",
193
+ " # Output layer Raw number for prediction\n",
194
+ " output = self.layer4(a3)\n",
195
+ "\n",
196
+ " return output\n"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 2: Write your training loop here:\n",
206
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
207
+ " # Set the model to training mode\n",
208
+ " model.train()\n",
209
+ "\n",
210
+ " running_loss = 0.0\n",
211
+ "\n",
212
+ " for X_batch, y_batch in train_loader:\n",
213
+ " # Move batch to the selected device\n",
214
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
215
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
216
+ "\n",
217
+ "\n",
218
+ " # Forward pass\n",
219
+ " outputs = model(X_batch)\n",
220
+ " loss = criterion(outputs, y_batch)\n",
221
+ "\n",
222
+ " # Backward pass & optimization\n",
223
+ " optimizer.zero_grad() # Clear previous gradients\n",
224
+ " loss.backward() # Compute gradients\n",
225
+ " optimizer.step() # Update model parameters\n",
226
+ "\n",
227
+ " running_loss += loss.item()\n",
228
+ "\n",
229
+ " # Average loss over all batches\n",
230
+ " avg_loss = running_loss / len(train_loader)\n",
231
+ "\n",
232
+ " return avg_loss"
233
+ ],
234
+ "execution_count": null,
235
+ "outputs": []
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "metadata": {},
240
+ "source": [
241
+ "# Task 3: Write your validation loop here:\n",
242
+ "def validate(model, criterion, test_loader, device):\n",
243
+ " # Set the model to evaluation mode\n",
244
+ " model.eval()\n",
245
+ "\n",
246
+ " running_loss = 0.0\n",
247
+ " correct = 0\n",
248
+ " total = 0\n",
249
+ "\n",
250
+ " with torch.no_grad():\n",
251
+ " for X_batch, y_batch in test_loader:\n",
252
+ " # Move data to device\n",
253
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
254
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
255
+ "\n",
256
+ " # Forward pass\n",
257
+ " outputs = model(X_batch)\n",
258
+ "\n",
259
+ " loss = criterion(outputs, y_batch)\n",
260
+ " running_loss += loss.item()\n",
261
+ "\n",
262
+ "\n",
263
+ " avg_loss = running_loss / len(test_loader)\n",
264
+ "\n",
265
+ " return avg_loss"
266
+ ],
267
+ "execution_count": null,
268
+ "outputs": []
269
+ },
270
+ {
271
+ "cell_type": "code",
272
+ "metadata": {},
273
+ "source": [
274
+ "# Task 4: Define device, model, loss, optimizer:\n",
275
+ "# Device setup\n",
276
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
277
+ "\n",
278
+ "# Model parameters\n",
279
+ "input_dim = 3 * 36 * 36\n",
280
+ "hidden_dim = 16 # Design choice\n",
281
+ "\n",
282
+ "# Instantiate model\n",
283
+ "model = NN4Layer(input_dim=input_dim, hidden_dim=hidden_dim).to(device)\n",
284
+ "\n",
285
+ "# Print the model architecture\n",
286
+ "print(\"Model Architecture:\\n\")\n",
287
+ "print(model)\n",
288
+ "\n",
289
+ "# Calculate the total number of trainable parameters\n",
290
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
291
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
292
+ ],
293
+ "execution_count": null,
294
+ "outputs": []
295
+ },
296
+ {
297
+ "cell_type": "code",
298
+ "metadata": {},
299
+ "source": [
300
+ "# Task 5: Start training for 20 epochs:\n",
301
+ "\n",
302
+ "\n",
303
+ "\n",
304
+ "\n",
305
+ "\n",
306
+ "# Got stuck here with a float TypeError. Part 3 (Plots) is implemented\n",
307
+ "\n",
308
+ "\n",
309
+ "\n",
310
+ "\n",
311
+ "\n",
312
+ "\n",
313
+ "num_epochs = 20\n",
314
+ "learning_rate = 0.001\n",
315
+ "\n",
316
+ "# Define criterion (loss function)\n",
317
+ "criterion = nn.MSELoss()\n",
318
+ "# Define optimizer\n",
319
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
320
+ "\n",
321
+ "\n",
322
+ "\n",
323
+ "\n",
324
+ "\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
+ "\n",
343
+ "print('Training Complete!')\n",
344
+ "\n"
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
+ "\n",
355
+ "# Plotting results\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/220/Q3.ipynb ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\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
+ "# Imports\n",
27
+ "\n",
28
+ "import pandas as pd\n",
29
+ "import numpy as np\n",
30
+ "from sklearn.model_selection import StratifiedKFold\n",
31
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder\n",
32
+ "import matplotlib.pyplot as plt\n",
33
+ "from sklearn.metrics import accuracy_score, f1_score"
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
+ "df_raw = pd.read_csv(\"/kaggle/input/q3-exam-data/Q3_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
+ "df_raw.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_raw.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_raw.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
+ "\n",
84
+ "# Checking missing values\n",
85
+ "\n",
86
+ "# print(\"Missing values per column:\")\n",
87
+ "# print(df_raw.isnull().sum())\n",
88
+ "# print(f\"\\nTotal missing: {df_raw.isnull().sum().sum()}\")\n",
89
+ "\n",
90
+ "df = df_raw.copy()\n",
91
+ "\n",
92
+ "cols = df.columns.drop('Target')\n",
93
+ "\n",
94
+ "df[cols] = df[cols].fillna(df[cols].mean())"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 2: Write your code here:\n",
104
+ "print(f\"Duplicates: {df.duplicated().sum()}\")\n",
105
+ "\n",
106
+ "# No duplicates"
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 = df.select_dtypes(include=['object']).columns\n",
117
+ "print(\"Categorical columns:\", list(categorical_cols))\n",
118
+ "\n",
119
+ "# There are no categorical columns"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 4: Write your code here:\n",
129
+ "X = df[cols]\n",
130
+ "\n",
131
+ "scaler = StandardScaler()\n",
132
+ "X_scaled = scaler.fit_transform(X)"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 5: Write your code here:\n",
142
+ "plt.figure(figsize=(10, 5))\n",
143
+ "plt.hist(df['Target'], bins=2, edgecolor='black')\n",
144
+ "plt.title('Target Distribution')\n",
145
+ "plt.xlabel('Target')\n",
146
+ "plt.ylabel('Frequency')\n",
147
+ "plt.show()\n",
148
+ "\n",
149
+ "\n",
150
+ "# There is an imbalance, this Stratification is advised"
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[cols]\n",
161
+ "y = df['Target']\n"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "X"
171
+ ],
172
+ "execution_count": null,
173
+ "outputs": []
174
+ },
175
+ {
176
+ "cell_type": "code",
177
+ "metadata": {},
178
+ "source": [
179
+ "# Installing Catboost\n",
180
+ "!pip install catboost"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "# Task 2,3,4,5: Write your code here:\n",
190
+ "from catboost import CatBoostClassifier\n",
191
+ "\n",
192
+ "n_splits=5\n",
193
+ "\n",
194
+ "# To store scores\n",
195
+ "accuracy_all = []\n",
196
+ "f1_all = []\n",
197
+ "\n",
198
+ "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42 )\n",
199
+ "\n",
200
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
201
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
202
+ "\n",
203
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
204
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
205
+ "\n",
206
+ " model = CatBoostClassifier(n_estimators=320, max_depth=4)\n",
207
+ " model.fit(X_train, y_train) # train\n",
208
+ " y_pred = model.predict(X_test) # validate\n",
209
+ "\n",
210
+ " # Calculate evaluation metrics\n",
211
+ " accuracy = accuracy_score(y_test, y_pred)\n",
212
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
213
+ "\n",
214
+ " # Store results\n",
215
+ " accuracy_all.append(accuracy)\n",
216
+ " f1_all.append(f1)"
217
+ ],
218
+ "execution_count": null,
219
+ "outputs": []
220
+ },
221
+ {
222
+ "cell_type": "code",
223
+ "metadata": {},
224
+ "source": [
225
+ "accuracy_avg = sum(accuracy_all) / len(accuracy_all)\n",
226
+ "f1_avg = sum(f1_all) / len(f1_all)\n",
227
+ "\n",
228
+ "print(f\"Average accuracy is: {accuracy_avg}\")\n",
229
+ "print(f\"Average f1 is: {f1_avg}\")"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Task 1: Write your code here:\n",
239
+ "\n",
240
+ "logistic_importance = list(zip(X.columns, model.feature_importances_))\n",
241
+ "sorted_logistic_importance = sorted(logistic_importance, key=lambda x: abs(x[1]), reverse=True)\n",
242
+ "sorted_logistic_importance = sorted_logistic_importance[:10] # Choosing the highest 10 features\n",
243
+ "\n",
244
+ "\n",
245
+ "# Extract sorted features and their coefficients\n",
246
+ "features, coefficients = zip(*sorted_logistic_importance)\n",
247
+ "\n",
248
+ "\n",
249
+ "\n",
250
+ "# Plot feature importances\n",
251
+ "plt.figure(figsize=(10, 6))\n",
252
+ "plt.barh(features, np.abs(coefficients), color='darkblue')\n",
253
+ "plt.xlabel('Coefficient Value')\n",
254
+ "plt.ylabel('Features')\n",
255
+ "plt.title('Logistic Regression Feature Importance')\n",
256
+ "plt.gca().invert_yaxis() # Invert y-axis to show the most important features at the top\n",
257
+ "plt.show()"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Task 2: Write your code here:\n",
267
+ "print(\" The most important feature is: P_2\")"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task Bonus: Write your code here:\n",
277
+ "\n",
278
+ "\n",
279
+ "\n",
280
+ "\n",
281
+ "# Everything worked here except transforming the single feature column into a working array\n",
282
+ "\n",
283
+ "\n",
284
+ "# Error here\n",
285
+ "new_X = df['P_2']\n",
286
+ "\n",
287
+ "X_scaled = scaler.fit_transform(new_X)\n",
288
+ "\n",
289
+ "\n",
290
+ "# Task 2,3,4,5: Write your code here:\n",
291
+ "from catboost import CatBoostClassifier\n",
292
+ "\n",
293
+ "n_splits=5\n",
294
+ "\n",
295
+ "# To store scores\n",
296
+ "accuracy_all_merged = []\n",
297
+ "f1_all_merged = []\n",
298
+ "\n",
299
+ "skf = StratifiedKFold(n_splits, shuffle=True, random_state=42 )\n",
300
+ "\n",
301
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(new_X, y)):\n",
302
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
303
+ "\n",
304
+ " X_train, X_test = new_X.iloc[train_index], new_X.iloc[test_index]\n",
305
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
306
+ "\n",
307
+ " model = CatBoostClassifier(n_estimators=320, max_depth=4)\n",
308
+ " model.fit(X_train, y_train) # train\n",
309
+ " y_pred = model.predict(X_test) # validate\n",
310
+ "\n",
311
+ " # Calculate evaluation metrics\n",
312
+ " accuracy = accuracy_score(y_test, y_pred)\n",
313
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
314
+ "\n",
315
+ " # Store results\n",
316
+ " accuracy_all_merged.append(accuracy)\n",
317
+ " f1_all_merged.append(f1)"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "accuracy_avg_merged = sum(accuracy_all_merged) / len(accuracy_all_merged)\n",
327
+ "f1_avg_merged = sum(f1_all_merged) / len(f1_all_merged)\n",
328
+ "\n",
329
+ "print(f\"Average accuracy is: {accuracy_avg_merged}\")\n",
330
+ "print(f\"Average f1 is: {f1_avg_merged}\")"
331
+ ],
332
+ "execution_count": null,
333
+ "outputs": []
334
+ },
335
+ {
336
+ "cell_type": "code",
337
+ "metadata": {},
338
+ "source": [],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ }
342
+ ],
343
+ "metadata": {
344
+ "kernelspec": {
345
+ "display_name": "Python 3",
346
+ "name": "python3"
347
+ },
348
+ "language_info": {
349
+ "name": "python"
350
+ }
351
+ },
352
+ "nbformat": 4,
353
+ "nbformat_minor": 0
354
+ }
submissions_extracted/221/Q1.ipynb ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/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 seaborn as sns"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "# Task 1: Write your code here:\n",
35
+ "df_path = os.path.join(path, 'Q1_data.csv')\n",
36
+ "df = pd.read_csv(df_path)"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 2: Write your code here:\n",
46
+ "df.head()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# 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
+ "def check_target_distribution(df, target_column):\n",
76
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
77
+ "\n",
78
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
79
+ " plt.xlabel(target_column)\n",
80
+ " plt.ylabel(\"Frequency\")\n",
81
+ " plt.grid(False)\n",
82
+ "\n",
83
+ " plt.show()\n",
84
+ "\n",
85
+ "check_target_distribution(df, \"Delivery_Time\")"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 1: Write your code here:\n",
95
+ "df = df.drop(\"Order_ID\", axis=1)"
96
+ ],
97
+ "execution_count": null,
98
+ "outputs": []
99
+ },
100
+ {
101
+ "cell_type": "code",
102
+ "metadata": {},
103
+ "source": [
104
+ "df.head()"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 2: Write your code here:\n",
114
+ "# Analyze missing values\n",
115
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
116
+ "missing_data = pd.DataFrame({\n",
117
+ " 'Column': missing_percentage.index,\n",
118
+ " 'Missing_Percentage': missing_percentage.values\n",
119
+ "})\n",
120
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
121
+ "\n",
122
+ "print(\"Missing Data Analysis:\")\n",
123
+ "missing_data.head(10)"
124
+ ],
125
+ "execution_count": null,
126
+ "outputs": []
127
+ },
128
+ {
129
+ "cell_type": "code",
130
+ "metadata": {},
131
+ "source": [
132
+ "# Drop rows where\n",
133
+ "print(f\"Before: {df.shape}\")\n",
134
+ "df = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day', 'Courier_Experience_yrs'])\n",
135
+ "print(f\"After dropping missings: {df.shape}\")"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].median())"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "# Task 3: Write your code here:\n",
154
+ "def check_duplicates(df):\n",
155
+ " duplicates = df.duplicated().sum()\n",
156
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
157
+ " if duplicates > 0:\n",
158
+ " print(\"Dropping Duplicates...\")\n",
159
+ " df.drop_duplicates(inplace=True)\n",
160
+ " print(\"Duplicates Dropped.\")\n",
161
+ " else:\n",
162
+ " print(\"No Duplicate Samples Found.\")\n",
163
+ "\n",
164
+ "check_duplicates(df)"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 4: Write your code here:\n",
174
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
175
+ "\n",
176
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
177
+ "for col in categorical_cols:\n",
178
+ " le = LabelEncoder()\n",
179
+ " df[col] = le.fit_transform(df[col].astype(str))\n",
180
+ "\n",
181
+ "df.head()"
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 5: Write your code here:\n",
198
+ "#Shouldn't we do this after splitting?!\n",
199
+ "scaler = StandardScaler()\n",
200
+ "scaled = scaler.fit_transform(df)\n",
201
+ "\n",
202
+ "print(\"Original:\\n\", df)\n",
203
+ "print(\"\\nScaled (mean≈0, std≈1):\\n\", scaled)\n",
204
+ "print(\"\\nMeans:\", scaled.mean(axis=0))\n",
205
+ "print(\"Stds:\", scaled.std(axis=0))"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 6: Write your code here:"
215
+ ],
216
+ "execution_count": null,
217
+ "outputs": []
218
+ },
219
+ {
220
+ "cell_type": "code",
221
+ "metadata": {},
222
+ "source": [
223
+ "# Task 1: Write your code here:\n",
224
+ "X = df.drop(\"Delivery_Time\", axis=1)\n",
225
+ "y = df['Delivery_Time']"
226
+ ],
227
+ "execution_count": null,
228
+ "outputs": []
229
+ },
230
+ {
231
+ "cell_type": "code",
232
+ "metadata": {},
233
+ "source": [
234
+ "X.describe()"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "# Task 2,3,4,5: Write your code here:\n",
244
+ "from sklearn.model_selection import train_test_split, KFold\n",
245
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
246
+ "\n",
247
+ "n_splits = 5\n",
248
+ "\n",
249
+ "# 5-Fold Cross-Validation, shuffled\n",
250
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
251
+ ],
252
+ "execution_count": null,
253
+ "outputs": []
254
+ },
255
+ {
256
+ "cell_type": "code",
257
+ "metadata": {},
258
+ "source": [
259
+ "# Storage for linear regression results for each fold\n",
260
+ "lr_losses = []\n",
261
+ "lr_mse = []\n",
262
+ "lr_rmse = []\n",
263
+ "lr_r2 = []"
264
+ ],
265
+ "execution_count": null,
266
+ "outputs": []
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "metadata": {},
271
+ "source": [
272
+ "from tqdm import tqdm\n",
273
+ "\n",
274
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
275
+ " m, n = X.shape # m rows, n columns (dimensions)\n",
276
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
277
+ " losses = []\n",
278
+ "\n",
279
+ " for _ in tqdm(range(n_iters), desc=\"Training Linear Regression\"):\n",
280
+ " y_hat = np.dot(X, theta)\n",
281
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
282
+ " theta -= learning_rate * gradient\n",
283
+ "\n",
284
+ " loss = mean_squared_error(y, y_hat)\n",
285
+ " losses.append(loss)\n",
286
+ "\n",
287
+ " return theta, losses"
288
+ ],
289
+ "execution_count": null,
290
+ "outputs": []
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "metadata": {},
295
+ "source": [
296
+ "# Mean Squared Error in NumPy\n",
297
+ "def mean_squared_error(y, y_hat):\n",
298
+ " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [
307
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
308
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
309
+ "\n",
310
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
311
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
312
+ "\n",
313
+ " # Train\n",
314
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
315
+ "\n",
316
+ " # Validate\n",
317
+ " y_pred = np.dot(X_test.values, theta)\n",
318
+ "\n",
319
+ " # Calculate evaluation metrics\n",
320
+ " mse = sklearn_mse(y_test, y_pred)\n",
321
+ " rmse = np.sqrt(mse)\n",
322
+ " r2 = r2_score(y_test, y_pred)\n",
323
+ "\n",
324
+ " # Store results\n",
325
+ " lr_losses.append(losses)\n",
326
+ " lr_mse.append(mse)\n",
327
+ " lr_rmse.append(rmse)\n",
328
+ " lr_r2.append(r2)"
329
+ ],
330
+ "execution_count": null,
331
+ "outputs": []
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "metadata": {},
336
+ "source": [
337
+ "# Task 1: Write your code here:"
338
+ ],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ },
342
+ {
343
+ "cell_type": "code",
344
+ "metadata": {},
345
+ "source": [
346
+ "# Task 2: Write your code here:\n",
347
+ "average_losses = np.mean(lr_losses, axis=0)\n",
348
+ "\n",
349
+ "plt.figure(figsize=(10, 6))\n",
350
+ "plt.plot(average_losses, label='Average Loss')\n",
351
+ "plt.xlabel('Iteration')\n",
352
+ "plt.ylabel('MSE Loss')\n",
353
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
354
+ "plt.legend()\n",
355
+ "plt.grid(True, alpha=0.3)\n",
356
+ "plt.show()"
357
+ ],
358
+ "execution_count": null,
359
+ "outputs": []
360
+ },
361
+ {
362
+ "cell_type": "code",
363
+ "metadata": {},
364
+ "source": [
365
+ "# Task Bonus: Write your code here:"
366
+ ],
367
+ "execution_count": null,
368
+ "outputs": []
369
+ }
370
+ ],
371
+ "metadata": {
372
+ "kernelspec": {
373
+ "display_name": "Python 3",
374
+ "name": "python3"
375
+ },
376
+ "language_info": {
377
+ "name": "python"
378
+ }
379
+ },
380
+ "nbformat": 4,
381
+ "nbformat_minor": 0
382
+ }
submissions_extracted/221/Q2.ipynb ADDED
@@ -0,0 +1,361 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "import torch\n",
69
+ "import torch.nn as nn\n",
70
+ "from torch.optim import Adam\n",
71
+ "import matplotlib.pyplot as plt\n",
72
+ "from sklearn.datasets import load_breast_cancer\n",
73
+ "from sklearn.model_selection import train_test_split\n",
74
+ "from sklearn.preprocessing import StandardScaler\n",
75
+ "from torch.utils.data import TensorDataset\n",
76
+ "from torch.utils.data import DataLoader"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
86
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
87
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
88
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
89
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# 2. Create TensorDataset objects\n",
99
+ "train_dataset = TensorDataset(X_train, y_train)\n",
100
+ "test_dataset = TensorDataset(X_test, y_test)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 3. Create DataLoaders\n",
110
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
111
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# 4. Print shape of one batch\n",
121
+ "first_sample, _ = train_dataset[0]\n",
122
+ "print(f\"Shape of one sample: {first_sample.shape}\")"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# Get one batch of images and labels\n",
132
+ "images, labels = next(iter(train_loader))\n",
133
+ "\n",
134
+ "# Display the first 6 images in the batch\n",
135
+ "plt.figure(figsize=(8, 4))\n",
136
+ "\n",
137
+ "for i in range(6):\n",
138
+ " plt.subplot(2, 3, i + 1)\n",
139
+ "\n",
140
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
141
+ " img = images[i].permute(1, 2, 0)\n",
142
+ "\n",
143
+ " plt.imshow(img)\n",
144
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
145
+ " plt.axis('off')\n",
146
+ "\n",
147
+ "plt.tight_layout()\n",
148
+ "plt.show()"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 1: Write your model class here:\n",
158
+ "class NN4Layer(nn.Module):\n",
159
+ "\n",
160
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
161
+ " super(NN4Layer, self).__init__()\n",
162
+ "\n",
163
+ " # First linear layer: input features -> hidden layer\n",
164
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
165
+ "\n",
166
+ " # Second linear layer: hidden layer -> hidden layer\n",
167
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
168
+ "\n",
169
+ " # Third linear layer: hidden layer -> hidden layer\n",
170
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
171
+ "\n",
172
+ " # Output layer: hidden layer -> number of classes (logits)\n",
173
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
174
+ "\n",
175
+ " # ReLU activation for non-linearity\n",
176
+ " self.relu = nn.ReLU()\n",
177
+ "\n",
178
+ " # Defines how input data flows through the network\n",
179
+ " def forward(self, x):\n",
180
+ " # First hidden layer\n",
181
+ " a1 = self.relu(self.layer1(x))\n",
182
+ "\n",
183
+ " # Second hidden layer\n",
184
+ " a2 = self.relu(self.layer2(a1))\n",
185
+ "\n",
186
+ " # Third hidden layer\n",
187
+ " a3 = self.relu(self.layer3(a2))\n",
188
+ "\n",
189
+ " # Output layer (raw scores / logits)\n",
190
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
191
+ "\n",
192
+ " return output\n"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "# Task 2: Write your training loop here:\n",
202
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
203
+ " # Set the model to training mode\n",
204
+ " model.train()\n",
205
+ "\n",
206
+ " running_loss = 0.0\n",
207
+ "\n",
208
+ " for X_batch, y_batch in train_loader:\n",
209
+ " # Move batch to the selected device\n",
210
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
211
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
212
+ "\n",
213
+ " # Forward pass (continuous output)\n",
214
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
215
+ " loss = criterion(outputs, y_batch)\n",
216
+ "\n",
217
+ " # Backward pass & optimization\n",
218
+ " optimizer.zero_grad() # Clear previous gradients\n",
219
+ " loss.backward() # Compute gradients\n",
220
+ " optimizer.step() # Update model parameters\n",
221
+ "\n",
222
+ " running_loss += loss.item()\n",
223
+ "\n",
224
+ " # Average loss over all batches\n",
225
+ " avg_loss = running_loss / len(train_loader)\n",
226
+ "\n",
227
+ " return avg_loss"
228
+ ],
229
+ "execution_count": null,
230
+ "outputs": []
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "metadata": {},
235
+ "source": [
236
+ "# Task 3: Write your validation loop here:\n",
237
+ "def validate(model, criterion, test_loader, device):\n",
238
+ " # Set the model to evaluation mode\n",
239
+ " model.eval()\n",
240
+ "\n",
241
+ " running_loss = 0.0\n",
242
+ "\n",
243
+ " with torch.no_grad():\n",
244
+ " for X_batch, y_batch in test_loader:\n",
245
+ " # Move data to device\n",
246
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
247
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
248
+ "\n",
249
+ " # Forward pass (continuous output)\n",
250
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
251
+ " loss = criterion(outputs, y_batch)\n",
252
+ "\n",
253
+ " running_loss += loss.item()\n",
254
+ "\n",
255
+ " # Average loss over all batches\n",
256
+ " avg_loss = running_loss / len(test_loader)\n",
257
+ "\n",
258
+ " return avg_loss"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 4: Define device, model, loss, optimizer:\n",
268
+ "from torch.optim import AdamW\n",
269
+ "\n",
270
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
271
+ "\n",
272
+ "input_dim = 3*36*36 # Number of features\n",
273
+ "\n",
274
+ "hidden_dim = 128 # Design choice\n",
275
+ "\n",
276
+ "model = NN4Layer(input_dim, hidden_dim,1).to(device)\n",
277
+ "\n",
278
+ "num_epochs = 20\n",
279
+ "\n",
280
+ "learning_rate = 0.001\n",
281
+ "\n",
282
+ "criterion = nn.MSELoss()\n",
283
+ "\n",
284
+ "optimizer = AdamW(model.parameters(), learning_rate)"
285
+ ],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "# Run Training\n",
294
+ "train_losses = []\n",
295
+ "val_losses = []\n",
296
+ "\n",
297
+ "print('Starting Training...')\n",
298
+ "for epoch in range(num_epochs):\n",
299
+ " # Train one epoch\n",
300
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
301
+ "\n",
302
+ " # Validate\n",
303
+ " val_loss = validate(model, criterion, test_loader, device)\n",
304
+ "\n",
305
+ " train_losses.append(train_loss)\n",
306
+ " val_losses.append(val_loss)\n",
307
+ "\n",
308
+ " if (epoch + 1) % 5 == 0:\n",
309
+ " print(\n",
310
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
311
+ " f'Train Loss: {train_loss:.4f}, '\n",
312
+ " f'Val Loss: {val_loss:.4f}'\n",
313
+ " )\n",
314
+ "\n",
315
+ "print('Training Complete!')"
316
+ ],
317
+ "execution_count": null,
318
+ "outputs": []
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "metadata": {},
323
+ "source": [
324
+ "# Print the model architecture\n",
325
+ "print(\"Model Architecture:\\n\")\n",
326
+ "print(model)"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ },
331
+ {
332
+ "cell_type": "code",
333
+ "metadata": {},
334
+ "source": [
335
+ "# Task 1: Write your code here:"
336
+ ],
337
+ "execution_count": null,
338
+ "outputs": []
339
+ },
340
+ {
341
+ "cell_type": "code",
342
+ "metadata": {},
343
+ "source": [
344
+ "# Task 2 (Bonus): Write your code here:"
345
+ ],
346
+ "execution_count": null,
347
+ "outputs": []
348
+ }
349
+ ],
350
+ "metadata": {
351
+ "kernelspec": {
352
+ "display_name": "Python 3",
353
+ "name": "python3"
354
+ },
355
+ "language_info": {
356
+ "name": "python"
357
+ }
358
+ },
359
+ "nbformat": 4,
360
+ "nbformat_minor": 0
361
+ }
submissions_extracted/221/Q3.ipynb ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "import numpy as np\n",
28
+ "import pandas as pd\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "import os\n",
31
+ "import seaborn as sns\n",
32
+ "\n",
33
+ "df_path = os.path.join(path, 'Q3_data.csv')\n",
34
+ "df = pd.read_csv(df_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
+ "missing_percentage = (df.isna().sum() / len(df)) * 100\n",
75
+ "missing_data = pd.DataFrame({\n",
76
+ " 'Column': missing_percentage.index,\n",
77
+ " 'Missing_Percentage': missing_percentage.values\n",
78
+ "})\n",
79
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
80
+ "\n",
81
+ "print(\"Missing Data Analysis:\")\n",
82
+ "missing_data.head(50)"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "missing = missing_data['Column'].head(50)"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "missing = missing.to_list"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "df = df.drop(df[cols], axis=1)"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 2: Write your code here:\n",
119
+ "def check_duplicates(df):\n",
120
+ " duplicates = df.duplicated().sum()\n",
121
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
122
+ " if duplicates > 0:\n",
123
+ " print(\"Dropping Duplicates...\")\n",
124
+ " df.drop_duplicates(inplace=True)\n",
125
+ " print(\"Duplicates Dropped.\")\n",
126
+ " else:\n",
127
+ " print(\"No Duplicate Samples Found.\")\n",
128
+ "\n",
129
+ "check_duplicates(df)"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 3: Write your code here:"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 4: Write your code here:\n",
148
+ "from sklearn.preprocessing import StandardScaler\n",
149
+ "\n",
150
+ "scaler = StandardScaler()\n",
151
+ "scaled = scaler.fit_transform(df)"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 5: Write your code here:\n",
161
+ "# 1. Is the target imbalanced?\n",
162
+ "def check_target_imbalance(df, target_column):\n",
163
+ " print(\"Target Distribution:\")\n",
164
+ " print(df[target_column].value_counts(normalize=True))\n",
165
+ " sns.countplot(x=df[target_column])\n",
166
+ " plt.title(\"Target Distribution\")\n",
167
+ " plt.show()\n",
168
+ "\n",
169
+ "check_target_imbalance(df, \"Target\")"
170
+ ],
171
+ "execution_count": null,
172
+ "outputs": []
173
+ },
174
+ {
175
+ "cell_type": "code",
176
+ "metadata": {},
177
+ "source": [
178
+ "# Task 1: Write your code here:\n",
179
+ "X = df.drop(\"Target\", axis=1)\n",
180
+ "y = df['Target']"
181
+ ],
182
+ "execution_count": null,
183
+ "outputs": []
184
+ },
185
+ {
186
+ "cell_type": "code",
187
+ "metadata": {},
188
+ "source": [
189
+ "!pip install catboost"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 2,3,4,5: Write your code here:\n",
199
+ "from sklearn.model_selection import KFold, StratifiedKFold, cross_val_score\n",
200
+ "from catboost import CatBoostClassifier\n",
201
+ "\n",
202
+ "model = CatBoostClassifier(\n",
203
+ " verbose=0,\n",
204
+ " n_estimators=320,\n",
205
+ " max_depth=4\n",
206
+ " )\n",
207
+ "\n",
208
+ "skfold = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
209
+ "scores_strat = cross_val_score(model, X, y, cv=skfold, scoring='accuracy')\n",
210
+ "print(\"\\nStratifiedKFold scores:\", scores_strat)\n",
211
+ "print(f\"Mean accuracy: {scores_strat.mean():.3f}\")"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "cols = X.columns.to_list"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "metadata": {},
228
+ "source": [
229
+ "print(cols)"
230
+ ],
231
+ "execution_count": null,
232
+ "outputs": []
233
+ },
234
+ {
235
+ "cell_type": "code",
236
+ "metadata": {},
237
+ "source": [
238
+ "# Feature importance\n",
239
+ "feature_importance = pd.DataFrame({\n",
240
+ " 'feature': cols,\n",
241
+ " 'importance': model.feature_importances_\n",
242
+ "}).sort_values('importance', ascending=False)\n",
243
+ "\n",
244
+ "plt.figure(figsize=(10, 6))\n",
245
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
246
+ "plt.xlabel('Importance')\n",
247
+ "plt.title('Feature Importance')\n",
248
+ "plt.gca().invert_yaxis()\n",
249
+ "plt.show()"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "metadata": {},
257
+ "source": [
258
+ "# Task 2: Write your code here:"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task Bonus: Write your code here:"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ }
272
+ ],
273
+ "metadata": {
274
+ "kernelspec": {
275
+ "display_name": "Python 3",
276
+ "name": "python3"
277
+ },
278
+ "language_info": {
279
+ "name": "python"
280
+ }
281
+ },
282
+ "nbformat": 4,
283
+ "nbformat_minor": 0
284
+ }
submissions_extracted/222/Q1.ipynb ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
22
+ "\n",
23
+ "\n",
24
+ "import kagglehub\n",
25
+ "\n",
26
+ "# Download latest version\n",
27
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
28
+ "\n",
29
+ "print(\"Path to dataset files:\", path)"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 1: Write your code here:\n",
39
+ "# Load the dataset\n",
40
+ "q1_path = os.path.join(path, 'Q1_data.csv')\n",
41
+ "df_q1 = pd.read_csv(q1_path)\n",
42
+ "\n"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "# Task 2: Write your code here:\n",
52
+ "print(f\"Dataset shape: {df_q1.shape}\")\n",
53
+ "df_q1.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
+ "# Check data types and structure\n",
64
+ "df_q1.info()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 4: Write your code here:\n",
74
+ "# Descriptive statistics for numerical columns\n",
75
+ "df_q1.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_q1['Delivery_Time'].dropna(), bins=30, edgecolor='black')\n",
87
+ "plt.title('delivery_time dist')\n",
88
+ "plt.xlabel('delivery_time')\n",
89
+ "plt.ylabel('Frequency')\n",
90
+ "plt.show()"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# Task 1: Write your code here:\n",
100
+ "dfq1_cleaned =df_q1.drop(columns=['Order_ID']).copy()\n",
101
+ "\n"
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
+ "missing_percentage = (dfq1_cleaned.isnull().sum() / len(dfq1_cleaned)) * 100\n",
113
+ "missing_data = pd.DataFrame({\n",
114
+ " 'Column': missing_percentage.index,\n",
115
+ " 'Missing_Percentage': missing_percentage.values\n",
116
+ "})\n",
117
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
118
+ "\n",
119
+ "print(\"Missing Data Analysis:\")\n",
120
+ "missing_data.head(10)"
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
+ "#i will just drop missing rows since we have enough data.\n",
131
+ "df_clean=dfq1_cleaned.dropna(subset=['Delivery_Time']).copy()\n",
132
+ "df_clean=df_clean.dropna(subset=['Weather']).copy()\n",
133
+ "df_clean=df_clean.dropna(subset=['Traffic_Level']).copy()\n",
134
+ "df_clean=df_clean.dropna(subset=['Time_of_Day']).copy()\n",
135
+ "df_clean=df_clean.dropna(subset=['Courier_Experience_yrs']).copy()\n",
136
+ "\n",
137
+ "\n",
138
+ "\n",
139
+ "\n",
140
+ "\n",
141
+ "print(\"Missing values:\") #should be none after all of this\n",
142
+ "print(df_clean.isnull().sum())"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 4: Write your code here:\n",
152
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
153
+ "onehot_encoder = OneHotEncoder(sparse_output=False)\n",
154
+ "categ=['Weather','Traffic_Level','Time_of_Day', 'Vehicle_Type']\n",
155
+ "le = LabelEncoder()\n",
156
+ "df_clean['Weather'] = le.fit_transform(df_clean['Weather'])\n",
157
+ "df_clean['Traffic_Level'] = le.fit_transform(df_clean['Traffic_Level'])\n",
158
+ "df_clean['Time_of_Day'] = le.fit_transform(df_clean['Time_of_Day'])\n",
159
+ "df_clean['Vehicle_Type'] = le.fit_transform(df_clean['Vehicle_Type'])\n",
160
+ "df_clean.info() #should be no objects now"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task 5: Write your code here:\n",
170
+ "scaler = StandardScaler()\n",
171
+ "cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs','Delivery_Time']\n",
172
+ "df_clean[cols]= scaler.fit_transform(df_clean[cols])\n",
173
+ "\n",
174
+ "df_clean.info()\n",
175
+ "\n"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 6: Write your code here: LOOKS IMBALANCED TO ME\n",
185
+ "plt.figure(figsize=(10, 5))\n",
186
+ "plt.hist(df_q1['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
187
+ "plt.title('delivery_time dist')\n",
188
+ "plt.xlabel('delivery_time')\n",
189
+ "plt.ylabel('Frequency')\n",
190
+ "plt.show()"
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_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
201
+ "y= df_clean['Delivery_Time'].astype(float)\n",
202
+ "\n"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 2,3,4,5: Write your code here:\n",
212
+ "\n",
213
+ "from sklearn.ensemble import RandomForestRegressor\n",
214
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
215
+ "\n",
216
+ "\n",
217
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
218
+ "\n",
219
+ "# Train RandomForestRegressor\n",
220
+ "model = RandomForestRegressor(n_estimators=100, max_depth=15, random_state=42)\n",
221
+ "\n",
222
+ "model.fit(X_train, y_train)\n",
223
+ "\n",
224
+ "\n",
225
+ "y_pred = model.predict(X_test)\n",
226
+ "mae = mean_absolute_error(y_test, y_pred)\n",
227
+ "\n",
228
+ "print(mae)\n",
229
+ "\n",
230
+ "#-------------------\n",
231
+ "#from sklearn.model_selection import StratifiedKFold\n",
232
+ "\n",
233
+ "#skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\n",
234
+ "#scores = []\n",
235
+ "\n",
236
+ "#for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
237
+ "\n",
238
+ " # X_f_train, X_f_val = X_train[train_idx], X_train[test_idx]\n",
239
+ " # y_f_train, y_f_val = y_train.iloc[train_idx], y_train.iloc[test_idx]\n",
240
+ "\n",
241
+ " # model.fit(X_f_train, y_f_train)\n",
242
+ " #fold_acc = accuracy_score(y_f_val, model.predict(X_f_val))\n",
243
+ " #scores.append(fold_acc)\n",
244
+ "\n",
245
+ "#print(f\"Final Average Accuracy: {np.mean(scores):.2f}\")\n",
246
+ "\n",
247
+ "\n"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "# Task 1: Write your code here:\n",
257
+ "feature_cols=['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
258
+ "\n",
259
+ "feature_importance = pd.DataFrame({\n",
260
+ " 'feature': feature_cols,\n",
261
+ " 'importance': model.feature_importances_\n",
262
+ "}).sort_values('importance', ascending=False)\n",
263
+ "\n",
264
+ "plt.figure(figsize=(10, 6))\n",
265
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
266
+ "plt.xlabel('Importance')\n",
267
+ "plt.title('Feature Importance')\n",
268
+ "plt.gca().invert_yaxis()\n",
269
+ "plt.show()"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "metadata": {},
277
+ "source": [
278
+ "# Task 2: Write your code here:\n",
279
+ "plt.figure(figsize=(10, 5))\n",
280
+ "plt.hist(y_pred, bins=50, edgecolor='black')\n",
281
+ "plt.title('delivery time')\n",
282
+ "plt.xlabel(' d time')\n",
283
+ "plt.ylabel('Frequency')\n",
284
+ "plt.show()"
285
+ ],
286
+ "execution_count": null,
287
+ "outputs": []
288
+ },
289
+ {
290
+ "cell_type": "code",
291
+ "metadata": {},
292
+ "source": [
293
+ "# Task Bonus: Write your code here:"
294
+ ],
295
+ "execution_count": null,
296
+ "outputs": []
297
+ }
298
+ ],
299
+ "metadata": {
300
+ "kernelspec": {
301
+ "display_name": "Python 3",
302
+ "name": "python3"
303
+ },
304
+ "language_info": {
305
+ "name": "python"
306
+ }
307
+ },
308
+ "nbformat": 4,
309
+ "nbformat_minor": 0
310
+ }
submissions_extracted/222/Q2.ipynb ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "\n",
70
+ "import kagglehub\n",
71
+ "import pandas as pd\n",
72
+ "import torch\n",
73
+ "import torch.nn as nn\n",
74
+ "from torch.optim import AdamW\n",
75
+ "import matplotlib.pyplot as plt\n",
76
+ "import torch.nn.functional as F\n",
77
+ "from torch.utils.data import DataLoader, TensorDataset\n",
78
+ "from sklearn.model_selection import train_test_split\n",
79
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
80
+ "\n",
81
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
82
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
83
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
84
+ "y_test = torch.tensor(y_test, dtype=torch.long)\n"
85
+ ],
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
+ "# Create TensorDatasets for training and testing\n",
96
+ "train_dataset = TensorDataset(X_train, y_train)\n",
97
+ "test_dataset = TensorDataset(X_test, y_test)\n"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# 3. Create DataLoaders\n",
107
+ "\n",
108
+ "\n",
109
+ "# Create Dataloaders to train and test data in batches\n",
110
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
111
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)"
112
+ ],
113
+ "execution_count": null,
114
+ "outputs": []
115
+ },
116
+ {
117
+ "cell_type": "code",
118
+ "metadata": {},
119
+ "source": [
120
+ "# 4. Print shape of one batch\n",
121
+ "\n",
122
+ "# Print dataset sizes\n",
123
+ "print(\"Train dataset:\", len(train_dataset))\n",
124
+ "print(\"Test dataset:\", len(test_dataset))\n",
125
+ "\n",
126
+ "# Get the first batch from the training DataLoader\n",
127
+ "X_batch, y_batch = next(iter(train_loader))\n",
128
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
129
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# 5. Display sample images\n",
139
+ "import matplotlib.pyplot as plt\n",
140
+ "\n",
141
+ "\n"
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 NN3Layer(nn.Module):\n",
153
+ " def __init__(self, input_dim, hidden_dim):\n",
154
+ " super(NN3Layer, self).__init__()\n",
155
+ "\n",
156
+ " # First linear layer: input features -> hidden layer\n",
157
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
158
+ "\n",
159
+ " # Second linear layer: hidden layer -> hidden layer\n",
160
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
161
+ " # Second linear layer: hidden layer -> hidden layer\n",
162
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
163
+ "\n",
164
+ " # Output layer: hidden layer -> single continuous value\n",
165
+ " self.layer4 = nn.Linear(hidden_dim, 1)\n",
166
+ "\n",
167
+ " # ReLU activation for non-linearity in hidden layers\n",
168
+ " self.relu = nn.ReLU()\n",
169
+ "\n",
170
+ " # Defines how input data flows through the network\n",
171
+ " def forward(self, x):\n",
172
+ " # First hidden layer\n",
173
+ " a1 = self.relu(self.layer1(x))\n",
174
+ "\n",
175
+ " # Second hidden layer\n",
176
+ " a2 = self.relu(self.layer2(a1))\n",
177
+ "\n",
178
+ " # Second hidden layer\n",
179
+ " a3 = self.relu(self.layer3(a2))\n",
180
+ "\n",
181
+ " # Output layer (regression output)\n",
182
+ " output = self.layer4(a3)\n",
183
+ "\n",
184
+ " return output"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 2: Write your training loop here:\n",
194
+ "\n",
195
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
196
+ " # Set the model to training mode\n",
197
+ " model.train()\n",
198
+ "\n",
199
+ " running_loss = 0.0\n",
200
+ "\n",
201
+ " for X_batch, y_batch in train_loader:\n",
202
+ " # Move batch to the selected device\n",
203
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
204
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
205
+ "\n",
206
+ " # Forward pass (continuous output)\n",
207
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
208
+ " loss = criterion(outputs, y_batch)\n",
209
+ "\n",
210
+ " # Backward pass & optimization\n",
211
+ " optimizer.zero_grad() # Clear previous gradients\n",
212
+ " loss.backward() # Compute gradients\n",
213
+ " optimizer.step() # Update model parameters\n",
214
+ "\n",
215
+ " running_loss += loss.item()\n",
216
+ "\n",
217
+ " # Average loss over all batches\n",
218
+ " avg_loss = running_loss / len(train_loader)\n",
219
+ "\n",
220
+ " return avg_loss"
221
+ ],
222
+ "execution_count": null,
223
+ "outputs": []
224
+ },
225
+ {
226
+ "cell_type": "code",
227
+ "metadata": {},
228
+ "source": [
229
+ "# Task 3: Write your validation loop here:\n",
230
+ "def validate(model, criterion, test_loader, device):\n",
231
+ " # Set the model to evaluation mode\n",
232
+ " model.eval()\n",
233
+ "\n",
234
+ " running_loss = 0.0\n",
235
+ "\n",
236
+ " with torch.no_grad():\n",
237
+ " for X_batch, y_batch in test_loader:\n",
238
+ " # Move data to device\n",
239
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
240
+ " y_batch = y_batch.view(-1, 1).to(device) # shape: (batch_size, 1)\n",
241
+ "\n",
242
+ " # Forward pass (continuous output)\n",
243
+ " outputs = model(X_batch) # shape: (batch_size, 1)\n",
244
+ " loss = criterion(outputs, y_batch)\n",
245
+ "\n",
246
+ " running_loss += loss.item()\n",
247
+ "\n",
248
+ " # Average loss over all batches\n",
249
+ " avg_loss = running_loss / len(test_loader)\n",
250
+ "\n",
251
+ " return avg_loss"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task 4: Define device, model, loss, optimizer:\n",
261
+ "# TODO: Set up the device (use GPU if available, otherwise CPU)\n",
262
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
263
+ "\n",
264
+ "# Model parameters\n",
265
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
266
+ "hidden_dim = 64 # Design choice\n",
267
+ "\n",
268
+ "# Instantiate regression model\n",
269
+ "model = NN3Layer(input_dim, hidden_dim).to(device)\n",
270
+ "\n",
271
+ "# Print the model architecture\n",
272
+ "print(\"Model Architecture:\\n\")\n",
273
+ "print(model)\n",
274
+ "\n",
275
+ "# Calculate the total number of trainable parameters\n",
276
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
277
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
278
+ "\n",
279
+ "# Define criterion (loss function)\n",
280
+ "criterion = nn.MSELoss()\n",
281
+ "# Define optimizer\n",
282
+ "optimizer = AdamW(model.parameters(), learning_rate)"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "metadata": {},
290
+ "source": [
291
+ "# Task 5: Start training for 20 epochs:\n",
292
+ "\n",
293
+ "# Hyperparameters (feel free to experiment!)\n",
294
+ "num_epochs = 20\n",
295
+ "learning_rate = 0.001\n",
296
+ "\n",
297
+ "# Run Training\n",
298
+ "train_losses = []\n",
299
+ "val_losses = []\n",
300
+ "\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 = validate(model, criterion, test_loader, device)\n",
308
+ "\n",
309
+ " train_losses.append(train_loss)\n",
310
+ " val_losses.append(val_loss)\n",
311
+ "\n",
312
+ " if (epoch + 1) % 5 == 0:\n",
313
+ " print(\n",
314
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
315
+ " f'Train Loss: {train_loss:.4f}, '\n",
316
+ " f'Val Loss: {val_loss:.4f}'\n",
317
+ " )\n",
318
+ "\n",
319
+ "print('Training Complete!')"
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
+ "\n",
330
+ "# Plotting results\n",
331
+ "plt.figure(figsize=(7, 5))\n",
332
+ "\n",
333
+ "plt.plot(train_losses, label='Train Loss')\n",
334
+ "plt.plot(val_losses, label='Validation Loss')\n",
335
+ "plt.title('Loss over Epochs')\n",
336
+ "plt.xlabel('Epoch')\n",
337
+ "plt.ylabel('Loss (MSE)')\n",
338
+ "plt.legend()\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 2 (Bonus): Write your code here:"
351
+ ],
352
+ "execution_count": null,
353
+ "outputs": []
354
+ }
355
+ ],
356
+ "metadata": {
357
+ "kernelspec": {
358
+ "display_name": "Python 3",
359
+ "name": "python3"
360
+ },
361
+ "language_info": {
362
+ "name": "python"
363
+ }
364
+ },
365
+ "nbformat": 4,
366
+ "nbformat_minor": 0
367
+ }
submissions_extracted/222/Q3.ipynb ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "\n",
28
+ "import numpy as np\n",
29
+ "import pandas as pd\n",
30
+ "import matplotlib.pyplot as plt\n",
31
+ "import os\n",
32
+ "import kagglehub\n",
33
+ "\n",
34
+ "from sklearn.model_selection import train_test_split, KFold\n",
35
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
36
+ "from sklearn.ensemble import RandomForestRegressor\n",
37
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
38
+ "\n",
39
+ "import warnings\n",
40
+ "warnings.filterwarnings('ignore')\n",
41
+ "\n",
42
+ "\n",
43
+ "\n",
44
+ "path = os.path.join(path, 'Q3_data.csv')\n",
45
+ "df= pd.read_csv(path)\n",
46
+ "\n"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 2: Write your code here:\n",
56
+ "\n",
57
+ "print(f\"Dataset shape: {df.shape}\")\n",
58
+ "df.head()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 3: Write your code here:\n",
68
+ "df.info()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 4: Write your code here:\n",
78
+ "df.describe()"
79
+ ],
80
+ "execution_count": null,
81
+ "outputs": []
82
+ },
83
+ {
84
+ "cell_type": "code",
85
+ "metadata": {},
86
+ "source": [
87
+ "# Task 1: Write your code here:\n",
88
+ "missing_percentage = (df.isnull().sum() / len(df)) * 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
+ "\n",
96
+ "df_clean =df.drop(columns=missing_data.Column).copy()\n",
97
+ "print(\"Missing values:\") #should be none after all of this\n",
98
+ "print(df_clean.isnull().sum())\n",
99
+ "\n"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# Task 2: Write your code here:\n",
109
+ "\n",
110
+ "# 4. Do we have duplicate samples?\n",
111
+ "def check_duplicates(df):\n",
112
+ " duplicates = df.duplicated().sum()\n",
113
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
114
+ " if duplicates > 0:\n",
115
+ " print(\"Dropping Duplicates...\")\n",
116
+ " df.drop_duplicates(inplace=True)\n",
117
+ " print(\"Duplicates Dropped.\")\n",
118
+ " else:\n",
119
+ " print(\"No Duplicate Samples Found.\")\n",
120
+ "\n",
121
+ "check_duplicates(df,)"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 3: Write your code here:\n",
131
+ "df_clean.info() #no objects as u see"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 4: Write your code here:\n",
141
+ "\n",
142
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
143
+ "\n",
144
+ "scaler = StandardScaler()\n",
145
+ "df_scaled=scaler.fit_transform(df_clean)\n"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# 1. Is the target imbalanced?\n",
155
+ "import seaborn as sns\n",
156
+ "\n",
157
+ "def check_target_imbalance(df, target_column):\n",
158
+ " print(\"Target Distribution:\")\n",
159
+ " print(df[target_column].value_counts(normalize=True))\n",
160
+ " sns.countplot(x=df[target_column])\n",
161
+ " plt.title(\"Target Distribution\")\n",
162
+ " plt.show()\n",
163
+ "check_target_imbalance(df, \"Target\")\n",
164
+ "\n",
165
+ "print(\"Target is imbalanced\")#target is imbalanced"
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
+ "\n",
176
+ "X =df_clean.drop(\"Target\", axis=1).astype(float)\n",
177
+ "y= df_clean['Target'].astype(float)"
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
+ "%pip install kagglehub catboost xgboost tqdm -q\n",
188
+ "\n",
189
+ "from catboost import CatBoostClassifier\n",
190
+ "from sklearn.model_selection import StratifiedKFold\n",
191
+ "from sklearn.metrics import accuracy_score, f1_score\n",
192
+ "\n",
193
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
194
+ "\n",
195
+ "models = {\n",
196
+ " \"CatBoost\": CatBoostClassifier(\n",
197
+ " verbose=0,\n",
198
+ " n_estimators=200,\n",
199
+ " max_depth=4\n",
200
+ " )\n",
201
+ "}\n",
202
+ "\n",
203
+ "results = {}\n",
204
+ "\n",
205
+ "for model_name in models:\n",
206
+ " results[model_name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
207
+ "\n",
208
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
209
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
210
+ " print(f\"\\nFold {fold_idx + 1}/{5}\")\n",
211
+ "\n",
212
+ " # Get the train & test split for this fold\n",
213
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
214
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
215
+ "\n",
216
+ " # Train & Validate Models\n",
217
+ " for model_name, model in models.items():\n",
218
+ "\n",
219
+ " print(f\"Training {model_name}...\")\n",
220
+ "\n",
221
+ " # Fit the model on train data\n",
222
+ " model.fit(X_train, y_train)\n",
223
+ "\n",
224
+ " # Use the model to predict the test data\n",
225
+ " y_pred = model.predict(X_test)\n",
226
+ "\n",
227
+ " # Calculate evaluation metrics\n",
228
+ " accuracy = accuracy_score(y_test, y_pred)\n",
229
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, you should set the average hyperparameter (\"macro\", \"micro\", \"weighted\")\n",
230
+ "\n",
231
+ " results[model_name]['accuracy'].append(accuracy)\n",
232
+ " results[model_name]['f1'].append(f1)"
233
+ ],
234
+ "execution_count": null,
235
+ "outputs": []
236
+ },
237
+ {
238
+ "cell_type": "code",
239
+ "metadata": {},
240
+ "source": [
241
+ "# Task 1: Write your code here:\n",
242
+ "\n",
243
+ "feature_cols=df_clean.columns\n",
244
+ "\n",
245
+ "print(feature_cols)\n",
246
+ "\n",
247
+ "\n",
248
+ "\n",
249
+ "feature_importance = pd.DataFrame({\n",
250
+ " 'feature': feature_cols,\n",
251
+ " 'importance': model.feature_importances_\n",
252
+ "}).sort_values('importance', ascending=False)\n",
253
+ "\n",
254
+ "plt.figure(figsize=(10, 6))\n",
255
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
256
+ "plt.xlabel('Importance')\n",
257
+ "plt.title('Feature Importance')\n",
258
+ "plt.gca().invert_yaxis()\n",
259
+ "plt.show()"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task 2: Write your code here:\n",
269
+ "\n",
270
+ "print(feature_col)"
271
+ ],
272
+ "execution_count": null,
273
+ "outputs": []
274
+ },
275
+ {
276
+ "cell_type": "code",
277
+ "metadata": {},
278
+ "source": [
279
+ "# Task Bonus: Write your code here:"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ }
284
+ ],
285
+ "metadata": {
286
+ "kernelspec": {
287
+ "display_name": "Python 3",
288
+ "name": "python3"
289
+ },
290
+ "language_info": {
291
+ "name": "python"
292
+ }
293
+ },
294
+ "nbformat": 4,
295
+ "nbformat_minor": 0
296
+ }
submissions_extracted/223/Q1.ipynb ADDED
@@ -0,0 +1,382 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "from sklearn.model_selection import StratifiedKFold\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
+ "import pandas as pd\n",
18
+ "import numpy as np\n",
19
+ "import matplotlib.pyplot as plt\n",
20
+ "import seaborn as sns\n",
21
+ "import kagglehub\n",
22
+ "import os\n",
23
+ "from tqdm import tqdm\n",
24
+ "\n",
25
+ "import warnings\n",
26
+ "warnings.filterwarnings('ignore')"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "import kagglehub\n",
36
+ "\n",
37
+ "# Download latest version\n",
38
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\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
+ "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 2: Write your code here:\n",
60
+ "df.head()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 3: Write your code here:\n",
70
+ "df.info()"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "# Task 4: Write your code here:\n",
80
+ "df.describe()"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 5: Write your code here:\n",
90
+ "def check_target_distribution(df, target_column):\n",
91
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
92
+ "\n",
93
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
94
+ " plt.xlabel(target_column)\n",
95
+ " plt.ylabel(\"Frequency\")\n",
96
+ " plt.grid(False)\n",
97
+ "\n",
98
+ " plt.show()\n",
99
+ "\n",
100
+ "check_target_distribution(df, 'Delivery_Time')"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 1: Write your code here:\n",
110
+ "df = df.drop(\"Order_ID\", axis=1)"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "# Task 2: Write your code here:\n",
120
+ "def check_missing_values(df):\n",
121
+ " missing_values = df.isnull().sum()\n",
122
+ " print(\"Missing Values per Column:\")\n",
123
+ " print(missing_values[missing_values > 0])\n",
124
+ " if missing_values.any():\n",
125
+ " print(\"\\nHandle Missing Values as needed.\")\n",
126
+ " else:\n",
127
+ " print(\"\\nNo Missing Values Found.\")\n",
128
+ "\n",
129
+ "check_missing_values(df)"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "df.shape"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "df = df.dropna()"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "df.shape"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 3: Write your code here:\n",
166
+ "def check_duplicates(df):\n",
167
+ " duplicates = df.duplicated().sum()\n",
168
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
169
+ " if duplicates > 0:\n",
170
+ " print(\"Dropping Duplicates...\")\n",
171
+ " df.drop_duplicates(inplace=True)\n",
172
+ " print(\"Duplicates Dropped.\")\n",
173
+ " else:\n",
174
+ " print(\"No Duplicate Samples Found.\")\n",
175
+ "\n",
176
+ "check_duplicates(df)"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 4: Write your code here:\n",
186
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
187
+ "\n",
188
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
189
+ "\n",
190
+ "for col in categorical_cols:\n",
191
+ " print(f\"Encoding column: {col}\")\n",
192
+ " le = LabelEncoder() # ????\n",
193
+ " df[col] = le.fit_transform(df[col])\n",
194
+ "df"
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
+ "numerical_cols = df.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n",
205
+ "\n",
206
+ "scaler = StandardScaler()\n",
207
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
208
+ "\n",
209
+ "df.head()"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "# Task 6: Write your code here:\n",
219
+ "def check_target_imbalance(df, target_column):\n",
220
+ " print(\"Target Distribution:\")\n",
221
+ " print(df[target_column].value_counts(normalize=True))\n",
222
+ " sns.countplot(x=df[target_column])\n",
223
+ " plt.title(\"Target Distribution\")\n",
224
+ " plt.show()\n",
225
+ "\n",
226
+ "check_target_imbalance(df, \"Delivery_Time\")"
227
+ ],
228
+ "execution_count": null,
229
+ "outputs": []
230
+ },
231
+ {
232
+ "cell_type": "code",
233
+ "metadata": {},
234
+ "source": [
235
+ "# Task 1: Write your code here:\n",
236
+ "feature_cols = ['Distance_km','Weather', 'Traffic_Level', 'Time_of_Day','Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs' ]\n",
237
+ "X = df[feature_cols]\n",
238
+ "y = df['Delivery_Time']"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "# Task 2,3,4,5: Write your code here:\n",
248
+ "# Define Stratified K-Fold\n",
249
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
250
+ "\n",
251
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
252
+ "\n",
253
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
254
+ " # indexing for each fold\n",
255
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
256
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
257
+ "\n",
258
+ " print(f\"Fold {fold}\")\n",
259
+ " print(\" X_train shape:\", X_train.shape)\n",
260
+ " print(\" X_test shape :\", X_test.shape)\n",
261
+ " print(\" y_train shape:\", y_train.shape)\n",
262
+ " print(\" y_test shape :\", y_test.shape)\n",
263
+ "\n",
264
+ " # showing class distribution\n",
265
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
266
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
267
+ "\n",
268
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
269
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
270
+ "\n",
271
+ " print(\"-\" * 40)\n",
272
+ "#X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
273
+ "#print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
274
+ "\n",
275
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
276
+ "model.fit(X_train, y_train)\n",
277
+ "print(\"Model trained!\")\n",
278
+ "#Evaluate using MAE (Mean Absolute Error) ONLY\n",
279
+ "y_pred = model.predict(X_test)\n",
280
+ "mae = mean_absolute_error(y_test, y_pred)\n",
281
+ "#Print the averaged score across all folds\n",
282
+ "print(f\"MAE: ${mae:,.2f}\")\n",
283
+ "\n"
284
+ ],
285
+ "execution_count": null,
286
+ "outputs": []
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "metadata": {},
291
+ "source": [
292
+ "# Task 1: Write your code here:\n",
293
+ "feature_importance = pd.DataFrame({\n",
294
+ " 'feature': feature_cols,\n",
295
+ " 'importance': model.feature_importances_\n",
296
+ "}).sort_values('importance', ascending=False)\n",
297
+ "\n",
298
+ "plt.figure(figsize=(10, 6))\n",
299
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
300
+ "plt.xlabel('Importance')\n",
301
+ "plt.title('Feature Importance')\n",
302
+ "plt.gca().invert_yaxis()\n",
303
+ "plt.show()"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "metadata": {},
311
+ "source": [
312
+ "# Task 2: Write your code here:\n",
313
+ "plt.figure(figsize=(6, 4))\n",
314
+ "plt.scatter(y_test, y_pred, alpha=0.7)\n",
315
+ "plt.plot([min(y_test), max(y_test)],\n",
316
+ " [min(y_test), max(y_test)],\n",
317
+ " 'r--', linewidth=2)\n",
318
+ "\n",
319
+ "plt.xlabel(\"Actual y_test (Ground Truth)\")\n",
320
+ "plt.ylabel(\"Predicted y_pred (Decision Tree)\")\n",
321
+ "plt.title(\"Decision Tree Regression: Predictions vs. Ground Truth\")\n",
322
+ "plt.grid(True)\n",
323
+ "\n",
324
+ "plt.tight_layout()\n",
325
+ "plt.show()"
326
+ ],
327
+ "execution_count": null,
328
+ "outputs": []
329
+ },
330
+ {
331
+ "cell_type": "code",
332
+ "metadata": {},
333
+ "source": [
334
+ "# Task Bonus: Write your code here:\n",
335
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
336
+ "\n",
337
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
338
+ " model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
339
+ "\n",
340
+ " model.fit(X_train, y_train)\n",
341
+ " # indexing for each fold\n",
342
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
343
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
344
+ "\n",
345
+ " print(f\"Fold {fold}\")\n",
346
+ " print(\" X_train shape:\", X_train.shape)\n",
347
+ " print(\" X_test shape :\", X_test.shape)\n",
348
+ " print(\" y_train shape:\", y_train.shape)\n",
349
+ " print(\" y_test shape :\", y_test.shape)\n",
350
+ "\n",
351
+ " # showing class distribution\n",
352
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
353
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
354
+ "\n",
355
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
356
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
357
+ "\n",
358
+ " print(\"-\" * 40)"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [],
367
+ "execution_count": null,
368
+ "outputs": []
369
+ }
370
+ ],
371
+ "metadata": {
372
+ "kernelspec": {
373
+ "display_name": "Python 3",
374
+ "name": "python3"
375
+ },
376
+ "language_info": {
377
+ "name": "python"
378
+ }
379
+ },
380
+ "nbformat": 4,
381
+ "nbformat_minor": 0
382
+ }
submissions_extracted/223/Q2.ipynb ADDED
@@ -0,0 +1,431 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Import required libraries\n",
8
+ "import kagglehub\n",
9
+ "import pandas as pd\n",
10
+ "import numpy as np\n",
11
+ "import torch\n",
12
+ "import torch.nn as nn\n",
13
+ "from torch.optim import AdamW\n",
14
+ "import matplotlib.pyplot as plt\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.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
19
+ "\n",
20
+ "print(f\"PyTorch version: {torch.__version__}\")\n",
21
+ "print(f\"CUDA available: {torch.cuda.is_available()}\")"
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/q2-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
+ "import os\n",
45
+ "import pandas as pd\n",
46
+ "import numpy as np\n",
47
+ "from PIL import Image\n",
48
+ "from sklearn.model_selection import train_test_split\n",
49
+ "\n",
50
+ "# Load Labels\n",
51
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
52
+ "img_dir = os.path.join(path, \"images\")\n",
53
+ "\n",
54
+ "images = []\n",
55
+ "ages = []\n",
56
+ "\n",
57
+ "# Load Images and Resize\n",
58
+ "print(\"Loading images...\")\n",
59
+ "for index, row in labels_df.iterrows():\n",
60
+ " img_name = row.iloc[0]\n",
61
+ " age = row.iloc[1]\n",
62
+ " img_path = os.path.join(img_dir, img_name)\n",
63
+ "\n",
64
+ " if os.path.exists(img_path):\n",
65
+ " img = Image.open(img_path).convert('RGB')\n",
66
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
67
+ " images.append(img_array)\n",
68
+ " ages.append(age)\n",
69
+ "\n",
70
+ "X = np.array(images)\n",
71
+ "y = np.array(ages)\n",
72
+ "\n",
73
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
74
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
75
+ "\n",
76
+ "# Split Data\n",
77
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
78
+ "\n",
79
+ "print(f\"X_train shape: {X_train.shape}\")\n",
80
+ "print(f\"X_test shape: {X_test.shape}\")\n",
81
+ "print(f\"y_train shape: {y_train.shape}\")\n",
82
+ "print(f\"y_test shape: {y_test.shape}\")"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
92
+ "\n",
93
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
94
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
95
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
96
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
97
+ "\n"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# 2. Create TensorDataset objects\n",
107
+ "train_dataset = TensorDataset(X_train, y_train)\n",
108
+ "test_dataset = TensorDataset(X_test, y_test)\n",
109
+ "\n"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# 3. Create DataLoaders\n",
119
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
120
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
121
+ "\n",
122
+ "\n"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# 4. Print shape of one batch\n",
132
+ "\n",
133
+ "X_batch, y_batch = next(iter(train_loader))\n",
134
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
135
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# 5. Display sample images\n",
145
+ "\n",
146
+ "images, labels = next(iter(train_loader))\n",
147
+ "\n",
148
+ "# Display the first 6 images in the batch\n",
149
+ "plt.figure(figsize=(8, 4))\n",
150
+ "\n",
151
+ "for i in range(6):\n",
152
+ " plt.subplot(2, 3, i + 1)\n",
153
+ "\n",
154
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
155
+ " img = images[i].permute(1, 2, 0)\n",
156
+ "\n",
157
+ " plt.imshow(img)\n",
158
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
159
+ " plt.axis('off')\n",
160
+ "\n",
161
+ "plt.tight_layout()\n",
162
+ "plt.show()"
163
+ ],
164
+ "execution_count": null,
165
+ "outputs": []
166
+ },
167
+ {
168
+ "cell_type": "code",
169
+ "metadata": {},
170
+ "source": [
171
+ "class NN3Layer(nn.Module):\n",
172
+ "\n",
173
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
174
+ " super(NN3Layer, self).__init__()\n",
175
+ "\n",
176
+ " # First linear layer: input features -> hidden layer\n",
177
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
178
+ "\n",
179
+ " # Second linear layer: hidden layer -> hidden layer\n",
180
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
181
+ "\n",
182
+ "\n",
183
+ " # third linear layer: hidden layer -> hidden layer\n",
184
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
185
+ "\n",
186
+ " # Output layer: hidden layer -> number of classes (logits)\n",
187
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
188
+ "\n",
189
+ " # ReLU activation for non-linearity\n",
190
+ " self.relu = nn.ReLU()\n",
191
+ "\n",
192
+ " # Defines how input data flows through the network\n",
193
+ " def forward(self, x):\n",
194
+ " # First hidden layer\n",
195
+ " z1 = self.layer1(x)\n",
196
+ " a1 = self.relu(z1)\n",
197
+ "\n",
198
+ " # Second hidden layer\n",
199
+ " z2 = self.layer2(a1)\n",
200
+ " a2 = self.relu(z2)\n",
201
+ "\n",
202
+ " # Output layer (raw scores / logits)\n",
203
+ " output = self.layer3(a2) # there is something missing here, remember? :)\n",
204
+ "\n",
205
+ " return output\n",
206
+ "\n"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 2: Write your training loop here:\n",
216
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
217
+ " # Set the model to training mode\n",
218
+ " model.train()\n",
219
+ "\n",
220
+ " running_loss = 0.0\n",
221
+ "\n",
222
+ " for X_batch, y_batch in train_loader:\n",
223
+ " # Move batch to the selected device\n",
224
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
225
+ " y_batch = y_batch.to(device)\n",
226
+ "\n",
227
+ " # Forward pass\n",
228
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
229
+ " loss = criterion(outputs, y_batch)\n",
230
+ "\n",
231
+ " # Backward pass & optimization\n",
232
+ " optimizer.zero_grad() # Clear previous gradients\n",
233
+ " loss.backward() # Compute gradients\n",
234
+ " optimizer.step() # Update model parameters\n",
235
+ "\n",
236
+ " running_loss += loss.item()\n",
237
+ "\n",
238
+ " # Average loss over all batches\n",
239
+ " avg_loss = running_loss / len(train_loader)\n",
240
+ "\n",
241
+ " return avg_loss"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# Task 3: Write your validation loop here:\n",
251
+ "def validate(model, criterion, test_loader, device):\n",
252
+ " # Set the model to evaluation mode\n",
253
+ " model.eval()\n",
254
+ "\n",
255
+ " running_loss = 0.0\n",
256
+ " correct = 0\n",
257
+ " total = 0\n",
258
+ "\n",
259
+ " with torch.no_grad():\n",
260
+ " for X_batch, y_batch in test_loader:\n",
261
+ " # Move data to device\n",
262
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
263
+ " y_batch = y_batch.to(device)\n",
264
+ "\n",
265
+ " # Forward pass\n",
266
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
267
+ " loss = criterion(outputs, y_batch)\n",
268
+ " running_loss += loss.item()\n",
269
+ "\n",
270
+ " # Apply Softmax to get probabilities\n",
271
+ " probabilities = F.softmax(outputs, dim=1)\n",
272
+ "\n",
273
+ " # Multiclass predictions\n",
274
+ " predicted = torch.argmax(probabilities, dim=1)\n",
275
+ "\n",
276
+ " # Accuracy calculation\n",
277
+ " correct += (predicted == y_batch).sum().item()\n",
278
+ " total += y_batch.size(0)\n",
279
+ "\n",
280
+ " avg_loss = running_loss / len(test_loader)\n",
281
+ " accuracy = correct / total\n",
282
+ "\n",
283
+ " return avg_loss, accuracy"
284
+ ],
285
+ "execution_count": null,
286
+ "outputs": []
287
+ },
288
+ {
289
+ "cell_type": "code",
290
+ "metadata": {},
291
+ "source": [
292
+ "# Task 4: Define device, model, loss, optimizer:\n",
293
+ "\n",
294
+ "num_epochs = 20\n",
295
+ "learning_rate = 0.001\n",
296
+ "\n",
297
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
298
+ "criterion = nn.CrossEntropyLoss()\n",
299
+ "# Define optimizer\n",
300
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
301
+ "\n",
302
+ "\n",
303
+ "# Device setup\n",
304
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
305
+ "print(\"Running Model on:\", device)\n",
306
+ "\n",
307
+ "# Model parameters\n",
308
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
309
+ "hidden_dim = 14 # Design choice (Number of nuerons in each layer)\n",
310
+ "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
311
+ "\n",
312
+ "# Instantiate model\n",
313
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
314
+ "\n",
315
+ "# Print the model architecture\n",
316
+ "print(\"Model Architecture:\\n\")\n",
317
+ "print(model)\n",
318
+ "\n",
319
+ "\n",
320
+ "# Calculate the total number of trainable parameters (why?)\n",
321
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
322
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n"
323
+ ],
324
+ "execution_count": null,
325
+ "outputs": []
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "metadata": {},
330
+ "source": [
331
+ "# Task 5: Start training for 20 epochs:\n",
332
+ "# Run Training\n",
333
+ "train_losses = []\n",
334
+ "val_losses = []\n",
335
+ "val_accuracies = []\n",
336
+ "\n",
337
+ "print('Starting Training...')\n",
338
+ "for epoch in range(num_epochs):\n",
339
+ " # Train one epoch\n",
340
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
341
+ "\n",
342
+ " # Validate\n",
343
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
344
+ "\n",
345
+ " train_losses.append(train_loss)\n",
346
+ " val_losses.append(val_loss)\n",
347
+ " val_accuracies.append(val_accuracy)\n",
348
+ "\n",
349
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
350
+ "\n",
351
+ "print('Training Complete!')"
352
+ ],
353
+ "execution_count": null,
354
+ "outputs": []
355
+ },
356
+ {
357
+ "cell_type": "code",
358
+ "metadata": {},
359
+ "source": [
360
+ "# Task 1: Write your code here:\n",
361
+ "plt.figure(figsize=(7, 5))\n",
362
+ "\n",
363
+ "plt.plot(train_losses, label='Train Loss')\n",
364
+ "plt.plot(val_losses, label='Validation Loss')\n",
365
+ "plt.title('Loss over Epochs')\n",
366
+ "plt.xlabel('Epoch')\n",
367
+ "plt.ylabel('Loss')\n",
368
+ "plt.legend()\n",
369
+ "\n",
370
+ "plt.tight_layout()\n",
371
+ "plt.show()"
372
+ ],
373
+ "execution_count": null,
374
+ "outputs": []
375
+ },
376
+ {
377
+ "cell_type": "code",
378
+ "metadata": {},
379
+ "source": [
380
+ "# Task 2 (Bonus): Write your code here:\n",
381
+ "model.eval()\n",
382
+ "# Get one batch from the test DataLoader\n",
383
+ "images, labels = next(iter(test_loader))\n",
384
+ "# Move images to device\n",
385
+ "images = images.to(device)\n",
386
+ "labels = labels.to(device)\n",
387
+ "\n",
388
+ "with torch.no_grad():\n",
389
+ " # Flatten images before passing to the model\n",
390
+ " outputs = model(images.view(images.size(0), -1))\n",
391
+ " predictions = torch.argmax(outputs, dim=1)\n",
392
+ "\n",
393
+ "# Move tensors back to CPU for plotting\n",
394
+ "images = images.cpu()\n",
395
+ "labels = labels.cpu()\n",
396
+ "predictions = predictions.cpu()\n",
397
+ "\n",
398
+ "# Plot first 6 predictions\n",
399
+ "plt.figure(figsize=(8, 4))\n",
400
+ "for i in range(6):\n",
401
+ " plt.subplot(2, 3, i + 1)\n",
402
+ " plt.imshow(images[i].squeeze(), cmap='gray')\n",
403
+ " plt.title(f\"True: {labels[i]} | Pred: {predictions[i]}\")\n",
404
+ " plt.axis('off')\n",
405
+ "\n",
406
+ "plt.tight_layout()\n",
407
+ "plt.show()"
408
+ ],
409
+ "execution_count": null,
410
+ "outputs": []
411
+ },
412
+ {
413
+ "cell_type": "code",
414
+ "metadata": {},
415
+ "source": [],
416
+ "execution_count": null,
417
+ "outputs": []
418
+ }
419
+ ],
420
+ "metadata": {
421
+ "kernelspec": {
422
+ "display_name": "Python 3",
423
+ "name": "python3"
424
+ },
425
+ "language_info": {
426
+ "name": "python"
427
+ }
428
+ },
429
+ "nbformat": 4,
430
+ "nbformat_minor": 0
431
+ }
submissions_extracted/223/Q3.ipynb ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "from sklearn.model_selection import StratifiedKFold\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
+ "import pandas as pd\n",
18
+ "import numpy as np\n",
19
+ "import matplotlib.pyplot as plt\n",
20
+ "import seaborn as sns\n",
21
+ "import kagglehub\n",
22
+ "import os\n",
23
+ "from tqdm import tqdm\n",
24
+ "\n",
25
+ "import warnings\n",
26
+ "warnings.filterwarnings('ignore')"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "import kagglehub\n",
36
+ "\n",
37
+ "\n",
38
+ "\n",
39
+ "# Download latest version\n",
40
+ "\n",
41
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
42
+ "\n",
43
+ "\n",
44
+ "\n",
45
+ "print(\"Path to dataset files:\", path)"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "# Task 1: Write your code here:\n",
55
+ "df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')"
56
+ ],
57
+ "execution_count": null,
58
+ "outputs": []
59
+ },
60
+ {
61
+ "cell_type": "code",
62
+ "metadata": {},
63
+ "source": [
64
+ "# Task 2: Write your code here:\n",
65
+ "df.head()"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# Task 3: Write your code here:\n",
75
+ "df.info()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 4: Write your code here:\n",
85
+ "df.describe()"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 1: Write your code here:\n",
95
+ "# Task 1: Write your code here:\n",
96
+ "def check_missing_values(df):\n",
97
+ " missing_values = df.isnull().sum()\n",
98
+ " print(\"Missing Values per Column:\")\n",
99
+ " print(missing_values[missing_values > 0])\n",
100
+ " if missing_values.any():\n",
101
+ " print(\"\\nHandle Missing Values as needed.\")\n",
102
+ " else:\n",
103
+ " print(\"\\nNo Missing Values Found.\")\n",
104
+ "\n",
105
+ "check_missing_values(df)"
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
+ "def check_duplicates(df):\n",
116
+ " duplicates = df.duplicated().sum()\n",
117
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
118
+ " if duplicates > 0:\n",
119
+ " print(\"Dropping Duplicates...\")\n",
120
+ " df.drop_duplicates(inplace=True)\n",
121
+ " print(\"Duplicates Dropped.\")\n",
122
+ " else:\n",
123
+ " print(\"No Duplicate Samples Found.\")\n",
124
+ "\n",
125
+ "check_duplicates(df)\n"
126
+ ],
127
+ "execution_count": null,
128
+ "outputs": []
129
+ },
130
+ {
131
+ "cell_type": "code",
132
+ "metadata": {},
133
+ "source": [
134
+ "# Task 3: Write your code here:\n",
135
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
136
+ "\n",
137
+ "print(\"Categorical Columns:\", list(categorical_cols))\n"
138
+ ],
139
+ "execution_count": null,
140
+ "outputs": []
141
+ },
142
+ {
143
+ "cell_type": "code",
144
+ "metadata": {},
145
+ "source": [
146
+ "df.head()"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# Task 4: Write your code here:\n",
156
+ "from sklearn.preprocessing import StandardScaler\n",
157
+ "\n",
158
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
159
+ "scaler = StandardScaler()\n",
160
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
161
+ "df.head()"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 5: Write your code here:\n",
171
+ "def check_target_imbalance(df, target_column):\n",
172
+ " print(\"Target Distribution:\")\n",
173
+ " print(df[target_column].value_counts(normalize=True))\n",
174
+ " sns.countplot(x=df[target_column])\n",
175
+ " plt.title(\"Target Distribution\")\n",
176
+ " plt.show()\n",
177
+ "\n",
178
+ "check_target_imbalance(df, \"Target\")"
179
+ ],
180
+ "execution_count": null,
181
+ "outputs": []
182
+ },
183
+ {
184
+ "cell_type": "code",
185
+ "metadata": {},
186
+ "source": [
187
+ "# Task 1: Write your code here:\n",
188
+ "feature_cols = df.columns.drop('Target')\n",
189
+ "X = df[feature_cols]\n",
190
+ "y = df['Target']"
191
+ ],
192
+ "execution_count": null,
193
+ "outputs": []
194
+ },
195
+ {
196
+ "cell_type": "code",
197
+ "metadata": {},
198
+ "source": [
199
+ "# Task 2,3,4,5: Write your code here:\n",
200
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
201
+ "\n",
202
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
203
+ "\n",
204
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
205
+ " # indexing for each fold\n",
206
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
207
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
208
+ "\n",
209
+ " print(f\"Fold {fold}\")\n",
210
+ " print(\" X_train shape:\", X_train.shape)\n",
211
+ " print(\" X_test shape :\", X_test.shape)\n",
212
+ " print(\" y_train shape:\", y_train.shape)\n",
213
+ " print(\" y_test shape :\", y_test.shape)\n",
214
+ "\n",
215
+ " # showing class distribution\n",
216
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
217
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
218
+ "\n",
219
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
220
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
221
+ "\n",
222
+ "\n"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "from catboost import CatBoostClassifier"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "from sklearn.neighbors import KNeighborsClassifier\n",
241
+ "import sklearn\n",
242
+ "from sklearn.svm import SVC\n",
243
+ "from sklearn.tree import DecisionTreeClassifier\n",
244
+ "from sklearn.ensemble import RandomForestClassifier\n",
245
+ "from xgboost import XGBClassifier\n",
246
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, confusion_matrix\n",
247
+ "\n",
248
+ "\n",
249
+ "model = XGBClassifier(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
250
+ "model.fit(X_train, y_train)\n",
251
+ "print(\"Model trained!\")\n",
252
+ "\n",
253
+ "#Evaluate using MAE (Mean Absolute Error) ONLY\n",
254
+ "y_pred = model.predict(X_test)\n",
255
+ "mae = mean_absolute_error(y_test, y_pred)\n",
256
+ "#Print the averaged score across all folds\n",
257
+ "print(f\"MAE: ${mae:,.2f}\")\n",
258
+ "# Calculate metrics\n",
259
+ "accuracy = accuracy_score(y_test, y_pred)\n",
260
+ "precision = precision_score(y_test, y_pred)\n",
261
+ "recall = recall_score(y_test, y_pred)\n",
262
+ "f1 = f1_score(y_test, y_pred)\n",
263
+ "\n",
264
+ "print(\"Accuracy :\", accuracy)\n",
265
+ "print(\"Precision:\", precision)\n",
266
+ "print(\"Recall :\", recall)\n",
267
+ "print(\"F1 Score :\", f1)\n"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task 1: Write your code here:\n",
277
+ "feature_importance = pd.DataFrame({\n",
278
+ " 'feature': feature_cols,\n",
279
+ " 'importance': model.feature_importances_\n",
280
+ "}).sort_values('importance', ascending=False)\n",
281
+ "\n",
282
+ "plt.figure(figsize=(10, 6))\n",
283
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
284
+ "plt.xlabel('Importance')\n",
285
+ "plt.title('Feature Importance')\n",
286
+ "plt.gca().invert_yaxis()\n",
287
+ "plt.show()\n"
288
+ ],
289
+ "execution_count": null,
290
+ "outputs": []
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "metadata": {},
295
+ "source": [
296
+ "# Task 2: Write your code here:"
297
+ ],
298
+ "execution_count": null,
299
+ "outputs": []
300
+ },
301
+ {
302
+ "cell_type": "code",
303
+ "metadata": {},
304
+ "source": [
305
+ "# Task Bonus: Write your code here:"
306
+ ],
307
+ "execution_count": null,
308
+ "outputs": []
309
+ }
310
+ ],
311
+ "metadata": {
312
+ "kernelspec": {
313
+ "display_name": "Python 3",
314
+ "name": "python3"
315
+ },
316
+ "language_info": {
317
+ "name": "python"
318
+ }
319
+ },
320
+ "nbformat": 4,
321
+ "nbformat_minor": 0
322
+ }
submissions_extracted/224/Q1.ipynb ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "import kagglehub\n",
13
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.linear_model import LogisticRegression\n",
16
+ "from sklearn.metrics import f1_score\n",
17
+ "\n",
18
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
19
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
20
+ "from sklearn.ensemble import RandomForestClassifier\n",
21
+ "import warnings\n",
22
+ "warnings.filterwarnings('ignore')\n",
23
+ "import numpy as np\n",
24
+ "import pandas as pd\n",
25
+ "import matplotlib.pyplot as plt\n",
26
+ "import os\n",
27
+ "import kagglehub\n",
28
+ "\n",
29
+ "from sklearn.model_selection import train_test_split, KFold\n",
30
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
31
+ "from sklearn.ensemble import RandomForestRegressor\n",
32
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
33
+ "\n",
34
+ "\n",
35
+ "\n",
36
+ "# Download latest version\n",
37
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
38
+ "\n",
39
+ "print(\"Path to dataset files:\", path)\n",
40
+ "\n"
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
+ "# Load the CSV file\n",
51
+ "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n",
52
+ "df_Q1data = pd.read_csv(Q1_data_path)\n",
53
+ "\n",
54
+ "print(f\"Shape: {df_Q1data.shape}\")\n"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "# Task 2: Write your code here:\n",
64
+ "df_Q1data.head()"
65
+ ],
66
+ "execution_count": null,
67
+ "outputs": []
68
+ },
69
+ {
70
+ "cell_type": "code",
71
+ "metadata": {},
72
+ "source": [
73
+ "# Task 3: Write your code here:\n",
74
+ "df_Q1data.info()"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 4: Write your code here:\n",
84
+ "df_Q1data.describe()"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Task 5: Write your code here:\n",
94
+ "plt.figure(figsize=(10, 5))\n",
95
+ "plt.hist(df_Q1data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
96
+ "plt.title('Delivery_Time Distribution')\n",
97
+ "plt.xlabel('Delivery_Time')\n",
98
+ "plt.ylabel('Frequency')\n",
99
+ "plt.show()"
100
+ ],
101
+ "execution_count": null,
102
+ "outputs": []
103
+ },
104
+ {
105
+ "cell_type": "code",
106
+ "metadata": {},
107
+ "source": [
108
+ "# Task 1: Write your code here:\n",
109
+ "df_Q1data = df_Q1data.drop(['Order_ID'], axis=1)\n",
110
+ "\n",
111
+ "\n",
112
+ "\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# Task 2: Write your code here:\n",
122
+ "# 2. Do we have missing values?\n",
123
+ "def check_missing_values(df):\n",
124
+ " missing_values = df.isnull().sum()\n",
125
+ " print(\"Missing Values per Column:\")\n",
126
+ " print(missing_values[missing_values > 0])\n",
127
+ " if missing_values.any():\n",
128
+ " print(\"\\nHandle Missing Values as needed.\")\n",
129
+ " else:\n",
130
+ " print(\"\\nNo Missing Values Found.\")\n",
131
+ "\n",
132
+ "check_missing_values(df_Q1data)\n",
133
+ "\n",
134
+ "df_Q1data = df_Q1data.fillna(df_Q1data.mean())"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 3: Write your code here:\n",
144
+ "def check_duplicates(df):\n",
145
+ " duplicates = df.duplicated().sum()\n",
146
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
147
+ " if duplicates > 0:\n",
148
+ " print(\"Dropping Duplicates...\")\n",
149
+ " df.drop_duplicates(inplace=True)\n",
150
+ " print(\"Duplicates Dropped.\")\n",
151
+ " else:\n",
152
+ " print(\"No Duplicate Samples Found.\")\n",
153
+ "\n",
154
+ "check_duplicates(df_Q1data)"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 4: Write your code here:\n",
164
+ "\n",
165
+ "categorical_cols = df_Q1data.select_dtypes(include=[\"object\"]).columns\n",
166
+ "\n",
167
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
168
+ "\n",
169
+ "for col in categorical_cols:\n",
170
+ " print(f\"Encoding column: {col}\")\n",
171
+ " le = LabelEncoder()\n",
172
+ " # TODO: Apply fit_transform to encode the column\n",
173
+ " df_Q1data[col] = le.fit_transform(df_Q1data[col])\n",
174
+ "\n",
175
+ "df_Q1data.head()\n",
176
+ "\n",
177
+ "\n"
178
+ ],
179
+ "execution_count": null,
180
+ "outputs": []
181
+ },
182
+ {
183
+ "cell_type": "code",
184
+ "metadata": {},
185
+ "source": [
186
+ "# Task 5: Write your code here:\n",
187
+ "\n",
188
+ "\n",
189
+ "numerical_cols = df_Q1data.select_dtypes(include=[\"number\"]).columns.drop(\"Delivery_Time\")\n",
190
+ "\n",
191
+ "scaler = StandardScaler()\n",
192
+ "\n",
193
+ "# Apply fit_transform to scale the numerical columns\n",
194
+ "df_Q1data[numerical_cols] = scaler.fit_transform(df_Q1data[numerical_cols])\n",
195
+ "\n",
196
+ "df_Q1data.head()\n"
197
+ ],
198
+ "execution_count": null,
199
+ "outputs": []
200
+ },
201
+ {
202
+ "cell_type": "code",
203
+ "metadata": {},
204
+ "source": [
205
+ "# Task 6: Write your code here:\n",
206
+ " # Is the target imbalanced? no\n",
207
+ "def check_target_imbalance(df, target_column):\n",
208
+ " print(\"Target Distribution:\")\n",
209
+ "\n",
210
+ " df[target_column].hist()\n",
211
+ " plt.show()\n",
212
+ "\n",
213
+ "check_target_imbalance(df_Q1data, \"Delivery_Time\")"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 1: Write your code here:\n",
223
+ "X = df_Q1data.drop(\"Delivery_Time\", axis=1).astype(float)\n",
224
+ "y = df_Q1data['Delivery_Time']\n"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Task 2,3,4,5: Write your code here:\n",
234
+ "\n",
235
+ "# use Train-test split (80% train, 20% test)\n",
236
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
237
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
238
+ "\n",
239
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
240
+ "model.fit(X_train, y_train)\n",
241
+ "print(\"Model trained!\")\n",
242
+ "\n",
243
+ "y_pred = model.predict(X_train)\n",
244
+ "\n",
245
+ "mae = mean_absolute_error(y_test, y_pred)\n",
246
+ "\n",
247
+ "print(f\"MAE: ${mae:,.2f}\")\n",
248
+ "print(f\"MAE: ${mae.mean():,.2f}\")\n"
249
+ ],
250
+ "execution_count": null,
251
+ "outputs": []
252
+ },
253
+ {
254
+ "cell_type": "code",
255
+ "metadata": {},
256
+ "source": [
257
+ "# Task 1: Write your code here:\n",
258
+ "\n",
259
+ "feature_cols=['Distance_km','Weather','Traffic_Level','Time_of_Day']\n",
260
+ "# Feature importance\n",
261
+ "importance = pd.DataFrame({\n",
262
+ " 'feature': feature_cols,\n",
263
+ " 'importance': model.feature_importances_\n",
264
+ "}).sort_values('importance', ascending=False)\n",
265
+ "\n",
266
+ "plt.figure(figsize=(10, 6))\n",
267
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
268
+ "plt.xlabel('Importance')\n",
269
+ "plt.title('Feature Importance')\n",
270
+ "plt.gca().invert_yaxis()\n",
271
+ "plt.show()"
272
+ ],
273
+ "execution_count": null,
274
+ "outputs": []
275
+ },
276
+ {
277
+ "cell_type": "code",
278
+ "metadata": {},
279
+ "source": [
280
+ "# Task 2: Write your code here:\n",
281
+ "plt.figure(figsize=(10, 6))\n",
282
+ "plt.hist(y_pred, bins=30, edgecolor='black')\n",
283
+ "plt.title('Distribution of Predictions')\n",
284
+ "plt.xlabel('Predicted Delivery_Time')\n",
285
+ "plt.ylabel('Count')\n",
286
+ "plt.show()"
287
+ ],
288
+ "execution_count": null,
289
+ "outputs": []
290
+ },
291
+ {
292
+ "cell_type": "code",
293
+ "metadata": {},
294
+ "source": [
295
+ "from sklearn.linear_model import Ridge, Lasso\n",
296
+ "from sklearn.svm import SVR\n",
297
+ "from sklearn.tree import DecisionTreeRegressor\n",
298
+ "from sklearn.ensemble import RandomForestRegressor\n",
299
+ "from lightgbm import LGBMRegressor\n",
300
+ "from catboost import CatBoostRegressor"
301
+ ],
302
+ "execution_count": null,
303
+ "outputs": []
304
+ },
305
+ {
306
+ "cell_type": "code",
307
+ "metadata": {},
308
+ "source": [
309
+ "models = {\n",
310
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
311
+ " \"CatBoost\": CatBoostRegressor(verbose=0)\n",
312
+ "}"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "metadata": {},
320
+ "source": [
321
+ "all_results = {}\n",
322
+ "\n",
323
+ "for name in models:\n",
324
+ " all_results[name] = {'mae': [], 'rmse': [], 'r2': []}"
325
+ ],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
334
+ "\n",
335
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
336
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
337
+ "\n",
338
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
339
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
340
+ "\n",
341
+ " for model_name, model in models.items():\n",
342
+ " print(f\"Training {model_name}...\")\n",
343
+ "\n",
344
+ " # Train\n",
345
+ " model.fit(X_train, y_train)\n",
346
+ "\n",
347
+ " # Predict\n",
348
+ " y_pred = model.predict(X_test)\n",
349
+ "\n",
350
+ " # Calculate metrics\n",
351
+ " mae = mean_absolute_error(y_test, y_pred)\n",
352
+ " all_results[model_name][\"mae\"].append(mae)\n",
353
+ " all_results[model_name][\"rmse\"].append(rmse)\n",
354
+ " all_results[model_name][\"r2\"].append(r2)\n",
355
+ "\n",
356
+ "\n",
357
+ "\n",
358
+ "\n"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ }
363
+ ],
364
+ "metadata": {
365
+ "kernelspec": {
366
+ "display_name": "Python 3",
367
+ "name": "python3"
368
+ },
369
+ "language_info": {
370
+ "name": "python"
371
+ }
372
+ },
373
+ "nbformat": 4,
374
+ "nbformat_minor": 0
375
+ }
submissions_extracted/224/Q3.ipynb ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import numpy as np\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import os\n",
12
+ "import kagglehub\n",
13
+ "from sklearn.preprocessing import OneHotEncoder #import OneHotEncoder\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.linear_model import LogisticRegression\n",
16
+ "from sklearn.metrics import f1_score\n",
17
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n",
18
+ "\n",
19
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
20
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
21
+ "from sklearn.ensemble import RandomForestClassifier\n",
22
+ "import warnings\n",
23
+ "warnings.filterwarnings('ignore')\n",
24
+ "import numpy as np\n",
25
+ "import pandas as pd\n",
26
+ "import matplotlib.pyplot as plt\n",
27
+ "import os\n",
28
+ "import kagglehub\n",
29
+ "\n",
30
+ "from sklearn.model_selection import train_test_split, KFold\n",
31
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
32
+ "from sklearn.ensemble import RandomForestRegressor\n",
33
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
34
+ "\n",
35
+ "\n",
36
+ "# Download latest version\n",
37
+ "\n",
38
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
39
+ "\n",
40
+ "\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
+ "# Task 1: Write your code here:\n",
52
+ "# Load the CSV file\n",
53
+ "Q3_data_path = os.path.join(path, 'Q3_data.csv')\n",
54
+ "df_Q3data = pd.read_csv(Q3_data_path)\n",
55
+ "\n",
56
+ "print(f\"Shape: {df_Q3data.shape}\")\n"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 2: Write your code here:\n",
66
+ "df_Q3data.head()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 3: Write your code here:\n",
76
+ "df_Q3data.info()"
77
+ ],
78
+ "execution_count": null,
79
+ "outputs": []
80
+ },
81
+ {
82
+ "cell_type": "code",
83
+ "metadata": {},
84
+ "source": [
85
+ "# Task 4: Write your code here:\n",
86
+ "df_Q3data.describe()"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ " # Task 1: Write your code here:\n",
96
+ "def check_missing_values(df):\n",
97
+ " missing_values = df.isnull().sum()\n",
98
+ " print(\"Missing Values per Column:\")\n",
99
+ " print(missing_values[missing_values > 0])\n",
100
+ " if missing_values.any():\n",
101
+ " print(\"\\nHandle Missing Values as needed.\")\n",
102
+ " else:\n",
103
+ " print(\"\\nNo Missing Values Found.\")\n",
104
+ "\n",
105
+ "check_missing_values(df_Q3data)\n",
106
+ "\n",
107
+ "# Drop unnecessary columns\n",
108
+ "# df_Q3data = df_Q3data.drop(['P_2', 'S_3','D_142'], axis=1) # salary النل مثير وحذفناه\n",
109
+ "# df_Q3data.head()"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 2: Write your code here:\n",
119
+ "def check_duplicates(df):\n",
120
+ " duplicates = df.duplicated().sum()\n",
121
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
122
+ " if duplicates > 0:\n",
123
+ " print(\"Dropping Duplicates...\")\n",
124
+ " df.drop_duplicates(inplace=True)\n",
125
+ " print(\"Duplicates Dropped.\")\n",
126
+ " else:\n",
127
+ " print(\"No Duplicate Samples Found.\")\n",
128
+ "\n",
129
+ "check_duplicates(df_Q3data)"
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
+ "\n",
140
+ "categorical_cols = df_Q3data.select_dtypes(include=[\"object\"]).columns\n",
141
+ "\n",
142
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
143
+ "\n",
144
+ "for col in categorical_cols:\n",
145
+ " print(f\"Encoding column: {col}\")\n",
146
+ " le = LabelEncoder()\n",
147
+ " # TODO: Apply fit_transform to encode the column\n",
148
+ " df_Q3data[col] = le.fit_transform(df_Q3data[col])\n",
149
+ "\n",
150
+ "df_Q3data.head()\n",
151
+ "\n",
152
+ "\n"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "# Task 5: Write your code here:\n",
162
+ "\n",
163
+ "numerical_cols = df_Q3data.select_dtypes(include=[\"number\"]).columns.drop(\"Target\")\n",
164
+ "\n",
165
+ "scaler = StandardScaler()\n",
166
+ "\n",
167
+ "# Apply fit_transform to scale the numerical columns\n",
168
+ "df_Q3data[numerical_cols] = scaler.fit_transform(df_Q3data[numerical_cols])\n",
169
+ "\n",
170
+ "df_Q3data.head()\n"
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
+ " # Is the target imbalanced? no\n",
181
+ "def check_target_imbalance(df, target_column):\n",
182
+ " print(\"Target Distribution:\")\n",
183
+ "\n",
184
+ " df[target_column].hist()\n",
185
+ " plt.show()\n",
186
+ "\n",
187
+ "check_target_imbalance(df_Q3data, \"Target\")"
188
+ ],
189
+ "execution_count": null,
190
+ "outputs": []
191
+ },
192
+ {
193
+ "cell_type": "code",
194
+ "metadata": {},
195
+ "source": [
196
+ "# Task 1: Write your code here:\n",
197
+ "X = df_Q3data.drop(\"Target\", axis=1).astype(float)\n",
198
+ "y = df_Q3data['Target']\n"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 2,3,4,5: Write your code here:\n",
208
+ "\n",
209
+ "# Import base linear model for classification (Logistic Regression)\n",
210
+ "from catboost import CatBoostClassifier\n",
211
+ "# split ratio (80% train, 20% test)\n",
212
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
213
+ " X, y,\n",
214
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
215
+ " random_state=42, # reproducible output\n",
216
+ " shuffle=True, # representative splits\n",
217
+ " stratify=y # preserve class distribution\n",
218
+ ")\n",
219
+ "\n",
220
+ "model = CatBoostClassifier(verbose=0, n_estimators=320,max_depth=4) # instantiate\n",
221
+ "model.fit(X_train, y_train) # fit\n",
222
+ "y_pred = model.predict(X_test) # predict\n",
223
+ "\n",
224
+ "\n",
225
+ "print(f\"Accuracy: {accuracy_score(y_test, y_pred):.4f}\\n\")\n",
226
+ "f1 = f1_score(y_test, y_pred)\n",
227
+ "print(\"Accuracy :\", accuracy)\n",
228
+ "print(\"F1 Score :\", f1)\n",
229
+ "print(f\"Average: ${f1.mean():,.2f}\")\n",
230
+ "\n",
231
+ "\n"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 1: Write your code here:\n",
241
+ "feature_importance = pd.DataFrame({\n",
242
+ " 'feature': X,\n",
243
+ " 'importance': model.feature_importances_\n",
244
+ "}).sort_values('importance', ascending=False)\n",
245
+ "\n",
246
+ "plt.figure(figsize=(10, 6))\n",
247
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
248
+ "plt.xlabel('Importance')\n",
249
+ "plt.title('Feature Importance')\n",
250
+ "plt.gca().invert_yaxis()\n",
251
+ "plt.show()"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task 2: Write your code here:"
261
+ ],
262
+ "execution_count": null,
263
+ "outputs": []
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "metadata": {},
268
+ "source": [
269
+ "# Task Bonus: Write your code here:"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ }
274
+ ],
275
+ "metadata": {
276
+ "kernelspec": {
277
+ "display_name": "Python 3",
278
+ "name": "python3"
279
+ },
280
+ "language_info": {
281
+ "name": "python"
282
+ }
283
+ },
284
+ "nbformat": 4,
285
+ "nbformat_minor": 0
286
+ }
submissions_extracted/225/Q1.ipynb ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import pandas as pd\n",
8
+ "import os\n",
9
+ "import numpy as np\n",
10
+ "import matplotlib.pyplot as plt"
11
+ ],
12
+ "execution_count": null,
13
+ "outputs": []
14
+ },
15
+ {
16
+ "cell_type": "code",
17
+ "metadata": {},
18
+ "source": [
19
+ "import kagglehub\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
23
+ "\n",
24
+ "print(\"Path to dataset files:\", path)"
25
+ ],
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "source": [
33
+ "# Task 1: Read the dataset Q1_data.csv using read_csv()\n",
34
+ "\n",
35
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
36
+ "df = pd.read_csv(csv_path)\n"
37
+ ],
38
+ "execution_count": null,
39
+ "outputs": []
40
+ },
41
+ {
42
+ "cell_type": "code",
43
+ "metadata": {},
44
+ "source": [
45
+ "# Task 2: Inspect the first few rows using head()\n",
46
+ "df.head()"
47
+ ],
48
+ "execution_count": null,
49
+ "outputs": []
50
+ },
51
+ {
52
+ "cell_type": "code",
53
+ "metadata": {},
54
+ "source": [
55
+ "# Task 3: Display dataset information using info()\n",
56
+ "df.info()"
57
+ ],
58
+ "execution_count": null,
59
+ "outputs": []
60
+ },
61
+ {
62
+ "cell_type": "code",
63
+ "metadata": {},
64
+ "source": [
65
+ "# Task 4: Show statistical description using describe()\n",
66
+ "df.describe()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "# Task 5: Plot the target distribution (delivery_time)\n",
76
+ "\n",
77
+ "def check_target_distribution(df, target_column):\n",
78
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
79
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
80
+ " plt.xlabel(target_column)\n",
81
+ " plt.ylabel(\"Frequency\")\n",
82
+ " plt.grid(False)\n",
83
+ " plt.show()\n",
84
+ "\n",
85
+ "check_target_distribution(df, \"Delivery_Time\")\n"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "df.head()"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 1: Drop the 'Order_ID' column from the data\n",
104
+ "df = df.drop(columns=\"Order_ID\", axis=1)\n",
105
+ "df.head()"
106
+ ],
107
+ "execution_count": null,
108
+ "outputs": []
109
+ },
110
+ {
111
+ "cell_type": "code",
112
+ "metadata": {},
113
+ "source": [
114
+ "# Task 2: Handle missing values appropriately\n",
115
+ "\n",
116
+ "def check_missing_values(df):\n",
117
+ " missing_values = df.isnull().sum()\n",
118
+ " print(\"Missing Values per Column:\")\n",
119
+ " print(missing_values[missing_values > 0])\n",
120
+ "\n",
121
+ "\n",
122
+ " if missing_values.any():\n",
123
+ " print(\"\\nHandle Missing Values as needed.\")\n",
124
+ " df.fillna(df.mean(numeric_only=True), inplace=True)\n",
125
+ " df.fillna(df.mode, inplace=True)\n",
126
+ "\n",
127
+ " else:\n",
128
+ " print(\"\\nNo Missing Values Found.\")\n",
129
+ "\n",
130
+ "check_missing_values(df)\n"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "df.head()"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 3: Check and remove duplicates if any exist\n",
149
+ "def check_duplicates(df):\n",
150
+ " duplicates = df.duplicated().sum()\n",
151
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
152
+ "\n",
153
+ " if duplicates > 0:\n",
154
+ " print(\"Dropping Duplicates...\")\n",
155
+ " df.drop_duplicates(inplace=True)\n",
156
+ " print(\"Duplicates Dropped.\")\n",
157
+ "\n",
158
+ " else:\n",
159
+ " print(\"No Duplicate Samples Found.\")\n",
160
+ "check_duplicates(df)"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "categories = df.select_dtypes(include=[\"object\"]).columns\n",
170
+ "#print(\"Categorical Columns:\", list(categories))\n",
171
+ "categories"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "# Task 4: Encode categorical variables if needed (Bonus if used One Hot Encoding)\n",
181
+ "\n",
182
+ "from sklearn.preprocessing import OneHotEncoder\n",
183
+ "\n",
184
+ "print('data before encoding:\\n', df) #show before encoding\n",
185
+ "\n",
186
+ "onehot_encoder = OneHotEncoder(sparse_output=False) # Instantiate\n",
187
+ "\n",
188
+ "#df.head()\n",
189
+ "data_onehot_encoded = onehot_encoder.fit_transform(categories)\n"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "print('\\nData after encoding:\\n', data_onehot_encoded)"
199
+ ],
200
+ "execution_count": null,
201
+ "outputs": []
202
+ },
203
+ {
204
+ "cell_type": "code",
205
+ "metadata": {},
206
+ "source": [
207
+ "# Task 5: Apply feature scaling for all features (Use StandardScaler)\n",
208
+ "from sklearn.preprocessing import StandardScaler\n",
209
+ "print('data before scaling:\\n', df)\n",
210
+ "\n",
211
+ "standard_scaler = StandardScaler()\n",
212
+ "data_standard_scaled = standard_scaler.fit_transform(df)\n",
213
+ "print('\\nData after scaling:\\n', data_standard_scaled)"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 6: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "# Task 1: Split the dataset into features (X) and target (y)\n",
232
+ "\n",
233
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
234
+ "y = df['Delivery_Time'].astype(float)"
235
+ ],
236
+ "execution_count": null,
237
+ "outputs": []
238
+ },
239
+ {
240
+ "cell_type": "code",
241
+ "metadata": {},
242
+ "source": [
243
+ "from sklearn.ensemble import RandomForestRegressor\n",
244
+ "from sklearn.model_selection import KFold"
245
+ ],
246
+ "execution_count": null,
247
+ "outputs": []
248
+ },
249
+ {
250
+ "cell_type": "code",
251
+ "metadata": {},
252
+ "source": [
253
+ "model = RandomForestRegressor(n_estimators=200,\n",
254
+ "max_depth=10)"
255
+ ],
256
+ "execution_count": null,
257
+ "outputs": []
258
+ },
259
+ {
260
+ "cell_type": "code",
261
+ "metadata": {},
262
+ "source": [
263
+ "# Task 2: Use the correct split: KFold OR StratifiedKFold\n",
264
+ "\n",
265
+ "n_splits = 5 # K=5 Folds\n",
266
+ "\n",
267
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task 3: Train a RandomForest model\n",
277
+ "\n",
278
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
279
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
280
+ " # Get the train & test split for this fold\n",
281
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
282
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
283
+ "\n",
284
+ "# Train & Validate Models\n",
285
+ " print(f\"Training a RandomForest model...\")\n",
286
+ " # Fit the model on train data\n",
287
+ " model.fit(X_train, y_train)\n",
288
+ " # Use the model to predict the test data\n",
289
+ "\n",
290
+ " y_pred = model.predict(X_test)\n",
291
+ " # Calculate evaluation metrics\n",
292
+ "\n",
293
+ " accuracy = accuracy_score(y_test, y_pred)\n",
294
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score,\n",
295
+ " results[model_name]['accuracy'].append(accuracy)\n",
296
+ " results[model_name]['f1'].append(f1)\n",
297
+ "\n",
298
+ "\n",
299
+ "\n",
300
+ "# Task 4: Evaluate using MAE (Mean Absolute Error) ONLY\n",
301
+ "\n",
302
+ "\n",
303
+ "\n",
304
+ "# Task 5: Print the averaged score across all folds"
305
+ ],
306
+ "execution_count": null,
307
+ "outputs": []
308
+ },
309
+ {
310
+ "cell_type": "code",
311
+ "metadata": {},
312
+ "source": [
313
+ "# Task 1: Write your code here:"
314
+ ],
315
+ "execution_count": null,
316
+ "outputs": []
317
+ },
318
+ {
319
+ "cell_type": "code",
320
+ "metadata": {},
321
+ "source": [
322
+ "# Task 2: Write your code here:"
323
+ ],
324
+ "execution_count": null,
325
+ "outputs": []
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "metadata": {},
330
+ "source": [
331
+ "# Task Bonus: Write your code here:"
332
+ ],
333
+ "execution_count": null,
334
+ "outputs": []
335
+ }
336
+ ],
337
+ "metadata": {
338
+ "kernelspec": {
339
+ "display_name": "Python 3",
340
+ "name": "python3"
341
+ },
342
+ "language_info": {
343
+ "name": "python"
344
+ }
345
+ },
346
+ "nbformat": 4,
347
+ "nbformat_minor": 0
348
+ }
submissions_extracted/225/Q2.ipynb ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
24
+ "csv_path = os.path.join(path, \"labels.csv\")\n",
25
+ "df = pd.read_csv(csv_path)"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "import torch\n",
35
+ "import numpy as np\n",
36
+ "from PIL import Image\n",
37
+ "from sklearn.model_selection import train_test_split\n",
38
+ "\n",
39
+ "# Load Labels\n",
40
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
41
+ "img_dir = os.path.join(path, \"images\")\n",
42
+ "\n",
43
+ "images = []\n",
44
+ "ages = []\n",
45
+ "\n",
46
+ "# Load Images and Resize\n",
47
+ "print(\"Loading images...\")\n",
48
+ "for index, row in labels_df.iterrows():\n",
49
+ " img_name = row.iloc[0]\n",
50
+ " age = row.iloc[1]\n",
51
+ " img_path = os.path.join(img_dir, img_name)\n",
52
+ "\n",
53
+ " if os.path.exists(img_path):\n",
54
+ " img = Image.open(img_path).convert('RGB')\n",
55
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
56
+ " images.append(img_array)\n",
57
+ " ages.append(age)\n",
58
+ "\n",
59
+ "X = np.array(images)\n",
60
+ "y = np.array(ages)\n",
61
+ "\n",
62
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
63
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
64
+ "\n",
65
+ "# Split Data\n",
66
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
67
+ "\n",
68
+ "print(f\"X_train shape: {X_train.shape}\")\n",
69
+ "print(f\"X_test shape: {X_test.shape}\")\n",
70
+ "print(f\"y_train shape: {y_train.shape}\")\n",
71
+ "print(f\"y_test shape: {y_test.shape}\")"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
81
+ "\n",
82
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
83
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
84
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
85
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
86
+ "\n"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "from torch.utils.data import TensorDataset\n",
96
+ "from torch.utils.data import DataLoader"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# 2. Create TensorDataset objects\n",
106
+ "train_dataset = TensorDataset(X_train, y_train)\n",
107
+ "test_dataset = TensorDataset(X_test, y_test)"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# 3. Create DataLoaders\n",
117
+ "from torch.utils.data import DataLoader\n",
118
+ "\n",
119
+ "# DataLoader for training data\n",
120
+ "train_loader = DataLoader(\n",
121
+ " train_dataset,\n",
122
+ " batch_size=32,\n",
123
+ " shuffle=True,\n",
124
+ " num_workers=2\n",
125
+ ")\n",
126
+ "# DataLoader for test/validation data\n",
127
+ "test_loader = DataLoader(\n",
128
+ " test_dataset,\n",
129
+ " batch_size=32,\n",
130
+ " shuffle=False,\n",
131
+ " num_workers=2\n",
132
+ ")\n",
133
+ "\n"
134
+ ],
135
+ "execution_count": null,
136
+ "outputs": []
137
+ },
138
+ {
139
+ "cell_type": "code",
140
+ "metadata": {},
141
+ "source": [
142
+ "# 4. Print shape of one batch\n",
143
+ "\n",
144
+ "X_batch, y_batch = next(iter(train_loader))\n",
145
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
146
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
147
+ ],
148
+ "execution_count": null,
149
+ "outputs": []
150
+ },
151
+ {
152
+ "cell_type": "code",
153
+ "metadata": {},
154
+ "source": [
155
+ "# 5. Display sample images\n",
156
+ "#X_batch[0]\n",
157
+ "sample_image = X_batch[0]\n",
158
+ "\n",
159
+ "print(f\"\\n Image shape: {sample_image.shape}\")"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "import torch.nn as nn"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "class NN4Layer(nn.Module):\n",
178
+ " def __init__(self, input_dim):\n",
179
+ " super(NN4Layer, self).__init__()\n",
180
+ "\n",
181
+ " # output activation function\n",
182
+ " self.sigmoid = nn.Linear()\n",
183
+ "\n",
184
+ " # forward pass\n",
185
+ " def forward(self, x):\n",
186
+ " z = self.layer_1(x)\n",
187
+ " a = self.sigmoid(z) # linear\n",
188
+ " return a"
189
+ ],
190
+ "execution_count": null,
191
+ "outputs": []
192
+ },
193
+ {
194
+ "cell_type": "code",
195
+ "metadata": {},
196
+ "source": [
197
+ "input_dim = 4\n",
198
+ "hidden_dim = 3 # number of input features\n",
199
+ "\n",
200
+ "# number of hidden neurons\n",
201
+ "model = NN4Layer(input_dim, hidden_dim)\n",
202
+ "\n",
203
+ "# Print the model architecture\n",
204
+ "print(\"Model Architecture:\\n\")\n",
205
+ "\n",
206
+ "print(model)\n",
207
+ "# Calculate the total number of trainable parameters\n",
208
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_gra ######\n",
209
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
210
+ ],
211
+ "execution_count": null,
212
+ "outputs": []
213
+ },
214
+ {
215
+ "cell_type": "code",
216
+ "metadata": {},
217
+ "source": [
218
+ "# Task 2: Create a training loop function\n",
219
+ "\n",
220
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
221
+ "# Set the model to training mode\n",
222
+ " model.train()\n",
223
+ " running_loss = 0.0\n",
224
+ " for X_batch, y_batch in train_loader:\n",
225
+ " # Move batch to the selected device\n",
226
+ " X_batch = X_batch.to(device)\n",
227
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
228
+ "\n",
229
+ "# Forward pass\n",
230
+ " outputs = model(X_batch)\n",
231
+ " loss = criterion(outputs, y_batch)\n",
232
+ "\n",
233
+ "# Backward pass & optimization\n",
234
+ " optimizer.zero_grad() # Clear previous gradients\n",
235
+ " loss.backward() # Compute gradients\n",
236
+ " optimizer.step() # Update model parameters\n",
237
+ " running_loss += loss.item()\n",
238
+ "\n",
239
+ "# Average loss over all batches\n",
240
+ " avg_loss = running_loss / len(train_loader)\n",
241
+ " return avg_loss"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# Task 3: Create a validation loop function\n",
251
+ "\n",
252
+ "def validate(model, criterion, test_loader, device):\n",
253
+ "# Set the model to evaluation mode\n",
254
+ " model.eval()\n",
255
+ " running_loss = 0.0\n",
256
+ " correct = 0\n",
257
+ " total = 0\n",
258
+ "\n",
259
+ " with torch.no_grad(): # Disable gradient computation\n",
260
+ " for X_batch, y_batch in test_loader:\n",
261
+ " # Move batch to the selected device\n",
262
+ " X_batch = X_batch.to(device)\n",
263
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
264
+ " # Forward pass\n",
265
+ " outputs = model(X_batch)\n",
266
+ " loss = criterion(outputs, y_batch)\n",
267
+ " running_loss += loss.item()\n",
268
+ " # Binary predictions\n",
269
+ " predicted = (outputs > 0.5).float()\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
+ " return avg_loss, accuracy"
277
+ ],
278
+ "execution_count": null,
279
+ "outputs": []
280
+ },
281
+ {
282
+ "cell_type": "code",
283
+ "metadata": {},
284
+ "source": [
285
+ "# Task 1: Create a model class with 4 linear layers\n",
286
+ "\n",
287
+ "# Create a linear layer: 3 input features -> 1 output\n",
288
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
289
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
290
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
291
+ "linear = nn.Linear(in_features=3, out_features=1)\n",
292
+ "\n",
293
+ "# Example input: batch of 4 samples, each with 3 features\n",
294
+ "x = torch.randn(4, 3)\n",
295
+ "# Forward through the layer\n",
296
+ "y = linear(x)\n",
297
+ "print(\"Input shape:\", x.shape) # torch.Size([4, 3])\n",
298
+ "print(\"Output shape:\", y.shape) # torch.Size([4, 1])\n"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [
307
+ "# Task 4: Define device, model, loss, optimizer:\n"
308
+ ],
309
+ "execution_count": null,
310
+ "outputs": []
311
+ },
312
+ {
313
+ "cell_type": "code",
314
+ "metadata": {},
315
+ "source": [
316
+ "# Task 5: Start training for 20 epochs and track training and validation losses\n",
317
+ "\n"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [],
326
+ "execution_count": null,
327
+ "outputs": []
328
+ },
329
+ {
330
+ "cell_type": "code",
331
+ "metadata": {},
332
+ "source": [
333
+ "# Task 1: Write your code here:"
334
+ ],
335
+ "execution_count": null,
336
+ "outputs": []
337
+ },
338
+ {
339
+ "cell_type": "code",
340
+ "metadata": {},
341
+ "source": [
342
+ "# Task 2 (Bonus): Write your code here:"
343
+ ],
344
+ "execution_count": null,
345
+ "outputs": []
346
+ }
347
+ ],
348
+ "metadata": {
349
+ "kernelspec": {
350
+ "display_name": "Python 3",
351
+ "name": "python3"
352
+ },
353
+ "language_info": {
354
+ "name": "python"
355
+ }
356
+ },
357
+ "nbformat": 4,
358
+ "nbformat_minor": 0
359
+ }
submissions_extracted/225/Q3.ipynb ADDED
@@ -0,0 +1,476 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "print(\"Path to dataset files:\", path)"
17
+ ],
18
+ "execution_count": null,
19
+ "outputs": []
20
+ },
21
+ {
22
+ "cell_type": "code",
23
+ "metadata": {},
24
+ "source": [
25
+ "# Task 1: Write your code here:\n",
26
+ "\n",
27
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
28
+ "df = pd.read_csv(csv_path)"
29
+ ],
30
+ "execution_count": null,
31
+ "outputs": []
32
+ },
33
+ {
34
+ "cell_type": "code",
35
+ "metadata": {},
36
+ "source": [
37
+ "# Task 2: Inspect the first few rows using head()\n",
38
+ "\n",
39
+ "df.head()"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "# Task 3: Display dataset information using info()\n",
49
+ "df.info()"
50
+ ],
51
+ "execution_count": null,
52
+ "outputs": []
53
+ },
54
+ {
55
+ "cell_type": "code",
56
+ "metadata": {},
57
+ "source": [
58
+ "# Task 4: Show statistical description using describe()\n",
59
+ "df.describe()"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "df.head()"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# Task 1: Handle missing values appropriately\n",
85
+ "\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
+ "\n",
91
+ "\n",
92
+ " if missing_values.any():\n",
93
+ " print(\"\\nHandle Missing Values as needed.\")\n",
94
+ " df.fillna(df.mean(numeric_only=True), inplace=True)\n",
95
+ " #df.fillna(df.mode, inplace=True)\n",
96
+ "\n",
97
+ " else:\n",
98
+ " print(\"\\nNo Missing Values Found.\")\n",
99
+ "\n",
100
+ "check_missing_values(df)"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 2: Check and remove duplicates if any exist\n",
110
+ "\n",
111
+ "def check_duplicates(df):\n",
112
+ " duplicates = df.duplicated().sum()\n",
113
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
114
+ "\n",
115
+ " if duplicates > 0:\n",
116
+ " print(\"Dropping Duplicates...\")\n",
117
+ " df.drop_duplicates(inplace=True)\n",
118
+ " print(\"Duplicates Dropped.\")\n",
119
+ "\n",
120
+ " else:\n",
121
+ " print(\"No Duplicate Samples Found.\")\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: Encode categorical variables if needed\n",
132
+ "\n",
133
+ "categories = df.select_dtypes(include=[\"object\"]).columns\n",
134
+ "#print(\"Categorical Columns:\", list(categories))\n",
135
+ "categories\n"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "df.head()"
145
+ ],
146
+ "execution_count": null,
147
+ "outputs": []
148
+ },
149
+ {
150
+ "cell_type": "code",
151
+ "metadata": {},
152
+ "source": [
153
+ "#features = df.select_dtypes(include=[\"float64\"]).columns\n",
154
+ "#print(\"Categorical Columns:\", list(categories))\n",
155
+ "#features\n"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 4: Apply feature scaling to numerical features (Use StandardScaler)\n",
165
+ "\n",
166
+ "from sklearn.preprocessing import StandardScaler\n",
167
+ "\n",
168
+ "features = df.columns.drop(\"Target\")\n",
169
+ "scaler = StandardScaler()\n",
170
+ "\n",
171
+ "df[features] = scaler.fit_transform(df[features])\n",
172
+ "df.head()"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 5: Check for target imbalance and state if it is imbalanced or not\n",
182
+ "import matplotlib.pyplot as plt\n",
183
+ "\n",
184
+ "def check_target_distribution(df, target_column):\n",
185
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
186
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
187
+ " plt.xlabel(target_column)\n",
188
+ " plt.ylabel(\"Frequency\")\n",
189
+ " plt.grid(False)\n",
190
+ " plt.show()\n",
191
+ "\n",
192
+ "check_target_distribution(df, \"Target\")\n"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "# Task 1: Split the dataset into features (X) and target (y)\n",
202
+ "\n",
203
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
204
+ "y = df['Target'].astype(float)"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "metadata": {},
212
+ "source": [
213
+ "y"
214
+ ],
215
+ "execution_count": null,
216
+ "outputs": []
217
+ },
218
+ {
219
+ "cell_type": "code",
220
+ "metadata": {},
221
+ "source": [
222
+ "# Task 2: Use the correct split: KFold OR StratifiedKFold\n",
223
+ "from sklearn.model_selection import KFold\n",
224
+ "\n",
225
+ "n_splits = 5 # K=5 Folds\n",
226
+ "# 5-Fold Cross-Validation, shuffled\n",
227
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n"
228
+ ],
229
+ "execution_count": null,
230
+ "outputs": []
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "metadata": {},
235
+ "source": [
236
+ "%pip install kagglehub catboost lightgbm tqdm -q"
237
+ ],
238
+ "execution_count": null,
239
+ "outputs": []
240
+ },
241
+ {
242
+ "cell_type": "code",
243
+ "metadata": {},
244
+ "source": [
245
+ "from catboost import CatBoostRegressor\n",
246
+ "models = {\"CatBoost\": CatBoostRegressor(verbose=0)}"
247
+ ],
248
+ "execution_count": null,
249
+ "outputs": []
250
+ },
251
+ {
252
+ "cell_type": "code",
253
+ "metadata": {},
254
+ "source": [
255
+ "from sklearn.model_selection import StratifiedKFold\n",
256
+ "from sklearn.metrics import accuracy_score, f1_score\n",
257
+ "from tqdm import tqdm"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "def softmax(z):\n",
267
+ " z_shifted = z - np.max(z, axis=1, keepdims=True)\n",
268
+ " exp_z = np.exp(z_shifted)\n",
269
+ " return exp_z / np.sum(exp_z, axis=1, keepdims=True)"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ },
274
+ {
275
+ "cell_type": "code",
276
+ "metadata": {},
277
+ "source": [
278
+ "def categorical_cross_entropy(y, y_hat):\n",
279
+ " epsilon = 1e-15\n",
280
+ " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n",
281
+ " loss = -np.mean(np.sum(y * np.log(y_hat), axis=1))\n",
282
+ " return loss"
283
+ ],
284
+ "execution_count": null,
285
+ "outputs": []
286
+ },
287
+ {
288
+ "cell_type": "code",
289
+ "metadata": {},
290
+ "source": [
291
+ "def one_hot_encode(y, num_classes):\n",
292
+ " y = np.array(y)\n",
293
+ " m = len(y)\n",
294
+ " # 1. Create a grid of all zeros (num_samples, num_classes)\n",
295
+ " one_hot = np.zeros((m, num_classes))\n",
296
+ " # 2. Go through each sample one by one\n",
297
+ " for i in range(m):\n",
298
+ " # Identify which class this sample belongs to\n",
299
+ " class_label = int(y[i])\n",
300
+ " # In this row (i), set the specific class column to 1\n",
301
+ " one_hot[i, class_label] = 1\n",
302
+ " return one_hot"
303
+ ],
304
+ "execution_count": null,
305
+ "outputs": []
306
+ },
307
+ {
308
+ "cell_type": "code",
309
+ "metadata": {},
310
+ "source": [
311
+ "def gradient_descent(X, y, num_classes, lr, n_iters=1000):\n",
312
+ "# Get the number of samples (m) and number of features (n)\n",
313
+ " m, n = X.shape\n",
314
+ " theta = np.zeros((n, num_classes))\n",
315
+ "# One-hot encode the labels\n",
316
+ " y_onehot = one_hot_encode(y, num_classes)\n",
317
+ " losses = []\n",
318
+ " for _ in tqdm(range(n_iters), desc=\"Training CatBoostClassifier model\"):\n",
319
+ " # Calculate the logits z\n",
320
+ " z = np.dot(X, theta)\n",
321
+ " # Get class probabilities using softmax\n",
322
+ " y_pred = softmax(z)\n",
323
+ " # Compute the gradient of Categorical Cross-Entropy with Softmax\n",
324
+ " # ∂J/∂θ = (1/m) * X^T * (y_pred - y_onehot)\n",
325
+ " gradient = np.dot(X.T, (y_pred - y_onehot)) / m\n",
326
+ " # Update weights\n",
327
+ " theta -= lr * gradient\n",
328
+ " # Track loss\n",
329
+ " loss = categorical_cross_entropy(y_onehot, y_pred)\n",
330
+ " losses.append(loss)\n",
331
+ " return theta, losses"
332
+ ],
333
+ "execution_count": null,
334
+ "outputs": []
335
+ },
336
+ {
337
+ "cell_type": "code",
338
+ "metadata": {},
339
+ "source": [
340
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
341
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
342
+ " # Get the train & test split for this fold\n",
343
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
344
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
345
+ " # Train using gradient descent with learning rate = 0.5\n",
346
+ " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=2)\n",
347
+ " # Calculate z & class probabilities for X_test\n",
348
+ " z = np.dot(X_test, theta)\n",
349
+ " y_pred_proba = softmax(z)\n",
350
+ " # Pick the predicted classes with the highest probability\n",
351
+ " y_pred = np.argmax(y_pred_proba, axis=1)\n",
352
+ " accuracy = accuracy_score(y_test, y_pred)\n",
353
+ " f1 = f1_score(y_test, y_pred, average='macro') # for multiclass f1 score, y\n",
354
+ " # Store results\n",
355
+ " re['loss'].append(losses)\n",
356
+ " re['acc'].append(accuracy)\n",
357
+ " re['f1'].append(f1)"
358
+ ],
359
+ "execution_count": null,
360
+ "outputs": []
361
+ },
362
+ {
363
+ "cell_type": "code",
364
+ "metadata": {},
365
+ "source": [
366
+ "re = {}\n",
367
+ "for model_name in models:\n",
368
+ " re[model_name] = {'accuracy': [], 'f1':[]}"
369
+ ],
370
+ "execution_count": null,
371
+ "outputs": []
372
+ },
373
+ {
374
+ "cell_type": "code",
375
+ "metadata": {},
376
+ "source": [
377
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X, y)):\n",
378
+ "\n",
379
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
380
+ " # Get the train & test split for this fold\n",
381
+ "\n",
382
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
383
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
384
+ "\n",
385
+ " theta, losses = gradient_descent(X_train, y_train, lr=0.5, num_classes=4)\n",
386
+ " # Calculate z & class probabilities for X_test\n",
387
+ " z = np.dot(X_test, theta)\n",
388
+ " y_pred_proba = softmax(z)\n",
389
+ " # Pick the predicted classes with the highest probability\n",
390
+ " y_pred = np.argmax(y_pred_proba, axis=1)\n",
391
+ "\n",
392
+ " # Train & Validate Models\n",
393
+ " for model_name, model in models.items():\n",
394
+ " print(f\"Training {model_name}...\")\n",
395
+ " # Fit the model on train data\n",
396
+ " model.fit(X_train, y_train)\n",
397
+ " # Use the model to predict the test data\n",
398
+ " y_pred = model.predict(X_test)\n",
399
+ " # Calculate evaluation metrics\n",
400
+ " accuracy = accuracy_score(y_test, y_pred)\n",
401
+ " #f1 = f1_score(y_test, y_pred, average='micro') # for multiclass f1 score,\n",
402
+ " results[model_name]['accuracy'].append(accuracy)\n",
403
+ " #results[model_name]['f1'].append(f1)"
404
+ ],
405
+ "execution_count": null,
406
+ "outputs": []
407
+ },
408
+ {
409
+ "cell_type": "code",
410
+ "metadata": {},
411
+ "source": [
412
+ "# Task 2,3,4,5: Write your code here:\n",
413
+ "\n",
414
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
415
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
416
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
417
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
418
+ "\n",
419
+ "for model_name, model in models.items():\n",
420
+ " print(f\"Training {model_name}...\")\n",
421
+ " # Train\n",
422
+ " model.fit(X_train, y_train)\n",
423
+ " # Predict\n",
424
+ " y_pred = model.predict(X_test)\n",
425
+ "\n",
426
+ "\n",
427
+ " # Calculate metrics\n",
428
+ " accuracy = accuracy_score(y_test, y_pred)\n",
429
+ " f1 = f1_score(y_test, y_pred, average='macro')\n",
430
+ "\n",
431
+ " results['acc'].append(accuracy)\n",
432
+ " results['f1'].append(f1)"
433
+ ],
434
+ "execution_count": null,
435
+ "outputs": []
436
+ },
437
+ {
438
+ "cell_type": "code",
439
+ "metadata": {},
440
+ "source": [
441
+ "# Task 1: Write your code here:"
442
+ ],
443
+ "execution_count": null,
444
+ "outputs": []
445
+ },
446
+ {
447
+ "cell_type": "code",
448
+ "metadata": {},
449
+ "source": [
450
+ "# Task 2: Write your code here:"
451
+ ],
452
+ "execution_count": null,
453
+ "outputs": []
454
+ },
455
+ {
456
+ "cell_type": "code",
457
+ "metadata": {},
458
+ "source": [
459
+ "# Task Bonus: Write your code here:"
460
+ ],
461
+ "execution_count": null,
462
+ "outputs": []
463
+ }
464
+ ],
465
+ "metadata": {
466
+ "kernelspec": {
467
+ "display_name": "Python 3",
468
+ "name": "python3"
469
+ },
470
+ "language_info": {
471
+ "name": "python"
472
+ }
473
+ },
474
+ "nbformat": 4,
475
+ "nbformat_minor": 0
476
+ }
submissions_extracted/226/Q1.ipynb ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import numpy as np\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import seaborn as sns\n",
12
+ "import kagglehub\n",
13
+ "import os\n",
14
+ "from tqdm import tqdm\n",
15
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
16
+ "\n",
17
+ "%matplotlib inline\n",
18
+ "\n",
19
+ "# Download latest version\n",
20
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
21
+ "\n",
22
+ "print(\"Path to dataset files:\", path)"
23
+ ],
24
+ "execution_count": null,
25
+ "outputs": []
26
+ },
27
+ {
28
+ "cell_type": "code",
29
+ "metadata": {},
30
+ "source": [
31
+ "# Task 1: Write your code here:\n",
32
+ "csv_path = os.path.join(path, \"Q1_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 5: Write your code here:\n",
74
+ "def check_target_distribution(df, target_column):\n",
75
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
76
+ "\n",
77
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
78
+ " plt.xlabel(target_column)\n",
79
+ " plt.ylabel(\"Time\")\n",
80
+ " plt.grid(False)\n",
81
+ "\n",
82
+ " plt.show()\n",
83
+ "\n",
84
+ "check_target_distribution(df, \"Delivery_Time\")"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Task 1: Write your code here:\n",
94
+ "data_col = [\"Order_ID\",\t\"Distance_km\",\t\"Preparation_Time_min\",\t\"Courier_Experience_yrs\",\t\"Delivery_Time\"]\n",
95
+ "df_clean = df.drop(\"Order_ID\", axis=1).copy()\n",
96
+ "print(f\"Shape after cleaning: {df_clean.shape}\")\n",
97
+ "df_clean"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 2: Write your code here:\n",
107
+ "def check_missing_values(df):\n",
108
+ " missing_values = df.isnull().sum()\n",
109
+ " print(\"Missing Values per Column:\")\n",
110
+ " print(missing_values[missing_values > 0])\n",
111
+ " if missing_values.any():\n",
112
+ " print(\"\\nHandle Missing Values as needed.\")\n",
113
+ " else:\n",
114
+ " print(\"\\nNo Missing Values Found.\")\n",
115
+ "\n",
116
+ "check_missing_values(df)"
117
+ ],
118
+ "execution_count": null,
119
+ "outputs": []
120
+ },
121
+ {
122
+ "cell_type": "code",
123
+ "metadata": {},
124
+ "source": [
125
+ "# Task 3: Write your code here:\n",
126
+ "def check_duplicates(df):\n",
127
+ " duplicates = df.duplicated().sum()\n",
128
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
129
+ " if duplicates > 0:\n",
130
+ " print(\"Dropping Duplicates...\")\n",
131
+ " df.drop_duplicates(inplace=True)\n",
132
+ " print(\"Duplicates Dropped.\")\n",
133
+ " else:\n",
134
+ " print(\"No Duplicate Samples Found.\")\n",
135
+ "\n",
136
+ "check_duplicates(df)"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 4: Write your code here:\n",
146
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
147
+ "for col in categorical_cols:\n",
148
+ " print(f\"Encoding column: {col}\")\n",
149
+ " le = LabelEncoder()\n",
150
+ " df[col] = le.fit_transform(df[col])\n",
151
+ "df"
152
+ ],
153
+ "execution_count": null,
154
+ "outputs": []
155
+ },
156
+ {
157
+ "cell_type": "code",
158
+ "metadata": {},
159
+ "source": [
160
+ "# Task 5: Write your code here: Apply feature scaling for all features (Use StandardScaler)\n",
161
+ "from sklearn.preprocessing import StandardScaler #import StandardScaler\n",
162
+ "print(\"Before scaling:\")\n",
163
+ "df\n",
164
+ "print('data before scaling:\\n', df) #show before scaling\n",
165
+ "standard_scaler = StandardScaler() # Instantiate StandardScaler\n",
166
+ "data_standard_scaled = standard_scaler.fit_transform(df) # Apply fit_transform\n",
167
+ "\n",
168
+ "print('\\nData after scaling:\\n', data_standard_scaled) #show after scaling"
169
+ ],
170
+ "execution_count": null,
171
+ "outputs": []
172
+ },
173
+ {
174
+ "cell_type": "code",
175
+ "metadata": {},
176
+ "source": [
177
+ "# Task 6: Write your code here: Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
178
+ "def check_target_imbalance(df, target_column):\n",
179
+ " print(\"Target Distribution:\")\n",
180
+ " print(df[target_column].value_counts(normalize=True))\n",
181
+ " sns.countplot(x=df[target_column])\n",
182
+ " plt.title(\"Target Distribution\")\n",
183
+ " plt.show()\n",
184
+ "\n",
185
+ "check_target_imbalance(df, \"Delivery_Time\")"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "from sklearn.ensemble import RandomForestRegressor\n",
195
+ "from sklearn.model_selection import KFold"
196
+ ],
197
+ "execution_count": null,
198
+ "outputs": []
199
+ },
200
+ {
201
+ "cell_type": "code",
202
+ "metadata": {},
203
+ "source": [
204
+ "# Task 1: Write your code here:\n",
205
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
206
+ "y = df['Delivery_Time'].astype(float)"
207
+ ],
208
+ "execution_count": null,
209
+ "outputs": []
210
+ },
211
+ {
212
+ "cell_type": "code",
213
+ "metadata": {},
214
+ "source": [
215
+ "# Task 2,3,4,5: Write your code here:\n",
216
+ "from sklearn.metrics import f1_score\n",
217
+ "models = {\"Random Forest Classifier\": RandomForestClassifier(n_estimators=100)}\n",
218
+ "\n",
219
+ "for model in models.values():\n",
220
+ " scores_accuracy = []\n",
221
+ " scores_precision = []\n",
222
+ " scores_recall = []\n",
223
+ " scores_f1 = []\n",
224
+ "\n",
225
+ " # Stratified 5-Fold Cross-Validation\n",
226
+ " skf = KFold(n_splits=5)\n",
227
+ " for train_index, test_index in skf.split(X, y):\n",
228
+ " # Split data into training and testing sets\n",
229
+ " X_Train, X_Test = X.loc[train_index, :], X.loc[test_index, :]\n",
230
+ " y_Train, y_Test = y.iloc[train_index], y.iloc[test_index]\n",
231
+ " # Train the model\n",
232
+ " model.fit(X_Train, y_Train)\n",
233
+ " # Predict on the test set\n",
234
+ " y_pred = model.predict(X_Test)\n",
235
+ "\n",
236
+ " # Calculate metrics\n",
237
+ " scores_f1.append(f1_score(y_Test, y_pred, average='weighted'))\n",
238
+ "\n",
239
+ " # Print the results\n",
240
+ " print(f\"F1-Score: {np.mean(scores_f1):.4f}\")\n",
241
+ " print(\"\\n\")\n"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "import numpy as np\n",
251
+ "import pandas as pd\n",
252
+ "import matplotlib.pyplot as plt\n",
253
+ "import os\n",
254
+ "import kagglehub\n",
255
+ "\n",
256
+ "from sklearn.model_selection import train_test_split, StratifiedKFold, cross_val_score\n",
257
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
258
+ "from sklearn.ensemble import RandomForestClassifier\n",
259
+ "from sklearn.metrics import classification_report, confusion_matrix, accuracy_score\n"
260
+ ],
261
+ "execution_count": null,
262
+ "outputs": []
263
+ },
264
+ {
265
+ "cell_type": "code",
266
+ "metadata": {},
267
+ "source": [
268
+ "# Task 1: Write your code here:\n",
269
+ "importance = pd.DataFrame({\n",
270
+ " 'feature': df.columns,\n",
271
+ " 'importance': model.feature_importances_\n",
272
+ "}).sort_values('importance', ascending=False)\n",
273
+ "\n",
274
+ "plt.figure(figsize=(10, 6))\n",
275
+ "plt.barh(importance['feature'], importance['importance'], color='purple')\n",
276
+ "plt.xlabel('Importance')\n",
277
+ "plt.title('Feature Importance')\n",
278
+ "plt.gca().invert_yaxis()\n",
279
+ "plt.show()"
280
+ ],
281
+ "execution_count": null,
282
+ "outputs": []
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "metadata": {},
287
+ "source": [
288
+ "# Task 2: Write your code here:"
289
+ ],
290
+ "execution_count": null,
291
+ "outputs": []
292
+ },
293
+ {
294
+ "cell_type": "code",
295
+ "metadata": {},
296
+ "source": [
297
+ "# Task Bonus: Write your code here:"
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/226/Q2.ipynb ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "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
+ "from sklearn.model_selection import train_test_split\n",
71
+ "from sklearn.preprocessing import StandardScaler\n",
72
+ "from torch.utils.data import TensorDataset\n",
73
+ "from torch.utils.data import DataLoader\n",
74
+ "import torch\n",
75
+ "\n",
76
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
77
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
78
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
79
+ "y_test = torch.tensor(y_test, dtype=torch.float32)\n",
80
+ "\n"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# 2. Create TensorDataset objects: Create Datasets: Use TensorDataset to create train_dataset and test_dataset from the tensors.\n",
90
+ "\n",
91
+ "train_dataset = TensorDataset(X_train, y_train)\n",
92
+ "test_dataset = TensorDataset(X_test, y_test)"
93
+ ],
94
+ "execution_count": null,
95
+ "outputs": []
96
+ },
97
+ {
98
+ "cell_type": "code",
99
+ "metadata": {},
100
+ "source": [
101
+ "# 3. Create DataLoaders: Create DataLoaders: Create train_loader and test_loader with a batch size of 32.\n",
102
+ "\n",
103
+ "# DataLoader for training data\n",
104
+ "train_loader = DataLoader(\n",
105
+ " train_dataset,\n",
106
+ " batch_size=32,\n",
107
+ " shuffle=True,\n",
108
+ " num_workers=2\n",
109
+ ")\n",
110
+ "# DataLoader for test/validation data\n",
111
+ "test_loader = DataLoader(\n",
112
+ " test_dataset,\n",
113
+ " batch_size=32,\n",
114
+ " shuffle=False,\n",
115
+ " num_workers=2\n",
116
+ ")\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
+ "X_batch, y_batch = next(iter(train_loader))\n",
129
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
130
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
131
+ ],
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
+ " plt.imshow(images[i].squeeze(), cmap='gray')\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()\n"
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
+ "import torch.nn as nn\n",
164
+ "class NN3Layer(nn.Module):\n",
165
+ "\n",
166
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
167
+ " super(NN3Layer, 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
+ " # Fourth linear layer: hidden layer -> hidden layer\n",
179
+ " self.layer4 = nn.Linear(hidden_dim, hidden_dim)\n",
180
+ "\n",
181
+ " # Output layer: hidden layer -> number of classes (logits)\n",
182
+ " self.layer5 = nn.Linear(hidden_dim, output_dim)\n",
183
+ "\n",
184
+ " # ReLU activation for non-linearity\n",
185
+ " self.relu = nn.ReLU()\n",
186
+ "\n",
187
+ " # Defines how input data flows through the network\n",
188
+ " def forward(self, x):\n",
189
+ " # First hidden layer\n",
190
+ " z1 = self.layer1(x)\n",
191
+ " a1 = self.relu(z1)\n",
192
+ "\n",
193
+ " # Second hidden layer\n",
194
+ " z2 = self.layer2(a1)\n",
195
+ " a2 = self.relu(z2)\n",
196
+ "\n",
197
+ " # Output layer (raw scores / logits)\n",
198
+ " output = self.layer3(a2) # there is something missing here, remember? :)\n",
199
+ "\n",
200
+ " return output\n"
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
+ "def validate(model, criterion, test_loader, device):\n",
246
+ " # Set the model to evaluation mode\n",
247
+ " model.eval()\n",
248
+ "\n",
249
+ " running_loss = 0.0\n",
250
+ " correct = 0\n",
251
+ " total = 0\n",
252
+ "\n",
253
+ " with torch.no_grad():\n",
254
+ " for X_batch, y_batch in test_loader:\n",
255
+ " # Move data to device\n",
256
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
257
+ " y_batch = y_batch.to(device)\n",
258
+ "\n",
259
+ " # Forward pass\n",
260
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
261
+ " loss = criterion(outputs, y_batch)\n",
262
+ " running_loss += loss.item()\n",
263
+ "\n",
264
+ " # Apply Softmax to get probabilities\n",
265
+ " probabilities = F.softmax(outputs, dim=1)\n",
266
+ "\n",
267
+ " # Multiclass predictions\n",
268
+ " predicted = torch.argmax(probabilities, dim=1)\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
+ "# Device setup\n",
288
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
289
+ "\n",
290
+ "# Model parameters\n",
291
+ "input_dim = 28 * 28 # MNIST images flattened\n",
292
+ "hidden_dim = 14 # Design choice\n",
293
+ "output_dim = 10 # Digits 0–9\n",
294
+ "\n",
295
+ "# Instantiate model\n",
296
+ "model = NN3Layer(input_dim, hidden_dim, output_dim).to(device)\n",
297
+ "\n",
298
+ "# Print the model architecture\n",
299
+ "print(\"Model Architecture:\\n\")\n",
300
+ "print(model)\n",
301
+ "\n",
302
+ "# Calculate the total number of trainable parameters\n",
303
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
304
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
305
+ ],
306
+ "execution_count": null,
307
+ "outputs": []
308
+ },
309
+ {
310
+ "cell_type": "code",
311
+ "metadata": {},
312
+ "source": [
313
+ "# Task 5: Start training for 20 epochs:\n",
314
+ "from torch.optim import Adam\n",
315
+ "num_epochs = 20\n",
316
+ "learning_rate = 0.001\n",
317
+ "\n",
318
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
319
+ "criterion = nn.CrossEntropyLoss()\n",
320
+ "# Define optimizer\n",
321
+ "optimizer = Adam(model.parameters(), learning_rate)\n",
322
+ "\n"
323
+ ],
324
+ "execution_count": null,
325
+ "outputs": []
326
+ },
327
+ {
328
+ "cell_type": "code",
329
+ "metadata": {},
330
+ "source": [
331
+ "# Task 1: Write your code here:\n",
332
+ "train_losses = []\n",
333
+ "val_losses = []\n",
334
+ "val_accuracies = []\n",
335
+ "\n",
336
+ "print('Starting Training...')\n",
337
+ "for epoch in range(num_epochs):\n",
338
+ " # Train one epoch\n",
339
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
340
+ "\n",
341
+ " # Validate\n",
342
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
343
+ "\n",
344
+ " train_losses.append(train_loss)\n",
345
+ " val_losses.append(val_loss)\n",
346
+ " val_accuracies.append(val_accuracy)\n",
347
+ "\n",
348
+ "plt.figure(figsize=(7, 5))\n",
349
+ "\n",
350
+ "plt.plot(train_losses, label='Train Loss')\n",
351
+ "plt.plot(val_losses, label='Validation Loss')\n",
352
+ "plt.title('Loss over Epochs')\n",
353
+ "plt.xlabel('Epoch')\n",
354
+ "plt.ylabel('Loss')\n",
355
+ "plt.legend()\n",
356
+ "\n",
357
+ "plt.tight_layout()\n",
358
+ "plt.show()"
359
+ ],
360
+ "execution_count": null,
361
+ "outputs": []
362
+ },
363
+ {
364
+ "cell_type": "code",
365
+ "metadata": {},
366
+ "source": [
367
+ "# Task 2 (Bonus): Write your code here:"
368
+ ],
369
+ "execution_count": null,
370
+ "outputs": []
371
+ }
372
+ ],
373
+ "metadata": {
374
+ "kernelspec": {
375
+ "display_name": "Python 3",
376
+ "name": "python3"
377
+ },
378
+ "language_info": {
379
+ "name": "python"
380
+ }
381
+ },
382
+ "nbformat": 4,
383
+ "nbformat_minor": 0
384
+ }
submissions_extracted/226/Q3.ipynb ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "import pandas as pd\n",
9
+ "import numpy as np\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import seaborn as sns\n",
12
+ "import kagglehub\n",
13
+ "import os\n",
14
+ "from tqdm import tqdm\n",
15
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
16
+ "from catboost import CatBoostClassifier\n",
17
+ "from sklearn.model_selection import KFold\n",
18
+ "from sklearn.metrics import mean_squared_error, mean_absolute_error\n",
19
+ "\n",
20
+ "# Download latest version\n",
21
+ "\n",
22
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
23
+ "\n",
24
+ "\n",
25
+ "\n",
26
+ "print(\"Path to dataset files:\", path)"
27
+ ],
28
+ "execution_count": null,
29
+ "outputs": []
30
+ },
31
+ {
32
+ "cell_type": "code",
33
+ "metadata": {},
34
+ "source": [
35
+ "# Task 1: Write your code here: Read the dataset Q3_data.csv using read_csv()\n",
36
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
37
+ "\n",
38
+ "df = pd.read_csv(csv_path)"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 2: Write your code here:\n",
48
+ "df.head()"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "# Task 3: Write your code here:\n",
58
+ "df.info()"
59
+ ],
60
+ "execution_count": null,
61
+ "outputs": []
62
+ },
63
+ {
64
+ "cell_type": "code",
65
+ "metadata": {},
66
+ "source": [
67
+ "# Task 4: Write your code here:\n",
68
+ "df.describe()"
69
+ ],
70
+ "execution_count": null,
71
+ "outputs": []
72
+ },
73
+ {
74
+ "cell_type": "code",
75
+ "metadata": {},
76
+ "source": [
77
+ "# Task 1: Write your code here: Handle missing values appropriately\n",
78
+ "def check_missing_values(df):\n",
79
+ " missing_values = df.isnull().sum()\n",
80
+ " print(\"Missing Values per Column:\")\n",
81
+ " print(missing_values[missing_values > 0])\n",
82
+ " if missing_values.any():\n",
83
+ " print(\"\\nHandle Missing Values as needed.\")\n",
84
+ " else:\n",
85
+ " print(\"\\nNo Missing Values Found.\")\n",
86
+ "\n",
87
+ "check_missing_values(df)"
88
+ ],
89
+ "execution_count": null,
90
+ "outputs": []
91
+ },
92
+ {
93
+ "cell_type": "code",
94
+ "metadata": {},
95
+ "source": [
96
+ "# Task 2: Write your code here: Check and remove duplicates if any exist\n",
97
+ "def check_duplicates(df):\n",
98
+ " duplicates = df.duplicated().sum()\n",
99
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
100
+ " if duplicates > 0:\n",
101
+ " print(\"Dropping Duplicates...\")\n",
102
+ " df.drop_duplicates(inplace=True)\n",
103
+ " print(\"Duplicates Dropped.\")\n",
104
+ " else:\n",
105
+ " print(\"No Duplicate Samples Found.\")\n",
106
+ "\n",
107
+ "check_duplicates(df)"
108
+ ],
109
+ "execution_count": null,
110
+ "outputs": []
111
+ },
112
+ {
113
+ "cell_type": "code",
114
+ "metadata": {},
115
+ "source": [
116
+ "# Task 3: Write your code here: Encode categorical variables if needed\n",
117
+ "\n",
118
+ "label_encoder = LabelEncoder()\n",
119
+ "\n",
120
+ "for col in df.select_dtypes(include=[\"object\"]).columns:\n",
121
+ " df[col] = label_encoder.fit_transform(df[col])\n"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 4: Write your code here: Apply feature scaling to numerical features (Use StandardScaler)\n",
131
+ "scaler = StandardScaler()\n",
132
+ "X_scaled = scaler.fit_transform(df)"
133
+ ],
134
+ "execution_count": null,
135
+ "outputs": []
136
+ },
137
+ {
138
+ "cell_type": "code",
139
+ "metadata": {},
140
+ "source": [
141
+ "# Task 5: Write your code here: Check for target imbalance and state if it is imbalanced or not\n",
142
+ "def check_target_imbalance(df, target_column):\n",
143
+ " print(\"Target Distribution:\")\n",
144
+ " print(df[target_column].value_counts(normalize=True))\n",
145
+ " sns.countplot(x=df[target_column])\n",
146
+ " plt.title(\"Target Distribution\")\n",
147
+ " plt.show()\n",
148
+ "\n",
149
+ "check_target_imbalance(df, \"Target\")"
150
+ ],
151
+ "execution_count": null,
152
+ "outputs": []
153
+ },
154
+ {
155
+ "cell_type": "code",
156
+ "metadata": {},
157
+ "source": [
158
+ "!pip install catboost"
159
+ ],
160
+ "execution_count": null,
161
+ "outputs": []
162
+ },
163
+ {
164
+ "cell_type": "code",
165
+ "metadata": {},
166
+ "source": [
167
+ "# Task 1: Write your code here:\n",
168
+ "\n",
169
+ "X = df.drop(\"Target\", axis=1)\n",
170
+ "y = df[\"Target\"]\n",
171
+ "\n"
172
+ ],
173
+ "execution_count": null,
174
+ "outputs": []
175
+ },
176
+ {
177
+ "cell_type": "code",
178
+ "metadata": {},
179
+ "source": [
180
+ "# Task 2,3,4,5: Write your code here:\n",
181
+ "\n",
182
+ "model = CatBoostClassifier(verbose=0)\n",
183
+ "\n",
184
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
185
+ "\n",
186
+ "mse_scores = []\n",
187
+ "mae_scores = []\n",
188
+ "\n",
189
+ "for train_idx, test_idx in kf.split(X_scaled):\n",
190
+ " X_train, X_test = X_scaled[train_idx], X_scaled[test_idx]\n",
191
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
192
+ "\n",
193
+ " # Train model\n",
194
+ " model.fit(X_train, y_train)\n",
195
+ "\n",
196
+ " # Predict\n",
197
+ " y_pred = model.predict(X_test)\n",
198
+ "\n",
199
+ " # Evaluation metrics\n",
200
+ " mse_scores.append(mean_squared_error(y_test, y_pred))\n",
201
+ " mae_scores.append(mean_absolute_error(y_test, y_pred))\n",
202
+ "\n"
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
+ "feature_importance = pd.DataFrame({\n",
213
+ " 'feature': df.columns,\n",
214
+ " 'importance': model.feature_importances_\n",
215
+ "}).sort_values('importance', ascending=False)\n",
216
+ "\n",
217
+ "plt.figure(figsize=(10, 30))\n",
218
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
219
+ "plt.xlabel('Importance')\n",
220
+ "plt.title('Feature Importance')\n",
221
+ "plt.gca().invert_yaxis()\n",
222
+ "plt.show()"
223
+ ],
224
+ "execution_count": null,
225
+ "outputs": []
226
+ },
227
+ {
228
+ "cell_type": "code",
229
+ "metadata": {},
230
+ "source": [
231
+ "# Task 2: Write your code here:"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task Bonus: Write your code here:"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ }
245
+ ],
246
+ "metadata": {
247
+ "kernelspec": {
248
+ "display_name": "Python 3",
249
+ "name": "python3"
250
+ },
251
+ "language_info": {
252
+ "name": "python"
253
+ }
254
+ },
255
+ "nbformat": 4,
256
+ "nbformat_minor": 0
257
+ }
submissions_extracted/227/Q1.ipynb ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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"
12
+ ],
13
+ "execution_count": null,
14
+ "outputs": []
15
+ },
16
+ {
17
+ "cell_type": "code",
18
+ "metadata": {},
19
+ "source": [
20
+ "import kagglehub\n",
21
+ "\n",
22
+ "# Download latest version\n",
23
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
24
+ "\n",
25
+ "print(\"Path to dataset files:\", path)"
26
+ ],
27
+ "execution_count": null,
28
+ "outputs": []
29
+ },
30
+ {
31
+ "cell_type": "code",
32
+ "metadata": {},
33
+ "source": [
34
+ "# Task 1: Write your code here:\n",
35
+ "\n",
36
+ "# Load the CSV file\n",
37
+ "Q1_data_path = os.path.join(path, 'Q1_data.csv')\n",
38
+ "\n",
39
+ "df_Q1_data = pd.read_csv(Q1_data_path)\n",
40
+ "\n",
41
+ "print(f\"Shape: {df_Q1_data.shape}\")\n"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 2: Write your code here:\n",
51
+ "#Inspect the first few rows using head()\n",
52
+ "df_Q1_data.head()"
53
+ ],
54
+ "execution_count": null,
55
+ "outputs": []
56
+ },
57
+ {
58
+ "cell_type": "code",
59
+ "metadata": {},
60
+ "source": [
61
+ "# Task 3: Write your code here:\n",
62
+ "#Display dataset information using info()\n",
63
+ "df_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
+ "#Show statistical description using describe()\n",
74
+ "df_Q1_data.describe()"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# Task 5: Write your code here:\n",
84
+ "#Plot the target distribution (delivery_time)\n",
85
+ "\n",
86
+ "def check_target_distribution(df, target_column):\n",
87
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
88
+ "\n",
89
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
90
+ " plt.xlabel(target_column)\n",
91
+ " plt.ylabel(\"Frequency\")\n",
92
+ " plt.grid(False)\n",
93
+ "\n",
94
+ " plt.show()\n",
95
+ "\n",
96
+ "check_target_distribution(df_Q1_data, \"Delivery_Time\")"
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
+ "\n",
107
+ "#Drop the 'Order_ID' column from the data\n",
108
+ "df = df_Q1_data.drop(['Order_ID'], axis=1)\n",
109
+ "df.head()"
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
+ "\n",
120
+ "#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :)\n",
121
+ "\n",
122
+ "def check_missing_values(df):\n",
123
+ "\n",
124
+ " # Get missing values using pandas\n",
125
+ " missing_values = df.isnull().sum()\n",
126
+ "\n",
127
+ " print(\"Missing Values per Column:\")\n",
128
+ " print(missing_values[missing_values > 0])\n",
129
+ "\n",
130
+ " if missing_values.any():\n",
131
+ " print(\"\\nHandle Missing Values as needed.\")\n",
132
+ " else:\n",
133
+ " print(\"\\nNo Missing Values Found.\")\n",
134
+ "\n",
135
+ "check_missing_values(df)"
136
+ ],
137
+ "execution_count": null,
138
+ "outputs": []
139
+ },
140
+ {
141
+ "cell_type": "code",
142
+ "metadata": {},
143
+ "source": [
144
+ "# Fill cylinders with mode - discrete feature, mode is most representative\n",
145
+ "df['Weather'] = df['Weather'].fillna(df['Weather'].mode()[0])\n",
146
+ "\n",
147
+ "df['Traffic_Level'] = df['Traffic_Level'].fillna(df['Traffic_Level'].mode()[0])\n",
148
+ "\n",
149
+ "df['Time_of_Day'] = df['Time_of_Day'].fillna(df['Time_of_Day'].mode()[0])\n",
150
+ "\n",
151
+ "df['Courier_Experience_yrs'] = df['Courier_Experience_yrs'].fillna(df['Courier_Experience_yrs'].mode()[0])\n",
152
+ "\n",
153
+ "df['Delivery_Time'] = df['Delivery_Time'].fillna(df['Delivery_Time'].mode()[0])"
154
+ ],
155
+ "execution_count": null,
156
+ "outputs": []
157
+ },
158
+ {
159
+ "cell_type": "code",
160
+ "metadata": {},
161
+ "source": [
162
+ "# Task 2: Write your code here:\n",
163
+ "\n",
164
+ "#Handle missing values appropriately (Hint: I guess you want to have a closer look at the columns with missing values :)\n",
165
+ "\n",
166
+ "def check_missing_values(df):\n",
167
+ "\n",
168
+ " # Get missing values using pandas\n",
169
+ " missing_values = df.isnull().sum()\n",
170
+ "\n",
171
+ " print(\"Missing Values per Column:\")\n",
172
+ " print(missing_values[missing_values > 0])\n",
173
+ "\n",
174
+ " if missing_values.any():\n",
175
+ " print(\"\\nHandle Missing Values as needed.\")\n",
176
+ " else:\n",
177
+ " print(\"\\nNo Missing Values Found.\")\n",
178
+ "\n",
179
+ "check_missing_values(df)"
180
+ ],
181
+ "execution_count": null,
182
+ "outputs": []
183
+ },
184
+ {
185
+ "cell_type": "code",
186
+ "metadata": {},
187
+ "source": [
188
+ "# Task 3: Write your code here:\n",
189
+ "\n",
190
+ "#Check and remove duplicates if any exist\n",
191
+ "\n",
192
+ "def check_duplicates(df):\n",
193
+ " duplicates = df.duplicated().sum()\n",
194
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
195
+ " if duplicates > 0:\n",
196
+ " print(\"Dropping Duplicates...\")\n",
197
+ " df.drop_duplicates(inplace=True)\n",
198
+ " print(\"Duplicates Dropped.\")\n",
199
+ " else:\n",
200
+ " print(\"No Duplicate Samples Found.\")\n",
201
+ "\n",
202
+ "check_duplicates(df)"
203
+ ],
204
+ "execution_count": null,
205
+ "outputs": []
206
+ },
207
+ {
208
+ "cell_type": "code",
209
+ "metadata": {},
210
+ "source": [
211
+ "# Task 4: Write your code here:\n",
212
+ "#Encode categorical variables if needed (Bonus if used One Hot Encoding)"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# 3. Do we have categorical columns?\n",
222
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
223
+ "\n",
224
+ "print(\"Categorical Columns:\", list(categorical_cols))"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Encode categorical columns - converts text to integers\n",
234
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
235
+ "\n",
236
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
237
+ "for col in categorical_cols:\n",
238
+ " le = LabelEncoder()\n",
239
+ " df[col] = le.fit_transform(df[col].astype(str))\n",
240
+ "\n",
241
+ "df.head()"
242
+ ],
243
+ "execution_count": null,
244
+ "outputs": []
245
+ },
246
+ {
247
+ "cell_type": "code",
248
+ "metadata": {},
249
+ "source": [
250
+ "# 3. Do we have categorical columns?\n",
251
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
252
+ "\n",
253
+ "print(\"Categorical Columns:\", list(categorical_cols))"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 5: Write your code here:\n",
263
+ "#Apply feature scaling for all features (Use StandardScaler)\n",
264
+ "\n",
265
+ "\n",
266
+ "from sklearn.preprocessing import StandardScaler\n",
267
+ "\n",
268
+ "features = df.columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
269
+ "\n",
270
+ "scaler = StandardScaler()\n",
271
+ "df[features] = scaler.fit_transform(df[features])\n",
272
+ "df.head()\n"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# Task 6: Write your code here:\n",
282
+ "#Check for target imbalance and state if it is imbalanced or not (keep this cell empty if not needed)\n",
283
+ "\n",
284
+ "# 1. Is the target imbalanced?\n",
285
+ "def check_target_imbalance(df, target_column):\n",
286
+ " print(\"Target Distribution:\")\n",
287
+ " print(df[target_column].value_counts(normalize=True))\n",
288
+ " sns.countplot(x=df[target_column])\n",
289
+ " plt.title(\"Target Distribution\")\n",
290
+ " plt.show()\n",
291
+ "\n",
292
+ "check_target_imbalance(df, \"Delivery_Time\")\n"
293
+ ],
294
+ "execution_count": null,
295
+ "outputs": []
296
+ },
297
+ {
298
+ "cell_type": "code",
299
+ "metadata": {},
300
+ "source": [
301
+ "# Task 1: Write your code here:\n",
302
+ "X = df.drop(\"Delivery_Time\", axis=1).astype(float)\n",
303
+ "y = df['Delivery_Time'].astype(float)"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "metadata": {},
311
+ "source": [
312
+ "# Task 2,3,4,5: Write your code here:\n",
313
+ "\n",
314
+ "from sklearn.model_selection import KFold\n",
315
+ "\n",
316
+ "X, y = X.copy(), y.copy()\n",
317
+ "\n",
318
+ "# Define K-Fold Cross Validation\n",
319
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
320
+ "\n",
321
+ "# Iterate through folds\n",
322
+ "for fold, (train_idx, test_idx) in enumerate(kf.split(X), start=1):\n",
323
+ " # indexing for each fold\n",
324
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx] #نستخدم .iloc لاستخراج البيانات\n",
325
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
326
+ " # print shapes\n",
327
+ " print(f\"Fold {fold}\")\n",
328
+ " print(\" X_train shape:\", X_train.shape)\n",
329
+ " print(\" X_test shape :\", X_test.shape)\n",
330
+ " print(\" y_train shape:\", y_train.shape)\n",
331
+ " print(\" y_test shape :\", y_test.shape)\n",
332
+ " print(\"-\" * 30)"
333
+ ],
334
+ "execution_count": null,
335
+ "outputs": []
336
+ },
337
+ {
338
+ "cell_type": "code",
339
+ "metadata": {},
340
+ "source": [
341
+ "\n",
342
+ "from sklearn.ensemble import RandomForestRegressor\n",
343
+ "\n",
344
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
345
+ "model.fit(X, y)\n",
346
+ "print(\"Model trained!\")"
347
+ ],
348
+ "execution_count": null,
349
+ "outputs": []
350
+ },
351
+ {
352
+ "cell_type": "code",
353
+ "metadata": {},
354
+ "source": [
355
+ "#Evaluate using MAE (Mean Absolute Error) ONLY\n",
356
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
357
+ "\n",
358
+ "# Predict and evaluate\n",
359
+ "y_pred = model.predict(X_test)\n",
360
+ "\n",
361
+ "mae = mean_absolute_error(y_test, y_pred)\n",
362
+ "\n",
363
+ "print(f\"MAE: ${mae:,.2f}\")\n",
364
+ "\n"
365
+ ],
366
+ "execution_count": null,
367
+ "outputs": []
368
+ },
369
+ {
370
+ "cell_type": "code",
371
+ "metadata": {},
372
+ "source": [
373
+ "#Print the averaged score across all folds\n"
374
+ ],
375
+ "execution_count": null,
376
+ "outputs": []
377
+ },
378
+ {
379
+ "cell_type": "code",
380
+ "metadata": {},
381
+ "source": [],
382
+ "execution_count": null,
383
+ "outputs": []
384
+ },
385
+ {
386
+ "cell_type": "code",
387
+ "metadata": {},
388
+ "source": [
389
+ "feature_cols = ['Distance_km', 'Weather', 'Traffic_Level', 'Time_of_Day',\n",
390
+ " 'Vehicle_Type', 'Preparation_Time_min', 'Courier_Experience_yrs']"
391
+ ],
392
+ "execution_count": null,
393
+ "outputs": []
394
+ },
395
+ {
396
+ "cell_type": "code",
397
+ "metadata": {},
398
+ "source": [
399
+ "# Task 1: Write your code here:\n",
400
+ "#Plot feature importance from your trained model\n",
401
+ "# Feature importance\n",
402
+ "feature_importance = pd.DataFrame({\n",
403
+ " 'feature': feature_cols,\n",
404
+ " 'importance': model.feature_importances_\n",
405
+ "}).sort_values('importance', ascending=False)\n",
406
+ "\n",
407
+ "plt.figure(figsize=(10, 6))\n",
408
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
409
+ "plt.xlabel('Importance')\n",
410
+ "plt.title('Feature Importance')\n",
411
+ "plt.gca().invert_yaxis()\n",
412
+ "plt.show()"
413
+ ],
414
+ "execution_count": null,
415
+ "outputs": []
416
+ },
417
+ {
418
+ "cell_type": "code",
419
+ "metadata": {},
420
+ "source": [
421
+ "# Task 2: Write your code here:\n",
422
+ "#Plot predicted delivery time histogram\n"
423
+ ],
424
+ "execution_count": null,
425
+ "outputs": []
426
+ },
427
+ {
428
+ "cell_type": "code",
429
+ "metadata": {},
430
+ "source": [
431
+ "# Task Bonus: Write your code here:"
432
+ ],
433
+ "execution_count": null,
434
+ "outputs": []
435
+ }
436
+ ],
437
+ "metadata": {
438
+ "kernelspec": {
439
+ "display_name": "Python 3",
440
+ "name": "python3"
441
+ },
442
+ "language_info": {
443
+ "name": "python"
444
+ }
445
+ },
446
+ "nbformat": 4,
447
+ "nbformat_minor": 0
448
+ }
submissions_extracted/227/Q2.ipynb ADDED
@@ -0,0 +1,374 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "import kagglehub\n",
69
+ "import pandas as pd\n",
70
+ "import torch\n",
71
+ "import torch.nn as nn\n",
72
+ "from torch.optim import AdamW\n",
73
+ "import matplotlib.pyplot as plt\n",
74
+ "import torch.nn.functional as F\n",
75
+ "from torch.utils.data import DataLoader, TensorDataset\n",
76
+ "from sklearn.model_selection import train_test_split\n",
77
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder"
78
+ ],
79
+ "execution_count": null,
80
+ "outputs": []
81
+ },
82
+ {
83
+ "cell_type": "code",
84
+ "metadata": {},
85
+ "source": [
86
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
87
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
88
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
89
+ "y_test = torch.tensor(y_test, dtype=torch.long)"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# 2. Create TensorDataset objects\n",
99
+ "\n",
100
+ "train_dataset = TensorDataset(X_train, y_train)\n",
101
+ "test_dataset = TensorDataset(X_test, y_test)\n"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# 3. Create DataLoaders\n",
111
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
112
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n"
113
+ ],
114
+ "execution_count": null,
115
+ "outputs": []
116
+ },
117
+ {
118
+ "cell_type": "code",
119
+ "metadata": {},
120
+ "source": [
121
+ "# 4. Print shape of one batch\n",
122
+ "\n",
123
+ "# Print dataset sizes\n",
124
+ "print(\"Train dataset:\", len(train_dataset))\n",
125
+ "print(\"Test dataset:\", len(test_dataset))\n",
126
+ "\n",
127
+ "# Get the first batch from the training DataLoader\n",
128
+ "X_batch, y_batch = next(iter(train_loader))\n",
129
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
130
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# 5. Display sample images\n",
140
+ "\n",
141
+ "\n",
142
+ "\n"
143
+ ],
144
+ "execution_count": null,
145
+ "outputs": []
146
+ },
147
+ {
148
+ "cell_type": "code",
149
+ "metadata": {},
150
+ "source": [
151
+ "# Task 1: Write your model class here:\n",
152
+ "class NN4Layer(nn.Module):\n",
153
+ "\n",
154
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
155
+ " super(NN4Layer, self).__init__()\n",
156
+ "\n",
157
+ " # First linear layer: input features -> hidden layer\n",
158
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
159
+ "\n",
160
+ " # Second linear layer: hidden layer -> hidden layer\n",
161
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
162
+ "\n",
163
+ " # Third 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\n"
187
+ ],
188
+ "execution_count": null,
189
+ "outputs": []
190
+ },
191
+ {
192
+ "cell_type": "code",
193
+ "metadata": {},
194
+ "source": [
195
+ "# Task 2: Write your training loop here:\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\n"
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
+ "\n",
284
+ "# Print the model architecture\n",
285
+ "print(\"Model Architecture:\\n\")\n",
286
+ "print(model)\n",
287
+ "\n",
288
+ "# Calculate the total number of trainable parameters\n",
289
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
290
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
291
+ "\n",
292
+ "num_epochs = 20\n",
293
+ "learning_rate = 0.001\n",
294
+ "\n",
295
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
296
+ "criterion = nn.CrossEntropyLoss()\n",
297
+ "# Define optimizer\n",
298
+ "optimizer = AdamW(model.parameters(), learning_rate)"
299
+ ],
300
+ "execution_count": null,
301
+ "outputs": []
302
+ },
303
+ {
304
+ "cell_type": "code",
305
+ "metadata": {},
306
+ "source": [
307
+ "# Task 5: Start training for 20 epochs:\n",
308
+ "# Run Training\n",
309
+ "train_losses = []\n",
310
+ "val_losses = []\n",
311
+ "val_accuracies = []\n",
312
+ "\n",
313
+ "print('Starting Training...')\n",
314
+ "for epoch in range(num_epochs):\n",
315
+ " # Train one epoch\n",
316
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
317
+ "\n",
318
+ " # Validate\n",
319
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
320
+ "\n",
321
+ " train_losses.append(train_loss)\n",
322
+ " val_losses.append(val_loss)\n",
323
+ " val_accuracies.append(val_accuracy)\n",
324
+ "\n",
325
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
326
+ "\n",
327
+ "print('Training Complete!')"
328
+ ],
329
+ "execution_count": null,
330
+ "outputs": []
331
+ },
332
+ {
333
+ "cell_type": "code",
334
+ "metadata": {},
335
+ "source": [
336
+ "# Task 1: Write your code here:\n",
337
+ "# Plotting results\n",
338
+ "plt.figure(figsize=(7, 5))\n",
339
+ "\n",
340
+ "plt.plot(train_losses, label='Train Loss')\n",
341
+ "plt.plot(val_losses, label='Validation Loss')\n",
342
+ "plt.title('Loss over Epochs')\n",
343
+ "plt.xlabel('Epoch')\n",
344
+ "plt.ylabel('Loss')\n",
345
+ "plt.legend()\n",
346
+ "\n",
347
+ "plt.tight_layout()\n",
348
+ "plt.show()"
349
+ ],
350
+ "execution_count": null,
351
+ "outputs": []
352
+ },
353
+ {
354
+ "cell_type": "code",
355
+ "metadata": {},
356
+ "source": [
357
+ "# Task 2 (Bonus): Write your code here:"
358
+ ],
359
+ "execution_count": null,
360
+ "outputs": []
361
+ }
362
+ ],
363
+ "metadata": {
364
+ "kernelspec": {
365
+ "display_name": "Python 3",
366
+ "name": "python3"
367
+ },
368
+ "language_info": {
369
+ "name": "python"
370
+ }
371
+ },
372
+ "nbformat": 4,
373
+ "nbformat_minor": 0
374
+ }
submissions_extracted/228/Q1.ipynb ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os\n",
24
+ "import pandas as pd\n",
25
+ "\n",
26
+ "foodDelivery_path = os.path.join(path, 'Q1_data.csv')\n",
27
+ "df_foodDelivery = pd.read_csv(foodDelivery_path)\n"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 2: Write your code here:\n",
37
+ "\n",
38
+ "df_foodDelivery.head()"
39
+ ],
40
+ "execution_count": null,
41
+ "outputs": []
42
+ },
43
+ {
44
+ "cell_type": "code",
45
+ "metadata": {},
46
+ "source": [
47
+ "# Task 3: Write your code here:\n",
48
+ "\n",
49
+ "df_foodDelivery.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
+ "\n",
60
+ "df_foodDelivery.describe()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 5: Write your code here:\n",
70
+ "\n",
71
+ "import matplotlib.pyplot as plt\n",
72
+ "\n",
73
+ "# Delivery_Time distribution (target variable)\n",
74
+ "\n",
75
+ "plt.hist(df_foodDelivery['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
76
+ "plt.title(f\"Target Distribution ({'Delivery_Time'})\")\n",
77
+ "plt.xlabel('Delivery_Time')\n",
78
+ "plt.ylabel(\"Frequency\")\n",
79
+ "plt.grid(False)\n",
80
+ "\n",
81
+ "plt.show()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 1: Write your code here:\n",
91
+ "df_foodDelivery.columns.drop(\"Order_ID\")\n"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "# Task 2: Write your code here:\n",
101
+ "\n",
102
+ "def check_missing_values(df):\n",
103
+ " missing_values = df.isnull().sum()\n",
104
+ " print(\"Missing Values per Column:\")\n",
105
+ " print(missing_values[missing_values > 0])\n",
106
+ " if missing_values.any():\n",
107
+ " print(\"\\nHandle Missing Values as needed.\")\n",
108
+ " else:\n",
109
+ " print(\"\\nNo Missing Values Found.\")\n",
110
+ "\n",
111
+ "check_missing_values(df_foodDelivery)\n",
112
+ "\n",
113
+ "print(\"Handeling missing values...\")\n",
114
+ "\n",
115
+ "df_foodDelivery['Weather'] = df_foodDelivery['Weather'].fillna(df_foodDelivery['Weather'].mode()[0])\n",
116
+ "df_foodDelivery['Traffic_Level'] = df_foodDelivery['Traffic_Level'].fillna(df_foodDelivery['Traffic_Level'].mode()[0])\n",
117
+ "df_foodDelivery['Time_of_Day'] = df_foodDelivery['Time_of_Day'].fillna(df_foodDelivery['Time_of_Day'].mode()[0])\n",
118
+ "df_foodDelivery['Courier_Experience_yrs'] = df_foodDelivery['Courier_Experience_yrs'].fillna(df_foodDelivery['Courier_Experience_yrs'].mean())\n",
119
+ "df_foodDelivery['Delivery_Time'] = df_foodDelivery['Delivery_Time'].fillna(df_foodDelivery['Delivery_Time'].mean())\n",
120
+ "\n",
121
+ "print(\"Done\")\n",
122
+ "\n",
123
+ "df_foodDelivery.head(20)\n",
124
+ "\n"
125
+ ],
126
+ "execution_count": null,
127
+ "outputs": []
128
+ },
129
+ {
130
+ "cell_type": "code",
131
+ "metadata": {},
132
+ "source": [
133
+ "# Task 3: Write your code here:\n",
134
+ "\n",
135
+ "def check_duplicates(df):\n",
136
+ " duplicates = df.duplicated().sum()\n",
137
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
138
+ " if duplicates > 0:\n",
139
+ " print(\"Dropping Duplicates...\")\n",
140
+ " df.drop_duplicates(inplace=True)\n",
141
+ " print(\"Duplicates Dropped.\")\n",
142
+ " else:\n",
143
+ " print(\"No Duplicate Samples Found.\")\n",
144
+ "\n",
145
+ "check_duplicates(df_foodDelivery)"
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
+ "from sklearn.preprocessing import LabelEncoder\n",
157
+ "\n",
158
+ "categorical_cols = df_foodDelivery.select_dtypes(include=[\"object\"]).columns\n",
159
+ "\n",
160
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
161
+ "\n",
162
+ "for col in categorical_cols:\n",
163
+ " le = LabelEncoder()\n",
164
+ " df_foodDelivery[col] = le.fit_transform(df_foodDelivery[col].astype(str))\n",
165
+ "\n",
166
+ "df_foodDelivery.head()\n"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 5: Write your code here:\n",
176
+ "\n",
177
+ "from sklearn.preprocessing import StandardScaler\n",
178
+ "\n",
179
+ "numerical_cols = df_foodDelivery.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
180
+ "print(numerical_cols)\n",
181
+ "\n",
182
+ "scaler = StandardScaler()\n",
183
+ "df_foodDelivery[numerical_cols] = scaler.fit_transform(df_foodDelivery[numerical_cols])\n",
184
+ "df_foodDelivery.head()\n"
185
+ ],
186
+ "execution_count": null,
187
+ "outputs": []
188
+ },
189
+ {
190
+ "cell_type": "code",
191
+ "metadata": {},
192
+ "source": [
193
+ "# Task 6: Write your code here:\n",
194
+ "import seaborn as sns\n",
195
+ "\n",
196
+ "# Is the target imbalanced?\n",
197
+ "\n",
198
+ "def check_target_imbalance(df, target_column):\n",
199
+ " print(\"Target Distribution:\")\n",
200
+ " print(df[target_column])\n",
201
+ " sns.countplot(x=df[target_column])\n",
202
+ " plt.title(\"Target Distribution\")\n",
203
+ " plt.show()\n",
204
+ "\n",
205
+ "check_target_imbalance(df_foodDelivery, \"Delivery_Time\")\n"
206
+ ],
207
+ "execution_count": null,
208
+ "outputs": []
209
+ },
210
+ {
211
+ "cell_type": "code",
212
+ "metadata": {},
213
+ "source": [
214
+ "# Task 1: Write your code here:\n",
215
+ "feature_cols = ['Distance_km','Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
216
+ "X = df_foodDelivery[feature_cols]\n",
217
+ "y = df_foodDelivery['Delivery_Time']"
218
+ ],
219
+ "execution_count": null,
220
+ "outputs": []
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "metadata": {},
225
+ "source": [
226
+ "# Task 2,3,4,5: Write your code here:\n",
227
+ "\n",
228
+ "from sklearn.model_selection import StratifiedKFold\n",
229
+ "from sklearn.ensemble import RandomForestRegressor\n",
230
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
231
+ "from sklearn.model_selection import KFold\n",
232
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
233
+ "import numpy as np\n",
234
+ "\n",
235
+ "\n",
236
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
237
+ "\n",
238
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=-1)\n",
239
+ "mae = []\n",
240
+ "\n",
241
+ "\n",
242
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
243
+ "\n",
244
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
245
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
246
+ "\n",
247
+ " # Train\n",
248
+ " model.fit(X_train, y_train)\n",
249
+ "\n",
250
+ " # Predict\n",
251
+ " y_pred = model.predict(X_test)\n",
252
+ "\n",
253
+ " meanabs = mean_absolute_error(y_test, y_pred)\n",
254
+ "\n",
255
+ " mae.append(meanabs)\n",
256
+ " print(\"RandomForestRegressor\")\n",
257
+ " print(meanabs)\n",
258
+ " print(\"\\n\")\n",
259
+ "\n",
260
+ "\n",
261
+ "print(\"Avrage score across all folds: \\n\")\n",
262
+ "sum = 0\n",
263
+ "for num in mae:\n",
264
+ " sum += num\n",
265
+ "\n",
266
+ "print(sum / len(mae))\n",
267
+ "\n"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task 1: Write your code here:\n",
277
+ "\n",
278
+ "\n"
279
+ ],
280
+ "execution_count": null,
281
+ "outputs": []
282
+ },
283
+ {
284
+ "cell_type": "code",
285
+ "metadata": {},
286
+ "source": [
287
+ "# Task 2: Write your code here:"
288
+ ],
289
+ "execution_count": null,
290
+ "outputs": []
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "metadata": {},
295
+ "source": [
296
+ "# Task Bonus: Write your code here:"
297
+ ],
298
+ "execution_count": null,
299
+ "outputs": []
300
+ }
301
+ ],
302
+ "metadata": {
303
+ "kernelspec": {
304
+ "display_name": "Python 3",
305
+ "name": "python3"
306
+ },
307
+ "language_info": {
308
+ "name": "python"
309
+ }
310
+ },
311
+ "nbformat": 4,
312
+ "nbformat_minor": 0
313
+ }
submissions_extracted/228/Q2.ipynb ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "\n",
71
+ "X_train = 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.long)\n",
74
+ "y_test = torch.tensor(y_test, dtype=torch.long)\n"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# 2. Create TensorDataset objects\n",
84
+ "from torch.utils.data import DataLoader, TensorDataset\n",
85
+ "\n",
86
+ "\n",
87
+ "# Create TensorDatasets for training and testing\n",
88
+ "train_dataset = TensorDataset(X_train, y_train)\n",
89
+ "test_dataset = TensorDataset(X_test, y_test)\n"
90
+ ],
91
+ "execution_count": null,
92
+ "outputs": []
93
+ },
94
+ {
95
+ "cell_type": "code",
96
+ "metadata": {},
97
+ "source": [
98
+ "# 3. Create DataLoaders\n",
99
+ "\n",
100
+ "# Create Dataloaders to train and test data in batches\n",
101
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
102
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
103
+ "\n",
104
+ "\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 4. Print shape of one batch\n",
114
+ "\n",
115
+ "# Print dataset sizes\n",
116
+ "print(\"Train dataset:\", len(train_dataset))\n",
117
+ "print(\"Test dataset:\", len(test_dataset))\n",
118
+ "\n",
119
+ "# Get the first batch from the training DataLoader\n",
120
+ "X_batch, y_batch = next(iter(train_loader))\n",
121
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
122
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
123
+ ],
124
+ "execution_count": null,
125
+ "outputs": []
126
+ },
127
+ {
128
+ "cell_type": "code",
129
+ "metadata": {},
130
+ "source": [
131
+ "# 5. Display sample images\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 1: Write your model class here:\n",
141
+ "\n",
142
+ "import torch.nn as nn\n",
143
+ "\n",
144
+ "class NN4Layer(nn.Module):\n",
145
+ "\n",
146
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
147
+ " super(NN4Layer, self).__init__()\n",
148
+ "\n",
149
+ " # First linear layer: input features -> hidden layer\n",
150
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
151
+ "\n",
152
+ " # Second linear layer: hidden layer -> hidden layer\n",
153
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
154
+ "\n",
155
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
156
+ "\n",
157
+ " # Output layer: hidden layer -> number of classes (logits)\n",
158
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
159
+ "\n",
160
+ " # ReLU activation for non-linearity\n",
161
+ " self.relu = nn.ReLU()\n",
162
+ "\n",
163
+ " # Defines how input data flows through the network\n",
164
+ " def forward(self, x):\n",
165
+ " # First hidden layer\n",
166
+ " z1 = self.layer1(x)\n",
167
+ " a1 = self.relu(z1)\n",
168
+ "\n",
169
+ " # Second hidden layer\n",
170
+ " z2 = self.layer2(a1)\n",
171
+ " a2 = self.relu(z2)\n",
172
+ "\n",
173
+ " # Output layer (raw scores / logits)\n",
174
+ " output = self.layer3(a2) # there is something missing here, remember? :)\n",
175
+ "\n",
176
+ " return output"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 2: Write your training loop here:\n",
186
+ "\n",
187
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
188
+ " # Set the model to training mode\n",
189
+ " model.train()\n",
190
+ "\n",
191
+ " running_loss = 0.0\n",
192
+ "\n",
193
+ " for X_batch, y_batch in train_loader:\n",
194
+ " # Move batch to the selected device\n",
195
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
196
+ " y_batch = y_batch.to(device)\n",
197
+ "\n",
198
+ " # Forward pass\n",
199
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
200
+ " loss = criterion(outputs, y_batch)\n",
201
+ "\n",
202
+ " # Backward pass & optimization\n",
203
+ " optimizer.zero_grad() # Clear previous gradients\n",
204
+ " loss.backward() # Compute gradients\n",
205
+ " optimizer.step() # Update model parameters\n",
206
+ "\n",
207
+ " running_loss += loss.item()\n",
208
+ "\n",
209
+ " # Average loss over all batches\n",
210
+ " avg_loss = running_loss / len(train_loader)\n",
211
+ "\n",
212
+ " return avg_loss"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# Task 3: Write your validation loop here:\n",
222
+ "\n",
223
+ "def validate(model, criterion, test_loader, device):\n",
224
+ " # Set the model to evaluation mode\n",
225
+ " model.eval()\n",
226
+ "\n",
227
+ " running_loss = 0.0\n",
228
+ " correct = 0\n",
229
+ " total = 0\n",
230
+ "\n",
231
+ " with torch.no_grad():\n",
232
+ " for X_batch, y_batch in test_loader:\n",
233
+ " # Move data to device\n",
234
+ " X_batch = X_batch.view(X_batch.size(0), -1).to(device)\n",
235
+ " y_batch = y_batch.to(device)\n",
236
+ "\n",
237
+ " # Forward pass\n",
238
+ " outputs = model(X_batch) # shape: (batch_size, 10)\n",
239
+ " loss = criterion(outputs, y_batch)\n",
240
+ " running_loss += loss.item()\n",
241
+ "\n",
242
+ " # Apply Softmax to get probabilities\n",
243
+ " probabilities = F.softmax(outputs, dim=1)\n",
244
+ "\n",
245
+ " # Multiclass predictions\n",
246
+ " predicted = torch.argmax(probabilities, dim=1)\n",
247
+ "\n",
248
+ " # Accuracy calculation\n",
249
+ " correct += (predicted == y_batch).sum().item()\n",
250
+ " total += y_batch.size(0)\n",
251
+ "\n",
252
+ " avg_loss = running_loss / len(test_loader)\n",
253
+ " accuracy = correct / total\n",
254
+ "\n",
255
+ " return avg_loss, accuracy"
256
+ ],
257
+ "execution_count": null,
258
+ "outputs": []
259
+ },
260
+ {
261
+ "cell_type": "code",
262
+ "metadata": {},
263
+ "source": [
264
+ "# Task 4: Define device, model, loss, optimizer:\n",
265
+ "\n",
266
+ "from torch.optim import Adam\n",
267
+ "\n",
268
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
269
+ "\n",
270
+ "# Model parameters\n",
271
+ "input_dim = 28 * 28 # MNIST images flattened\n",
272
+ "hidden_dim = 14 # Design choice\n",
273
+ "output_dim = 10 # Digits 0–9\n",
274
+ "\n",
275
+ "# Instantiate model\n",
276
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
277
+ "\n",
278
+ "# Print the model architecture\n",
279
+ "print(\"Model Architecture:\\n\")\n",
280
+ "print(model)\n",
281
+ "\n",
282
+ "# Calculate the total number of trainable parameters\n",
283
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
284
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
285
+ "\n",
286
+ "# Define optimizer\n",
287
+ "optimizer = Adam(model.parameters(), learning_rate)\n"
288
+ ],
289
+ "execution_count": null,
290
+ "outputs": []
291
+ },
292
+ {
293
+ "cell_type": "code",
294
+ "metadata": {},
295
+ "source": [
296
+ "# Task 5: Start training for 20 epochs:\n",
297
+ "from torch.optim import Adam\n",
298
+ "\n",
299
+ "num_epochs = 20\n",
300
+ "learning_rate = 0.001\n",
301
+ "\n"
302
+ ],
303
+ "execution_count": null,
304
+ "outputs": []
305
+ },
306
+ {
307
+ "cell_type": "code",
308
+ "metadata": {},
309
+ "source": [
310
+ "# Task 1: Write your code here:\n"
311
+ ],
312
+ "execution_count": null,
313
+ "outputs": []
314
+ },
315
+ {
316
+ "cell_type": "code",
317
+ "metadata": {},
318
+ "source": [
319
+ "# Task 2 (Bonus): Write your code here:"
320
+ ],
321
+ "execution_count": null,
322
+ "outputs": []
323
+ }
324
+ ],
325
+ "metadata": {
326
+ "kernelspec": {
327
+ "display_name": "Python 3",
328
+ "name": "python3"
329
+ },
330
+ "language_info": {
331
+ "name": "python"
332
+ }
333
+ },
334
+ "nbformat": 4,
335
+ "nbformat_minor": 0
336
+ }
submissions_extracted/228/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
+ "# Task 1: Write your code here:\n",
27
+ "import os\n",
28
+ "import pandas as pd\n",
29
+ "\n",
30
+ "df_path = os.path.join(path, 'Q3_data.csv')\n",
31
+ "df = pd.read_csv(df_path)\n"
32
+ ],
33
+ "execution_count": null,
34
+ "outputs": []
35
+ },
36
+ {
37
+ "cell_type": "code",
38
+ "metadata": {},
39
+ "source": [
40
+ "# Task 2: Write your code here:\n",
41
+ "df.head()"
42
+ ],
43
+ "execution_count": null,
44
+ "outputs": []
45
+ },
46
+ {
47
+ "cell_type": "code",
48
+ "metadata": {},
49
+ "source": [
50
+ "# Task 3: Write your code here:\n",
51
+ "df.info()"
52
+ ],
53
+ "execution_count": null,
54
+ "outputs": []
55
+ },
56
+ {
57
+ "cell_type": "code",
58
+ "metadata": {},
59
+ "source": [
60
+ "# Task 4: Write your code here:\n",
61
+ "df.describe()"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 1: Write your code here:\n",
71
+ "def check_missing_values(df):\n",
72
+ " missing_values = df.isnull().sum()\n",
73
+ " print(\"Missing Values per Column:\")\n",
74
+ " print(missing_values[missing_values > 0])\n",
75
+ " if missing_values.any():\n",
76
+ " print(\"\\nHandle Missing Values as needed.\")\n",
77
+ " else:\n",
78
+ " print(\"\\nNo Missing Values Found.\")\n",
79
+ "\n",
80
+ "check_missing_values(df)\n",
81
+ "\n",
82
+ "df = df.fillna(df.mean())\n",
83
+ "\n"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 2: Write your code here:\n",
93
+ "\n",
94
+ "def check_duplicates(df):\n",
95
+ " duplicates = df.duplicated().sum()\n",
96
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
97
+ " if duplicates > 0:\n",
98
+ " print(\"Dropping Duplicates...\")\n",
99
+ " df.drop_duplicates(inplace=True)\n",
100
+ " print(\"Duplicates Dropped.\")\n",
101
+ " else:\n",
102
+ " print(\"No Duplicate Samples Found.\")\n",
103
+ "\n",
104
+ "check_duplicates(df)"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 3: Write your code here:\n",
114
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
115
+ "\n",
116
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
117
+ "\n",
118
+ "# no Categorical columns..."
119
+ ],
120
+ "execution_count": null,
121
+ "outputs": []
122
+ },
123
+ {
124
+ "cell_type": "code",
125
+ "metadata": {},
126
+ "source": [
127
+ "# Task 4: Write your code here:\n",
128
+ "from sklearn.preprocessing import StandardScaler\n",
129
+ "\n",
130
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
131
+ "\n",
132
+ "scaler = StandardScaler()\n",
133
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
134
+ "df.head()"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "# Task 5: Write your code here:\n",
144
+ "\n",
145
+ "import matplotlib.pyplot as plt\n",
146
+ "\n",
147
+ "# Delivery_Time distribution (target variable)\n",
148
+ "\n",
149
+ "plt.hist(df['Target'].dropna(), bins=50, edgecolor='black')\n",
150
+ "plt.title(f\"Target Distribution ({'Delivery_Time'})\")\n",
151
+ "plt.xlabel('Target')\n",
152
+ "plt.ylabel(\"Frequency\")\n",
153
+ "plt.grid(False)\n",
154
+ "\n",
155
+ "plt.show()"
156
+ ],
157
+ "execution_count": null,
158
+ "outputs": []
159
+ },
160
+ {
161
+ "cell_type": "code",
162
+ "metadata": {},
163
+ "source": [
164
+ "# Task 1: Write your code here:\n",
165
+ "\n",
166
+ "X = df.drop(\"Target\", axis=1)\n",
167
+ "y = df[\"Target\"]"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "# Task 2,3,4,5: Write your code here:\n",
177
+ "\n",
178
+ "from sklearn.model_selection import StratifiedKFold\n",
179
+ "from catboost import CatBoostClassifier\n",
180
+ "from sklearn.model_selection import KFold\n",
181
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
182
+ "import numpy as np\n",
183
+ "\n",
184
+ "\n",
185
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
186
+ "\n",
187
+ "model = CatBoostClassifier(\n",
188
+ " verbose=0,\n",
189
+ " n_estimators=320,\n",
190
+ " max_depth=4\n",
191
+ " )\n",
192
+ "\n",
193
+ "all_results = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
194
+ "\n",
195
+ "\n",
196
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\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
+ "\n",
201
+ " # Train\n",
202
+ " model.fit(X_train, y_train)\n",
203
+ "\n",
204
+ " # Predict\n",
205
+ " y_pred = model.predict(X_test)\n",
206
+ "\n",
207
+ " # 3. Save metrics for that model in this fold\n",
208
+ " accuracy = accuracy_score(y_test, y_pred)\n",
209
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
210
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
211
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
212
+ "\n",
213
+ " all_results['accuracy'].append(accuracy)\n",
214
+ " all_results['precision'].append(precision)\n",
215
+ " all_results['recall'].append(recall)\n",
216
+ " all_results['f1'].append(f1)\n",
217
+ "\n",
218
+ "\n",
219
+ " print(f\"\\n CatBoosterClassfier:\")\n",
220
+ " print(f\" Accuracy: {np.mean(all_results['accuracy']):.4f}\")\n",
221
+ " print(f\" Precision: {np.mean(all_results['precision']):.4f}\")\n",
222
+ " print(f\" Recall: {np.mean(all_results['recall']):.4f}\")\n",
223
+ " print(f\" F1-Score: {np.mean(all_results['f1']):.4f}\")\n"
224
+ ],
225
+ "execution_count": null,
226
+ "outputs": []
227
+ },
228
+ {
229
+ "cell_type": "code",
230
+ "metadata": {},
231
+ "source": [
232
+ "# Task 1: Write your code here:\n"
233
+ ],
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/229/Q1.ipynb ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "%matplotlib inline"
16
+ ],
17
+ "execution_count": null,
18
+ "outputs": []
19
+ },
20
+ {
21
+ "cell_type": "code",
22
+ "metadata": {},
23
+ "source": [
24
+ "import kagglehub\n",
25
+ "\n",
26
+ "# Download latest version\n",
27
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
28
+ "\n",
29
+ "print(\"Path to dataset files:\", path)"
30
+ ],
31
+ "execution_count": null,
32
+ "outputs": []
33
+ },
34
+ {
35
+ "cell_type": "code",
36
+ "metadata": {},
37
+ "source": [
38
+ "# Task 1: Write your code here:\n",
39
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
40
+ "\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
+ "plt.figure(figsize=(10, 5))\n",
82
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
83
+ "plt.title('Delivery_Time Distribution')\n",
84
+ "plt.xlabel('Delivery_Time')\n",
85
+ "plt.ylabel('Frequency')\n",
86
+ "plt.show()"
87
+ ],
88
+ "execution_count": null,
89
+ "outputs": []
90
+ },
91
+ {
92
+ "cell_type": "code",
93
+ "metadata": {},
94
+ "source": [
95
+ "# Task 1: Write your code here:\n",
96
+ "df = df.drop(columns=['Order_ID'])\n",
97
+ "df.head()"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 2: Write your code here:\n",
107
+ "\n",
108
+ "def check_missing_values(df):\n",
109
+ " missing_values = df.isnull().sum()\n",
110
+ " print(\"Missing Values per Column:\")\n",
111
+ " print(missing_values[missing_values > 0])\n",
112
+ " if missing_values.any():\n",
113
+ " print(\"\\nHandle Missing Values as needed.\")\n",
114
+ " else:\n",
115
+ " print(\"\\nNo Missing Values Found.\")\n",
116
+ "\n",
117
+ "check_missing_values(df)\n",
118
+ "df_clean = df.dropna(subset=['Weather', 'Traffic_Level', 'Time_of_Day','Courier_Experience_yrs','Delivery_Time'])\n",
119
+ "check_missing_values(df_clean)"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 3: Write your code here:\n",
129
+ "def check_duplicates(df):\n",
130
+ " duplicates = df.duplicated().sum()\n",
131
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
132
+ " if duplicates > 0:\n",
133
+ " print(\"Dropping Duplicates...\")\n",
134
+ " df.drop_duplicates(inplace=True)\n",
135
+ " print(\"Duplicates Dropped.\")\n",
136
+ " else:\n",
137
+ " print(\"No Duplicate Samples Found.\")\n",
138
+ "\n",
139
+ "check_duplicates(df_clean)"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Write your code here:\n",
149
+ "from sklearn.preprocessing import OneHotEncoder\n",
150
+ "from sklearn.preprocessing import LabelEncoder\n",
151
+ "\n",
152
+ "label_encoder = LabelEncoder()\n",
153
+ "\n",
154
+ "categorie= ['Traffic_Level', 'Time_of_Day', 'Vehicle_Type','Weather']\n",
155
+ "#categories = pd.DataFrame({\"Weather\": ['Windy', 'Clear', 'Foggy', 'Rainy']})\n",
156
+ "#e = OneHotEncoder(sparse_output=False)\n",
157
+ "#df_clean = le.fit_transform(categories)\n",
158
+ "#print('\\nData after encoding:\\n', df_clean) #show after encoding\n",
159
+ "df_clean =label_encoder.fit_transform(categorie)\n",
160
+ "print('\\nData after encoding:\\n', df_clean) #show after encoding\n"
161
+ ],
162
+ "execution_count": null,
163
+ "outputs": []
164
+ },
165
+ {
166
+ "cell_type": "code",
167
+ "metadata": {},
168
+ "source": [
169
+ "# Task 5: Write your code here:\n",
170
+ "from sklearn.preprocessing import StandardScaler\n",
171
+ "\n",
172
+ "features = df_clean.drop(columns=['Delivery_Time'])\n",
173
+ "\n",
174
+ "scaler = StandardScaler()\n",
175
+ "\n",
176
+ "data_standard_scaled = scaler.fit_transform(features)"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 6: Write your code here:\n",
186
+ "def check_target_imbalance(df, target_column):\n",
187
+ " print(\"Target Distribution:\")\n",
188
+ " print(df[target_column].value_counts(normalize=True))\n",
189
+ " sns.countplot(x=df[target_column])\n",
190
+ " plt.title(\"Target Distribution\")\n",
191
+ " plt.show()\n",
192
+ "\n",
193
+ "check_target_imbalance(df_clean, \"Delivery_Time\")"
194
+ ],
195
+ "execution_count": null,
196
+ "outputs": []
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "metadata": {},
201
+ "source": [
202
+ "# Task 1: Write your code here:\n",
203
+ "X = df_clean.drop(\"Delivery_Time\", axis=1).astype(float)\n",
204
+ "y = df_clean['status'].astype(float)"
205
+ ],
206
+ "execution_count": null,
207
+ "outputs": []
208
+ },
209
+ {
210
+ "cell_type": "code",
211
+ "metadata": {},
212
+ "source": [
213
+ "# Task 2,3,4,5: Write your code here:\n",
214
+ "from sklearn.linear_model import Ridge, Lasso\n",
215
+ "from sklearn.svm import SVR\n",
216
+ "from sklearn.tree import DecisionTreeRegressor\n",
217
+ "from sklearn.ensemble import RandomForestRegressor\n",
218
+ "from lightgbm import LGBMRegressor\n",
219
+ "from sklearn.model_selection import KFold\n",
220
+ "from sklearn.metrics import mean_squared_error as sklearn_mse,sklearn_mae\n",
221
+ "\n",
222
+ "n_splits = 5 # K=5 Folds\n",
223
+ "\n",
224
+ "# 5-Fold Cross-Validation, shuffled\n",
225
+ "kf = KFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
226
+ "\n",
227
+ "lr_mae = []\n",
228
+ "\n",
229
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\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 = sklearn_mae(y_test, y_pred)\n",
243
+ "\n",
244
+ "\n",
245
+ "\n",
246
+ " # Store results\n",
247
+ " lr_mae.append(mae)\n",
248
+ "\n",
249
+ "model = RandomForestClassifier(n_estimators=100, max_depth=15,\n",
250
+ " class_weight='balanced', random_state=42)\n",
251
+ "model.fit(X_train_scaled, y_train)\n",
252
+ "print(\"Model trained!\")\n",
253
+ "\n"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 1: Write your code here:\n",
263
+ "average_losses = np.mean(lr_losses, axis=0)\n",
264
+ "\n",
265
+ "plt.figure(figsize=(10, 6))\n",
266
+ "plt.plot(average_losses, label='Average Loss')\n",
267
+ "plt.xlabel('Iteration')\n",
268
+ "plt.ylabel('MSE Loss')\n",
269
+ "plt.title('Linear Regression Training Loss (Averaged Across Folds)')\n",
270
+ "plt.legend()\n",
271
+ "plt.grid(True, alpha=0.3)\n",
272
+ "plt.show()"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# Task 2: Write your code here:"
282
+ ],
283
+ "execution_count": null,
284
+ "outputs": []
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "metadata": {},
289
+ "source": [
290
+ "# Task Bonus: Write your code here:"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ }
295
+ ],
296
+ "metadata": {
297
+ "kernelspec": {
298
+ "display_name": "Python 3",
299
+ "name": "python3"
300
+ },
301
+ "language_info": {
302
+ "name": "python"
303
+ }
304
+ },
305
+ "nbformat": 4,
306
+ "nbformat_minor": 0
307
+ }
submissions_extracted/229/Q2.ipynb ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import kagglehub\n",
70
+ "import pandas as pd\n",
71
+ "import torch\n",
72
+ "import torch.nn as nn\n",
73
+ "from torch.optim import AdamW\n",
74
+ "import matplotlib.pyplot as plt\n",
75
+ "import torch.nn.functional as F\n",
76
+ "from torch.utils.data import DataLoader, TensorDataset\n",
77
+ "from sklearn.model_selection import train_test_split\n",
78
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
79
+ "\n",
80
+ "X_train = torch.tensor(X_train.values, dtype=torch.float32)\n",
81
+ "X_test = torch.tensor(X_test.values, dtype=torch.float32)\n",
82
+ "y_train = torch.tensor(y_train.values, dtype=torch.long)\n",
83
+ "y_test = torch.tensor(y_test.values, dtype=torch.long)\n",
84
+ "\n"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# 2. Create TensorDataset objects\n",
94
+ "train_dataset = TensorDataset(X_train, y_train)\n",
95
+ "test_dataset = TensorDataset(X_test, y_test)\n",
96
+ "\n"
97
+ ],
98
+ "execution_count": null,
99
+ "outputs": []
100
+ },
101
+ {
102
+ "cell_type": "code",
103
+ "metadata": {},
104
+ "source": [
105
+ "# 3. Create DataLoaders\n",
106
+ "rain_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
107
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
108
+ "\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
+ "\n",
119
+ "X_batch, y_batch = next(iter(train_loader))\n",
120
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
121
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# 5. Display sample images\n",
131
+ "\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 1: Write your model class here:\n",
141
+ "class NN4Layer(nn.Module):\n",
142
+ "\n",
143
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
144
+ " super(NN4Layer, self).__init__()\n",
145
+ "\n",
146
+ " # First linear layer: input features -> hidden layer\n",
147
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
148
+ "\n",
149
+ " # Second linear layer: hidden layer -> hidden layer\n",
150
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
151
+ "\n",
152
+ " # Third linear layer: hidden layer -> hidden layer\n",
153
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
154
+ "\n",
155
+ " # Output layer: hidden layer -> number of classes (logits)\n",
156
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
157
+ "\n",
158
+ " # ReLU activation for non-linearity\n",
159
+ " self.relu = nn.ReLU()\n",
160
+ "\n",
161
+ " # Defines how input data flows through the network\n",
162
+ " def forward(self, x):\n",
163
+ " # First hidden layer\n",
164
+ " a1 = self.relu(self.layer1(x))\n",
165
+ "\n",
166
+ " # Second hidden layer\n",
167
+ " a2 = self.relu(self.layer2(a1))\n",
168
+ "\n",
169
+ " # Third hidden layer\n",
170
+ " a3 = self.relu(self.layer3(a2))\n",
171
+ "\n",
172
+ " # Output layer (raw scores / logits)\n",
173
+ " output = self.layer4(a3)\n",
174
+ "\n",
175
+ " return output"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "# Task 2: Write your training loop here:\n",
185
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
186
+ " # Set the model to training mode\n",
187
+ " model.train()\n",
188
+ "\n",
189
+ " running_loss = 0.0\n",
190
+ "\n",
191
+ " for X_batch, y_batch in train_loader:\n",
192
+ " # Move batch to the selected device\n",
193
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
194
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
195
+ "\n",
196
+ " # Forward pass (outputs are logits)\n",
197
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
198
+ " loss = criterion(outputs, y_batch)\n",
199
+ "\n",
200
+ " # Backward pass & optimization\n",
201
+ " optimizer.zero_grad() # Clear previous gradients\n",
202
+ " loss.backward() # Compute gradients\n",
203
+ " optimizer.step() # Update model parameters\n",
204
+ "\n",
205
+ " running_loss += loss.item()\n",
206
+ "\n",
207
+ " # Average loss over all batches\n",
208
+ " avg_loss = running_loss / len(train_loader)\n",
209
+ "\n",
210
+ " return avg_loss"
211
+ ],
212
+ "execution_count": null,
213
+ "outputs": []
214
+ },
215
+ {
216
+ "cell_type": "code",
217
+ "metadata": {},
218
+ "source": [
219
+ "# Task 3: Write your validation loop here:\n",
220
+ "def validate(model, criterion, test_loader, device):\n",
221
+ " # Set the model to evaluation mode\n",
222
+ " model.eval()\n",
223
+ "\n",
224
+ " running_loss = 0.0\n",
225
+ " correct = 0\n",
226
+ " total = 0\n",
227
+ "\n",
228
+ " with torch.no_grad():\n",
229
+ " for X_batch, y_batch in test_loader:\n",
230
+ " # Move data to device\n",
231
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
232
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
233
+ "\n",
234
+ " # Forward pass\n",
235
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
236
+ " loss = criterion(outputs, y_batch)\n",
237
+ " running_loss += loss.item()\n",
238
+ "\n",
239
+ " # Apply Softmax to get probabilities\n",
240
+ " probabilities = F.softmax(outputs, dim=1)\n",
241
+ "\n",
242
+ " # Pick the classes with highest probabilities\n",
243
+ " predicted = torch.argmax(probabilities, dim=1)\n",
244
+ "\n",
245
+ " # Accuracy calculation\n",
246
+ " correct += (predicted == y_batch).sum().item()\n",
247
+ " total += y_batch.size(0)\n",
248
+ "\n",
249
+ " avg_loss = running_loss / len(test_loader)\n",
250
+ " accuracy = correct / total\n",
251
+ "\n",
252
+ " return avg_loss, accuracy"
253
+ ],
254
+ "execution_count": null,
255
+ "outputs": []
256
+ },
257
+ {
258
+ "cell_type": "code",
259
+ "metadata": {},
260
+ "source": [
261
+ "# Task 4: Define device, model, loss, optimizer:\n",
262
+ "# Device setup\n",
263
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
264
+ "\n",
265
+ "# Model parameters\n",
266
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
267
+ "hidden_dim = 14 # Design choice\n",
268
+ "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
269
+ "\n",
270
+ "# Instantiate model\n",
271
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
272
+ "\n",
273
+ "# Print the model architecture\n",
274
+ "print(\"Model Architecture:\\n\")\n",
275
+ "print(model)\n",
276
+ "\n",
277
+ "# Calculate the total number of trainable parameters\n",
278
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
279
+ "print(f\"\\nTotal trainable parameters: {total_params}\")"
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
+ "num_epochs = 20\n",
290
+ "learning_rate = 0.001\n",
291
+ "\n",
292
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
293
+ "criterion = nn.CrossEntropyLoss()\n",
294
+ "# Define optimizer\n",
295
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
296
+ "\n",
297
+ "train_losses = []\n",
298
+ "val_losses = []\n",
299
+ "val_accuracies = []\n",
300
+ "\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
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
314
+ "\n",
315
+ "print('Training Complete!')\n",
316
+ "\n"
317
+ ],
318
+ "execution_count": null,
319
+ "outputs": []
320
+ },
321
+ {
322
+ "cell_type": "code",
323
+ "metadata": {},
324
+ "source": [
325
+ "# Task 1: Write your code here:\n",
326
+ "plt.figure(figsize=(7, 5))\n",
327
+ "\n",
328
+ "plt.plot(train_losses, label='Train Loss')\n",
329
+ "plt.plot(val_losses, label='Validation Loss')\n",
330
+ "plt.title('Loss over Epochs')\n",
331
+ "plt.xlabel('Epoch')\n",
332
+ "plt.ylabel('Loss')\n",
333
+ "plt.legend()\n",
334
+ "\n",
335
+ "plt.tight_layout()\n",
336
+ "plt.show()"
337
+ ],
338
+ "execution_count": null,
339
+ "outputs": []
340
+ },
341
+ {
342
+ "cell_type": "code",
343
+ "metadata": {},
344
+ "source": [
345
+ "# Task 2 (Bonus): Write your code here:\n"
346
+ ],
347
+ "execution_count": null,
348
+ "outputs": []
349
+ }
350
+ ],
351
+ "metadata": {
352
+ "kernelspec": {
353
+ "display_name": "Python 3",
354
+ "name": "python3"
355
+ },
356
+ "language_info": {
357
+ "name": "python"
358
+ }
359
+ },
360
+ "nbformat": 4,
361
+ "nbformat_minor": 0
362
+ }
submissions_extracted/229/Q3.ipynb ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "import pandas as pd\n",
28
+ "import numpy as np\n",
29
+ "import matplotlib.pyplot as plt\n",
30
+ "import seaborn as sns\n",
31
+ "import kagglehub\n",
32
+ "import os\n",
33
+ "from tqdm import tqdm\n",
34
+ "\n",
35
+ "%matplotlib inline\n",
36
+ "df = pd.read_csv(f\"{path}/Q3_data.csv\")\n",
37
+ "df.head()"
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.info()"
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.describe"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 4: Write your code here:"
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
+ " missing_values = df.isnull().sum()\n",
78
+ " print(\"Missing Values per Column:\")\n",
79
+ " print(missing_values[missing_values > 0])\n",
80
+ " if missing_values.any():\n",
81
+ " print(\"\\nHandle Missing Values as needed.\")\n",
82
+ " else:\n",
83
+ " print(\"\\nNo Missing Values Found.\")\n",
84
+ "\n",
85
+ "check_missing_values(df)\n"
86
+ ],
87
+ "execution_count": null,
88
+ "outputs": []
89
+ },
90
+ {
91
+ "cell_type": "code",
92
+ "metadata": {},
93
+ "source": [
94
+ "# Task 2: Write your code here:\n",
95
+ "def check_duplicates(df):\n",
96
+ " duplicates = df.duplicated().sum()\n",
97
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
98
+ " if duplicates > 0:\n",
99
+ " print(\"Dropping Duplicates...\")\n",
100
+ " df.drop_duplicates(inplace=True)\n",
101
+ " print(\"Duplicates Dropped.\")\n",
102
+ " else:\n",
103
+ " print(\"No Duplicate Samples Found.\")"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 3: Write your code here:\n",
113
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
114
+ "\n",
115
+ "print(\"Categorical Columns:\", list(categorical_cols))"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# Task 4: Write your code here:\n",
125
+ "from sklearn.preprocessing import StandardScaler\n",
126
+ "\n",
127
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
128
+ "\n",
129
+ "scaler = StandardScaler()\n",
130
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
131
+ "df.head()\n"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 5: Write your code here:\n",
141
+ "def check_target_imbalance(df, target_column):\n",
142
+ " print(\"Target Distribution:\")\n",
143
+ " print(df[target_column].value_counts(normalize=True))\n",
144
+ " sns.countplot(x=df[target_column])\n",
145
+ " plt.title(\"Target Distribution\")\n",
146
+ " plt.show()\n",
147
+ "\n",
148
+ "check_target_imbalance(df, \"Target\")"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 1: Write your code here:\n",
158
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
159
+ "y = df['Target'].astype(float)"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 2,3,4,5: Write your code here:\n",
169
+ "from sklearn.neighbors import KNeighborsClassifier\n",
170
+ "from sklearn.svm import SVC\n",
171
+ "from sklearn.tree import DecisionTreeClassifier\n",
172
+ "from sklearn.ensemble import RandomForestClassifier\n",
173
+ "from xgboost import XGBClassifier\n",
174
+ "from catboost import CatBoostClassifier\n",
175
+ "from sklearn.model_selection import StratifiedKFold\n",
176
+ "from sklearn.metrics import accuracy_score, f1_score\n",
177
+ "\n",
178
+ "sklearn_models = {\n",
179
+ " \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
180
+ " n_neighbors=3, # Number of neighbors to consider\n",
181
+ " ),\n",
182
+ " \"Support Vector Machine\": SVC(\n",
183
+ " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
184
+ " C=0.75 # Regularization parameter\n",
185
+ " ),\n",
186
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
187
+ " max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
188
+ " ),\n",
189
+ " \"Random Forest\": RandomForestClassifier(\n",
190
+ " n_estimators=320, # Number of trees\n",
191
+ " max_depth=4\n",
192
+ " ),\n",
193
+ " \"XGBoost\": XGBClassifier(\n",
194
+ " verbosity=0,\n",
195
+ " n_estimators=300, # Number of boosting rounds\n",
196
+ " max_depth=5,\n",
197
+ " learning_rate=0.05 # Step size shrinkage\n",
198
+ " ),\n",
199
+ " \"CatBoost\": CatBoostClassifier(\n",
200
+ " verbose=0,\n",
201
+ " n_estimators=320,\n",
202
+ " max_depth=4\n",
203
+ " )\n",
204
+ "}\n",
205
+ "\n",
206
+ "all_results = {}\n",
207
+ "\n",
208
+ "for name in sklearn_models:\n",
209
+ " all_results[name] = {'accuracy': [], 'f1': []}\n",
210
+ "\n",
211
+ "n_splits = 5 # K\n",
212
+ "\n",
213
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
214
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
215
+ "\n",
216
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
217
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
218
+ "\n",
219
+ " # 1. Split data\n",
220
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
221
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
222
+ "\n",
223
+ " # 2. Train & Validate sklearn models\n",
224
+ " for model_name, model in sklearn_models.items():\n",
225
+ " print(f\"Training {model_name}...\")\n",
226
+ " model.fit(X_train, y_train) # train\n",
227
+ " y_pred = model.predict(X_test) # validate\n",
228
+ "\n",
229
+ " # 3. Save metrics for that model in this fold\n",
230
+ " accuracy = accuracy_score(y_test, y_pred)\n",
231
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
232
+ "\n",
233
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
234
+ " all_results[model_name]['f1'].append(f1)\n",
235
+ "\n",
236
+ "for model_name in all_results:\n",
237
+ " print(f\"\\n{model_name}:\")\n",
238
+ " print(f\" Accuracy: {np.mean(all_results[model_name]['accuracy']):.4f}\")\n",
239
+ " print(f\" F1-Score: {np.mean(all_results[model_name]['f1']):.4f}\")"
240
+ ],
241
+ "execution_count": null,
242
+ "outputs": []
243
+ },
244
+ {
245
+ "cell_type": "code",
246
+ "metadata": {},
247
+ "source": [
248
+ "# Task 1: Write your code here:importances = {}\n",
249
+ "importances = {}\n",
250
+ "\n",
251
+ "importances['Random Forest'] = sklearn_models['Random Forest'].feature_importances_\n",
252
+ "importances['XGBoost'] = sklearn_models['XGBoost'].feature_importances_\n",
253
+ "importances['CatBoost'] = sklearn_models['CatBoost'].feature_importances_\n",
254
+ "\n",
255
+ "# Create a 1x3 plot\n",
256
+ "fig, axes = plt.subplots(1, 3, figsize=(18, 6))\n",
257
+ "axes = axes.flatten()\n",
258
+ "features = X.columns\n",
259
+ "\n",
260
+ "for i, (model_name, imp) in enumerate(importances.items()):\n",
261
+ " # Sort features by importance for a cleaner plot\n",
262
+ " sorted_idx = np.argsort(imp)\n",
263
+ "\n",
264
+ " ax = axes[i]\n",
265
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
266
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
267
+ " ax.set_xlabel(\"Importance Score\")\n",
268
+ "\n",
269
+ "plt.tight_layout()\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
+ "print(importances)"
281
+ ],
282
+ "execution_count": null,
283
+ "outputs": []
284
+ },
285
+ {
286
+ "cell_type": "code",
287
+ "metadata": {},
288
+ "source": [
289
+ "# Task Bonus: Write your code here:"
290
+ ],
291
+ "execution_count": null,
292
+ "outputs": []
293
+ }
294
+ ],
295
+ "metadata": {
296
+ "kernelspec": {
297
+ "display_name": "Python 3",
298
+ "name": "python3"
299
+ },
300
+ "language_info": {
301
+ "name": "python"
302
+ }
303
+ },
304
+ "nbformat": 4,
305
+ "nbformat_minor": 0
306
+ }
submissions_extracted/23/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 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
+ "# Download latest version\n",
15
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "csv_path = os.path.join(path, \"Q1_data.csv\")\n",
28
+ "\n",
29
+ "df = pd.read_csv(csv_path)\n",
30
+ "df.head()"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "# Task 2: Write your code here:\n",
40
+ "df.head()"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 3: Write your code here:\n",
50
+ "df.info()"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 4: Write your code here:\n",
60
+ "df.describe()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 5: Write your code here:\n",
70
+ "def check_target_distribution(df, target_column):\n",
71
+ " df[target_column].hist(bins=30, edgecolor='black')\n",
72
+ "\n",
73
+ " plt.title(f\"Target Distribution ({target_column})\")\n",
74
+ " plt.xlabel(target_column)\n",
75
+ " plt.ylabel(\"Frequency\")\n",
76
+ " plt.grid(False)\n",
77
+ "\n",
78
+ " plt.show()\n",
79
+ "\n",
80
+ "check_target_distribution(df, \"delivery_time\")"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 1: Write your code here:\n",
90
+ "df = df.drop(columns=\"Unnamed: 0\", axis=1)"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# Task 2: Write your code here:\n",
100
+ "def check_missing_values(df):\n",
101
+ " missing_values = df.isnull().sum()\n",
102
+ " print(\"Missing Values per Column:\")\n",
103
+ " print(missing_values[missing_values > 0])\n",
104
+ " if missing_values.any():\n",
105
+ " print(\"\\nHandle Missing.\")\n",
106
+ " else:\n",
107
+ " print(\"\\nNo Missing.\")\n",
108
+ "\n",
109
+ "check_missing_values(df)"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# Task 3: Write your code here:\n",
119
+ "def check_duplicates(df):\n",
120
+ " duplicates = df.duplicated().sum()\n",
121
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
122
+ " if duplicates > 0:\n",
123
+ " print(\"Dropping Duplicates...\")\n",
124
+ " df.drop_duplicates(inplace=True)\n",
125
+ " print(\"Duplicates Dropped.\")\n",
126
+ " else:\n",
127
+ " print(\"No Duplicate Samples Found.\")\n",
128
+ "\n",
129
+ "check_duplicates(df)"
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
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
140
+ "\n",
141
+ "print(\"Categorical Columns:\", list(categorical_cols))"
142
+ ],
143
+ "execution_count": null,
144
+ "outputs": []
145
+ },
146
+ {
147
+ "cell_type": "code",
148
+ "metadata": {},
149
+ "source": [
150
+ "# Task 5: Write your code here:\n",
151
+ "from sklearn.preprocessing import MinMaxScaler\n",
152
+ "\n",
153
+ "features = df.columns.drop(\"Order_ID\")\n",
154
+ "\n",
155
+ "scaler = MinMaxScaler()\n",
156
+ "df[features] = scaler.fit_transform(df[features])\n",
157
+ "df.head()"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "# Task 6: Write your code here:"
167
+ ],
168
+ "execution_count": null,
169
+ "outputs": []
170
+ },
171
+ {
172
+ "cell_type": "code",
173
+ "metadata": {},
174
+ "source": [
175
+ "# Task 1: Write your code here:\n",
176
+ "X = df.drop(\"Order_ID\", axis=1).astype(int)\n",
177
+ "y = df['Order_ID'].astype(int)"
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
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
189
+ "\n",
190
+ "n_kfold = 5\n",
191
+ "\n",
192
+ "kf = KFold(n_splits=n_kfold, shuffle=True, random_state=42)\n",
193
+ "\n",
194
+ "lr_losses = []\n",
195
+ "lr_mse = []\n",
196
+ "lr_rmse = []\n",
197
+ "lr_r2 = []"
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/23/Q2.ipynb ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "x_tarin_tensor = torch.tensor(X_train)\n",
71
+ "x_test_tensor = torch.tensor(X_test)\n",
72
+ "y_tarin_tensor = torch.tensor(y_train)\n",
73
+ "y_test_tensor = torch.tensor(y_test)\n",
74
+ "\n",
75
+ "\n"
76
+ ],
77
+ "execution_count": null,
78
+ "outputs": []
79
+ },
80
+ {
81
+ "cell_type": "code",
82
+ "metadata": {},
83
+ "source": [
84
+ "# 2. Create TensorDataset objects\n",
85
+ "train_dataset = TensorDataset(X_train, y_train)\n",
86
+ "test_dataset = TensorDataset(X_test, y_test)\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
+ "from torch.utils.data import DataLoader\n",
98
+ "\n",
99
+ "train_loader = DataLoader(\n",
100
+ " train_dataset,\n",
101
+ " batch_size=32,\n",
102
+ " shuffle=True,\n",
103
+ " num_workers=2\n",
104
+ ")\n",
105
+ "\n",
106
+ "test_loader = DataLoader(\n",
107
+ " test_dataset,\n",
108
+ " batch_size=32,\n",
109
+ " shuffle=False,\n",
110
+ " num_workers=2\n",
111
+ ")\n",
112
+ "\n",
113
+ "\n",
114
+ "\n"
115
+ ],
116
+ "execution_count": null,
117
+ "outputs": []
118
+ },
119
+ {
120
+ "cell_type": "code",
121
+ "metadata": {},
122
+ "source": [
123
+ "# 4. Print shape of one batch\n",
124
+ "X_batch, y_batch = next(iter(train_loader))\n",
125
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
126
+ "print(f\"Training batch labels shape: {y_batch.shape}\")\n"
127
+ ],
128
+ "execution_count": null,
129
+ "outputs": []
130
+ },
131
+ {
132
+ "cell_type": "code",
133
+ "metadata": {},
134
+ "source": [
135
+ "# 5. Display sample images\n",
136
+ "\n"
137
+ ],
138
+ "execution_count": null,
139
+ "outputs": []
140
+ },
141
+ {
142
+ "cell_type": "code",
143
+ "metadata": {},
144
+ "source": [
145
+ "# Task 1: Write your model class here:"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 2: Write your training loop here:"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 3: Write your validation loop here:"
164
+ ],
165
+ "execution_count": null,
166
+ "outputs": []
167
+ },
168
+ {
169
+ "cell_type": "code",
170
+ "metadata": {},
171
+ "source": [
172
+ "# Task 4: Define device, model, loss, optimizer:"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 5: Start training for 20 epochs:"
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 (Bonus): Write your code here:"
200
+ ],
201
+ "execution_count": null,
202
+ "outputs": []
203
+ }
204
+ ],
205
+ "metadata": {
206
+ "kernelspec": {
207
+ "display_name": "Python 3",
208
+ "name": "python3"
209
+ },
210
+ "language_info": {
211
+ "name": "python"
212
+ }
213
+ },
214
+ "nbformat": 4,
215
+ "nbformat_minor": 0
216
+ }
submissions_extracted/23/Q3.ipynb ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:"
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
+ }
submissions_extracted/230/Q1.ipynb ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import os\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
11
+ "from sklearn.model_selection import train_test_split, KFold\n",
12
+ "import numpy as np\n",
13
+ "from sklearn.model_selection import train_test_split\n",
14
+ "from sklearn.ensemble import RandomForestRegressor\n",
15
+ "from sklearn.model_selection import StratifiedKFold\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\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
+ "# Download latest version\n",
28
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-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
+ "csv_file_path = os.path.join(path, '/kaggle/input/q1-exam-data/Q1_data.csv')\n",
40
+ "\n",
41
+ "df = pd.read_csv(csv_file_path)\n",
42
+ "\n",
43
+ "print(f\"Dataset downloaded to: {path}\")\n",
44
+ "print(f\"CSV file loaded from: {csv_file_path}\")\n",
45
+ "df.head()"
46
+ ],
47
+ "execution_count": null,
48
+ "outputs": []
49
+ },
50
+ {
51
+ "cell_type": "code",
52
+ "metadata": {},
53
+ "source": [
54
+ "df.head()"
55
+ ],
56
+ "execution_count": null,
57
+ "outputs": []
58
+ },
59
+ {
60
+ "cell_type": "code",
61
+ "metadata": {},
62
+ "source": [
63
+ "df.info()"
64
+ ],
65
+ "execution_count": null,
66
+ "outputs": []
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "metadata": {},
71
+ "source": [
72
+ "df.describe()"
73
+ ],
74
+ "execution_count": null,
75
+ "outputs": []
76
+ },
77
+ {
78
+ "cell_type": "code",
79
+ "metadata": {},
80
+ "source": [
81
+ "plt.figure(figsize=(10, 5))\n",
82
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
83
+ "plt.title('the target distribution')\n",
84
+ "plt.show()"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "df.drop(columns=['Order_ID'])"
94
+ ],
95
+ "execution_count": null,
96
+ "outputs": []
97
+ },
98
+ {
99
+ "cell_type": "code",
100
+ "metadata": {},
101
+ "source": [
102
+ "# Analyze missing values\n",
103
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
104
+ "missing_data = pd.DataFrame({\n",
105
+ " 'Column': missing_percentage.index,\n",
106
+ " 'Missing_Percentage': missing_percentage.values})\n",
107
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
108
+ "\n",
109
+ "print(\"Missing Data Analysis:\")\n",
110
+ "missing_data.head(10)"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "def check_duplicates(df):\n",
120
+ " duplicates = df.duplicated().sum()\n",
121
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
122
+ " if duplicates > 0:\n",
123
+ " print(\"Dropping Duplicates...\")\n",
124
+ " df.drop_duplicates(inplace=True)\n",
125
+ " print(\"Duplicates Dropped.\")\n",
126
+ " else:\n",
127
+ " print(\"No Duplicate Samples Found.\")\n",
128
+ "\n",
129
+ "check_duplicates(df)"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
139
+ "\n",
140
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
141
+ "\n",
142
+ "categorical_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
143
+ "for col in categorical_cols:\n",
144
+ " le = LabelEncoder()\n",
145
+ " df[col] = le.fit_transform(df[col].astype(str))\n",
146
+ "\n",
147
+ "df.head()"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "feature_cols = ['Weather', 'Traffic_Level', 'Time_of_Day', 'Vehicle_Type']\n",
157
+ "X = df[feature_cols]\n",
158
+ "y = df['Delivery_Time']\n",
159
+ "\n",
160
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
161
+ "print(f\"Train: {X_train.shape}, Test: {X_test.shape}\")\n",
162
+ "scaler = StandardScaler()\n",
163
+ "X_train_scaled = scaler.fit_transform(X_train)\n",
164
+ "X_test_scaled = scaler.transform(X_test)\n",
165
+ "\n",
166
+ "print(f\"\\nScaled ranges - Min: {X_train_scaled.min():.2f}, Max: {X_train_scaled.max():.2f}\")\n",
167
+ "pd.DataFrame(X_train_scaled, columns=X_train.columns).head(3)"
168
+ ],
169
+ "execution_count": null,
170
+ "outputs": []
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "metadata": {},
175
+ "source": [
176
+ "# Task 6: Write your code here:"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "np.random.seed(42)\n",
186
+ "\n",
187
+ "X_reg = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n",
188
+ "y_reg = 3 * X_reg[\"Feature_1\"] + np.random.randn(500) * 0.5\n",
189
+ "X_clf = pd.DataFrame({\"Feature_1\": np.random.randn(500)})\n",
190
+ "y_clf = (X_clf[\"Feature_1\"] > 0).astype(int)\n",
191
+ "\n",
192
+ "X, y = X_clf.copy(), y_clf.copy()\n",
193
+ "\n",
194
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
195
+ " X, y,\n",
196
+ " test_size=0.2,\n",
197
+ " random_state=42,\n",
198
+ " shuffle=True,\n",
199
+ " stratify=y)\n",
200
+ "\n",
201
+ "print(\"X_train shape:\", X_train.shape)\n",
202
+ "print(\"X_test shape:\", X_test.shape)\n",
203
+ "print(\"y_train shape:\", y_train.shape)\n",
204
+ "print(\"y_test shape:\", y_test.shape)\n",
205
+ "\n",
206
+ "\n",
207
+ "X, y = X_clf.copy(), y_clf.copy()\n",
208
+ "\n",
209
+ "full_ratio = (y.value_counts(normalize=True) * 100).sort_index()\n",
210
+ "print(\"Full Dataset Class Distribution\")\n",
211
+ "print(\" y class percentages:\", {k: f\"{v:.2f}%\" for k, v in full_ratio.items()})\n",
212
+ "print(\"---------------------------------------------------\")\n",
213
+ "\n",
214
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
215
+ "\n",
216
+ "print(\"Stratified K-Fold Cross Validation\\n\" + \"-\"*40)\n",
217
+ "\n",
218
+ "for fold, (train_idx, test_idx) in enumerate(skf.split(X, y), start=1):\n",
219
+ " # indexing for each fold\n",
220
+ " X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]\n",
221
+ " y_train, y_test = y.iloc[train_idx], y.iloc[test_idx]\n",
222
+ " print(f\"Fold {fold}\")\n",
223
+ " print(\" X_train shape:\", X_train.shape)\n",
224
+ " print(\" X_test shape :\", X_test.shape)\n",
225
+ " print(\" y_train shape:\", y_train.shape)\n",
226
+ " print(\" y_test shape :\", y_test.shape)\n",
227
+ " train_ratio = (y_train.value_counts(normalize=True) * 100).sort_index()\n",
228
+ " test_ratio = (y_test.value_counts(normalize=True) * 100).sort_index()\n",
229
+ "\n",
230
+ " print(\" y_train class percentages:\", {k: f\"{v:.2f}%\" for k, v in train_ratio.items()})\n",
231
+ " print(\" y_test class percentages :\", {k: f\"{v:.2f}%\" for k, v in test_ratio.items()})\n",
232
+ "\n",
233
+ " print(\"--------------------------------------\")"
234
+ ],
235
+ "execution_count": null,
236
+ "outputs": []
237
+ },
238
+ {
239
+ "cell_type": "code",
240
+ "metadata": {},
241
+ "source": [
242
+ "\n",
243
+ "model = RandomForestRegressor(n_estimators=100, max_depth=20, random_state=42, n_jobs=1)\n",
244
+ "model.fit(X_train_scaled, y_train)\n",
245
+ "print(\"Model trained!\")\n",
246
+ "\n",
247
+ "y_pred = model.predict(X_test_scaled)\n",
248
+ "\n",
249
+ "mae = mean_absolute_error(y_test, y_pred)\n",
250
+ "rmse = np.sqrt(mean_squared_error(y_test, y_pred))\n",
251
+ "\n",
252
+ "print(f\"MAE: ${mae:,.2f}\")\n",
253
+ "print(f\"RMSE: ${rmse:,.2f}\")\n",
254
+ "\n",
255
+ "kfold = KFold(n_splits=5, shuffle=True, random_state=42)\n",
256
+ "\n",
257
+ "mae_scores = []\n",
258
+ "rmse_scores = []\n",
259
+ "\n",
260
+ "for train_idx, val_idx in kfold.split(X_train_scaled):\n",
261
+ " X_fold_train, X_fold_val = X_train_scaled[train_idx], X_train_scaled[val_idx]\n",
262
+ " y_fold_train, y_fold_val = y_train.iloc[train_idx], y_train.iloc[val_idx]\n",
263
+ "\n",
264
+ " model.fit(X_fold_train, y_fold_train)\n",
265
+ " y_fold_pred = model.predict(X_fold_val)\n",
266
+ "\n",
267
+ " mae_scores.append(mean_absolute_error(y_fold_val, y_fold_pred))\n",
268
+ " rmse_scores.append(np.sqrt(mean_squared_error(y_fold_val, y_fold_pred)))\n",
269
+ "\n",
270
+ "mae_scores = np.array(mae_scores)\n",
271
+ "rmse_scores = np.array(rmse_scores)\n",
272
+ "\n",
273
+ "print(f\"5-Fold CV Results:\")\n",
274
+ "print(f\"MAE: ${mae_scores.mean():,.2f}\")\n",
275
+ "print(f\"RMSE: ${rmse_scores.mean():,.2f}\")"
276
+ ],
277
+ "execution_count": null,
278
+ "outputs": []
279
+ },
280
+ {
281
+ "cell_type": "code",
282
+ "metadata": {},
283
+ "source": [
284
+ "feature_importance = pd.DataFrame({\n",
285
+ " 'feature': feature_cols,\n",
286
+ " 'importance': model.feature_importances_\n",
287
+ "}).sort_values('importance', ascending=False)\n",
288
+ "\n",
289
+ "plt.figure(figsize=(10, 6))\n",
290
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
291
+ "plt.xlabel('Importance')\n",
292
+ "plt.title('Feature Importance')\n",
293
+ "plt.gca().invert_yaxis()\n",
294
+ "plt.show()"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "plt.figure(figsize=(6, 4))\n",
304
+ "plt.scatter(y_test, y_pred, alpha=0.6)\n",
305
+ "plt.plot(\n",
306
+ " [y_test.min(), y_test.max()],\n",
307
+ " [y_test.min(), y_test.max()],\n",
308
+ " \"r--\",\n",
309
+ " linewidth=2)\n",
310
+ "\n",
311
+ "plt.xlabel(\"Actual Exam Scores (Ground Truth)\")\n",
312
+ "plt.ylabel(\"Predicted Exam Scores\")\n",
313
+ "plt.title(\"Linear Regression: Predictions vs Ground Truth\")\n",
314
+ "plt.grid(True)\n",
315
+ "\n",
316
+ "plt.tight_layout()\n",
317
+ "plt.show()\n"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "# Task Bonus: Write your code here:"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ }
331
+ ],
332
+ "metadata": {
333
+ "kernelspec": {
334
+ "display_name": "Python 3",
335
+ "name": "python3"
336
+ },
337
+ "language_info": {
338
+ "name": "python"
339
+ }
340
+ },
341
+ "nbformat": 4,
342
+ "nbformat_minor": 0
343
+ }
submissions_extracted/230/Q2.ipynb ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import kagglehub\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "import torch\n",
25
+ "import torch.nn as nn\n",
26
+ "from torch.optim import AdamW\n",
27
+ "import matplotlib.pyplot as plt\n",
28
+ "from torch.utils.data import DataLoader, TensorDataset\n",
29
+ "from sklearn.model_selection import train_test_split\n",
30
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
31
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\n",
32
+ "\n",
33
+ "# Load Labels\n",
34
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
35
+ "img_dir = os.path.join(path, \"images\")\n",
36
+ "\n",
37
+ "images = []\n",
38
+ "ages = []\n",
39
+ "\n",
40
+ "# Load Images and Resize\n",
41
+ "print(\"Loading images...\")\n",
42
+ "for index, row in labels_df.iterrows():\n",
43
+ " img_name = row.iloc[0]\n",
44
+ " age = row.iloc[1]\n",
45
+ " img_path = os.path.join(img_dir, img_name)\n",
46
+ "\n",
47
+ " if os.path.exists(img_path):\n",
48
+ " img = Image.open(img_path).convert('RGB')\n",
49
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
50
+ " images.append(img_array)\n",
51
+ " ages.append(age)\n",
52
+ "\n",
53
+ "X = np.array(images)\n",
54
+ "y = np.array(ages)\n",
55
+ "\n",
56
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
57
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
58
+ "\n",
59
+ "# Split Data\n",
60
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
61
+ "\n",
62
+ "print(f\"X_train shape: {X_train.shape}\")\n",
63
+ "print(f\"X_test shape: {X_test.shape}\")\n",
64
+ "print(f\"y_train shape: {y_train.shape}\")\n",
65
+ "print(f\"y_test shape: {y_test.shape}\")"
66
+ ],
67
+ "execution_count": null,
68
+ "outputs": []
69
+ },
70
+ {
71
+ "cell_type": "code",
72
+ "metadata": {},
73
+ "source": [
74
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
75
+ "data = load_breast_cancer()\n",
76
+ "X = data.data\n",
77
+ "y = data.target\n",
78
+ "\n",
79
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)\n",
80
+ "scaler = StandardScaler()\n",
81
+ "X_train = scaler.fit_transform(X_train)\n",
82
+ "X_test = scaler.transform(X_test)\n",
83
+ "\n",
84
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
85
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
86
+ "y_train = torch.tensor(y_train, dtype=torch.float32)\n",
87
+ "y_test = torch.tensor(y_test, dtype=torch.float32)"
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)"
99
+ ],
100
+ "execution_count": null,
101
+ "outputs": []
102
+ },
103
+ {
104
+ "cell_type": "code",
105
+ "metadata": {},
106
+ "source": [
107
+ "# 3. Create DataLoaders\n",
108
+ "train_loader = DataLoader(train_dataset,batch_size=32,shuffle=True,num_workers=2)\n",
109
+ "test_loader = DataLoader(test_dataset,batch_size=32,shuffle=False,num_workers=2)"
110
+ ],
111
+ "execution_count": null,
112
+ "outputs": []
113
+ },
114
+ {
115
+ "cell_type": "code",
116
+ "metadata": {},
117
+ "source": [
118
+ "# 4. Print shape of one batch\n",
119
+ "X_batch, y_batch = next(iter(train_loader))\n",
120
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
121
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# 5. Display sample images\n",
131
+ "\n",
132
+ "sample_image, sample_label = train_dataset[0]\n",
133
+ "print(f\"\\n Image shape: {sample_image.shape}\")\n",
134
+ "print(f\"Label: {sample_label}\")"
135
+ ],
136
+ "execution_count": null,
137
+ "outputs": []
138
+ },
139
+ {
140
+ "cell_type": "code",
141
+ "metadata": {},
142
+ "source": [
143
+ "class NN3Layer(nn.Module):\n",
144
+ " def __init__(self, input_dim, hidden_dim):\n",
145
+ " super(NN3Layer, self).__init__()\n",
146
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
147
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
148
+ " self.layer3 = nn.Linear(hidden_dim, 1)\n",
149
+ " self.relu = nn.ReLU()\n",
150
+ "\n",
151
+ "\n",
152
+ " def forward(self, x):\n",
153
+ " a1 = self.relu(self.layer1(x))\n",
154
+ "\n",
155
+ " a2 = self.relu(self.layer2(a1))\n",
156
+ " output = self.layer3(a2)\n",
157
+ " return output"
158
+ ],
159
+ "execution_count": null,
160
+ "outputs": []
161
+ },
162
+ {
163
+ "cell_type": "code",
164
+ "metadata": {},
165
+ "source": [
166
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
167
+ " model.train()\n",
168
+ " running_loss = 0.0\n",
169
+ " for X_batch, y_batch in train_loader:\n",
170
+ " X_batch = X_batch.to(device)\n",
171
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
172
+ "\n",
173
+ " outputs = model(X_batch)\n",
174
+ " loss = criterion(outputs, y_batch)\n",
175
+ " optimizer.zero_grad()\n",
176
+ " loss.backward()\n",
177
+ " optimizer.step()\n",
178
+ "\n",
179
+ " running_loss += loss.item()\n",
180
+ " avg_loss = running_loss / len(train_loader)\n",
181
+ "\n",
182
+ " return avg_loss"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "def validate(model, criterion, test_loader, device):\n",
192
+ " model.eval()\n",
193
+ " running_loss = 0.0\n",
194
+ "\n",
195
+ " with torch.no_grad():\n",
196
+ " for X_batch, y_batch in test_loader:\n",
197
+ "\n",
198
+ " X_batch = X_batch.to(device)\n",
199
+ " y_batch = y_batch.view(-1, 1).to(device)\n",
200
+ "\n",
201
+ " outputs = model(X_batch)\n",
202
+ " loss = criterion(outputs, y_batch)\n",
203
+ "\n",
204
+ " running_loss += loss.item()\n",
205
+ " avg_loss = running_loss / len(test_loader)\n",
206
+ "\n",
207
+ " return avg_loss"
208
+ ],
209
+ "execution_count": null,
210
+ "outputs": []
211
+ },
212
+ {
213
+ "cell_type": "code",
214
+ "metadata": {},
215
+ "source": [
216
+ "# Task 4: Define device, model, loss, optimizer:\n",
217
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
218
+ "input_dim = X_train.shape[1]\n",
219
+ "hidden_dim = 64\n",
220
+ "model = NN3Layer(input_dim, hidden_dim).to(device)\n",
221
+ "\n",
222
+ "print(\"Model Architecture:\\n\")\n",
223
+ "print(model)\n",
224
+ "learning_rate = 0.001\n",
225
+ "criterion = nn.MSELoss()\n",
226
+ "\n",
227
+ "optimizer = AdamW(model.parameters(), learning_rate)"
228
+ ],
229
+ "execution_count": null,
230
+ "outputs": []
231
+ },
232
+ {
233
+ "cell_type": "code",
234
+ "metadata": {},
235
+ "source": [
236
+ "num_epochs = 20\n",
237
+ "learning_rate = 0.001\n",
238
+ "train_losses = []\n",
239
+ "val_losses = []\n",
240
+ "\n",
241
+ "print('Starting Training...')\n",
242
+ "for epoch in range(num_epochs):\n",
243
+ "\n",
244
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
245
+ " val_loss = validate(model, criterion, test_loader, device)\n",
246
+ "\n",
247
+ " train_losses.append(train_loss)\n",
248
+ " val_losses.append(val_loss)\n",
249
+ "\n",
250
+ " if (epoch + 1) % 5 == 0:\n",
251
+ " print(\n",
252
+ " f'Epoch [{epoch+1}/{num_epochs}], '\n",
253
+ " f'Train Loss: {train_loss:.4f}, '\n",
254
+ " f'Val Loss: {val_loss:.4f}'\n",
255
+ " )\n",
256
+ "\n",
257
+ "print('Training Complete!')"
258
+ ],
259
+ "execution_count": null,
260
+ "outputs": []
261
+ },
262
+ {
263
+ "cell_type": "code",
264
+ "metadata": {},
265
+ "source": [
266
+ "# Plotting results\n",
267
+ "plt.figure(figsize=(7, 5))\n",
268
+ "\n",
269
+ "plt.plot(train_losses, label='Train Loss')\n",
270
+ "plt.plot(val_losses, label='Validation Loss')\n",
271
+ "plt.title('Loss over Epochs')\n",
272
+ "plt.xlabel('Epoch')\n",
273
+ "plt.ylabel('Loss (MSE)')\n",
274
+ "plt.legend()\n",
275
+ "\n",
276
+ "plt.tight_layout()\n",
277
+ "plt.show()"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task 2 (Bonus): Write your code here:\n",
287
+ "model.eval()\n",
288
+ "with torch.no_grad():\n",
289
+ " predictions = model(X_test.to(device)).cpu().numpy()\n",
290
+ "mae = mean_absolute_error(y_test.numpy(), predictions)\n",
291
+ "mse = mean_squared_error(y_test.numpy(), predictions)\n",
292
+ "rmse = np.sqrt(mse)\n",
293
+ "r2 = r2_score(y_test.numpy(), predictions)\n",
294
+ "\n",
295
+ "print(\"Model Evaluation\")\n",
296
+ "print(f\" MAE: ${mae:.2f}\")\n",
297
+ "print(f\" MSE: {mse:.2f}\")\n",
298
+ "print(f\" RMSE: ${rmse:.2f}\")\n",
299
+ "print(f\" R2: {r2:.4f}\")"
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/230/Q3.ipynb ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "%pip install catboost -q\n",
8
+ "import os\n",
9
+ "import pandas as pd\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
12
+ "from sklearn.model_selection import train_test_split, KFold\n",
13
+ "import numpy as np\n",
14
+ "from sklearn.model_selection import train_test_split\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.model_selection import StratifiedKFold\n",
17
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
18
+ "from sklearn.model_selection import StratifiedKFold\n",
19
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score"
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/q3-exam-data\")\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_file_path = os.path.join(path, '/kaggle/input/q3-exam-data/Q3_data.csv')\n",
43
+ "\n",
44
+ "df = pd.read_csv(csv_file_path)\n",
45
+ "\n",
46
+ "print(f\"Dataset downloaded to: {path}\")\n",
47
+ "print(f\"CSV file loaded from: {csv_file_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
+ "def check_missing_values(df):\n",
87
+ " missing_values = df.isnull().sum()\n",
88
+ "\n",
89
+ " print(\"Missing Values per Column:\")\n",
90
+ " print(missing_values[missing_values > 0])\n",
91
+ "\n",
92
+ " if missing_values.any():\n",
93
+ " print(\"\\nHandle Missing Values as needed.\")\n",
94
+ " else:\n",
95
+ " print(\"\\nNo Missing Values Found.\")\n",
96
+ "\n",
97
+ "check_missing_values(df)"
98
+ ],
99
+ "execution_count": null,
100
+ "outputs": []
101
+ },
102
+ {
103
+ "cell_type": "code",
104
+ "metadata": {},
105
+ "source": [
106
+ "# Task 2: Write your code here:\n",
107
+ "def check_duplicates(df):\n",
108
+ " duplicates = df.duplicated().sum()\n",
109
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
110
+ " if duplicates > 0:\n",
111
+ " print(\"Dropping Duplicates...\")\n",
112
+ " df.drop_duplicates(inplace=True)\n",
113
+ " print(\"Duplicates Dropped.\")\n",
114
+ " else:\n",
115
+ " print(\"No Duplicate Samples Found.\")\n",
116
+ "\n",
117
+ "check_duplicates(df)"
118
+ ],
119
+ "execution_count": null,
120
+ "outputs": []
121
+ },
122
+ {
123
+ "cell_type": "code",
124
+ "metadata": {},
125
+ "source": [
126
+ "# Task 3: Write your code here:\n",
127
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
128
+ "\n",
129
+ "print(\"Categorical Columns:\", list(categorical_cols))"
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
+ "from sklearn.preprocessing import StandardScaler\n",
140
+ "\n",
141
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"D_43\")\n",
142
+ "\n",
143
+ "scaler = StandardScaler()\n",
144
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
145
+ "df.head()"
146
+ ],
147
+ "execution_count": null,
148
+ "outputs": []
149
+ },
150
+ {
151
+ "cell_type": "code",
152
+ "metadata": {},
153
+ "source": [
154
+ "# Task 5: Write your code here:"
155
+ ],
156
+ "execution_count": null,
157
+ "outputs": []
158
+ },
159
+ {
160
+ "cell_type": "code",
161
+ "metadata": {},
162
+ "source": [
163
+ "# Task 1: Write your code here:\n",
164
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
165
+ "y = df['Target'].astype(float)"
166
+ ],
167
+ "execution_count": null,
168
+ "outputs": []
169
+ },
170
+ {
171
+ "cell_type": "code",
172
+ "metadata": {},
173
+ "source": [
174
+ "# Task 2,3,4,5: Write your code here:\n",
175
+ "from sklearn.model_selection import StratifiedKFold\n",
176
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
177
+ "from tqdm import tqdm\n",
178
+ "\n",
179
+ "def sigmoid(z):\n",
180
+ " return 1 / (1 + np.exp(-z))\n",
181
+ "\n",
182
+ "def binary_cross_entropy(y, y_hat):\n",
183
+ " epsilon = 1e-15\n",
184
+ " y_hat = np.clip(y_hat, epsilon, 1 - epsilon)\n",
185
+ "\n",
186
+ " loss = -1/len(y) * np.sum(y * np.log(y_hat) + (1 - y) * np.log(1 - y_hat))\n",
187
+ " return loss\n",
188
+ "\n",
189
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
190
+ " m, n = X.shape\n",
191
+ " theta = np.zeros(n)\n",
192
+ " losses = []\n",
193
+ "\n",
194
+ " for _ in tqdm(range(n_iters), desc=\"Training Logistic Regression\"):\n",
195
+ " z = np.dot(X, theta)\n",
196
+ " y_hat = sigmoid(z)\n",
197
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
198
+ " theta -= learning_rate * gradient\n",
199
+ "\n",
200
+ " loss = binary_cross_entropy(y, y_hat)\n",
201
+ " losses.append(loss)\n",
202
+ "\n",
203
+ " return theta, losses\n",
204
+ "\n",
205
+ "n_splits = 5\n",
206
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
207
+ "\n",
208
+ "lr_losses = []\n",
209
+ "lr_accuracy = []\n",
210
+ "lr_precision = []\n",
211
+ "lr_recall = []\n",
212
+ "lr_f1 = []\n",
213
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
214
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
215
+ "\n",
216
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
217
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
218
+ "\n",
219
+ " theta, losses = gradient_descent(X_train, y_train, learning_rate=0.5, n_iters=500)\n",
220
+ "\n",
221
+ " y_pred_proba = sigmoid(np.dot(X_test, theta))\n",
222
+ " y_pred = (y_pred_proba >= 0.5).astype(int)\n",
223
+ "\n",
224
+ "\n",
225
+ " accuracy = accuracy_score(y_test, y_pred)\n",
226
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
227
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
228
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
229
+ "\n",
230
+ "\n",
231
+ " lr_losses.append(losses)\n",
232
+ " lr_accuracy.append(accuracy)\n",
233
+ " lr_precision.append(precision)\n",
234
+ " lr_recall.append(recall)\n",
235
+ " lr_f1.append(f1)"
236
+ ],
237
+ "execution_count": null,
238
+ "outputs": []
239
+ },
240
+ {
241
+ "cell_type": "code",
242
+ "metadata": {},
243
+ "source": [
244
+ "avg_loss = np.mean(lr_losses, axis=0)\n",
245
+ "\n",
246
+ "plt.figure(figsize=(10, 6))\n",
247
+ "plt.plot(avg_loss, label='Logistic Regression Loss', color='purple')\n",
248
+ "plt.title('Average Logistic Regression Loss Curve (Across 5 Folds)')\n",
249
+ "plt.xlabel('Iteration')\n",
250
+ "plt.ylabel('Binary Cross-Entropy Loss')\n",
251
+ "plt.legend()\n",
252
+ "plt.grid(True, alpha=0.3)\n",
253
+ "plt.show()"
254
+ ],
255
+ "execution_count": null,
256
+ "outputs": []
257
+ },
258
+ {
259
+ "cell_type": "code",
260
+ "metadata": {},
261
+ "source": [
262
+ "# Task 1: Write your code here:\n",
263
+ "feature_importance = pd.DataFrame({\n",
264
+ " 'feature': feature,\n",
265
+ " 'importance': model.feature_importances_}).sort_values('importance', ascending=False)\n",
266
+ "\n",
267
+ "plt.figure(figsize=(10, 6))\n",
268
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
269
+ "plt.xlabel('Importance')\n",
270
+ "plt.title('Feature Importance')\n",
271
+ "plt.gca().invert_yaxis()\n",
272
+ "plt.show()"
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# Task 2: Write your code here:"
282
+ ],
283
+ "execution_count": null,
284
+ "outputs": []
285
+ },
286
+ {
287
+ "cell_type": "code",
288
+ "metadata": {},
289
+ "source": [
290
+ "# Task Bonus: Write your code here:"
291
+ ],
292
+ "execution_count": null,
293
+ "outputs": []
294
+ }
295
+ ],
296
+ "metadata": {
297
+ "kernelspec": {
298
+ "display_name": "Python 3",
299
+ "name": "python3"
300
+ },
301
+ "language_info": {
302
+ "name": "python"
303
+ }
304
+ },
305
+ "nbformat": 4,
306
+ "nbformat_minor": 0
307
+ }
submissions_extracted/231/Q1.ipynb ADDED
@@ -0,0 +1,303 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ "# imports\n",
22
+ "import os\n",
23
+ "import pandas as pd\n",
24
+ "import matplotlib.pyplot as plt\n",
25
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
26
+ "from sklearn.model_selection import StratifiedKFold, train_test_split\n",
27
+ "from sklearn.ensemble import RandomForestClassifier\n",
28
+ "from sklearn.metrics import mean_absolute_error\n",
29
+ "import numpy as np\n",
30
+ "\n"
31
+ ],
32
+ "execution_count": null,
33
+ "outputs": []
34
+ },
35
+ {
36
+ "cell_type": "code",
37
+ "metadata": {},
38
+ "source": [
39
+ "df = pd.read_csv('/kaggle/input/q1-exam-data/Q1_data.csv')"
40
+ ],
41
+ "execution_count": null,
42
+ "outputs": []
43
+ },
44
+ {
45
+ "cell_type": "code",
46
+ "metadata": {},
47
+ "source": [
48
+ "df.head()"
49
+ ],
50
+ "execution_count": null,
51
+ "outputs": []
52
+ },
53
+ {
54
+ "cell_type": "code",
55
+ "metadata": {},
56
+ "source": [
57
+ "df.info()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "df.describe()"
67
+ ],
68
+ "execution_count": null,
69
+ "outputs": []
70
+ },
71
+ {
72
+ "cell_type": "code",
73
+ "metadata": {},
74
+ "source": [
75
+ "plt.figure(figsize=(10, 5))\n",
76
+ "plt.hist(df['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
77
+ "plt.title('Target Distribution')\n",
78
+ "plt.xlabel('Delievery Time')\n",
79
+ "plt.ylabel('Frequency')\n",
80
+ "plt.show()"
81
+ ],
82
+ "execution_count": null,
83
+ "outputs": []
84
+ },
85
+ {
86
+ "cell_type": "code",
87
+ "metadata": {},
88
+ "source": [
89
+ "# Task 1: Write df code here:\n",
90
+ "df = df.drop(\"Order_ID\", axis = 1)"
91
+ ],
92
+ "execution_count": null,
93
+ "outputs": []
94
+ },
95
+ {
96
+ "cell_type": "code",
97
+ "metadata": {},
98
+ "source": [
99
+ "# Task 2: Write your code here:\n",
100
+ "\n",
101
+ "# Since missing samples are relatively not that much, im gonna drop them\n",
102
+ "\n",
103
+ "df = df.dropna()"
104
+ ],
105
+ "execution_count": null,
106
+ "outputs": []
107
+ },
108
+ {
109
+ "cell_type": "code",
110
+ "metadata": {},
111
+ "source": [
112
+ "# Task 3: Write your code here:\n",
113
+ "\n",
114
+ "def check_duplicates(df):\n",
115
+ " duplicates = df.duplicated().sum()\n",
116
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
117
+ " if duplicates > 0:\n",
118
+ " print(\"Dropping Duplicates...\")\n",
119
+ " df.drop_duplicates(inplace=True)\n",
120
+ " print(\"Duplicates Dropped.\")\n",
121
+ " else:\n",
122
+ " print(\"No Duplicate Samples Found.\")\n",
123
+ "check_duplicates(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
+ "\n",
134
+ "categorical_cols = [\"Weather\", \"Traffic_Level\", \"Time_of_Day\", \"Vehicle_Type\"]\n",
135
+ "\n",
136
+ "for col in categorical_cols:\n",
137
+ " le = LabelEncoder()\n",
138
+ " df[col] = le.fit_transform(df[col])"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "df.info()"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 5: Write your code here:\n",
157
+ "\n",
158
+ "scaler = StandardScaler()\n",
159
+ "\n",
160
+ "# i will not be scaling cols that have been encoded and the target varible\n",
161
+ "cols_no_target_or_encoded = [\"Distance_km\", \"Preparation_Time_min\", \"Courier_Experience_yrs\" ]\n",
162
+ "\n",
163
+ "\n",
164
+ "df[cols_no_target_or_encoded] = scaler.fit_transform(df[cols_no_target_or_encoded])"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 6: Write your code here:\n",
174
+ "\n",
175
+ "plt.figure(figsize=(10, 5))\n",
176
+ "plt.hist(df[\"Delivery_Time\"].value_counts(), bins=50, edgecolor='black')\n",
177
+ "plt.title('Distribution')\n",
178
+ "plt.xlabel('Delievery Time')\n",
179
+ "plt.ylabel('Frequency')\n",
180
+ "plt.show()\n",
181
+ "\n",
182
+ "# there is an imbalance so doing stratified sampling here would be much better"
183
+ ],
184
+ "execution_count": null,
185
+ "outputs": []
186
+ },
187
+ {
188
+ "cell_type": "code",
189
+ "metadata": {},
190
+ "source": [
191
+ "X = df.drop(\"Delivery_Time\", axis=1).copy()\n",
192
+ "y = df[\"Delivery_Time\"]\n",
193
+ "\n"
194
+ ],
195
+ "execution_count": null,
196
+ "outputs": []
197
+ },
198
+ {
199
+ "cell_type": "code",
200
+ "metadata": {},
201
+ "source": [
202
+ "# Task 2,3,4,5: Write your code here:\n",
203
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
204
+ " X, y,\n",
205
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
206
+ " random_state=42, # reproducible output\n",
207
+ " shuffle=True, # representative splits\n",
208
+ ")\n",
209
+ "skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n",
210
+ "\n",
211
+ "\n",
212
+ "model = RandomForestClassifier(\n",
213
+ " n_estimators=200,\n",
214
+ " max_depth=10\n",
215
+ " )\n",
216
+ "mae = []\n",
217
+ "mae_sum = 0\n",
218
+ "y_preds = []\n",
219
+ "\n",
220
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
221
+ " print(f\"\\nFold {fold_idx + 1}/{5}\")\n",
222
+ "\n",
223
+ " # 1. Split data\n",
224
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
225
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
226
+ "\n",
227
+ " # 2. Train & Validate sklearn models\n",
228
+ " model.fit(X_train, y_train) # train\n",
229
+ " y_pred = model.predict(X_test) # validate\n",
230
+ " mae_sum+=mean_absolute_error(y_test, y_pred)\n",
231
+ " y_preds.append(y_pred)\n",
232
+ "\n",
233
+ "\n",
234
+ "\n",
235
+ "\n",
236
+ "print(\"MAE:\", mae_sum)\n",
237
+ "print(\"avg MAE:\", mae_sum/5)\n",
238
+ "\n"
239
+ ],
240
+ "execution_count": null,
241
+ "outputs": []
242
+ },
243
+ {
244
+ "cell_type": "code",
245
+ "metadata": {},
246
+ "source": [
247
+ "model.feature_importances_"
248
+ ],
249
+ "execution_count": null,
250
+ "outputs": []
251
+ },
252
+ {
253
+ "cell_type": "code",
254
+ "metadata": {},
255
+ "source": [
256
+ "feature_importance = pd.DataFrame({\n",
257
+ " 'feature': X.columns,\n",
258
+ " 'importance': model.feature_importances_\n",
259
+ "}).sort_values('importance', ascending=False)\n",
260
+ "\n",
261
+ "plt.figure(figsize=(10, 6))\n",
262
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
263
+ "plt.xlabel('Importance')\n",
264
+ "plt.title('Feature Importance')\n",
265
+ "plt.gca().invert_yaxis()\n",
266
+ "plt.show()"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "# Task 2: Write your code here:\n",
276
+ "plt.hist(y_preds)\n",
277
+ "plt.show()"
278
+ ],
279
+ "execution_count": null,
280
+ "outputs": []
281
+ },
282
+ {
283
+ "cell_type": "code",
284
+ "metadata": {},
285
+ "source": [
286
+ "# Task Bonus: Write your code here:\n"
287
+ ],
288
+ "execution_count": null,
289
+ "outputs": []
290
+ }
291
+ ],
292
+ "metadata": {
293
+ "kernelspec": {
294
+ "display_name": "Python 3",
295
+ "name": "python3"
296
+ },
297
+ "language_info": {
298
+ "name": "python"
299
+ }
300
+ },
301
+ "nbformat": 4,
302
+ "nbformat_minor": 0
303
+ }
submissions_extracted/231/Q2.ipynb ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import torch\n",
8
+ "from torch.utils.data import TensorDataset\n",
9
+ "from torch.utils.data import DataLoader, TensorDataset\n",
10
+ "import matplotlib.pyplot as plt\n",
11
+ "import kagglehub\n",
12
+ "import pandas as pd\n",
13
+ "import torch\n",
14
+ "import torch.nn as nn\n",
15
+ "from torch.optim import AdamW\n",
16
+ "import matplotlib.pyplot as plt\n",
17
+ "import torch.nn.functional as F\n",
18
+ "from torch.utils.data import DataLoader, TensorDataset\n",
19
+ "from sklearn.model_selection import train_test_split\n",
20
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
21
+ "import pandas as pd"
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/q2-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
+ "import os\n",
45
+ "import pandas as pd\n",
46
+ "import numpy as np\n",
47
+ "from PIL import Image\n",
48
+ "from sklearn.model_selection import train_test_split\n",
49
+ "\n",
50
+ "# Load Labels\n",
51
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
52
+ "img_dir = os.path.join(path, \"images\")\n",
53
+ "\n",
54
+ "images = []\n",
55
+ "ages = []\n",
56
+ "\n",
57
+ "# Load Images and Resize\n",
58
+ "print(\"Loading images...\")\n",
59
+ "for index, row in labels_df.iterrows():\n",
60
+ " img_name = row.iloc[0]\n",
61
+ " age = row.iloc[1]\n",
62
+ " img_path = os.path.join(img_dir, img_name)\n",
63
+ "\n",
64
+ " if os.path.exists(img_path):\n",
65
+ " img = Image.open(img_path).convert('RGB')\n",
66
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
67
+ " images.append(img_array)\n",
68
+ " ages.append(age)\n",
69
+ "\n",
70
+ "X = np.array(images)\n",
71
+ "y = np.array(ages)\n",
72
+ "\n",
73
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
74
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
75
+ "\n",
76
+ "# Split Data\n",
77
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
78
+ "\n",
79
+ "print(f\"X_train shape: {X_train.shape}\")\n",
80
+ "print(f\"X_test shape: {X_test.shape}\")\n",
81
+ "print(f\"y_train shape: {y_train.shape}\")\n",
82
+ "print(f\"y_test shape: {y_test.shape}\")"
83
+ ],
84
+ "execution_count": null,
85
+ "outputs": []
86
+ },
87
+ {
88
+ "cell_type": "code",
89
+ "metadata": {},
90
+ "source": [
91
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
92
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
93
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
94
+ "y_test = torch.tensor(y_test, dtype=torch.long)"
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
+ "train_dataset = TensorDataset(X_train, y_train)\n",
106
+ "test_dataset = TensorDataset(X_test, y_test)\n"
107
+ ],
108
+ "execution_count": null,
109
+ "outputs": []
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "metadata": {},
114
+ "source": [
115
+ "# 3. Create DataLoaders\n",
116
+ "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
+ "\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
+ "X_batch, y_batch = next(iter(train_loader))\n",
130
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
131
+ "print(f\"Training batch labels shape: {y_batch.shape}\")"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# 5. Display sample images\n",
141
+ "# Get one batch of images and labels\n",
142
+ "images, labels = next(iter(train_loader))\n",
143
+ "\n",
144
+ "# Display the first 6 images in the batch\n",
145
+ "plt.figure(figsize=(8, 4))\n",
146
+ "\n",
147
+ "for i in range(6):\n",
148
+ " plt.subplot(2, 3, i + 1)\n",
149
+ " # i put 36 here to match the dimension\n",
150
+ " plt.imshow(images[i].reshape(-1,36), 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
+ "\n",
166
+ "class NN4Layer(nn.Module):\n",
167
+ "\n",
168
+ " def __init__(self, input_dim, hidden_dim, output_dim):\n",
169
+ " super(NN4Layer, self).__init__()\n",
170
+ "\n",
171
+ " # First linear layer: input features -> hidden layer\n",
172
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
173
+ "\n",
174
+ " # Second linear layer: hidden layer -> hidden layer\n",
175
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
176
+ "\n",
177
+ " # Third linear layer: hidden layer -> hidden layer\n",
178
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
179
+ "\n",
180
+ " # Output layer: hidden layer -> number of classes (logits)\n",
181
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
182
+ "\n",
183
+ " # ReLU activation for non-linearity\n",
184
+ " self.relu = nn.ReLU()\n",
185
+ "\n",
186
+ " # Defines how input data flows through the network\n",
187
+ " def forward(self, x):\n",
188
+ " # First hidden layer\n",
189
+ " x = x.view(x.size(0), -1)\n",
190
+ " a1 = self.relu(self.layer1(x))\n",
191
+ "\n",
192
+ " # Second hidden layer\n",
193
+ " a2 = self.relu(self.layer2(a1))\n",
194
+ "\n",
195
+ " # Third hidden layer\n",
196
+ " a3 = self.relu(self.layer3(a2))\n",
197
+ "\n",
198
+ " # Output layer (raw scores / logits)\n",
199
+ " output = self.layer4(a3)\n",
200
+ "\n",
201
+ " return output"
202
+ ],
203
+ "execution_count": null,
204
+ "outputs": []
205
+ },
206
+ {
207
+ "cell_type": "code",
208
+ "metadata": {},
209
+ "source": [
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
+ "def validate(model, criterion, test_loader, device):\n",
246
+ " # Set the model to evaluation mode\n",
247
+ " model.eval()\n",
248
+ "\n",
249
+ " running_loss = 0.0\n",
250
+ " correct = 0\n",
251
+ " total = 0\n",
252
+ "\n",
253
+ " with torch.no_grad():\n",
254
+ " for X_batch, y_batch in test_loader:\n",
255
+ " # Move data to device\n",
256
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
257
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
258
+ "\n",
259
+ " # Forward pass\n",
260
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
261
+ " loss = criterion(outputs, y_batch)\n",
262
+ " running_loss += loss.item()\n",
263
+ "\n",
264
+ " # Apply Softmax to get probabilities\n",
265
+ " probabilities = F.softmax(outputs, dim=1)\n",
266
+ "\n",
267
+ " # Pick the classes with highest probabilities\n",
268
+ " predicted = torch.argmax(probabilities, dim=1)\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"
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
+ "# Device setup\n",
288
+ "\n",
289
+ "num_epochs = 20\n",
290
+ "learning_rate = 0.001\n",
291
+ "\n",
292
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
293
+ "criterion = nn.CrossEntropyLoss()\n",
294
+ "# Define optimizer\n",
295
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
296
+ "\n",
297
+ "# Model parameters\n",
298
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
299
+ "hidden_dim = 32 # Design choice\n",
300
+ "output_dim = 100\n",
301
+ "\n",
302
+ "# Instantiate model\n",
303
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
304
+ "optimizer = AdamW(model.parameters(), learning_rate)\n",
305
+ "\n",
306
+ "# Print the model architecture\n",
307
+ "print(\"Model Architecture:\\n\")\n",
308
+ "print(model)\n",
309
+ "\n",
310
+ "# Calculate the total number of trainable parameters\n",
311
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
312
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\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
+ "# Run Training\n",
323
+ "train_losses = []\n",
324
+ "val_losses = []\n",
325
+ "val_accuracies = []\n",
326
+ "\n",
327
+ "print('Starting Training...')\n",
328
+ "for epoch in range(num_epochs):\n",
329
+ " # Train one epoch\n",
330
+ " train_loss = train_one_epoch(model, optimizer, criterion, train_loader, device)\n",
331
+ "\n",
332
+ " # Validate\n",
333
+ " val_loss, val_accuracy = validate(model, criterion, test_loader, device)\n",
334
+ "\n",
335
+ " train_losses.append(train_loss)\n",
336
+ " val_losses.append(val_loss)\n",
337
+ " val_accuracies.append(val_accuracy)\n",
338
+ "\n",
339
+ " print(f'Epoch [{epoch+1}/{num_epochs}], Train Loss: {train_loss:.4f}, Val Loss: {val_loss:.4f}, Val Accuracy: {val_accuracy:.4f}')\n",
340
+ "\n",
341
+ "print('Training Complete!')"
342
+ ],
343
+ "execution_count": null,
344
+ "outputs": []
345
+ },
346
+ {
347
+ "cell_type": "code",
348
+ "metadata": {},
349
+ "source": [
350
+ "# Plotting results\n",
351
+ "plt.figure(figsize=(7, 5))\n",
352
+ "\n",
353
+ "plt.plot(train_losses, label='Train Loss')\n",
354
+ "plt.plot(val_losses, label='Validation Loss')\n",
355
+ "plt.title('Loss over Epochs')\n",
356
+ "plt.xlabel('Epoch')\n",
357
+ "plt.ylabel('Loss')\n",
358
+ "plt.legend()\n",
359
+ "\n",
360
+ "plt.tight_layout()\n",
361
+ "plt.show()"
362
+ ],
363
+ "execution_count": null,
364
+ "outputs": []
365
+ },
366
+ {
367
+ "cell_type": "code",
368
+ "metadata": {},
369
+ "source": [
370
+ "# Task 2 (Bonus): Write your code here:"
371
+ ],
372
+ "execution_count": null,
373
+ "outputs": []
374
+ }
375
+ ],
376
+ "metadata": {
377
+ "kernelspec": {
378
+ "display_name": "Python 3",
379
+ "name": "python3"
380
+ },
381
+ "language_info": {
382
+ "name": "python"
383
+ }
384
+ },
385
+ "nbformat": 4,
386
+ "nbformat_minor": 0
387
+ }
submissions_extracted/231/Q3.ipynb ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Import models\n",
8
+ "from sklearn.neighbors import KNeighborsClassifier\n",
9
+ "from sklearn.svm import SVC\n",
10
+ "from sklearn.tree import DecisionTreeClassifier\n",
11
+ "from sklearn.ensemble import RandomForestClassifier\n",
12
+ "from xgboost import XGBClassifier\n",
13
+ "from catboost import CatBoostClassifier\n",
14
+ "from sklearn.metrics import accuracy_score"
15
+ ],
16
+ "execution_count": null,
17
+ "outputs": []
18
+ },
19
+ {
20
+ "cell_type": "code",
21
+ "metadata": {},
22
+ "source": [
23
+ "!pip install catboost"
24
+ ],
25
+ "execution_count": null,
26
+ "outputs": []
27
+ },
28
+ {
29
+ "cell_type": "code",
30
+ "metadata": {},
31
+ "source": [
32
+ "import pandas as pd\n",
33
+ "# imports\n",
34
+ "import os\n",
35
+ "import pandas as pd\n",
36
+ "import matplotlib.pyplot as plt\n",
37
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
38
+ "from sklearn.model_selection import StratifiedKFold, train_test_split\n",
39
+ "from sklearn.ensemble import RandomForestClassifier\n",
40
+ "from sklearn.metrics import mean_absolute_error\n",
41
+ "import numpy as np\n",
42
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n"
43
+ ],
44
+ "execution_count": null,
45
+ "outputs": []
46
+ },
47
+ {
48
+ "cell_type": "code",
49
+ "metadata": {},
50
+ "source": [
51
+ "import kagglehub\n",
52
+ "\n",
53
+ "\n",
54
+ "\n",
55
+ "# Download latest version\n",
56
+ "\n",
57
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
58
+ "\n",
59
+ "\n",
60
+ "\n",
61
+ "print(\"Path to dataset files:\", path)"
62
+ ],
63
+ "execution_count": null,
64
+ "outputs": []
65
+ },
66
+ {
67
+ "cell_type": "code",
68
+ "metadata": {},
69
+ "source": [
70
+ "# Task 1: Write your code here:\n",
71
+ "df = pd.read_csv('/kaggle/input/q3-exam-data/Q3_data.csv')"
72
+ ],
73
+ "execution_count": null,
74
+ "outputs": []
75
+ },
76
+ {
77
+ "cell_type": "code",
78
+ "metadata": {},
79
+ "source": [
80
+ "# Task 2: Write your code here:\n",
81
+ "df.head()"
82
+ ],
83
+ "execution_count": null,
84
+ "outputs": []
85
+ },
86
+ {
87
+ "cell_type": "code",
88
+ "metadata": {},
89
+ "source": [
90
+ "# Task 3: Write your code here:\n",
91
+ "df.info()"
92
+ ],
93
+ "execution_count": null,
94
+ "outputs": []
95
+ },
96
+ {
97
+ "cell_type": "code",
98
+ "metadata": {},
99
+ "source": [
100
+ "df"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# Task 4: Write your code here:\n",
110
+ "df.describe()"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "df"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 3: Write your code here:\n",
129
+ "\n",
130
+ "def check_duplicates(df):\n",
131
+ " duplicates = df.duplicated().sum()\n",
132
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
133
+ " if duplicates > 0:\n",
134
+ " print(\"Dropping Duplicates...\")\n",
135
+ " df.drop_duplicates(inplace=True)\n",
136
+ " print(\"Duplicates Dropped.\")\n",
137
+ " else:\n",
138
+ " print(\"No Duplicate Samples Found.\")\n",
139
+ "check_duplicates(df)"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 3: Write your code here:\n",
149
+ "\n",
150
+ "\n",
151
+ "#encoding is needed for target only to use classifier later, i will do encoding after scaling so labels odnt get affected\n",
152
+ "\n"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 4: Write your code here:\n",
169
+ "\n",
170
+ "scaler = StandardScaler()\n",
171
+ "\n",
172
+ "# i will not be scaling cols that have been encoded and the target varible\n",
173
+ "\n",
174
+ "\n",
175
+ "df[df.columns] = scaler.fit_transform(df[df.columns])"
176
+ ],
177
+ "execution_count": null,
178
+ "outputs": []
179
+ },
180
+ {
181
+ "cell_type": "code",
182
+ "metadata": {},
183
+ "source": [
184
+ "le = LabelEncoder()\n",
185
+ "df[\"Target\"] = le.fit_transform(df[\"Target\"])"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "target_df = df[\"Target\"]"
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
+ "\n",
206
+ "plt.figure(figsize=(10, 5))\n",
207
+ "plt.hist(target_df, bins=50, edgecolor='black')\n",
208
+ "plt.title('Distribution')\n",
209
+ "plt.show()\n",
210
+ "\n",
211
+ "\n",
212
+ "# there is an imbalance so doing stratified sampling here would be much better"
213
+ ],
214
+ "execution_count": null,
215
+ "outputs": []
216
+ },
217
+ {
218
+ "cell_type": "code",
219
+ "metadata": {},
220
+ "source": [
221
+ "# Task 1: Write your code here:\n",
222
+ "X = df.drop(\"Target\", axis=1).copy()\n",
223
+ "y = df[\"Target\"]\n",
224
+ "\n"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "n_splits = 5 # K\n",
234
+ "acc_scores = []\n",
235
+ "accsum=0\n",
236
+ "model = CatBoostClassifier(\n",
237
+ " verbose=0,\n",
238
+ " n_estimators=320,\n",
239
+ " max_depth=4\n",
240
+ " )\n",
241
+ "\n",
242
+ "X_train, X_test, y_train, y_test = train_test_split(\n",
243
+ " X, y,\n",
244
+ " test_size=0.2, # 20% for test, remaining 80% for train\n",
245
+ " random_state=42, # reproducible output\n",
246
+ " shuffle=True, # representative splits\n",
247
+ ")\n",
248
+ "\n",
249
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
250
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
251
+ "\n",
252
+ "\n",
253
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
254
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
255
+ "\n",
256
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
257
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
258
+ " model.fit(X_train, y_train) # train\n",
259
+ " y_pred = model.predict(X_test) # validate\n",
260
+ " accuracy = accuracy_score(y_test, y_pred)\n",
261
+ " acc_scores.append(accuracy)\n",
262
+ " accsum+=accuracy\n",
263
+ "\n",
264
+ "\n",
265
+ "accuracy\n",
266
+ "print(accsum/5)"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "feature_importance = pd.DataFrame({\n",
276
+ " 'feature': X.columns,\n",
277
+ " 'importance': model.feature_importances_\n",
278
+ "}).sort_values('importance', ascending=False)\n",
279
+ "\n",
280
+ "plt.figure(figsize=(10, 6))\n",
281
+ "plt.barh(feature_importance['feature'], feature_importance['importance'])\n",
282
+ "plt.xlabel('Importance')\n",
283
+ "plt.title('Feature Importance')\n",
284
+ "plt.gca().invert_yaxis()\n",
285
+ "plt.show()"
286
+ ],
287
+ "execution_count": null,
288
+ "outputs": []
289
+ },
290
+ {
291
+ "cell_type": "code",
292
+ "metadata": {},
293
+ "source": [
294
+ "#printing\n",
295
+ "np.argsort(model.feature_importances_)"
296
+ ],
297
+ "execution_count": null,
298
+ "outputs": []
299
+ },
300
+ {
301
+ "cell_type": "code",
302
+ "metadata": {},
303
+ "source": [
304
+ "for i, (model, imp) in enumerate(importances.items()):\n",
305
+ " # Sort features by importance for a cleaner plot\n",
306
+ " sorted_idx = np.argsort(imp)\n",
307
+ "\n",
308
+ " ax = axes[i]\n",
309
+ " ax.barh(features[sorted_idx], imp[sorted_idx])\n",
310
+ " ax.set_title(f\"{model_name} Feature Importance\")\n",
311
+ " ax.set_xlabel(\"Importance Score\")\n",
312
+ "\n",
313
+ "plt.tight_layout()\n",
314
+ "plt.show()"
315
+ ],
316
+ "execution_count": null,
317
+ "outputs": []
318
+ },
319
+ {
320
+ "cell_type": "code",
321
+ "metadata": {},
322
+ "source": [
323
+ "# Task 2: Write your code here:\n",
324
+ "\n",
325
+ "feature_importance = pd.DataFrame({\n",
326
+ " 'importance': model.feature_importances_\n",
327
+ "}).sort_values('importance', ascending=False)\n",
328
+ "\n"
329
+ ],
330
+ "execution_count": null,
331
+ "outputs": []
332
+ },
333
+ {
334
+ "cell_type": "code",
335
+ "metadata": {},
336
+ "source": [
337
+ "# Task Bonus: Write your code here:"
338
+ ],
339
+ "execution_count": null,
340
+ "outputs": []
341
+ }
342
+ ],
343
+ "metadata": {
344
+ "kernelspec": {
345
+ "display_name": "Python 3",
346
+ "name": "python3"
347
+ },
348
+ "language_info": {
349
+ "name": "python"
350
+ }
351
+ },
352
+ "nbformat": 4,
353
+ "nbformat_minor": 0
354
+ }
submissions_extracted/232/Q1.ipynb ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import pandas as pd\n",
22
+ "import os\n",
23
+ "# Task 1: Write your code here:# Load the CSV file\n",
24
+ "csv_path = os.path.join(path, 'Q1_data.csv')\n",
25
+ "df = pd.read_csv(csv_path)\n",
26
+ "\n",
27
+ "print(f\"Shape: {df.shape}\")"
28
+ ],
29
+ "execution_count": null,
30
+ "outputs": []
31
+ },
32
+ {
33
+ "cell_type": "code",
34
+ "metadata": {},
35
+ "source": [
36
+ "# Task 2: Write your code here:\n",
37
+ "df.head()"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 3: Write your code here:\n",
47
+ "df.info()"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {},
55
+ "source": [
56
+ "# Task 4: Write your code here:\n",
57
+ "df.describe()"
58
+ ],
59
+ "execution_count": null,
60
+ "outputs": []
61
+ },
62
+ {
63
+ "cell_type": "code",
64
+ "metadata": {},
65
+ "source": [
66
+ "# Task 5: Write your code here:\n",
67
+ "import matplotlib.pyplot as plt\n",
68
+ "plt.figure(figsize=(10, 5))\n",
69
+ "plt.hist(df['Delivery_Time'], bins=30, edgecolor='black')\n",
70
+ "plt.title('Delivery_Time')\n",
71
+ "plt.xlabel('time \"minuts\"')\n",
72
+ "plt.ylabel('Frequency')\n",
73
+ "plt.show()"
74
+ ],
75
+ "execution_count": null,
76
+ "outputs": []
77
+ },
78
+ {
79
+ "cell_type": "code",
80
+ "metadata": {},
81
+ "source": [
82
+ "# Task 1: Write your code here:\n",
83
+ "df = df.drop(columns='Order_ID')\n",
84
+ "print(f\"y_test shape: {df.shape}\")"
85
+ ],
86
+ "execution_count": null,
87
+ "outputs": []
88
+ },
89
+ {
90
+ "cell_type": "code",
91
+ "metadata": {},
92
+ "source": [
93
+ "# Task 2: Write your code here:\n",
94
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
95
+ "missing_data = pd.DataFrame({\n",
96
+ " 'Column': missing_percentage.index,\n",
97
+ " 'Missing_Percentage': missing_percentage.values\n",
98
+ "})\n",
99
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 0].sort_values('Missing_Percentage', ascending=False)\n",
100
+ "\n",
101
+ "print(\"Missing Data Analysis:\")\n",
102
+ "missing_data.head(10)\n"
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
+ "# Fill categorical columns with 'unknown'\n",
113
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
114
+ "\n",
115
+ "print(\"Categorical Columns:\", list(categorical_cols))\n",
116
+ "# just Weather , Traffic_Level , Time_of_Day , has missing categoral values so fill with unkown\n",
117
+ "\n",
118
+ "for col in ['Weather','Traffic_Level','Time_of_Day']:\n",
119
+ " df[col] = df[col].fillna('unknown')"
120
+ ],
121
+ "execution_count": null,
122
+ "outputs": []
123
+ },
124
+ {
125
+ "cell_type": "code",
126
+ "metadata": {},
127
+ "source": [
128
+ "# Task 2: Write your code here:\n",
129
+ "\n",
130
+ "# Fill numerical columns with 'mode'\n",
131
+ "\n",
132
+ "for col in ['Delivery_Time','Courier_Experience_yrs']:\n",
133
+ " df[col] = df[col].fillna(df[col].mode()[0])\n",
134
+ "\n",
135
+ "#check missing again\n",
136
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
137
+ "missing_percentage\n",
138
+ "#data is full"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 3: Write your code here:\n",
148
+ "def check_duplicates(df):\n",
149
+ " duplicates = df.duplicated().sum() #check whole row it has same or not\n",
150
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
151
+ " if duplicates > 0:\n",
152
+ " print(\"Dropping Duplicates...\")\n",
153
+ " df.drop_duplicates(inplace=True)\n",
154
+ " print(\"Duplicates Dropped.\")\n",
155
+ " else:\n",
156
+ " print(\"No Duplicate Samples Found.\")\n",
157
+ "\n",
158
+ "check_duplicates(df)\n",
159
+ "print(f'shape now {df.shape}')"
160
+ ],
161
+ "execution_count": null,
162
+ "outputs": []
163
+ },
164
+ {
165
+ "cell_type": "code",
166
+ "metadata": {},
167
+ "source": [
168
+ "# Task 4: Write your code here:\n",
169
+ "from sklearn.preprocessing import LabelEncoder #import LabelEncoder\n",
170
+ "\n",
171
+ "print('data before encoding:\\n', categorical_cols) #show before encoding\n",
172
+ "\n",
173
+ "label_encoder = LabelEncoder() # Instantiate LabelEncoder\n",
174
+ "for col in categorical_cols:\n",
175
+ " df[col] = label_encoder.fit_transform(df[col]) # Apply fit_transform to the column\n",
176
+ " print('\\nData after encoding:\\n', df[col]) #show after encoding\n"
177
+ ],
178
+ "execution_count": null,
179
+ "outputs": []
180
+ },
181
+ {
182
+ "cell_type": "code",
183
+ "metadata": {},
184
+ "source": [
185
+ "# Task 5: Write your code here:\n",
186
+ "from sklearn.preprocessing import StandardScaler\n",
187
+ "\n",
188
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
189
+ "\n",
190
+ "scaler = StandardScaler()\n",
191
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
192
+ "df.head()"
193
+ ],
194
+ "execution_count": null,
195
+ "outputs": []
196
+ },
197
+ {
198
+ "cell_type": "code",
199
+ "metadata": {},
200
+ "source": [
201
+ "# Task 6: Write your code here:\n",
202
+ "import seaborn as sns\n",
203
+ "def check_target_imbalance(df, target_column):\n",
204
+ " print(\"Target Distribution:\")\n",
205
+ " print(df[target_column].value_counts())\n",
206
+ " print(df[target_column].value_counts(normalize=True))\n",
207
+ " sns.countplot(x=df[target_column])\n",
208
+ " plt.title(\"Target Distribution\")\n",
209
+ " plt.show()\n",
210
+ "\n",
211
+ "check_target_imbalance(df, \"Delivery_Time\")"
212
+ ],
213
+ "execution_count": null,
214
+ "outputs": []
215
+ },
216
+ {
217
+ "cell_type": "code",
218
+ "metadata": {},
219
+ "source": [
220
+ "# Task 1: Write your code here:\n",
221
+ "# Define features (X) and target (y)\n",
222
+ "feature_cols = ['Distance_km','Weather','Traffic_Level','Time_of_Day','Vehicle_Type','Preparation_Time_min','Courier_Experience_yrs']\n",
223
+ "X = df[feature_cols]\n",
224
+ "y = df['Delivery_Time']\n",
225
+ "\n",
226
+ "# Storage for logistic regression results for each fold\n",
227
+ "lr_losses = []\n",
228
+ "lr_accuracy = []\n",
229
+ "lr_precision = []\n",
230
+ "lr_recall = []\n",
231
+ "lr_f1 = []"
232
+ ],
233
+ "execution_count": null,
234
+ "outputs": []
235
+ },
236
+ {
237
+ "cell_type": "code",
238
+ "metadata": {},
239
+ "source": [
240
+ "# Task 2,3,4,5: Write your code here:\n",
241
+ "from sklearn.model_selection import KFold\n",
242
+ "from sklearn.ensemble import RandomForestRegressor\n",
243
+ "from sklearn.metrics import mean_absolute_error\n",
244
+ "import numpy as np\n",
245
+ "\n",
246
+ "models = {\n",
247
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
248
+ "}\n",
249
+ "n_splits = 5\n",
250
+ "kf = KFold(n_splits, shuffle=True, random_state=42)\n",
251
+ "\n",
252
+ "\n",
253
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
254
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
255
+ "\n",
256
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
257
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
258
+ "\n",
259
+ " for model_name, model in models.items():\n",
260
+ " print(f\"Training {model_name}...\")\n",
261
+ "\n",
262
+ " # Train\n",
263
+ " model.fit(X_train, y_train)\n",
264
+ "\n",
265
+ " # Predict\n",
266
+ " y_pred = model.predict(X_test)\n",
267
+ "\n",
268
+ " # Calculate metrics\n",
269
+ " mae = mean_absolute_error(y_test,y_pred)\n",
270
+ "\n",
271
+ " print(f\" mae: {np.mean(mae):.4f}\")\n",
272
+ ""
273
+ ],
274
+ "execution_count": null,
275
+ "outputs": []
276
+ },
277
+ {
278
+ "cell_type": "code",
279
+ "metadata": {},
280
+ "source": [
281
+ "# Task 1: Write your code here:\n",
282
+ "from sklearn.linear_model import Ridge, Lasso\n",
283
+ "models = {\n",
284
+ " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
285
+ " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
286
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
287
+ "}\n",
288
+ "coeffs = {}\n",
289
+ "\n",
290
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
291
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
292
+ "\n",
293
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
294
+ "axes = axes.flatten()\n",
295
+ "features = X.columns\n",
296
+ "\n",
297
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
298
+ " # Sort features by absolute coefficient value\n",
299
+ " absolute_coef = np.abs(coef)\n",
300
+ " sorted_idx = np.argsort(absolute_coef)\n",
301
+ "\n",
302
+ " ax = axes[i]\n",
303
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
304
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
305
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
306
+ "\n",
307
+ "plt.tight_layout()\n",
308
+ "plt.show()"
309
+ ],
310
+ "execution_count": null,
311
+ "outputs": []
312
+ },
313
+ {
314
+ "cell_type": "code",
315
+ "metadata": {},
316
+ "source": [
317
+ "# Task 2: Write your code here:"
318
+ ],
319
+ "execution_count": null,
320
+ "outputs": []
321
+ },
322
+ {
323
+ "cell_type": "code",
324
+ "metadata": {},
325
+ "source": [
326
+ "# Task Bonus: Write your code here:"
327
+ ],
328
+ "execution_count": null,
329
+ "outputs": []
330
+ }
331
+ ],
332
+ "metadata": {
333
+ "kernelspec": {
334
+ "display_name": "Python 3",
335
+ "name": "python3"
336
+ },
337
+ "language_info": {
338
+ "name": "python"
339
+ }
340
+ },
341
+ "nbformat": 4,
342
+ "nbformat_minor": 0
343
+ }
submissions_extracted/232/Q2.ipynb ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "\n",
27
+ "# Load Labels\n",
28
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
29
+ "img_dir = os.path.join(path, \"images\")\n",
30
+ "\n",
31
+ "images = []\n",
32
+ "ages = []\n",
33
+ "\n",
34
+ "# Load Images and Resize\n",
35
+ "print(\"Loading images...\")\n",
36
+ "for index, row in labels_df.iterrows():\n",
37
+ " img_name = row.iloc[0]\n",
38
+ " age = row.iloc[1]\n",
39
+ " img_path = os.path.join(img_dir, img_name)\n",
40
+ "\n",
41
+ " if os.path.exists(img_path):\n",
42
+ " img = Image.open(img_path).convert('RGB')\n",
43
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
44
+ " images.append(img_array)\n",
45
+ " ages.append(age)\n",
46
+ "\n",
47
+ "X = np.array(images)\n",
48
+ "y = np.array(ages)\n",
49
+ "\n",
50
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
51
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
52
+ "\n",
53
+ "# Split Data\n",
54
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
55
+ "\n",
56
+ "print(f\"X_train shape: {X_train.shape}\")\n",
57
+ "print(f\"X_test shape: {X_test.shape}\")\n",
58
+ "print(f\"y_train shape: {y_train.shape}\")\n",
59
+ "print(f\"y_test shape: {y_test.shape}\")"
60
+ ],
61
+ "execution_count": null,
62
+ "outputs": []
63
+ },
64
+ {
65
+ "cell_type": "code",
66
+ "metadata": {},
67
+ "source": [
68
+ "# 1. Convert Numpy arrays to PyTorch Tensors\n",
69
+ "import torch\n",
70
+ "X_train = torch.tensor(X_train, dtype=torch.float32)\n",
71
+ "X_test = torch.tensor(X_test, dtype=torch.float32)\n",
72
+ "y_train = torch.tensor(y_train, dtype=torch.long)\n",
73
+ "y_test = torch.tensor(y_test, dtype=torch.long)\n",
74
+ "\n"
75
+ ],
76
+ "execution_count": null,
77
+ "outputs": []
78
+ },
79
+ {
80
+ "cell_type": "code",
81
+ "metadata": {},
82
+ "source": [
83
+ "# 2. Create TensorDataset objects\n",
84
+ "from torch.utils.data import TensorDataset\n",
85
+ "\n",
86
+ "train_dataset = TensorDataset(X_train, y_train)\n",
87
+ "test_dataset = TensorDataset(X_test, y_test)\n",
88
+ "\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
+ "train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True)\n",
101
+ "test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False)\n",
102
+ "\n",
103
+ "\n",
104
+ "\n"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# 4. Print shape of one batch\n",
114
+ "X_batch, y_batch = next(iter(train_loader))\n",
115
+ "print(f\"Training batch input shape: {X_batch.shape}\")\n",
116
+ "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
+ "import matplotlib.pyplot as plt\n",
127
+ "# Get one batch of images and labels\n",
128
+ "images, labels = next(iter(train_loader))\n",
129
+ "\n",
130
+ "# Display the first 6 images in the batch\n",
131
+ "plt.figure(figsize=(8, 4))\n",
132
+ "\n",
133
+ "for i in range(6):\n",
134
+ " plt.subplot(2, 3, i + 1)\n",
135
+ "\n",
136
+ " # Convert from (C, H, W) to (H, W, C) for matplotlib\n",
137
+ " img = images[i].permute(1, 2, 0)\n",
138
+ "\n",
139
+ " plt.imshow(img)\n",
140
+ " plt.title(f\"Label: {labels[i].item()}\")\n",
141
+ " plt.axis('off')\n",
142
+ "\n",
143
+ "plt.tight_layout()\n",
144
+ "plt.show()"
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
+ "import torch.nn as nn\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
+ " # First linear layer: input features -> hidden layer\n",
161
+ " self.layer1 = nn.Linear(input_dim, hidden_dim)\n",
162
+ "\n",
163
+ " # Second linear layer: hidden layer -> hidden layer\n",
164
+ " self.layer2 = nn.Linear(hidden_dim, hidden_dim)\n",
165
+ "\n",
166
+ " # Third linear layer: hidden layer -> hidden layer\n",
167
+ " self.layer3 = nn.Linear(hidden_dim, hidden_dim)\n",
168
+ "\n",
169
+ " # Output layer: hidden layer -> number of classes (logits)\n",
170
+ " self.layer4 = nn.Linear(hidden_dim, output_dim)\n",
171
+ "\n",
172
+ " # ReLU activation for non-linearity\n",
173
+ " self.relu = nn.ReLU()\n",
174
+ "\n",
175
+ " # Defines how input data flows through the network\n",
176
+ " def forward(self, x):\n",
177
+ " # First hidden layer\n",
178
+ " a1 = self.relu(self.layer1(x))\n",
179
+ "\n",
180
+ " # Second hidden layer\n",
181
+ " a2 = self.relu(self.layer2(a1))\n",
182
+ "\n",
183
+ " # Third hidden layer\n",
184
+ " a3 = self.relu(self.layer3(a2))\n",
185
+ "\n",
186
+ " # Output layer (raw scores / logits)\n",
187
+ " output = self.layer4(a3) # we said we'll use softmax, where is it? ¯\\(ツ)/¯\n",
188
+ "\n",
189
+ " return output\n"
190
+ ],
191
+ "execution_count": null,
192
+ "outputs": []
193
+ },
194
+ {
195
+ "cell_type": "code",
196
+ "metadata": {},
197
+ "source": [
198
+ "# Task 2: Write your training loop here:\n",
199
+ "def train_one_epoch(model, optimizer, criterion, train_loader, device):\n",
200
+ " # Set the model to training mode\n",
201
+ " model.train()\n",
202
+ "\n",
203
+ " running_loss = 0.0\n",
204
+ "\n",
205
+ " for X_batch, y_batch in train_loader:\n",
206
+ " # Move batch to the selected device\n",
207
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
208
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
209
+ "\n",
210
+ " # Forward pass (outputs are logits)\n",
211
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
212
+ " loss = criterion(outputs, y_batch)\n",
213
+ "\n",
214
+ " # Backward pass & optimization\n",
215
+ " optimizer.zero_grad() # Clear previous gradients\n",
216
+ " loss.backward() # Compute gradients\n",
217
+ " optimizer.step() # Update model parameters\n",
218
+ "\n",
219
+ " running_loss += loss.item()\n",
220
+ "\n",
221
+ " # Average loss over all batches\n",
222
+ " avg_loss = running_loss / len(train_loader)\n",
223
+ "\n",
224
+ " return avg_loss\n"
225
+ ],
226
+ "execution_count": null,
227
+ "outputs": []
228
+ },
229
+ {
230
+ "cell_type": "code",
231
+ "metadata": {},
232
+ "source": [
233
+ "# Task 3: Write your validation loop here:\n",
234
+ "def validate(model, criterion, test_loader, device):\n",
235
+ " # Set the model to evaluation mode\n",
236
+ " model.eval()\n",
237
+ "\n",
238
+ " running_loss = 0.0\n",
239
+ " correct = 0\n",
240
+ " total = 0\n",
241
+ "\n",
242
+ " with torch.no_grad():\n",
243
+ " for X_batch, y_batch in test_loader:\n",
244
+ " # Move data to device\n",
245
+ " X_batch = X_batch.to(device) # shape: (batch_size, num_features)\n",
246
+ " y_batch = y_batch.to(device) # shape: (batch_size,)\n",
247
+ "\n",
248
+ " # Forward pass\n",
249
+ " outputs = model(X_batch) # shape: (batch_size, num_classes)\n",
250
+ " loss = criterion(outputs, y_batch)\n",
251
+ " running_loss += loss.item()\n",
252
+ "\n",
253
+ " # Apply Softmax to get probabilities\n",
254
+ " probabilities = F.softmax(outputs, dim=1)\n",
255
+ "\n",
256
+ " # Pick the classes with highest probabilities\n",
257
+ " predicted = torch.argmax(probabilities, dim=1)\n",
258
+ "\n",
259
+ " # Accuracy calculation\n",
260
+ " correct += (predicted == y_batch).sum().item()\n",
261
+ " total += y_batch.size(0)\n",
262
+ "\n",
263
+ " avg_loss = running_loss / len(test_loader)\n",
264
+ " accuracy = correct / total\n",
265
+ "\n",
266
+ " return avg_loss, accuracy"
267
+ ],
268
+ "execution_count": null,
269
+ "outputs": []
270
+ },
271
+ {
272
+ "cell_type": "code",
273
+ "metadata": {},
274
+ "source": [
275
+ "# Task 4: Define device, model, loss, optimizer:\n",
276
+ "# Device setup\n",
277
+ "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
278
+ "\n",
279
+ "# Model parameters\n",
280
+ "input_dim = X_train.shape[1] # Number of tabular features\n",
281
+ "hidden_dim = 14 # Design choice\n",
282
+ "output_dim = 4 # Weather classes: Rainy, Sunny, Cloudy, Snowy\n",
283
+ "\n",
284
+ "# Instantiate model\n",
285
+ "model = NN4Layer(input_dim, hidden_dim, output_dim).to(device)\n",
286
+ "\n",
287
+ "# Print the model architecture\n",
288
+ "print(\"Model Architecture:\\n\")\n",
289
+ "print(model)\n",
290
+ "\n",
291
+ "# Calculate the total number of trainable parameters\n",
292
+ "total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n",
293
+ "print(f\"\\nTotal trainable parameters: {total_params}\")\n",
294
+ "\n"
295
+ ],
296
+ "execution_count": null,
297
+ "outputs": []
298
+ },
299
+ {
300
+ "cell_type": "code",
301
+ "metadata": {},
302
+ "source": [
303
+ "# Task 5: Start training for 20 epochs:\n",
304
+ "from torch.optim import AdamW\n",
305
+ "num_epochs = 20\n",
306
+ "learning_rate = 0.001\n",
307
+ "\n",
308
+ "# Define criterion (loss function) - using CrossEntropyLoss as model now outputs logits\n",
309
+ "criterion = nn.CrossEntropyLoss()\n",
310
+ "# Define optimizer\n",
311
+ "optimizer = AdamW(model.parameters(), learning_rate)\n"
312
+ ],
313
+ "execution_count": null,
314
+ "outputs": []
315
+ },
316
+ {
317
+ "cell_type": "code",
318
+ "metadata": {},
319
+ "source": [
320
+ "# Plotting results\n"
321
+ ],
322
+ "execution_count": null,
323
+ "outputs": []
324
+ },
325
+ {
326
+ "cell_type": "code",
327
+ "metadata": {},
328
+ "source": [
329
+ "# Task 2 (Bonus): Write your code here:"
330
+ ],
331
+ "execution_count": null,
332
+ "outputs": []
333
+ }
334
+ ],
335
+ "metadata": {
336
+ "kernelspec": {
337
+ "display_name": "Python 3",
338
+ "name": "python3"
339
+ },
340
+ "language_info": {
341
+ "name": "python"
342
+ }
343
+ },
344
+ "nbformat": 4,
345
+ "nbformat_minor": 0
346
+ }
submissions_extracted/232/Q3.ipynb ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "\n",
10
+ "\n",
11
+ "# Download latest version\n",
12
+ "\n",
13
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q3-exam-data\")\n",
14
+ "\n",
15
+ "\n",
16
+ "\n",
17
+ "print(\"Path to dataset files:\", path)"
18
+ ],
19
+ "execution_count": null,
20
+ "outputs": []
21
+ },
22
+ {
23
+ "cell_type": "code",
24
+ "metadata": {},
25
+ "source": [
26
+ "# Task 1: Write your code here:\n",
27
+ "import pandas as pd\n",
28
+ "import os\n",
29
+ "# Task 1: Write your code here:# Load the CSV file\n",
30
+ "csv_path = os.path.join(path, 'Q3_data.csv')\n",
31
+ "df = pd.read_csv(csv_path)\n",
32
+ "\n",
33
+ "print(f\"Shape: {df.shape}\")"
34
+ ],
35
+ "execution_count": null,
36
+ "outputs": []
37
+ },
38
+ {
39
+ "cell_type": "code",
40
+ "metadata": {},
41
+ "source": [
42
+ "# Task 2: Write your code here:\n",
43
+ "df.head()"
44
+ ],
45
+ "execution_count": null,
46
+ "outputs": []
47
+ },
48
+ {
49
+ "cell_type": "code",
50
+ "metadata": {},
51
+ "source": [
52
+ "# Task 3: Write your code here:\n",
53
+ "df.info()"
54
+ ],
55
+ "execution_count": null,
56
+ "outputs": []
57
+ },
58
+ {
59
+ "cell_type": "code",
60
+ "metadata": {},
61
+ "source": [
62
+ "# Task 4: Write your code here:\n",
63
+ "df.describe()"
64
+ ],
65
+ "execution_count": null,
66
+ "outputs": []
67
+ },
68
+ {
69
+ "cell_type": "code",
70
+ "metadata": {},
71
+ "source": [
72
+ "# Task 1: Write your code here:\n",
73
+ "missing_percentage = (df.isnull().sum() / len(df)) * 100\n",
74
+ "missing_data = pd.DataFrame({\n",
75
+ " 'Column': missing_percentage.index,\n",
76
+ " 'Missing_Percentage': missing_percentage.values\n",
77
+ "})\n",
78
+ "#if above 30% remove\n",
79
+ "missing_data = missing_data[missing_data['Missing_Percentage'] > 30].sort_values('Missing_Percentage', ascending=False)\n",
80
+ "\n",
81
+ "print(\"Missing Data Analysis:\")\n",
82
+ "df = df.drop(columns=missing_data['Column'])\n",
83
+ "df.head()"
84
+ ],
85
+ "execution_count": null,
86
+ "outputs": []
87
+ },
88
+ {
89
+ "cell_type": "code",
90
+ "metadata": {},
91
+ "source": [
92
+ "# Task 2: Write your code here:\n",
93
+ "def check_duplicates(df):\n",
94
+ " duplicates = df.duplicated().sum() #check whole row it has same or not\n",
95
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
96
+ " if duplicates > 0:\n",
97
+ " print(\"Dropping Duplicates...\")\n",
98
+ " df.drop_duplicates(inplace=True)\n",
99
+ " print(\"Duplicates Dropped.\")\n",
100
+ " else:\n",
101
+ " print(\"No Duplicate Samples Found.\")\n",
102
+ "\n",
103
+ "check_duplicates(df)\n",
104
+ "print(f'shape now {df.shape}')"
105
+ ],
106
+ "execution_count": null,
107
+ "outputs": []
108
+ },
109
+ {
110
+ "cell_type": "code",
111
+ "metadata": {},
112
+ "source": [
113
+ "# Task 3: Write your code here:\n",
114
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
115
+ "categorical_cols"
116
+ ],
117
+ "execution_count": null,
118
+ "outputs": []
119
+ },
120
+ {
121
+ "cell_type": "code",
122
+ "metadata": {},
123
+ "source": [
124
+ "# Task 4: Write your code here:\n",
125
+ "from sklearn.preprocessing import StandardScaler\n",
126
+ "\n",
127
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # DON'T SCALE THE TARGET\n",
128
+ "\n",
129
+ "scaler = StandardScaler()\n",
130
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
131
+ "df.head()"
132
+ ],
133
+ "execution_count": null,
134
+ "outputs": []
135
+ },
136
+ {
137
+ "cell_type": "code",
138
+ "metadata": {},
139
+ "source": [
140
+ "# Task 5: Write your code here:\n",
141
+ "import seaborn as sns\n",
142
+ "import matplotlib.pyplot as plt\n",
143
+ "def check_target_imbalance(df, target_column):\n",
144
+ " print(\"Target Distribution:\")\n",
145
+ " print(df[target_column].value_counts())\n",
146
+ " print(df[target_column].value_counts(normalize=True))\n",
147
+ " sns.countplot(x=df[target_column])\n",
148
+ " plt.title(\"Target Distribution\")\n",
149
+ " plt.show()\n",
150
+ "\n",
151
+ "check_target_imbalance(df, \"Target\")\n",
152
+ "#not balanced"
153
+ ],
154
+ "execution_count": null,
155
+ "outputs": []
156
+ },
157
+ {
158
+ "cell_type": "code",
159
+ "metadata": {},
160
+ "source": [
161
+ "!pip install catboost"
162
+ ],
163
+ "execution_count": null,
164
+ "outputs": []
165
+ },
166
+ {
167
+ "cell_type": "code",
168
+ "metadata": {},
169
+ "source": [
170
+ "# Task 1: Write your code here:\n",
171
+ "# Import models\n",
172
+ "from sklearn.neighbors import KNeighborsClassifier\n",
173
+ "from sklearn.svm import SVC\n",
174
+ "from sklearn.tree import DecisionTreeClassifier\n",
175
+ "from sklearn.ensemble import RandomForestClassifier\n",
176
+ "from xgboost import XGBClassifier\n",
177
+ "from catboost import CatBoostClassifier\n",
178
+ "from sklearn.model_selection import StratifiedKFold\n",
179
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
180
+ "\n",
181
+ "sklearn_models = {\n",
182
+ " \"K-Nearest Neighbors\": KNeighborsClassifier(\n",
183
+ " n_neighbors=3, # Number of neighbors to consider\n",
184
+ " ),\n",
185
+ " \"Support Vector Machine\": SVC(\n",
186
+ " kernel='rbf', # 'linear', 'poly', 'rbf', 'sigmoid'\n",
187
+ " C=0.75 # Regularization parameter\n",
188
+ " ),\n",
189
+ " \"Decision Tree\": DecisionTreeClassifier(\n",
190
+ " max_depth=3 # Maximum depth of tree (prevents overfitting)\n",
191
+ " ),\n",
192
+ " \"Random Forest\": RandomForestClassifier(\n",
193
+ " n_estimators=320, # Number of trees\n",
194
+ " max_depth=4\n",
195
+ " ),\n",
196
+ " \"XGBoost\": XGBClassifier(\n",
197
+ " verbosity=0,\n",
198
+ " n_estimators=300, # Number of boosting rounds\n",
199
+ " max_depth=5,\n",
200
+ " learning_rate=0.05 # Step size shrinkage\n",
201
+ " ),\n",
202
+ " \"CatBoost\": CatBoostClassifier(\n",
203
+ " verbose=0,\n",
204
+ " n_estimators=320,\n",
205
+ " max_depth=4\n",
206
+ " )\n",
207
+ "}\n",
208
+ "all_results = {}\n",
209
+ "\n",
210
+ "for name in sklearn_models:\n",
211
+ " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
212
+ "\n",
213
+ "n_splits = 5 # K\n",
214
+ "\n",
215
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
216
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
217
+ "\n",
218
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
219
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
220
+ "\n",
221
+ " # 1. Split data\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
+ " # 2. Train & Validate sklearn models\n",
226
+ " for model_name, model in sklearn_models.items():\n",
227
+ " print(f\"Training {model_name}...\")\n",
228
+ " model.fit(X_train, y_train) # train\n",
229
+ " y_pred = model.predict(X_test) # validate\n",
230
+ "\n",
231
+ " # 3. Save metrics for that model in this fold\n",
232
+ " accuracy = accuracy_score(y_test, y_pred)\n",
233
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
234
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
235
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
236
+ "\n",
237
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
238
+ " all_results[model_name]['precision'].append(precision)\n",
239
+ " all_results[model_name]['recall'].append(recall)\n",
240
+ " all_results[model_name]['f1'].append(f1)"
241
+ ],
242
+ "execution_count": null,
243
+ "outputs": []
244
+ },
245
+ {
246
+ "cell_type": "code",
247
+ "metadata": {},
248
+ "source": [
249
+ "# Task 2,3,4,5: Write your code here:"
250
+ ],
251
+ "execution_count": null,
252
+ "outputs": []
253
+ },
254
+ {
255
+ "cell_type": "code",
256
+ "metadata": {},
257
+ "source": [
258
+ "# Task 1: Write your code here:"
259
+ ],
260
+ "execution_count": null,
261
+ "outputs": []
262
+ },
263
+ {
264
+ "cell_type": "code",
265
+ "metadata": {},
266
+ "source": [
267
+ "# Task 2: Write your code here:"
268
+ ],
269
+ "execution_count": null,
270
+ "outputs": []
271
+ },
272
+ {
273
+ "cell_type": "code",
274
+ "metadata": {},
275
+ "source": [
276
+ "# Task Bonus: Write your code here:"
277
+ ],
278
+ "execution_count": null,
279
+ "outputs": []
280
+ }
281
+ ],
282
+ "metadata": {
283
+ "kernelspec": {
284
+ "display_name": "Python 3",
285
+ "name": "python3"
286
+ },
287
+ "language_info": {
288
+ "name": "python"
289
+ }
290
+ },
291
+ "nbformat": 4,
292
+ "nbformat_minor": 0
293
+ }
submissions_extracted/233/Q1.ipynb ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import numpy as np\n",
8
+ "import pandas as pd\n",
9
+ "import matplotlib.pyplot as plt\n",
10
+ "import os\n",
11
+ "import kagglehub\n",
12
+ "\n",
13
+ "from sklearn.model_selection import train_test_split, KFold\n",
14
+ "from sklearn.preprocessing import StandardScaler, LabelEncoder\n",
15
+ "from sklearn.ensemble import RandomForestRegressor\n",
16
+ "from sklearn.metrics import mean_absolute_error, mean_squared_error\n",
17
+ "\n",
18
+ "import warnings\n",
19
+ "warnings.filterwarnings('ignore')\n",
20
+ "\n",
21
+ "# Download latest version\n",
22
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q1-exam-data\")\n",
23
+ "\n",
24
+ "print(\"Path to dataset files:\", path)"
25
+ ],
26
+ "execution_count": null,
27
+ "outputs": []
28
+ },
29
+ {
30
+ "cell_type": "code",
31
+ "metadata": {},
32
+ "source": [
33
+ "# Task 1: Write your code here:\n",
34
+ "data_path = os.path.join(path, 'Q1_data.csv')\n",
35
+ "df_data = pd.read_csv(data_path)\n",
36
+ "\n",
37
+ "print(f\"Dataset shape: {df_data.shape}\")\n"
38
+ ],
39
+ "execution_count": null,
40
+ "outputs": []
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "metadata": {},
45
+ "source": [
46
+ "# Task 2: Write your code here:\n",
47
+ "df_data.head() #showing the first 5"
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_data.info() #gives us clear info of what we need to know"
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() #describes the scale between data, good for checking the need to scale"
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
+ "plt.figure(figsize=(10, 5))\n",
78
+ "plt.hist(df_data['Delivery_Time'].dropna(), bins=50, edgecolor='black')\n",
79
+ "plt.show()"
80
+ ],
81
+ "execution_count": null,
82
+ "outputs": []
83
+ },
84
+ {
85
+ "cell_type": "code",
86
+ "metadata": {},
87
+ "source": [
88
+ "# Task 1: Write your code here:\n",
89
+ "\n",
90
+ "df_data.dropna(subset=['Order_ID']) #we do not drop target!\n",
91
+ "\n",
92
+ "cols = [\t'Distance_km',\t'Weather',\t'Traffic_Level',\t'Time_of_Day',\t'Vehicle_Type',\t'Preparation_Time_min',\t'Courier_Experience_yrs']\n",
93
+ "df_clean = df_data.dropna(subset=cols).copy() #cleaning cols with\n",
94
+ "print(f\"Shape after cleaning: {df_clean.shape}\")"
95
+ ],
96
+ "execution_count": null,
97
+ "outputs": []
98
+ },
99
+ {
100
+ "cell_type": "code",
101
+ "metadata": {},
102
+ "source": [
103
+ "# Task 2: Write your code here:\n",
104
+ "for col in cols:\n",
105
+ " df_clean[col] = df_clean[col].fillna('unknown')#fills missing values\n",
106
+ "\n",
107
+ "\n",
108
+ "\n",
109
+ "print(\"Missing values remaining:\", df_clean.isnull().sum().sum())"
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
+ "def check_duplicates(df_data):\n",
120
+ " duplicates = df_data.duplicated().sum()\n",
121
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
122
+ " if duplicates > 0:\n",
123
+ " print(\"Dropping Duplicates...\")\n",
124
+ " df_data.drop_duplicates(inplace=True)\n",
125
+ " print(\"Duplicates Dropped.\")\n",
126
+ " else:\n",
127
+ " print(\"No Duplicate Samples Found.\")\n",
128
+ "\n",
129
+ "check_duplicates(df_data)\n",
130
+ "\n"
131
+ ],
132
+ "execution_count": null,
133
+ "outputs": []
134
+ },
135
+ {
136
+ "cell_type": "code",
137
+ "metadata": {},
138
+ "source": [
139
+ "# Task 4: Write your code here:\n",
140
+ "from sklearn.preprocessing import LabelEncoder\n",
141
+ "categorical_cols = df_data.select_dtypes(include=[\"object\"]).columns\n",
142
+ "label_encoders = {}\n",
143
+ "for col in categorical_cols:\n",
144
+ " le = LabelEncoder()\n",
145
+ " df_data[col] = le.fit_transform(df_data[col])\n",
146
+ " label_encoders[col] = le\n",
147
+ "\n",
148
+ " df_data\n"
149
+ ],
150
+ "execution_count": null,
151
+ "outputs": []
152
+ },
153
+ {
154
+ "cell_type": "code",
155
+ "metadata": {},
156
+ "source": [
157
+ "# Task 5: Write your code here:\n",
158
+ "from sklearn.preprocessing import StandardScaler\n",
159
+ "\n",
160
+ "numerical_cols = df_data.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Delivery_Time\") # DON'T SCALE THE TARGET\n",
161
+ "\n",
162
+ "scaler = StandardScaler()\n",
163
+ "df_data[numerical_cols] = scaler.fit_transform(df_data[numerical_cols])\n",
164
+ "df_data.head()"
165
+ ],
166
+ "execution_count": null,
167
+ "outputs": []
168
+ },
169
+ {
170
+ "cell_type": "code",
171
+ "metadata": {},
172
+ "source": [
173
+ "# Task 6: Write your code here:\n",
174
+ "\n"
175
+ ],
176
+ "execution_count": null,
177
+ "outputs": []
178
+ },
179
+ {
180
+ "cell_type": "code",
181
+ "metadata": {},
182
+ "source": [
183
+ "# Task 1: Write your code here:\n",
184
+ "X = df_data.drop(\"Delivery_Time\", axis=1).astype(float)\n",
185
+ "y = df_data['Delivery_Time'].astype(float)"
186
+ ],
187
+ "execution_count": null,
188
+ "outputs": []
189
+ },
190
+ {
191
+ "cell_type": "code",
192
+ "metadata": {},
193
+ "source": [
194
+ "# Task 2,3,4,5: Write your code here:\n",
195
+ "from sklearn.model_selection import KFold\n",
196
+ "from sklearn.metrics import mean_squared_error as sklearn_mse, mean_absolute_error, r2_score\n",
197
+ "from sklearn.linear_model import Ridge, Lasso\n",
198
+ "from sklearn.svm import SVR\n",
199
+ "from sklearn.tree import DecisionTreeRegressor\n",
200
+ "from sklearn.ensemble import RandomForestRegressor\n",
201
+ "from lightgbm import LGBMRegressor\n",
202
+ "\n",
203
+ "#here we go the traditional way of k-fold\n",
204
+ "def mean_squared_error(y, y_hat):\n",
205
+ " return (1 / (2 * len(y))) * np.sum((y_hat - y) ** 2)\n",
206
+ "\n",
207
+ "\n",
208
+ "\n",
209
+ " #defining a gradient descent func\n",
210
+ "def gradient_descent(X, y, learning_rate, n_iters=500):\n",
211
+ " m, n = X.shape # m rows, n columns\n",
212
+ " theta = np.zeros(n) # initialize a zeros weight vector with n dimensions\n",
213
+ " losses = []\n",
214
+ "\n",
215
+ "#here we train the model using everything we did previously\n",
216
+ "for _ in df_data(range(5000), desc=\"Training Linear Regression\"):\n",
217
+ " y_hat = np.dot(X, theta)\n",
218
+ " gradient = np.dot(X.T, (y_hat - y)) / m\n",
219
+ " theta -= 0.001 * gradient\n",
220
+ "\n",
221
+ " loss = mean_squared_error(y, y_hat)\n",
222
+ " losses.append(loss)\n",
223
+ "\n",
224
+ " return theta, losses\n",
225
+ "\n",
226
+ "lr_losses = []\n",
227
+ "lr_mse = []\n",
228
+ "lr_rmse = []\n",
229
+ "lr_r2 = []\n",
230
+ "\n",
231
+ "\n",
232
+ "n_splits = 5\n",
233
+ "\n",
234
+ "kf = KFold(n_splits=5, shuffle=True, random_state=42)\n",
235
+ "\n",
236
+ "for fold_idx, (train_index, test_index) in enumerate(kf.split(X)):\n",
237
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
238
+ "\n",
239
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
240
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
241
+ "\n",
242
+ " # Train\n",
243
+ " theta, losses = gradient_descent(X_train.values, y_train.values, learning_rate=0.1, n_iters=500)\n",
244
+ "\n",
245
+ " # Validate\n",
246
+ " y_pred = np.dot(X_test.values, theta)\n",
247
+ "\n",
248
+ " # Calculate evaluation metrics\n",
249
+ " mse = sklearn_mse(y_test, y_pred)\n",
250
+ " rmse = np.sqrt(mse)\n",
251
+ " r2 = r2_score(y_test, y_pred)\n",
252
+ "\n",
253
+ " # Store results\n",
254
+ " lr_losses.append(losses)\n",
255
+ " lr_mse.append(mse)\n",
256
+ " lr_rmse.append(rmse)\n",
257
+ " lr_r2.append(r2)\n",
258
+ "\n",
259
+ "\n",
260
+ "\n",
261
+ "\n",
262
+ "\n",
263
+ ""
264
+ ],
265
+ "execution_count": null,
266
+ "outputs": []
267
+ },
268
+ {
269
+ "cell_type": "code",
270
+ "metadata": {},
271
+ "source": [
272
+ "# Task 1: Write your code here:\n",
273
+ "\n",
274
+ "models = {\n",
275
+ " \"Ridge Regression\": Ridge(alpha=1.0, max_iter=10000),\n",
276
+ " \"LASSO Regression\": Lasso(alpha=1.0, max_iter=10000),\n",
277
+ " \"Support Vector Machine\": SVR(kernel='rbf'),\n",
278
+ " \"Decision Tree Regressor\": DecisionTreeRegressor(max_depth=10),\n",
279
+ " \"Random Forest Regressor\": RandomForestRegressor(n_estimators=200),\n",
280
+ " \"LightGBM\": LGBMRegressor(verbose=-1),\n",
281
+ "\n",
282
+ "}\n",
283
+ "coeffs = {}\n",
284
+ "\n",
285
+ "coeffs['Lasso'] = models['LASSO Regression'].coef_\n",
286
+ "coeffs['Ridge'] = models['Ridge Regression'].coef_\n",
287
+ "\n",
288
+ "fig, axes = plt.subplots(1, 2, figsize=(15, 6))\n",
289
+ "axes = axes.flatten()\n",
290
+ "features = X.columns\n",
291
+ "\n",
292
+ "for i, (model_name, coef) in enumerate(coeffs.items()):\n",
293
+ " # Sort features by absolute coefficient value\n",
294
+ " absolute_coef = np.abs(coef)\n",
295
+ " sorted_idx = np.argsort(absolute_coef)\n",
296
+ "\n",
297
+ " ax = axes[i]\n",
298
+ " ax.barh(features[sorted_idx], coef[sorted_idx])\n",
299
+ " ax.set_title(f\"{model_name} Coefficients\")\n",
300
+ " ax.set_xlabel(\"Coefficient Value (Impact)\")\n",
301
+ "\n",
302
+ "plt.tight_layout()\n",
303
+ "plt.show()"
304
+ ],
305
+ "execution_count": null,
306
+ "outputs": []
307
+ },
308
+ {
309
+ "cell_type": "code",
310
+ "metadata": {},
311
+ "source": [
312
+ "# Task 2: Write your code here:\n"
313
+ ],
314
+ "execution_count": null,
315
+ "outputs": []
316
+ },
317
+ {
318
+ "cell_type": "code",
319
+ "metadata": {},
320
+ "source": [
321
+ "# Task Bonus: Write your code here:"
322
+ ],
323
+ "execution_count": null,
324
+ "outputs": []
325
+ }
326
+ ],
327
+ "metadata": {
328
+ "kernelspec": {
329
+ "display_name": "Python 3",
330
+ "name": "python3"
331
+ },
332
+ "language_info": {
333
+ "name": "python"
334
+ }
335
+ },
336
+ "nbformat": 4,
337
+ "nbformat_minor": 0
338
+ }
submissions_extracted/233/Q2.ipynb ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "import kagglehub\n",
8
+ "\n",
9
+ "# Download latest version\n",
10
+ "path = kagglehub.dataset_download(\"ANON_OWNER/q2-exam-data\")\n",
11
+ "\n",
12
+ "print(\"Path to dataset files:\", path)"
13
+ ],
14
+ "execution_count": null,
15
+ "outputs": []
16
+ },
17
+ {
18
+ "cell_type": "code",
19
+ "metadata": {},
20
+ "source": [
21
+ "import os\n",
22
+ "import pandas as pd\n",
23
+ "import numpy as np\n",
24
+ "from PIL import Image\n",
25
+ "from sklearn.model_selection import train_test_split\n",
26
+ "import torch\n",
27
+ "import torch.nn as nn\n",
28
+ "from torchvision.datasets import MNIST\n",
29
+ "from torch.utils.data import DataLoader\n",
30
+ "from torch.optim import Adam\n",
31
+ "from torchvision.transforms.functional import to_tensor\n",
32
+ "import torch.nn.functional as F\n",
33
+ "import matplotlib.pyplot as plt\n",
34
+ "\n",
35
+ "# Load Labels\n",
36
+ "labels_df = pd.read_csv(os.path.join(path, \"labels.csv\"))\n",
37
+ "img_dir = os.path.join(path, \"images\")\n",
38
+ "\n",
39
+ "images = []\n",
40
+ "ages = []\n",
41
+ "\n",
42
+ "# Load Images and Resize\n",
43
+ "print(\"Loading images...\")\n",
44
+ "for index, row in labels_df.iterrows():\n",
45
+ " img_name = row.iloc[0]\n",
46
+ " age = row.iloc[1]\n",
47
+ " img_path = os.path.join(img_dir, img_name)\n",
48
+ "\n",
49
+ " if os.path.exists(img_path):\n",
50
+ " img = Image.open(img_path).convert('RGB')\n",
51
+ " img_array = np.array(img) / 255.0 # Normalize pixel values to [0, 1]\n",
52
+ " images.append(img_array)\n",
53
+ " ages.append(age)\n",
54
+ "\n",
55
+ "X = np.array(images)\n",
56
+ "y = np.array(ages)\n",
57
+ "\n",
58
+ "# Transpose image dimensions to match PyTorch format (N, C, H, W)\n",
59
+ "X = np.transpose(X, (0, 3, 1, 2))\n",
60
+ "\n",
61
+ "# Split Data\n",
62
+ "X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n",
63
+ "\n",
64
+ "print(f\"X_train shape: {X_train.shape}\")\n",
65
+ "print(f\"X_test shape: {X_test.shape}\")\n",
66
+ "print(f\"y_train shape: {y_train.shape}\")\n",
67
+ "print(f\"y_test shape: {y_test.shape}\")"
68
+ ],
69
+ "execution_count": null,
70
+ "outputs": []
71
+ },
72
+ {
73
+ "cell_type": "code",
74
+ "metadata": {},
75
+ "source": [
76
+ "# 1. Convert Numpy arrays to PyTorch Tensors\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
+ "\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
+ "\n",
100
+ "\n"
101
+ ],
102
+ "execution_count": null,
103
+ "outputs": []
104
+ },
105
+ {
106
+ "cell_type": "code",
107
+ "metadata": {},
108
+ "source": [
109
+ "# 4. Print shape of one batch\n",
110
+ "\n"
111
+ ],
112
+ "execution_count": null,
113
+ "outputs": []
114
+ },
115
+ {
116
+ "cell_type": "code",
117
+ "metadata": {},
118
+ "source": [
119
+ "# 5. Display sample images\n",
120
+ "\n"
121
+ ],
122
+ "execution_count": null,
123
+ "outputs": []
124
+ },
125
+ {
126
+ "cell_type": "code",
127
+ "metadata": {},
128
+ "source": [
129
+ "# Task 1: Write your model class here:"
130
+ ],
131
+ "execution_count": null,
132
+ "outputs": []
133
+ },
134
+ {
135
+ "cell_type": "code",
136
+ "metadata": {},
137
+ "source": [
138
+ "# Task 2: Write your training loop here:"
139
+ ],
140
+ "execution_count": null,
141
+ "outputs": []
142
+ },
143
+ {
144
+ "cell_type": "code",
145
+ "metadata": {},
146
+ "source": [
147
+ "# Task 3: Write your validation loop here:"
148
+ ],
149
+ "execution_count": null,
150
+ "outputs": []
151
+ },
152
+ {
153
+ "cell_type": "code",
154
+ "metadata": {},
155
+ "source": [
156
+ "# Task 4: Define device, model, loss, optimizer:"
157
+ ],
158
+ "execution_count": null,
159
+ "outputs": []
160
+ },
161
+ {
162
+ "cell_type": "code",
163
+ "metadata": {},
164
+ "source": [
165
+ "# Task 5: Start training for 20 epochs:"
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 (Bonus): Write your code here:"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ }
188
+ ],
189
+ "metadata": {
190
+ "kernelspec": {
191
+ "display_name": "Python 3",
192
+ "name": "python3"
193
+ },
194
+ "language_info": {
195
+ "name": "python"
196
+ }
197
+ },
198
+ "nbformat": 4,
199
+ "nbformat_minor": 0
200
+ }
submissions_extracted/233/Q3.ipynb ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "code",
5
+ "metadata": {},
6
+ "source": [
7
+ "\n",
8
+ "from IPython.display import clear_output\n",
9
+ "%pip install kagglehub catboost xgboost tqdm -q\n",
10
+ "clear_output()\n",
11
+ "import kagglehub\n",
12
+ "import pandas as pd\n",
13
+ "import numpy as np\n",
14
+ "import matplotlib.pyplot as plt\n",
15
+ "import seaborn as sns\n",
16
+ "import os\n",
17
+ "from tqdm import tqdm\n",
18
+ "%matplotlib inline\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
+ "csv_path = os.path.join(path, \"Q3_data.csv\")\n",
39
+ "\n",
40
+ "df = pd.read_csv(csv_path)\n"
41
+ ],
42
+ "execution_count": null,
43
+ "outputs": []
44
+ },
45
+ {
46
+ "cell_type": "code",
47
+ "metadata": {},
48
+ "source": [
49
+ "# Task 2: Write your code here:\n",
50
+ "df.head()"
51
+ ],
52
+ "execution_count": null,
53
+ "outputs": []
54
+ },
55
+ {
56
+ "cell_type": "code",
57
+ "metadata": {},
58
+ "source": [
59
+ "# Task 3: Write your code here:\n",
60
+ "df.info()"
61
+ ],
62
+ "execution_count": null,
63
+ "outputs": []
64
+ },
65
+ {
66
+ "cell_type": "code",
67
+ "metadata": {},
68
+ "source": [
69
+ "# Task 4: Write your code here:\n",
70
+ "df.describe()"
71
+ ],
72
+ "execution_count": null,
73
+ "outputs": []
74
+ },
75
+ {
76
+ "cell_type": "code",
77
+ "metadata": {},
78
+ "source": [
79
+ "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 1: Write your code here:\n",
98
+ "\n",
99
+ "\n",
100
+ "for col in ['P_2',\t'B_2',\t'S_3',\t'D_41','B_3','D_141','D_142','D_143','D_144','D_145']:\n",
101
+ " df[col].fillna(df[col].mode()[0])"
102
+ ],
103
+ "execution_count": null,
104
+ "outputs": []
105
+ },
106
+ {
107
+ "cell_type": "code",
108
+ "metadata": {},
109
+ "source": [
110
+ "# Task 2: Write your code here:\n",
111
+ "def check_duplicates(df):\n",
112
+ " duplicates = df.duplicated().sum()\n",
113
+ " print(f\"Number of Duplicate Samples: {duplicates}\")\n",
114
+ " if duplicates > 0:\n",
115
+ " print(\"Dropping Duplicates...\")\n",
116
+ " df.drop_duplicates(inplace=True)\n",
117
+ " print(\"Duplicates Dropped.\")\n",
118
+ " else:\n",
119
+ " print(\"No Duplicate Samples Found.\")\n",
120
+ "\n",
121
+ "check_duplicates(df)"
122
+ ],
123
+ "execution_count": null,
124
+ "outputs": []
125
+ },
126
+ {
127
+ "cell_type": "code",
128
+ "metadata": {},
129
+ "source": [
130
+ "# Task 3: Write your code here:\n",
131
+ "from sklearn.preprocessing import LabelEncoder\n",
132
+ "categorical_cols = df.select_dtypes(include=[\"object\"]).columns\n",
133
+ "label_encoders = {}\n",
134
+ "for col in categorical_cols:\n",
135
+ " le = LabelEncoder()\n",
136
+ " df[col] = le.fit_transform(df[col])\n",
137
+ " label_encoders[col] = le\n",
138
+ "\n",
139
+ "df"
140
+ ],
141
+ "execution_count": null,
142
+ "outputs": []
143
+ },
144
+ {
145
+ "cell_type": "code",
146
+ "metadata": {},
147
+ "source": [
148
+ "# Task 4: Write your code here:\n",
149
+ "from sklearn.preprocessing import StandardScaler\n",
150
+ "\n",
151
+ "numerical_cols = df.select_dtypes(include=[\"int64\", \"float64\"]).columns.drop(\"Target\") # we don't scale target\n",
152
+ "\n",
153
+ "scaler = StandardScaler()\n",
154
+ "df[numerical_cols] = scaler.fit_transform(df[numerical_cols])\n",
155
+ "df.head()"
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
+ "def check_target_imbalance(df, target_column):\n",
166
+ " print(\"Target Distribution:\")\n",
167
+ " print(df[target_column].value_counts(normalize=True))\n",
168
+ " sns.countplot(x=df[target_column])\n",
169
+ " plt.title(\"Target Distribution\")\n",
170
+ " plt.show()\n",
171
+ "\n",
172
+ "check_target_imbalance(df, \"Target\") #there is imbalance"
173
+ ],
174
+ "execution_count": null,
175
+ "outputs": []
176
+ },
177
+ {
178
+ "cell_type": "code",
179
+ "metadata": {},
180
+ "source": [
181
+ "# Task 1: Write your code here:\n",
182
+ "X = df.drop(\"Target\", axis=1).astype(float)\n",
183
+ "y = df['Target'].astype(float)"
184
+ ],
185
+ "execution_count": null,
186
+ "outputs": []
187
+ },
188
+ {
189
+ "cell_type": "code",
190
+ "metadata": {},
191
+ "source": [
192
+ "# Task 2,3,4,5: Write your code here:\n",
193
+ "from sklearn.neighbors import KNeighborsClassifier\n",
194
+ "from sklearn.svm import SVC\n",
195
+ "from sklearn.tree import DecisionTreeClassifier\n",
196
+ "from sklearn.ensemble import RandomForestClassifier\n",
197
+ "from xgboost import XGBClassifier\n",
198
+ "from catboost import CatBoostClassifier\n",
199
+ "from sklearn.model_selection import StratifiedKFold\n",
200
+ "from sklearn.model_selection import StratifiedKFold\n",
201
+ "from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\n",
202
+ "\n",
203
+ "sklearn_models = { #defining models\n",
204
+ "\n",
205
+ " \"CatBoost\": CatBoostClassifier(\n",
206
+ " verbose=0,\n",
207
+ " n_estimators=320,\n",
208
+ " max_depth=4\n",
209
+ " )\n",
210
+ "}\n",
211
+ "all_results = {}\n",
212
+ "n_splits = 5 # K\n",
213
+ "\n",
214
+ "# Stratified 5-Fold Cross-Validation, shuffled\n",
215
+ "skf = StratifiedKFold(n_splits=n_splits, shuffle=True, random_state=42)\n",
216
+ "\n",
217
+ "for name in sklearn_models:\n",
218
+ " all_results[name] = {'accuracy': [], 'precision': [], 'recall': [], 'f1': []}\n",
219
+ "\n",
220
+ "for fold_idx, (train_index, test_index) in enumerate(skf.split(X, y)):\n",
221
+ " print(f\"\\nFold {fold_idx + 1}/{n_splits}\")\n",
222
+ "\n",
223
+ " # 1. Split data\n",
224
+ " X_train, X_test = X.iloc[train_index], X.iloc[test_index]\n",
225
+ " y_train, y_test = y.iloc[train_index], y.iloc[test_index]\n",
226
+ "\n",
227
+ " # 2. Train & Validate sklearn models\n",
228
+ " for model_name, model in sklearn_models.items():\n",
229
+ " print(f\"Training {model_name}...\")\n",
230
+ " model.fit(X_train, y_train) # train\n",
231
+ " y_pred = model.predict(X_test) # validate\n",
232
+ "\n",
233
+ " # 3. Save metrics for that model in this fold\n",
234
+ " accuracy = accuracy_score(y_test, y_pred)\n",
235
+ " precision = precision_score(y_test, y_pred, zero_division=0)\n",
236
+ " recall = recall_score(y_test, y_pred, zero_division=0)\n",
237
+ " f1 = f1_score(y_test, y_pred, zero_division=0)\n",
238
+ "\n",
239
+ " all_results[model_name]['accuracy'].append(accuracy)\n",
240
+ " all_results[model_name]['precision'].append(precision)\n",
241
+ " all_results[model_name]['recall'].append(recall)\n",
242
+ " all_results[model_name]['f1'].append(f1)\n"
243
+ ],
244
+ "execution_count": null,
245
+ "outputs": []
246
+ },
247
+ {
248
+ "cell_type": "code",
249
+ "metadata": {},
250
+ "source": [
251
+ "# Task 1: Write your code here:"
252
+ ],
253
+ "execution_count": null,
254
+ "outputs": []
255
+ },
256
+ {
257
+ "cell_type": "code",
258
+ "metadata": {},
259
+ "source": [
260
+ "# Task 2: Write your code here:"
261
+ ],
262
+ "execution_count": null,
263
+ "outputs": []
264
+ },
265
+ {
266
+ "cell_type": "code",
267
+ "metadata": {},
268
+ "source": [
269
+ "# Task Bonus: Write your code here:"
270
+ ],
271
+ "execution_count": null,
272
+ "outputs": []
273
+ }
274
+ ],
275
+ "metadata": {
276
+ "kernelspec": {
277
+ "display_name": "Python 3",
278
+ "name": "python3"
279
+ },
280
+ "language_info": {
281
+ "name": "python"
282
+ }
283
+ },
284
+ "nbformat": 4,
285
+ "nbformat_minor": 0
286
+ }